Datasets:
File size: 10,120 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 | """Run original Node paired-source contract on a pinned agent image."""
from pathlib import Path
import argparse
import datetime
import hashlib
import json
import subprocess
import traceback
import uuid
parser = argparse.ArgumentParser()
parser.add_argument('--task-dir', required=True)
parser.add_argument('--image', required=True)
parser.add_argument('--world', choices=['all_buggy', 'all_fixed', 'candidate'], required=True)
parser.add_argument('--candidate-patches')
parser.add_argument('--output', required=True)
parser.add_argument('--prepare-only', action='store_true')
args = parser.parse_args()
T = Path(args.task_dir).resolve()
D = Path(args.output).resolve()
D.mkdir(parents=True, exist_ok=False)
HERE = Path(__file__).resolve().parent
task = json.loads((T / 'task.json').read_text())
assert task['instance_id'] == 'runtime-node-65621' and '@sha256:' in args.image
N = 'crossswe-node65621-' + args.world + '-' + uuid.uuid4().hex[:10]
S = {'state': 'PREPARING_ORIGINAL_CONTRACT', 'world': args.world, 'image': args.image, 'task_sha256': hashlib.sha256((T / 'task.json').read_bytes()).hexdigest(), 'container': N, 'slots': [], 'issues': []}
def sha(path):
return hashlib.sha256(Path(path).read_bytes()).hexdigest()
def put(path, value):
path.write_text(json.dumps(value, indent=2) + '\n')
def save():
S['updated_utc'] = datetime.datetime.now(datetime.timezone.utc).isoformat()
put(D / 'result.json', S)
def run(label, argv, data=None, check=True):
with (D / (label + '.stdout.raw')).open('xb') as stdout, (D / (label + '.stderr.raw')).open('xb') as stderr:
p = subprocess.run(argv, input=data, stdout=stdout, stderr=stderr, timeout=5400)
record = {'argv': argv, 'returncode': p.returncode, 'stdout': str(D / (label + '.stdout.raw')), 'stdout_sha256': sha(D / (label + '.stdout.raw')), 'stderr': str(D / (label + '.stderr.raw')), 'stderr_sha256': sha(D / (label + '.stderr.raw'))}
put(D / (label + '.execution.json'), record)
assert not check or p.returncode == 0, label
return record
snapshot = '''from pathlib import Path
import subprocess,json,hashlib,os
rows=[]
for root in ['/testbed/nodejs/node','/testbed/nodejs/node-addon-api']:
manifest=[]
for raw in subprocess.check_output(['git','-C',root,'ls-files','--cached','--others','--exclude-standard','-z']).split(b'\\0'):
if not raw:continue
path=Path(root)/os.fsdecode(raw)
if path.is_symlink():data=os.fsencode(os.readlink(path))
elif path.is_file():data=path.read_bytes()
else:continue
manifest.append([os.fsdecode(raw),hashlib.sha256(data).hexdigest()])
rows.append({'root':root,'head':subprocess.check_output(['git','-C',root,'rev-parse','HEAD'],text=True).strip(),'working_source_manifest_sha256':hashlib.sha256(json.dumps(manifest).encode()).hexdigest()})
print(json.dumps(rows,sort_keys=True))
'''
save()
try:
for artifact in task['artifacts']:
assert sha(T / artifact['path']) == artifact['sha256']
contract = json.loads((T / 'evaluation/contract.json').read_text())
run('create', ['docker', 'run', '-d', '--name', N, '--label', 'org.crossswe.instance=runtime-node-65621', '--network=none', '--cpus=16', '--memory=20g', '--memory-swap=20g', args.image, 'sleep', 'infinity'])
info = json.loads(subprocess.check_output(['docker', 'inspect', N]))[0]
put(D / 'container-inspect.json', info)
image = json.loads(subprocess.check_output(['docker', 'image', 'inspect', args.image]))[0]
assert info['Image'] == image['Id'] and not info['Mounts'] and info['HostConfig']['NetworkMode'] == 'none'
S['image_id'] = image['Id']
save()
for repository in task['repositories']:
root = repository['container_path']
key = repository['key']
assert subprocess.check_output(['docker', 'exec', '-w', root, N, 'git', 'rev-parse', 'HEAD'], text=True).strip() == repository['base_commit']
assert not subprocess.check_output(['docker', 'exec', '-w', root, N, 'git', 'diff', '--name-only']).strip()
if args.world == 'all_fixed':
run('frozen-Gold-' + key, ['docker', 'exec', '-i', '-w', root, N, 'git', 'apply', '-'], (T / repository['gold_patch']['path']).read_bytes())
elif args.world == 'candidate':
assert args.candidate_patches
patch = Path(args.candidate_patches) / (key + '.patch')
if patch.exists() and patch.stat().st_size:
run('candidate-' + key, ['docker', 'exec', '-i', '-w', root, N, 'git', 'apply', '-'], patch.read_bytes())
for index, patch in enumerate(repository['test_patches']):
run('frozen-test-' + key + '-' + str(index), ['docker', 'exec', '-i', '-w', root, N, 'git', 'apply', '-'], (T / patch['path']).read_bytes())
run('trusted-material-directories', ['docker', 'exec', N, 'mkdir', '-p', '/crossrepo-patches', '/opt/crossswe-eval-resource-bin'])
for artifact in contract['test_files']:
run('original-helper-' + artifact['original_path'], ['docker', 'cp', str(T / artifact['path']), N + ':/crossrepo-patches/' + artifact['original_path']])
resource = HERE / 'node-make-resource.sh'
run('resource-only-make-scheduler', ['docker', 'cp', str(resource), N + ':/opt/crossswe-eval-resource-bin/make'])
run('resource-only-scheduler-mode', ['docker', 'exec', N, 'chmod', '755', '/opt/crossswe-eval-resource-bin/make'])
run('source-before-setup', ['docker', 'exec', '-i', N, 'python3', '-B', '-'], snapshot.encode())
if args.prepare_only:
S['state'] = 'PREPARED_ONLY_NO_TESTS_EXECUTED'
else:
S['state'] = 'ORIGINAL_FROZEN_SETUP_RUNNING'
save()
environment = ['-e', 'PATH=/opt/crossswe-eval-resource-bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin', '-e', 'CC=/usr/bin/clang-19', '-e', 'CXX=/usr/bin/clang++-19']
for entry in sorted(contract['commands'], key=lambda item: item.get('evaluation_setup_order', 0)):
if entry.get('evaluation_setup_command'):
run('frozen-setup-' + entry['repository'], ['docker', 'exec', *environment, '-w', entry['container_path'], N, 'sh', '-c', entry['evaluation_setup_command']])
run('source-after-setup', ['docker', 'exec', '-i', N, 'python3', '-B', '-'], snapshot.encode())
assert (D / 'source-before-setup.stdout.raw').read_bytes() == (D / 'source-after-setup.stdout.raw').read_bytes(), 'frozen setup failed to restore source'
run('actual-native-runtime-source-binding', ['docker', 'cp', N + ':/tmp/crossrepo-node-build.json', str(D / 'actual-native-runtime-build.json')])
S['state'] = 'ORIGINAL_FOUR_SLOTS_RUNNING'
save()
for entry in contract['commands']:
for phase, field in [('p2p', 'pass_to_pass'), ('f2p', 'fail_to_pass')]:
label = entry['repository'] + '-' + phase
execution = run(label, ['docker', 'exec', *environment, '-w', entry['container_path'], N, 'sh', '-c', entry[field]], check=False)
events = []
for line in Path(execution['stdout']).read_text().splitlines():
try:
event = json.loads(line)
except ValueError:
continue
if isinstance(event, dict):
events.append(event)
cases = [row for row in events if row.get('type') == 'case']
summaries = [row for row in events if row.get('type') == 'summary']
expected = 8 if phase == 'p2p' else 16
complete = len(cases) == len({row['name'] for row in cases}) == expected and all(row['mode'] == phase and row['status'] in ['pass', 'fail'] for row in cases)
complete = complete and len(summaries) == 1 and summaries[0]['total'] == expected and summaries[0]['skipped'] == 0 and summaries[0]['failed'] == sum(row['status'] == 'fail' for row in cases)
if not complete:
S['issues'].append(label + ': complete original case evidence missing')
expected_code = 1 if any(row['status'] == 'fail' for row in cases) else 0
if execution['returncode'] != expected_code:
S['issues'].append(label + ': native returncode/case outcomes disagree')
for case in cases:
if case['status'] == 'fail':
allowed = args.world == 'all_buggy' and phase == 'f2p' and ('public C API rejects read-only arrays' in case.get('error', '') or 'public object construction overload unavailable' in case.get('error', ''))
if args.world != 'candidate' and not allowed:
S['issues'].append(label + ': failure is not the frozen base missing-public-API outcome: ' + case['name'])
S['slots'].append({'repository': entry['repository'], 'phase': phase, 'frozen_command': entry[field], 'execution': execution, 'cases': cases, 'native_summaries': summaries, 'complete': complete})
save()
run('source-after-programs', ['docker', 'exec', '-i', N, 'python3', '-B', '-'], snapshot.encode())
assert (D / 'source-after-setup.stdout.raw').read_bytes() == (D / 'source-after-programs.stdout.raw').read_bytes()
S.update(state='FORMAL_ORIGINAL_CASES_EXECUTED_REVIEW_PENDING', source_unchanged_during_programs=True, raw_case_observations=sum(len(row['cases']) for row in S['slots']))
except BaseException:
S['state'] = 'FORMAL_WORLD_BLOCKED'
S['issues'].append(traceback.format_exc())
finally:
run('final-inspect', ['docker', 'inspect', N], check=False)
run('retire-owned-world-container', ['docker', 'rm', '-f', N], check=False)
save()
good = S['state'] == 'PREPARED_ONLY_NO_TESTS_EXECUTED' and not S['slots'] if args.prepare_only else S['state'] == 'FORMAL_ORIGINAL_CASES_EXECUTED_REVIEW_PENDING' and not S['issues'] and len(S['slots']) == 4
print(json.dumps({'state': S['state'], 'world': args.world, 'raw_case_observations': S.get('raw_case_observations', 0), 'issues': S['issues'], 'expected_outcomes': good}))
raise SystemExit(0 if good else 1)
|