"""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 sys sys.path.insert(0,str(Path(__file__).resolve().parent/'reusable_support')) from batch05_case_reports_v5 import parse_report from batch05_runtime_resources import validate_runtime_descriptor,materialize_runtime from image_identity import validate_image from validation_policy import endpoint_plan from execution_io import write, run ROOT=Path(__file__).resolve().parents[1] CODE=Path(__file__).resolve().parent/'reusable_support' def main(): parser = argparse.ArgumentParser() parser.add_argument('--instance-id', required=True) parser.add_argument('--output-dir',type=Path,required=True) parser.add_argument('--attempt',default='endpoint-once') parser.add_argument('--check-only',action='store_true') parser.add_argument('--evaluator-resource-dir',type=Path) args = parser.parse_args(); iid = args.instance_id assert Path(iid).name==iid inp=ROOT/'instances'/iid task=json.loads((inp/'task.json').read_text());contract=json.loads((inp/task['evaluation']['path']).read_text()) image=json.loads((ROOT/'environments'/iid/'image.json').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']:assert hashlib.sha256((inp/artifact['path']).read_bytes()).hexdigest()==artifact['sha256'] args.image=image['image_ref'];assert re.fullmatch(r'[^@\s]+@sha256:[0-9a-f]{64}',args.image) resource=image['evaluator_resources'];validate_runtime_descriptor(resource) out=args.output_dir.resolve();assert not out.is_relative_to(ROOT) if args.check_only: print(json.dumps(dict(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=materialize_runtime(resource,out/'evaluator-resources',args.evaluator_resource_dir) 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 / 'batch05_node_source_audit.py').open('rb') as source: p = subprocess.run(['docker', 'run', '--rm', '-i', '--network', 'none', '--cpus', '2', '--memory', '2g', '--label', 'crossswe.owner=docker171-20261015', 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', '-c', command], target, timeout=timeout, check=check) try: memory = '6g' if iid in ('buildpkg-poetry-10606','buildpkg-pnpm-12400','buildpkg-pnpm-14110','buildpkg-pnpm-14825','buildpkg-pnpm-15106') else '3g' cpus = '4' if iid in ('buildpkg-poetry-10606','buildpkg-pnpm-14825','buildpkg-pnpm-14110') 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)) run(['docker','cp',str(assets)+'/.',cid+':/'],cell/'inject-evaluator-runtime') record['evaluator_resource']=dict(digest=resource['image_ref'].split('@')[1],agent_image_unchanged=True) 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 in ('buildpkg-pnpm-14825','buildpkg-pnpm-12400','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 ('buildpkg-pnpm-14825','buildpkg-pnpm-12400','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()