Datasets:
Download environments/security-rustls-3203/evaluator-a02/run_evaluation.py from CrossSWE/CrossSWE-Bench: direct link, hf CLI and curl.
- Browser
- Download file 10.1 kB
-
https://huggingface.co/datasets/CrossSWE/CrossSWE-Bench/resolve/main/environments/security-rustls-3203/evaluator-a02/run_evaluation.py
- Command line
-
hf download hf://datasets/CrossSWE/CrossSWE-Bench/environments/security-rustls-3203/evaluator-a02/run_evaluation.py
-
curl -L -o run_evaluation.py https://huggingface.co/datasets/CrossSWE/CrossSWE-Bench/resolve/main/environments/security-rustls-3203/evaluator-a02/run_evaluation.py
10.1 kB
| #!/usr/bin/env python3 | |
| """Portable caller-patch evaluation on the immutable Rustls/AWS image.""" | |
| from pathlib import Path | |
| import argparse,hashlib,json,os,shutil,subprocess,sys,tempfile,uuid | |
| from assess import assess | |
| INDEX='sha256:1d74de134f455ea020b68b339c575e92c6d27617c999ee2ecefc89a69c9298bb' | |
| CHILD='sha256:1d74de134f455ea020b68b339c575e92c6d27617c999ee2ecefc89a69c9298bb' | |
| CONFIG='sha256:c1540caf1328350841cd4eea7f571333fc8a2ad596f084d76d87e2c3952702ee' | |
| IMAGE='silinchen0617/crossrepo-bench@'+INDEX | |
| def sha(raw):return hashlib.sha256(raw).hexdigest() | |
| def write(p,v):p.write_text(json.dumps(v,sort_keys=True,indent=2)+'\n') | |
| def read_map(path,expected): | |
| path=path.resolve();raw=path.read_bytes() | |
| if sha(raw)!=expected:raise ValueError('External candidate map SHA mismatch') | |
| value=json.loads(raw) | |
| if value.get('schema')!='crossswe-rustls3203-candidate-map-a01':raise ValueError('Unsupported candidate map') | |
| if not isinstance(value.get('provenance'),str) or not value['provenance'].strip():raise ValueError('Caller provenance required') | |
| if not isinstance(value.get('patches'),dict) or not value['patches'] or set(value['patches'])-{'rustls','aws_lc_rs'}:raise ValueError('Explicit nonempty caller patches required') | |
| refs={} | |
| for repo,row in value['patches'].items(): | |
| relative=Path(row['path']) | |
| if relative.is_absolute() or '..' in relative.parts:raise ValueError('Patch path must remain within external map directory') | |
| p=path.parent/relative | |
| if p.is_symlink() or not p.is_file() or not p.resolve().is_relative_to(path.parent):raise ValueError('Unsafe candidate patch') | |
| raw=p.read_bytes() | |
| if not raw or len(raw)!=row['bytes'] or sha(raw)!=row['sha256']:raise ValueError('Candidate patch bytes/hash mismatch') | |
| refs[repo]=(p,raw) | |
| return value,refs | |
| def check_package(root,expected): | |
| raw=(root/'package-manifest.json').read_bytes() | |
| if sha(raw)!=expected:raise ValueError('External package manifest SHA mismatch') | |
| manifest=json.loads(raw) | |
| declared={r['path'] for r in manifest['files']} | |
| actual={str(p.relative_to(root)) for p in root.rglob('*') if p.is_file() and p.name!='package-manifest.json' and '__pycache__' not in p.parts} | |
| if declared!=actual:raise ValueError('Package file closure differs') | |
| for row in manifest['files']: | |
| relative=Path(row['path']);p=root/relative | |
| if relative.is_absolute() or '..' in relative.parts or p.is_symlink():raise ValueError('Unsafe package path') | |
| raw=p.read_bytes() | |
| if len(raw)!=row['bytes'] or sha(raw)!=row['sha256']:raise ValueError('Package file hash mismatch: '+row['path']) | |
| return manifest | |
| def run(args): | |
| root=args.package_root.resolve() | |
| manifest=check_package(root,args.package_manifest_sha256) | |
| if args.world=='candidate': | |
| if args.candidate_map is None or args.candidate_map_sha256 is None:raise ValueError('Candidate map and SHA are required') | |
| value,patches=read_map(args.candidate_map,args.candidate_map_sha256) | |
| else: | |
| if args.candidate_map is not None or args.candidate_map_sha256 is not None:raise ValueError('Baseline worlds do not accept caller patches') | |
| value,patches={'provenance':'explicit '+args.world+' baseline','patches':{}},{} | |
| checked={'state':'CHECKED_ZERO_NATIVE_TESTS','patches':{k:sha(raw) for k,(p,raw) in patches.items()},'package_manifest_sha256':args.package_manifest_sha256} | |
| if args.check:print(json.dumps(checked));return 0 | |
| if args.output is None:raise ValueError('--output is required for --run') | |
| out=args.output.resolve() | |
| if out.exists() or out.is_relative_to(root):raise ValueError('Fresh output must be outside evaluator package') | |
| if shutil.disk_usage(out.parent).free<512*1024**2:raise ValueError('Insufficient host output space') | |
| image=json.loads(subprocess.check_output(['docker','image','inspect',args.image]))[0] | |
| expected=manifest['image'] | |
| if image['Architecture']!='amd64' or image['RootFS']!=expected['RootFS']:raise ValueError('Immutable image architecture/RootFS mismatch') | |
| if image['Id'] not in (INDEX,CHILD,CONFIG):raise ValueError('Immutable image ID mismatch') | |
| out.mkdir() | |
| record={'state':'PREPARING','owner':'crossswe-rustls3203-candidate-'+uuid.uuid4().hex[:12],'image':args.image, | |
| 'package_manifest_sha256':args.package_manifest_sha256,'candidate_map_sha256':args.candidate_map_sha256,'commands':[],'errors':[]} | |
| write(out/'request.json',value) | |
| def call(label,argv,allowed=(0,),timeout=120): | |
| n=len(record['commands']) | |
| with (out/(str(n)+'-'+label+'.stdout.raw')).open('xb') as stdout,(out/(str(n)+'-'+label+'.stderr.raw')).open('xb') as stderr: | |
| p=subprocess.Popen(argv,stdout=stdout,stderr=stderr) | |
| row={'label':label,'argv':argv,'pid':p.pid};record['commands'].append(row);write(out/'execution.json',record) | |
| try:rc=p.wait(timeout=timeout) | |
| except subprocess.TimeoutExpired: | |
| record['state']='OBSERVATION_TIMEOUT_SAME_ACTOR_KEPT';write(out/'execution.json',record);rc=p.wait() | |
| row['returncode']=rc;write(out/'execution.json',record) | |
| if rc not in allowed:raise RuntimeError(label+' failed with '+str(rc)) | |
| return (out/(str(n)+'-'+label+'.stdout.raw')).read_bytes() | |
| try: | |
| with tempfile.TemporaryDirectory(prefix='crossswe-rustls3203-payload-') as temporary: | |
| payload=Path(temporary)/'crossswe-input';payload.mkdir() | |
| for name in ('frozen','run_contract.py','inner.py','candidate_inner.py'): | |
| p=root/name | |
| if p.is_dir():shutil.copytree(p,payload/name) | |
| else:shutil.copyfile(p,payload/name) | |
| # Reference patches stay external to every candidate evaluation actor. | |
| if args.world!='all_fixed':shutil.rmtree(payload/'frozen/gold') | |
| freeze=json.loads((root/'freeze.json').read_bytes()) | |
| if args.world!='all_fixed':freeze['files']=[row for row in freeze['files'] if not row['relative_path'].startswith('gold/')] | |
| write(payload/'freeze.json',freeze) | |
| request={'provenance':value['provenance'],'patches':{}} | |
| (payload/'caller-patches').mkdir() | |
| for repo,(p,raw) in patches.items(): | |
| filename=repo+'.patch';(payload/'caller-patches'/filename).write_bytes(raw) | |
| request['patches'][repo]={'file':filename,'bytes':len(raw),'sha256':sha(raw)} | |
| write(payload/'candidate.json',request) | |
| argv=['docker','create','--platform','linux/amd64','--pull','never','--name',record['owner'],'--network','none', | |
| '--cpus','4','--memory',str(12*1024**3),'--memory-swap',str(12*1024**3), | |
| '--tmpfs','/tmp:rw,exec,nosuid,nodev,size=8g,mode=1777','--security-opt','no-new-privileges', | |
| '--label','crossswe.owner='+record['owner'],'--log-opt','max-size=4m'] | |
| env={'CARGO_NET_OFFLINE':'true','CARGO_INCREMENTAL':'0','CARGO_BUILD_JOBS':'2', | |
| 'CARGO_PROFILE_DEV_DEBUG':'0','CARGO_PROFILE_TEST_DEBUG':'0','TMPDIR':'/tmp', | |
| 'PYTHONDONTWRITEBYTECODE':'1', | |
| 'GIT_CONFIG_NOSYSTEM':'1','GIT_CONFIG_GLOBAL':'/dev/null','GIT_OPTIONAL_LOCKS':'0'} | |
| for k,v in env.items():argv+=['--env',k+'='+v] | |
| argv+=['--entrypoint','python3',args.image,'-B','-u','/crossswe-input/candidate_inner.py' if args.world=='candidate' else '/crossswe-input/inner.py'] | |
| if args.world!='candidate':argv+=['--world',args.world] | |
| cid=call('create',argv).decode().strip();record['container_id']=cid | |
| actor=json.loads(call('inspect-before',['docker','inspect',cid]))[0];write(out/'inspect-before.json',actor) | |
| if actor['Mounts'] or actor['HostConfig']['NetworkMode']!='none' or actor['Image']!=image['Id']:raise ValueError('Actor isolation/image mismatch') | |
| call('stage-explicit-inputs',['docker','cp',str(payload),cid+':/crossswe-input']) | |
| call('evaluate-once',['docker','start','--attach',cid],allowed=(0,1,2),timeout=3300) | |
| actor=json.loads(call('inspect-after',['docker','inspect',cid]))[0];write(out/'inspect-after.json',actor) | |
| if actor['State']['Running'] or actor['State']['OOMKilled'] or actor['State']['Error']:raise ValueError('Actor lifecycle failed') | |
| call('capture-artifacts',['docker','cp',cid+':/artifacts',str(out/'artifacts')]) | |
| result=assess(out/'artifacts');write(out/'assessment.json',result) | |
| record.update(state=('RESOLVED' if args.world=='candidate' else 'BASELINE_EXPECTATIONS_MET') if not result['errors'] else 'TESTS_FAILED',counts=result['counts'],unique_counts=result['unique_counts'],world=args.world) | |
| call('remove-terminal-owned-actor',['docker','rm',cid]) | |
| record['owned_container_removed']=True | |
| except BaseException as error: | |
| record['state']='INFRASTRUCTURE_ERROR_PRESERVE_RAW_AND_ACTOR';record['errors'].append({'type':type(error).__name__,'message':str(error)}) | |
| finally:write(out/'execution.json',record) | |
| print(json.dumps({'state':record['state'],'counts':record.get('counts'),'errors':record['errors'],'output':str(out)})) | |
| return 2 if record['errors'] else 0 if record['state'] in ('RESOLVED','BASELINE_EXPECTATIONS_MET') else 1 | |
| if __name__=='__main__': | |
| p=argparse.ArgumentParser(description=__doc__) | |
| p.add_argument('--package-root',type=Path,default=Path(__file__).resolve().parent) | |
| p.add_argument('--package-manifest-sha256',required=True);p.add_argument('--candidate-map',type=Path) | |
| p.add_argument('--candidate-map-sha256');p.add_argument('--image',default=IMAGE) | |
| group=p.add_mutually_exclusive_group(required=True);group.add_argument('--check',action='store_true');group.add_argument('--run',action='store_true') | |
| p.add_argument('--world',choices=['candidate','all_buggy','all_fixed'],default='candidate') | |
| p.add_argument('--output',type=Path) | |
| try:raise SystemExit(run(p.parse_args())) | |
| except (ValueError,OSError) as error:p.error(str(error)) | |