CrossSWE-Bench / scripts /reusable_support /batch05_runtime_resources.py
Silin-Chen's picture
CrossSWE-Bench: current 171-instance release
0e239c6
Raw History Blame Contribute Delete
4.59 kB
"""Materialize pinned evaluator dependencies without following host symlinks."""
import hashlib
import json
import os
from pathlib import Path
import re
import shutil
import subprocess
import tarfile
def sha(p):
h=hashlib.sha256()
with Path(p).open('rb') as f:
for b in iter(lambda:f.read(1024*1024),b''):h.update(b)
return h.hexdigest()
def validate_runtime_descriptor(resource):
assert resource['kind']=='frozen-evaluator-dependencies' and resource['container_path']=='/crossswe-evaluator'
assert re.fullmatch(r'[^@\s]+@sha256:[0-9a-f]{64}',resource['image_ref'])
files=resource['files'];assert files and len({r['path'] for r in files})==len(files)
for r in files:
p=Path(r['path']);assert not p.is_absolute() and '..' not in p.parts and str(p)==r['path']
assert r['kind'] in ['file','symlink'] and type(r['bytes']) is int and r['bytes']>=0
assert re.fullmatch(r'[0-9a-f]{64}',r['sha256'])
if r['kind']=='symlink':assert isinstance(r['target'],str) and hashlib.sha256(r['target'].encode()).hexdigest()==r['sha256']
manifest=next(r for r in files if r['path']=='bundle-manifest.json')
assert manifest['kind']=='file' and manifest['sha256']==resource['manifest_sha256']
def verify_runtime_files(root,resource):
validate_runtime_descriptor(resource);root=Path(root)
assert sha(root/'bundle-manifest.json')==resource['manifest_sha256']
bundle=json.loads((root/'bundle-manifest.json').read_text())
if resource.get('manifest_contains_inventory'):
assert bundle['instance_id']==resource['instance_id'] and len(bundle['files'])==resource['full_file_count']
all_files=bundle['files']+resource['files']
else:all_files=resource['files']
expected={r['path']:r for r in all_files};assert len(expected)==len(all_files)
for name in expected:
q=Path(name);assert not q.is_absolute() and '..' not in q.parts and str(q)==name
actual={str(p.relative_to(root)) for p in root.rglob('*') if p.is_symlink() or p.is_file()}
assert actual==set(expected),'Evaluator resource inventory mismatch'
for name,r in expected.items():
p=root/name;assert p.parent.resolve().is_relative_to(root.resolve())
if r['kind']=='symlink':assert p.is_symlink() and os.readlink(p)==r['target']
else:
assert p.is_file() and not p.is_symlink() and p.stat().st_size==r['bytes'] and sha(p)==r['sha256']
if 'mode' in r:assert p.stat().st_mode&0o777==r['mode']
assert sha(root/'bundle-manifest.json')==resource['manifest_sha256']
def materialize_runtime(resource,destination,provided=None):
validate_runtime_descriptor(resource);destination=Path(destination)
assert not destination.exists()
if provided:shutil.copytree(provided,destination,symlinks=True)
else:
subprocess.run(['docker','pull','--platform','linux/amd64',resource['image_ref']],check=True)
cid=subprocess.check_output(['docker','create','--network','none','--label','crossswe.owner=portable-baseline',resource['image_ref'],'/bin/true'],text=True).strip()
destination.mkdir();seen=set()
try:
q=subprocess.Popen(['docker','cp',cid+':/crossswe-evaluator','-'],stdout=subprocess.PIPE)
with tarfile.open(fileobj=q.stdout,mode='r|') as tf:
for m in tf:
rel=Path(m.name).relative_to('crossswe-evaluator');assert not rel.is_absolute() and '..' not in rel.parts
p=destination/rel;assert p==destination or p.parent.resolve().is_relative_to(destination.resolve())
if m.isdir():p.mkdir(parents=True,exist_ok=True);continue
name=str(rel);assert name not in seen;seen.add(name)
p.parent.mkdir(parents=True,exist_ok=True)
if m.issym():p.symlink_to(m.linkname)
elif m.isfile():
with p.open('xb') as f:shutil.copyfileobj(tf.extractfile(m),f)
p.chmod(m.mode&0o777)
elif m.islnk():
origin=destination/Path(m.linkname).relative_to('crossswe-evaluator')
assert origin.is_file() and not origin.is_symlink() and origin.resolve().is_relative_to(destination.resolve());os.link(origin,p)
else:raise ValueError('Unsupported evaluator archive entry')
assert q.wait()==0
finally:subprocess.run(['docker','rm',cid],check=True,stdout=subprocess.DEVNULL)
verify_runtime_files(destination,resource)
return destination