CrossSWE-Bench / scripts /materialize_agent_context.py
Silin-Chen's picture
CrossSWE-Bench: current 171-instance release
0e239c6
Raw History Blame Contribute Delete
14.7 kB
"""Restore an exact, hash-bound Docker build context into a new directory."""
import argparse
from contextlib import contextmanager
import hashlib
import json
from pathlib import Path, PurePosixPath
import shutil
import tarfile
import tempfile
def digest(path):
value = hashlib.sha256()
with Path(path).open('rb') as stream:
for block in iter(lambda: stream.read(1024 * 1024), b''):
value.update(block)
return value.hexdigest()
def relative(name):
path = PurePosixPath(name)
if (not name or path.is_absolute() or '..' in path.parts or '.' in name.split('/')
or '\\' in name or str(path) != name):
raise ValueError('Unsafe context member: ' + name)
return path
def declared_container_links(manifest, entries, tar):
"""Allow only exact Git-bound links to a declared paired container checkout."""
absolute = {name: row for name, row in entries.items()
if row.get('kind') == 'symlink' and PurePosixPath(row['target']).is_absolute()}
if not absolute:
return {}
if manifest.get('schema_version', 1) < 3 or 'instance.json' not in entries:
raise ValueError('Absolute source link requires a version 3 instance binding')
member = tar.getmember('instance.json'); row = entries['instance.json']
if not member.isfile() or member.size != row['bytes'] or member.size > 2 * 1024 * 1024:
raise ValueError('Invalid source link declaration')
data = tar.extractfile(member).read()
if hashlib.sha256(data).hexdigest() != row['sha256']:
raise ValueError('Source link declaration hash mismatch')
instance = json.loads(data)
repositories = {r['key']: r for r in instance['repositories']}
allowed = {}
for repo in repositories.values():
path = PurePosixPath(repo['path'])
if not path.is_absolute() or path.parts[:2] != ('/', 'testbed') or '..' in path.parts or '.git' in path.parts:
raise ValueError('Invalid declared repository path')
for link in repo.get('workspace_links', []):
target = repositories[link['target_repository']]['path']
if target == repo['path'] or link['original_target'] != target:
raise ValueError('Container link does not bind a distinct paired repository')
blob = target.encode()
oid = hashlib.sha1(b'blob ' + str(len(blob)).encode() + b'\0' + blob).hexdigest()
if oid != link['expected_blob']:
raise ValueError('Container link differs from its original Git blob')
name = str(PurePosixPath(repo['path'].lstrip('/')) / relative(link['path']))
if name in allowed:
raise ValueError('Duplicate container link declaration')
allowed[name] = target
if any(allowed.get(name) != row['target'] for name, row in absolute.items()):
raise ValueError('Undeclared absolute context link')
return {name: row['target'].lstrip('/') for name, row in absolute.items()}
def check_virtual_links(entries, container_links):
"""Resolve link graphs without touching an absolute container path on the host."""
links = {name: row['target'] for name, row in entries.items() if row.get('kind') == 'symlink'}
for name in links:
pending = list(PurePosixPath(name).parts); stack = []; followed = 0
while pending:
part = pending.pop(0)
if part in ('', '.'):
continue
if part == '..':
if not stack:
raise ValueError('Context link escapes output')
stack.pop(); continue
stack.append(part); prefix = '/'.join(stack)
if prefix in links:
followed += 1
if followed > 40:
raise ValueError('Cyclic or excessive context link graph')
target = links[prefix]
if PurePosixPath(target).is_absolute():
if prefix not in container_links:
raise ValueError('Undeclared absolute context link')
stack = []; target = container_links[prefix]
else:
stack.pop()
pending = list(PurePosixPath(target).parts) + pending
@contextmanager
def archive_stream(root, reference):
parts=reference.get('parts')
if parts is not None:
if not isinstance(parts,list) or not parts:
raise ValueError('Archive parts must be nonempty')
with tempfile.TemporaryFile() as output:
total=0;whole=hashlib.sha256()
for part in parts:
source=root/relative(part['path'])
if source.is_symlink() or part['offset']!=total or source.stat().st_size!=part['bytes']:
raise ValueError('Archive part path/order/size mismatch')
actual=hashlib.sha256()
with source.open('rb') as stream:
for block in iter(lambda:stream.read(1024*1024),b''):
actual.update(block);whole.update(block);output.write(block);total+=len(block)
if actual.hexdigest()!=part['sha256']:
raise ValueError('Archive part hash mismatch')
if total!=reference['bytes'] or whole.hexdigest()!=reference['sha256']:
raise ValueError('Reconstructed archive hash/size mismatch')
output.seek(0)
yield output
else:
source=root/relative(reference['path'])
if source.is_symlink() or source.stat().st_size!=reference['bytes'] or digest(source)!=reference['sha256']:
raise ValueError('Context archive hash/size mismatch')
with source.open('rb') as stream:yield stream
def materialize(manifest_path, output, verify_only=False):
manifest_path, output = Path(manifest_path), Path(output) if output is not None else None
if output is not None and (output.exists() or output.is_symlink()):
raise FileExistsError(output)
manifest = json.loads(manifest_path.read_text())
reference = manifest['archive']
entries = {str(relative(row['path'])): row for row in manifest['files']}
if len(entries) != len(manifest['files']):
raise ValueError('Duplicate manifest members')
for name in entries:
if any(str(parent) in entries for parent in PurePosixPath(name).parents):
raise ValueError('File/directory context collision')
with archive_stream(manifest_path.parent,reference) as source, tarfile.open(fileobj=source,mode='r:gz') as tar:
members = tar.getmembers()
names = [str(relative(member.name)) for member in members]
if len(names) != len(set(names)) or set(names) != set(entries):
raise ValueError('Unlisted, missing or duplicate archive members')
container_links = declared_container_links(manifest, entries, tar)
for member in members:
row = entries[member.name]
if member.mode != row['mode'] or not 0 <= member.mode <= 0o777:
raise ValueError('Context member type/size/mode mismatch')
if row.get('kind','file')=='symlink':
target=row['target']
if (not member.issym() or member.linkname!=target or not target
or (PurePosixPath(target).is_absolute() and member.name not in container_links)
or '\\' in target or '\x00' in target):
raise ValueError('Unsafe or changed context link')
data=target.encode()
if len(data)!=row['bytes']:
raise ValueError('Context link size mismatch')
actual=hashlib.sha256(data).hexdigest()
elif row.get('kind','file')=='file' and member.isfile() and member.size==row['bytes']:
actual_hash=hashlib.sha256()
with tar.extractfile(member) as stream:
for block in iter(lambda:stream.read(1024*1024),b''):actual_hash.update(block)
actual=actual_hash.hexdigest()
else:
raise ValueError('Unsupported or changed context member')
if actual != row['sha256']:
raise ValueError('Context member hash mismatch: ' + member.name)
check_virtual_links(entries, container_links)
if verify_only:
return {'files':len(entries),'archive_sha256':reference['sha256'],'state':'ARCHIVE_VERIFIED'}
output.mkdir(parents=True, exist_ok=False)
try:
for member in members:(output/member.name).parent.mkdir(parents=True,exist_ok=True)
for member in members:
if member.isfile():
target=output/member.name
with tar.extractfile(member) as source,target.open('xb') as destination:shutil.copyfileobj(source,destination)
target.chmod(member.mode)
# No regular-file write occurs after creating any source link.
for member in members:
if member.issym():(output/member.name).symlink_to(member.linkname)
except BaseException:
shutil.rmtree(output)
raise
return {'files': len(entries), 'symlinks':sum(row.get('kind')=='symlink' for row in entries.values()),
'declared_container_symlinks': len(container_links), 'archive_sha256': reference['sha256'], 'output': str(output)}
# crossswe repair publication context compatibility v1
def descriptor_ref(folder, reference):
path = folder / relative(reference['path'])
if any(p.is_symlink() for p in (path, *path.parents)) or not path.is_file():
raise ValueError('Unsafe descriptor reference')
if path.stat().st_size != reference['bytes'] or digest(path) != reference['sha256']:
raise ValueError('Descriptor reference hash/size mismatch')
return path
def current_context(root, instance_id):
folder = root / 'environments' / relative(instance_id)
image_path = folder / 'image.json'
if any(p.is_symlink() for p in (image_path, *image_path.parents)):
raise ValueError('Unsafe image descriptor path')
image = json.loads(image_path.read_text())
if image['instance_id'] != instance_id:
raise ValueError('Image descriptor instance differs')
manifest = descriptor_ref(folder, image['context_manifest'])
recipe = None
if image.get('recipe'):
recipe = json.loads(descriptor_ref(folder, image['recipe']).read_text())
import re
if (recipe.get('kind') != 'immutable-parent-delta'
or not re.fullmatch(r'[^@\s]+@sha256:[0-9a-f]{64}', recipe.get('parent_image_ref', ''))
or recipe['actual_context'] != image['context_manifest']
or descriptor_ref(folder, recipe['actual_context']) != manifest):
raise ValueError('Invalid immutable parent/delta recipe')
parent = json.loads(descriptor_ref(folder, recipe['parent_image_descriptor']).read_text())
if parent.get('image_ref') != recipe['parent_image_ref']:
raise ValueError('Recipe parent descriptor identity differs')
descriptor_ref(folder, parent['context_manifest'])
descriptor_ref(folder, recipe['source_authority'])
descriptor_ref(folder, recipe['build_receipt'])
# Every parent descriptor uses environment-root-relative refs, including an
# exact historical descriptor stored below history/. Never rebase its refs
# to the history directory.
recipe_chain(folder, image)
return manifest, recipe
def recipe_chain(folder, image, seen=None):
seen = set() if seen is None else seen
identity = image['image_ref']
if identity in seen or len(seen) >= 40:
raise ValueError('Cyclic or excessive recipe chain')
seen.add(identity)
if image.get('provenance_only'):
if image.get('registry_digest') != 'sha256:e6c20a1727d4eb758737a9c2710a2e0a805bc534fc056929d7ddb2279b55437c' or identity != 'silinchen0617/crossrepo-bench@sha256:e6c20a1727d4eb758737a9c2710a2e0a805bc534fc056929d7ddb2279b55437c':
raise ValueError('Unsupported provenance-only immutable parent')
context = descriptor_ref(folder, image['context_manifest'])
for reference in image['verified_provenance'].values():
descriptor_ref(folder, reference)
original = json.loads(descriptor_ref(folder, image['original_descriptor']).read_text())
if original['registry_digest'] != 'sha256:dd0cf3223f7e9524c4c21aafce54a1b59a7e53288027a1332ddeb1577cad6dda':
raise ValueError('Historical original parent differs')
return [{'image_ref': identity, 'context_manifest': str(context), 'context_kind': 'verified-registry-parent-reference'}] + recipe_chain(folder, original, seen)
context = descriptor_ref(folder, image['context_manifest'])
result = [{'image_ref': identity, 'context_manifest': str(context),
'context_kind': 'delta' if image.get('recipe') else 'full'}]
if image.get('recipe'):
recipe = json.loads(descriptor_ref(folder, image['recipe']).read_text())
parent = json.loads(descriptor_ref(folder, recipe['parent_image_descriptor']).read_text())
if parent['image_ref'] != recipe['parent_image_ref'] or recipe['actual_context'] != image['context_manifest']:
raise ValueError('Recipe chain identity differs')
result.extend(recipe_chain(folder, parent, seen))
return result
def verify_manifest(manifest_path):
return materialize(manifest_path, None, verify_only=True)
def materialize_image(root, instance_id, output):
manifest, recipe = current_context(Path(root), instance_id)
result = materialize(manifest, output)
result['context_manifest'] = str(manifest)
result['context_kind'] = 'delta' if recipe else 'full'
if recipe:
result['parent_image_ref'] = recipe['parent_image_ref']
result['source_authority_full_build_context'] = recipe['source_authority_full_build_context']
result['recipe_note'] = 'Build this actual delta with its pinned parent; historical full context remains preserved.'
return result
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('--instance-id', required=True)
parser.add_argument('--output-dir', type=Path, required=True)
args = parser.parse_args()
if Path(args.instance_id).name != args.instance_id or args.instance_id in ('','.', '..'):
parser.error('Use a canonical instance ID')
root = Path(__file__).resolve().parents[1]
print(json.dumps(materialize_image(root, args.instance_id, args.output_dir)))
if __name__ == '__main__':
main()