simrepairbench / scripts /package_broken_objects.py
chrisvoncsefalvay's picture
Publish revised CASTAIGNE25 repair tasks and broken-object gallery
2767b5b verified
Raw History Blame Contribute Delete
15.6 kB
"""Assemble portable damaged-object archives with NVIDIA attribution and hashes."""
import argparse
import gzip
import hashlib
import json
from pathlib import Path, PurePosixPath
import shutil
import tarfile
from acquire_packages import digest
USD = {'.usd', '.usda', '.usdc'}
def source_only_resource(raw):
"""Original preview images and package reports are reference-only data."""
path = PurePosixPath(raw)
return '.thumbs' in path.parts or path.parts[0] == '.metadata' or path.name == 'com.nvidia.simready.packaging.json'
def sha256(path):
with path.open('rb') as stream:
return hashlib.file_digest(stream, 'sha256').hexdigest()
def save(path, obj):
path.parent.mkdir(parents=True, exist_ok=True)
path.write_text(json.dumps(obj, ensure_ascii=False, indent=2) + '\n')
def qualified_profile(root, cid, asset):
"""Bind a release to the exact input, code and completed controls."""
profile = json.loads((root / 'profiles/castaigne25' / (cid + '.json')).read_text())
pins = profile.get('controls', {})
if profile.get('case_id') != cid or not profile.get('frozen_for_trials') or not pins.get('revision_03_controls_passed'):
raise ValueError('Fresh controlled qualification is required before release packaging: ' + cid)
relative = PurePosixPath(pins.get('qualification_report', ''))
if relative.is_absolute() or '..' in relative.parts or not relative.parts:
raise ValueError('A confined qualification report is required: ' + cid)
receipt_path = root / relative
if not receipt_path.resolve().is_relative_to(root.resolve()) or sha256(receipt_path) != pins.get('qualification_report_sha256'):
raise ValueError('Qualification report hash mismatch: ' + cid)
receipt = json.loads(receipt_path.read_text())
required = {'source', 'broken', 'repaired', 'equivalent', 'partial', 'deletion', 'hiding',
'zero_scale', 'static_conversion', 'collision_disabled', 'duplicate_dummy',
'masked_weaker_layer', 'missing_dependency', 'forged_reward'}
if (receipt.get('case_id') != cid or receipt.get('case_version') != '0.3.0'
or receipt.get('all_passed') is not True
or set(receipt.get('required_controls', [])) != required
or any(receipt.get('controls', {}).get(name, {}).get('passed') is not True for name in required)):
raise ValueError('Incomplete qualification controls: ' + cid)
actual_input = sha256(asset)
if pins.get('input_asset_sha256') != actual_input or receipt.get('input_asset_sha256') != actual_input:
raise ValueError('Qualified input bytes changed: ' + cid)
module = profile.get('verifier_module', 'simrepairbench.repair_verifier')
allowed_modules = {'simrepairbench.repair_verifier': 'repair_verifier.py',
'simrepairbench.repair_verifier_r25': 'repair_verifier_r25.py'}
if (module not in allowed_modules or (module.endswith('_r25') and cid != 'R25')
or module != pins.get('verifier_module', 'simrepairbench.repair_verifier')
or module != receipt.get('verifier_module', 'simrepairbench.repair_verifier')):
raise ValueError('Qualified verifier module changed: ' + cid)
code = {'verifier_code_sha256': allowed_modules[module], 'geometry_faults_sha256': 'geometry_faults.py',
'actor_probes_sha256': 'actor_probes.py'}
for key, name in code.items():
if pins.get(key) != receipt.get(key) or pins.get(key) != sha256(root / 'src/simrepairbench' / name):
raise ValueError('Qualified code changed: ' + name)
if module.endswith('_r25'):
if (pins.get('base_verifier_code_sha256') != receipt.get('base_verifier_code_sha256')
or pins.get('base_verifier_code_sha256') != sha256(root / 'src/simrepairbench/repair_verifier.py')):
raise ValueError('Qualified base verifier changed: ' + cid)
harness_name = pins.get('qualification_harness', 'work/qualify_repair_profiles.py')
def harness_path(raw):
path = PurePosixPath(raw)
if path.is_absolute() or '..' in path.parts or not path.parts or path.parts[0] != 'work':
raise ValueError('A confined qualification harness is required: ' + cid)
result = root / path
if not result.resolve().is_relative_to(root.resolve()):
raise ValueError('Qualification harness escapes its project: ' + cid)
return result
if harness_name != receipt.get('qualification_harness', 'work/qualify_repair_profiles.py'):
raise ValueError('Qualification harness identity changed: ' + cid)
harness = harness_path(harness_name)
if pins.get('harness_sha256') != receipt.get('harness_sha256') or pins.get('harness_sha256') != sha256(harness):
raise ValueError('Qualification harness changed: ' + cid)
shared = pins.get('shared_qualification_harness')
if shared:
if (shared != receipt.get('shared_qualification_harness')
or pins.get('shared_harness_sha256') != receipt.get('shared_harness_sha256')
or pins.get('shared_harness_sha256') != sha256(harness_path(shared))):
raise ValueError('Shared qualification harness changed: ' + cid)
runtime = pins.get('runtime', {})
if (runtime != receipt.get('runtime') or runtime.get('openusd') != [0, 26, 8]
or not str(runtime.get('container_image', '')).startswith('sha256:')):
raise ValueError('Qualified runtime is not pinned: ' + cid)
return profile
def input_release_profile(root, cid, asset):
"""Keep input-artifact publication separate from verifier qualification."""
profile = json.loads((root / 'profiles/castaigne25' / (cid + '.json')).read_text())
if profile.get('frozen_for_trials'):
return qualified_profile(root, cid, asset)
controls = profile.get('controls', {})
if (profile.get('case_id') != cid or profile.get('schema') != 'simrepairbench-authored-usd-v3'
or controls.get('source_semantic_self_passed') is not True
or controls.get('broken_semantic_success') is not False
or controls.get('broken_targeted_repair_fraction') != 0
or controls.get('broken_preservation_pass') is not True):
raise ValueError('Measured source and broken-input checks are required: ' + cid)
report = json.loads((root / 'records' / cid / 'damage-verification.json').read_text())
if (report.get('case_version') != '0.3.0' or not report.get('passed')
or not report.get('component_presence', {}).get('passed')
or sha256(asset) != report['asset_sha256']):
raise ValueError('Current retained-component input is required: ' + cid)
return profile
def package(root, case, *, prepare_only=False, input_release=False):
cid = case['case_id']
report = json.loads((root / 'records' / cid / 'damage-verification.json').read_text())
if not report['passed'] or not all(d['passed'] for d in report['defects']):
raise ValueError('Fault checks must pass before packaging: ' + cid)
original = root / 'work/originals' / cid / case['source']['asset_id']
inventory = json.loads((root / 'records' / cid / 'upstream-inventory.json').read_text())
folder = root / 'work/damaged' / cid
if sha256(folder / 'asset.usdc') != report['asset_sha256']:
raise ValueError('Damaged asset bytes changed: ' + cid)
source = folder / 'source'
for row in inventory['files']:
p = original / row['path']
if not p.is_file() or p.stat().st_size != row['size']:
raise ValueError('Original package is incomplete: ' + row['path'])
if not digest(p, row):
raise ValueError('Original package hash mismatch: ' + row['path'])
if p.suffix.lower() in USD:
continue
dest = source / row['path']
if source_only_resource(row['path']):
# Only regenerated task copies are removed; pinned originals stay
# intact in the protected source tree and browsable reference view.
if dest.exists():
if dest.is_symlink() or not dest.is_file() or not digest(dest, row):
raise ValueError('Unexpected source-only task resource: ' + str(dest))
dest.unlink()
continue
dest.parent.mkdir(parents=True, exist_ok=True)
if not dest.exists():
# Resources stay immutable and can be shared on the build filesystem.
import os
os.link(p, dest)
for owner, refs in report['asset_dependencies'].items():
for raw in refs:
relative = PurePosixPath(owner).parent / raw
if relative.is_absolute() or '..' in relative.parts or ':' in raw:
raise ValueError('Nonportable asset dependency: ' + raw)
if '<UDIM>' in raw:
matches = list(folder.glob(str(relative).replace('<UDIM>', '[0-9][0-9][0-9][0-9]')))
else:
matches = [folder / relative] if (folder / relative).is_file() else []
if not matches:
raise ValueError('Missing package resource: ' + raw)
notice = original / '.metadata/LICENSE.txt'
if not notice.is_file():
raise ValueError('NVIDIA source licence missing')
if json.loads((original / 'com.nvidia.simready.packaging.json').read_text())['license'] != 'CC-BY-4.0':
raise ValueError('Unexpected source licence declaration')
shutil.copyfile(notice, folder / 'LICENSE-NVIDIA.txt')
(folder / 'NOTICE.md').write_text(
'# Attribution and modifications\n\n'
f"Derived from NVIDIA SimReady `{case['source']['asset_id']}` at revision `{inventory['revision']}`.\n\n"
f"Source: https://huggingface.co/datasets/nvidia/simready-assets/tree/{inventory['revision']}/{case['source']['asset_id']}\n\n"
'The source asset is licensed CC BY 4.0; its original licence and metadata are retained. '
'HCLTech Robotics modified USD composition, geometry and/or physical properties to create this SimRepairBench repair task. '
'This modified asset is not an original NVIDIA release and does not imply NVIDIA endorsement.\n')
save(folder / '.metadata/com.nvidia.simready.root_usds.json', {'format_version': '1.0', 'entries': ['asset.usdc']})
if not prepare_only:
profile = (input_release_profile if input_release else qualified_profile)(root, cid, folder / 'asset.usdc')
from simrepairbench.harbor import actor_requirements
evidence_path = folder / 'evidence.json'
evidence = json.loads(evidence_path.read_text())
if evidence.get('schema') != 'simrepairbench-observable-case-v03':
raise ValueError('Only current candidate observations belong in the actor package')
evidence['functional_brief'] = case['acceptance']['required_outcome']
evidence['scope'] = case['acceptance']['scope']
evidence['diagnosis'] = case.get('diagnosis', {})
evidence['functional_requirements'] = actor_requirements(profile)
save(evidence_path, evidence)
(folder / 'instruction.md').write_text(
f"# {case['title']}\n\n"
'Inspect and repair `asset.usdc` and its resources using the functional brief in `evidence.json`. '
'Keep every physical component present and usable.\n\n'
f"{case['failure_story']}\n\n{case['acceptance']['required_outcome']}\n\n{case['acceptance']['scope']}\n")
files = [{'path': p.relative_to(folder).as_posix(), 'size': p.stat().st_size, 'sha256': sha256(p)}
for p in sorted(folder.rglob('*')) if p.is_file() and p.name != 'MANIFEST.json']
save(folder / 'MANIFEST.json', {'case_id': cid, 'case_version': '0.3.0', 'entrypoint': 'asset.usdc',
'source_repository': inventory['repository'], 'source_revision': inventory['revision'],
'source_asset': inventory['asset_id'], 'licence': 'CC-BY-4.0',
'modified_by': 'HCLTech Robotics', 'files': files})
if prepare_only:
result = {'case_id': cid, 'case_version': '0.3.0', 'resources_prepared': True,
'file_count': len(files), 'asset_sha256': report['asset_sha256'],
'release_archive_created': False}
save(root / 'work/resource-preparation' / (cid + '.json'), result)
print(json.dumps(result), flush=True)
return result
target = root / 'packages' / (cid + '.tar.gz')
target.parent.mkdir(exist_ok=True)
temp = target.with_name(target.name + '.tmp')
with temp.open('wb') as stream, gzip.GzipFile(filename='', mode='wb', fileobj=stream, mtime=0, compresslevel=1) as compressed, tarfile.open(fileobj=compressed, mode='w') as archive:
for p in sorted(folder.rglob('*')):
if not p.is_file():
continue
info = archive.gettarinfo(str(p), arcname=cid + '/' + p.relative_to(folder).as_posix())
info.uid = info.gid = info.mtime = 0
info.uname = info.gname = ''
info.mode = 0o644
with p.open('rb') as data:
archive.addfile(info, data)
temp.replace(target)
# Read every member from the finished archive rather than trusting pack input.
expected = {cid + '/' + r['path']: r for r in files}
seen = set()
with tarfile.open(target, 'r:gz') as archive:
for member in archive:
if not member.isfile() or member.issym() or member.islnk() or not member.name.startswith(cid + '/') or '..' in PurePosixPath(member.name).parts:
raise ValueError('Unsafe archive member')
if member.name == cid + '/MANIFEST.json':
continue
row = expected[member.name]
with archive.extractfile(member) as data:
actual = hashlib.file_digest(data, 'sha256').hexdigest()
if actual != row['sha256'] or member.size != row['size']:
raise ValueError('Archive member hash mismatch: ' + member.name)
seen.add(member.name)
if seen != set(expected):
raise ValueError('Archive file set mismatch')
result = {'case_id': cid, 'path': 'packages/' + target.name, 'size': target.stat().st_size,
'sha256': sha256(target), 'member_count': len(files) + 1, 'archive_verified': True,
'entrypoint': cid + '/asset.usdc', 'fault_count': report['defect_count'],
'verification_scope': report['verification_scope'], 'asset_sha256': report['asset_sha256']}
result['verifier_qualified'] = bool(profile.get('frozen_for_trials'))
save(root / 'records' / cid / 'package-verification.json', result)
print(json.dumps(result), flush=True)
return result
def main():
p = argparse.ArgumentParser(description=__doc__)
p.add_argument('--root', type=Path, default=Path.cwd())
p.add_argument('--case', default='all')
p.add_argument('--prepare-only', action='store_true', help='Assemble verified resources for qualification without creating a release archive')
p.add_argument('--input-release', action='store_true', help='Publish verified inputs without claiming unfinished verifier qualification')
args = p.parse_args()
for case in json.loads((args.root / 'cases/castaigne25.json').read_text())['cases']:
if args.case in ('all', case['case_id']):
package(args.root.resolve(), case, prepare_only=args.prepare_only, input_release=args.input_release)
if __name__ == '__main__':
main()