Datasets:
File size: 16,501 Bytes
0e239c6 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 | """Two endpoint runs, once each, from an independently recovered agent image."""
import argparse
import ast
import collections
import datetime
import fcntl
import hashlib
import json
import os
from pathlib import Path
import re
import shlex
import subprocess
import traceback
import shutil
import sys
sys.path.insert(0,str(Path(__file__).resolve().parent / "reusable_support"))
from execution_io import write, run
from image_identity import validate_image
from batch04_case_reports import parse_report
from validation_policy import endpoint_plan
ROOT = Path(__file__).resolve().parents[1]
CODE = Path(__file__).resolve().parent / "reusable_support"
def validate_runtime_descriptor(resource):
assert resource['kind']=='browser-infrastructure'
assert re.fullmatch(r'[^@\s]+@sha256:[0-9a-f]{64}',resource['image_ref'])
assert resource['container_path']=='/crossswe-evaluator/browser-infra'
files=resource['files'];assert files
names=[f['path'] for f in files];assert len(names)==len(set(names))
for f in files:
path=Path(f['path']);assert not path.is_absolute() and '..' not in path.parts and path.as_posix()==f['path']
assert type(f['bytes']) is int and f['bytes']>=0 and re.fullmatch(r'[0-9a-f]{64}',f['sha256'])
manifests={f['path']:f for f in files if f['path'] in ['manifest.json','source-manifest.json']}
assert len(manifests)==2 and all(f['sha256']==resource['source_manifest_sha256'] for f in manifests.values())
def main():
parser = argparse.ArgumentParser()
parser.add_argument('--instance-id', required=True)
parser.add_argument('--output-dir', type=Path, required=True)
parser.add_argument('--check-only', action='store_true')
parser.add_argument('--evaluator-resource-dir', type=Path)
parser.add_argument('--attempt', default='endpoint-once')
args = parser.parse_args(); iid = args.instance_id
if Path(iid).name != iid: raise ValueError('Use a canonical instance ID')
inp = ROOT / 'instances' / iid
image = json.loads((ROOT / 'environments' / iid / 'image.json').read_text())
task = json.loads((inp / 'task.json').read_text())
contract = json.loads((inp / task['evaluation']['path']).read_text())
assert hashlib.sha256((inp/'task.json').read_bytes()).hexdigest() == image['task_sha256']
assert hashlib.sha256((inp/task['evaluation']['path']).read_bytes()).hexdigest() == image['contract_sha256']
for artifact in task['artifacts']:
relative = Path(artifact['path'])
assert not relative.is_absolute() and '..' not in relative.parts
assert hashlib.sha256((inp/relative).read_bytes()).hexdigest() == artifact['sha256']
args.image = image['image_ref']
assert re.fullmatch(r'[^@\s]+@sha256:[0-9a-f]{64}',args.image)
out = args.output_dir.resolve()
assert not out.is_relative_to(ROOT)
if image.get('evaluator_resources'):validate_runtime_descriptor(image['evaluator_resources'])
if args.check_only:
print(json.dumps({'instance_id':iid,'state':'INPUTS_VERIFIED','image':args.image,'worlds':['all_buggy','all_fixed'],'repeat_count':1,'model_calls':0}))
return
out.mkdir(parents=True, exist_ok=False)
subprocess.run(['docker','pull','--platform','linux/amd64',args.image],check=True)
actual = json.loads(subprocess.check_output(['docker','image','inspect',args.image]))[0]
validate_image(actual,image)
assets=None
resource=image.get('evaluator_resources')
if resource:
assert resource['kind']=='browser-infrastructure' and re.fullmatch(r'[^@\s]+@sha256:[0-9a-f]{64}',resource['image_ref'])
assets=out/'evaluator-resources'
if args.evaluator_resource_dir:
shutil.copytree(args.evaluator_resource_dir,assets,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()
try:subprocess.run(['docker','cp',cid+':'+resource['container_path'],str(assets)],check=True)
finally:subprocess.run(['docker','rm',cid],check=True,stdout=subprocess.DEVNULL)
expected={f['path']:f for f in resource['files']}
actual={str(p.relative_to(assets)) for p in assets.rglob('*') if p.is_file() or p.is_symlink()}
assert set(expected)==actual
for name,f in expected.items():
relative=Path(name);assert not relative.is_absolute() and '..' not in relative.parts
path=assets/relative;assert path.is_file() and not path.is_symlink()
assert path.stat().st_size==f['bytes'] and hashlib.sha256(path.read_bytes()).hexdigest()==f['sha256']
assert hashlib.sha256((assets/'source-manifest.json').read_bytes()).hexdigest()==resource['source_manifest_sha256']
lockdir = out.parent / '.crossswe-locks'; lockdir.mkdir(exist_ok=True)
lease = (lockdir / (iid+'.lock')).open('a+')
fcntl.flock(lease,fcntl.LOCK_EX|fcntl.LOCK_NB)
status = {'instance_id': iid, 'image': args.image, 'attempt': args.attempt, 'state': 'RUNNING',
'pid': os.getpid(), 'start_ticks': Path(f'/proc/{os.getpid()}/stat').read_text().split()[21],
'effective_policy': {'worlds': ['all_buggy', 'all_fixed'], 'repeat_count': 1},
'contract_sha256': hashlib.sha256((inp / task['evaluation']['path']).read_bytes()).hexdigest(),
'started_utc': datetime.datetime.now(datetime.timezone.utc).isoformat(), 'worlds': [], 'issues': []}
write(out / 'status.json', status)
inventories = {}
try:
with (CODE / 'batch04_node_source_audit.py').open('rb') as source:
p = subprocess.run(['docker', 'run', '--rm', '-i', '--network', 'none', '--cpus', '2', '--memory', '2g',
'--label', 'crossswe.owner=portable-baseline', args.image, 'python3', '-'],
stdin=source, capture_output=True, timeout=120)
(out / 'agent-source-audit.json').write_bytes(p.stdout)
(out / 'agent-source-audit.stderr.log').write_bytes(p.stderr)
assert p.returncode == 0, 'Recovered agent source audit failed'
for plan in endpoint_plan(contract, [r['key'] for r in task['repositories']]):
world = plan['world']; cell = out / world / 'repeat-1'; cell.mkdir(parents=True)
name = ('d171-' + iid + '-' + args.attempt + '-' + world).lower().replace('_', '-')
record = {'world': world, 'repeat': 1, 'fixed': plan['fixed'], 'commands': [], 'patches': [], 'issues': []}
status['worlds'].append(record); status['active'] = {'world': world, 'container': name}; write(out / 'status.json', status)
cid = None
def execute(command, target, cwd='/testbed', env=None, check=True, timeout=3600):
argv = ['docker', 'exec', '-w', cwd]
for key, value in (env or {}).items():argv += ['-e', key + '=' + value]
return run(argv + [cid, 'bash', '-lc', command], target, timeout=timeout, check=check)
try:
memory = '6g' if iid == 'buildpkg-poetry-10606' else '3g'
cpus = '4' if iid == 'buildpkg-poetry-10606' else '2'
run(['docker', 'create', '--name', name, '--network', 'none', '--cpus', cpus, '--memory', memory,
'--memory-swap', memory, '--label', 'crossswe.owner=docker171-20261015',
'--label', 'crossswe.instance=' + iid, args.image, 'sleep', 'infinity'], cell / 'create')
cid = name; run(['docker', 'start', cid], cell / 'start')
info = json.loads(subprocess.check_output(['docker', 'inspect', cid]))[0]
assert not info['Mounts'] and info['HostConfig']['NetworkMode'] == 'none'
record['container_image_id'] = info['Image']; record['mounts'] = info['Mounts']
for repo in task['repositories']:
execute('git diff --exit-code HEAD && test -z "$(git status --porcelain)"', cell / (repo['key'] + '-clean'), repo['container_path'])
selected = ([repo['gold_patch']] if plan['fixed'][repo['key']] else []) + repo['test_patches']
for n, patch in enumerate(selected, 1):
path = inp / patch['path']; assert hashlib.sha256(path.read_bytes()).hexdigest() == patch['sha256']
dst = '/tmp/' + repo['key'] + '-' + str(n) + '.patch'
run(['docker', 'cp', str(path), cid + ':' + dst], cell / f'{repo["key"]}-patch{n}-copy')
execute('git apply --check ' + shlex.quote(dst) + ' && git apply ' + shlex.quote(dst), cell / f'{repo["key"]}-patch{n}-apply', repo['container_path'])
record['patches'].append({'repository': repo['key'], 'path': patch['path'], 'sha256': patch['sha256'], 'applied': True})
execute('mkdir -p /crossrepo-patches /artifacts', cell / 'evaluator-dirs')
for artifact in contract.get('test_files', []):
source = inp / artifact['path']; assert hashlib.sha256(source.read_bytes()).hexdigest() == artifact['sha256']
rel = Path(artifact.get('original_path', source.name))
assert not rel.is_absolute() and '..' not in rel.parts
execute('mkdir -p ' + shlex.quote('/crossrepo-patches/' + str(rel.parent)), cell / ('mkdir-' + source.name))
run(['docker', 'cp', str(source), cid + ':/crossrepo-patches/' + str(rel)], cell / ('inject-' + source.name))
if iid == 'buildpkg-npm-cli-9026':
run(['docker', 'cp', str(CODE/'capture_tap_v2.cjs'), cid+':/tmp/crossswe-capture-tap.cjs'], cell/'inject-tap-reporter')
if resource:
destination='/crossswe-infra' if iid=='mcp-servers-3334' else '/opt/ee44-browser-infra'
run(['docker','cp',str(assets),cid+':'+destination],cell/'inject-browser-infrastructure')
commands = contract['commands']
environments = {}
for command in commands:
env = {'PIP_NO_INDEX': '1', 'PIP_DISABLE_PIP_VERSION_CHECK': '1', 'PYTHONDONTWRITEBYTECODE': '1', 'PIP_NO_DEPS':'1', 'PIP_NO_BUILD_ISOLATION':'0', 'npm_config_offline':'true', 'FORCE_COLOR':'0', **command.get('environment', {})}
if iid == 'buildpkg-poetry-10677':env.update(PIP_NO_DEPS='1', PIP_NO_BUILD_ISOLATION='0')
environments[command['repository']] = env
for command in sorted(commands, key=lambda d: d.get('setup_order') or 0):
if command.get('setup_command'):
execute(command['setup_command'], cell / (command['repository'] + '-source-setup'), command['container_path'], environments[command['repository']])
for command in sorted(commands, key=lambda d: d.get('evaluation_setup_order') or 0):
if command.get('evaluation_setup_command'):
execute(command['evaluation_setup_command'], cell / (command['repository'] + '-evaluator-setup'), command.get('evaluation_setup_cwd') or command['container_path'], environments[command['repository']])
for command in commands:
if command.get('evaluation_ready_command'):
execute(command['evaluation_ready_command'], cell / (command['repository'] + '-ready'), command['container_path'], environments[command['repository']])
for command in commands:
for kind in ['pass_to_pass', 'fail_to_pass']:
label = command['repository'] + '-' + kind; report_dir = '/tmp/crossswe-reports/' + label
env = environments[command['repository']]
execution = execute(command[kind], cell / label, command.get('test_cwd') or command['container_path'], env, check=False)
stdout = (cell / (label + '.stdout.log')).read_text(); stderr = (cell / (label + '.stderr.log')).read_text()
if iid == 'buildpkg-npm-cli-9026':
captured = subprocess.run(['docker','exec','-i',cid,'node','/tmp/crossswe-capture-tap.cjs'],input=stdout.encode(),capture_output=True,timeout=120)
(cell/(label+'-tap-report-v2.json')).write_bytes(captured.stdout)
(cell/(label+'-tap-report.stderr.log')).write_bytes(captured.stderr)
assert captured.returncode == 0, 'Native TAP reporting failed'
if iid in ('mcp-specification-2322','mcp-servers-3334','mcp-servers-3816'):
native=cell/'native-artifacts';native.mkdir(exist_ok=True)
run(['docker','cp',cid+':/artifacts/.',str(native)],cell/(label+'-capture-native-artifacts'))
rows,issues,report_metadata=parse_report(iid,command['repository'],kind,stdout,stderr,execution['returncode'],cell)
if any(x in stderr for x in ['ModuleNotFoundError:', 'TimeoutExpired:']):issues.append('Infrastructure/dependency failure')
ids = [r.get('id',r.get('name')) for r in rows]
if label in inventories and collections.Counter(inventories[label]) != collections.Counter(ids):issues.append('Case inventory differs between endpoints')
inventories.setdefault(label, ids)
passed = sum(r['passed'] for r in rows); failed = len(rows)-passed
if not rows:issues.append('No executed cases')
if kind == 'pass_to_pass' and (failed or execution['returncode']):issues.append('P2P regression')
result = {'repository':command['repository'],'kind':kind,'command':command[kind],'returncode':execution['returncode'],'passed':passed,'failed':failed,'cases':rows,'issues':issues,'report_metadata':report_metadata}
record['commands'].append(result); record['issues'] += [label + ': ' + x for x in issues]
observed = all(x['returncode'] == 0 and not x['failed'] and not x['issues'] for x in record['commands'] if x['kind']=='fail_to_pass')
record['observed_crossrepo_pass'] = observed
if observed != (world == 'all_fixed'):record['issues'].append('Endpoint behavioral expectation mismatch')
for command in reversed(commands):
if command.get('evaluation_teardown_command'):
execute(command['evaluation_teardown_command'], cell / (command['repository']+'-teardown'), command['container_path'], environments[command['repository']])
except Exception:
record['issues'].append(traceback.format_exc())
finally:
if cid:
if iid in ('mcp-specification-2322','mcp-servers-3334','mcp-servers-3816'):
copied = subprocess.run(['docker','cp',cid+':/artifacts',str(cell/'native-artifacts-final')],capture_output=True)
record['native_artifacts_copied'] = copied.returncode == 0
run(['docker','inspect',cid],cell/'final-container-inspect',check=False)
run(['docker','stop','--time','1',cid],cell/'stop',timeout=30,check=False)
run(['docker','rm',cid],cell/'remove',timeout=30)
write(cell/'result.json',record);write(out/'status.json',status)
print(json.dumps({'world':world,'commands':[(x['repository'],x['kind'],x['passed'],x['failed'],x['issues']) for x in record['commands']],'issues':record['issues']}),flush=True)
status['issues'] = [f'{r["world"]}: {x}' for r in status['worlds'] for x in r['issues']]
status['state'] = 'LOCAL_VALIDATED' if not status['issues'] else 'VALIDATION_ERROR'
except Exception:
status['state'] = 'VALIDATION_ERROR';status['issues'].append(traceback.format_exc())
status.pop('active',None);status['ended_utc']=datetime.datetime.now(datetime.timezone.utc).isoformat();write(out/'status.json',status)
print(json.dumps({'instance_id':iid,'state':status['state'],'receipt':str(out/'status.json')}),flush=True)
if __name__ == '__main__':
main()
|