File size: 21,956 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
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
"""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 case_guards import report_health
from native_reports import parse_contract_cases
from validation_policy import endpoint_plan
from execution_io import write, run
from image_identity import validate_image
from batch02_case_reports import parse_report
from inventory_policy import approved_gold_addition

BATCH02_IDS=['networking-urllib3-5091', 'observability-opentelemetry-python-5266', 'backend-flask-6133', 'backend-fastapi-14186', 'backend-fastapi-13314']

ROOT = Path(__file__).resolve().parents[1]
CODE = Path(__file__).resolve().parent / "reusable_support"


def main():
    # BEGIN crossswe Axum standalone guidance a01
    _axum_id = None
    for _n, _arg in enumerate(sys.argv[1:]):
        if _arg == '--instance-id' and _n + 2 < len(sys.argv):
            _axum_id = sys.argv[_n + 2]
        elif _arg.startswith('--instance-id='):
            _axum_id = _arg.split('=', 1)[1]
    if _axum_id == 'networking-axum-3801':
        raise SystemExit('Use the standalone candidate evaluator: python3 environments/networking-axum-3801/candidate/a04/code/evaluate_candidate_rust_pairs_a04.py; see environments/networking-axum-3801/README.md for the authenticated package SHA and check/run/review arguments. Existing formal baseline receipts are reused read-only.')
    # END crossswe Axum standalone guidance a01
    # BEGIN crossswe Hyper standalone guidance a01
    _hyper_id = None
    for _n, _arg in enumerate(sys.argv[1:]):
        if _arg == '--instance-id' and _n + 2 < len(sys.argv):
            _hyper_id = sys.argv[_n + 2]
        elif _arg.startswith('--instance-id='):
            _hyper_id = _arg.split('=', 1)[1]
    if _hyper_id == 'networking-hyper-3965':
        raise SystemExit('Use the standalone candidate evaluator: python3 environments/networking-hyper-3965/candidate/a03/code/evaluate_candidate_rust_pairs_a03.py; see environments/networking-hyper-3965/README.md for the authenticated package SHA and check/run/review arguments. Existing formal baseline receipts are reused read-only.')
    # END crossswe Hyper standalone guidance a01
    batch05_ids={'buildpkg-pnpm-12400','buildpkg-pnpm-13922','buildpkg-pnpm-14110','buildpkg-pnpm-14825','buildpkg-pnpm-15106'}
    if '--instance-id' in sys.argv and sys.argv[sys.argv.index('--instance-id')+1] in batch05_ids:
        from evaluate_reusable_batch05_image import main as batch05_main
        return batch05_main()
    batch04_ids={'mcp-servers-3246','mcp-specification-2322','mcp-servers-3334','mcp-servers-3816','mcp-specification-2685'}
    if '--instance-id' in sys.argv and sys.argv[sys.argv.index('--instance-id')+1] in batch04_ids:
        from evaluate_reusable_batch04_image import main as batch04_main
        return batch04_main()
    node_ids = {'buildpkg-npm-cli-8703','buildpkg-npm-cli-9026','buildpkg-npm-cli-9586','mcp-specification-2508','mcp-specification-2663'}
    if '--instance-id' in sys.argv and sys.argv[sys.argv.index('--instance-id')+1] in node_ids:
        from evaluate_reusable_node_image import main as node_main
        return node_main()
    parser = argparse.ArgumentParser()
    parser.add_argument('--instance-id', required=True)
    parser.add_argument('--output-dir', type=Path, required=True)
    parser.add_argument('--native-archives', type=Path)
    parser.add_argument('--dependency-bundle', type=Path)
    parser.add_argument('--check-only', action='store_true')
    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_manifest = ROOT / 'environments' / iid / 'image.json'
    image = json.loads(image_manifest.read_text())
    task = json.loads((inp / 'task.json').read_text())
    contract = json.loads((inp / task['evaluation']['path']).read_text())
    def checked(path, expected):
        if hashlib.sha256(path.read_bytes()).hexdigest() != expected:
            raise ValueError('Frozen input hash mismatch: ' + str(path))
    checked(inp / 'task.json', image['task_sha256'])
    checked(inp / task['evaluation']['path'], image['contract_sha256'])
    for artifact in task['artifacts']:
        relative = Path(artifact['path'])
        if relative.is_absolute() or '..' in relative.parts:
            raise ValueError('Unsafe artifact path')
        checked(inp / relative, artifact['sha256'])
    args.image = image['image_ref']
    if not re.fullmatch(r'[^@\s]+@sha256:[0-9a-f]{64}', args.image):
        raise ValueError('An immutable registry image reference is required')
    out = args.output_dir.resolve()
    if out.is_relative_to(ROOT):
        raise ValueError('Output must be outside the release checkout')
    if args.check_only:
        print(json.dumps({'instance_id': iid, 'state': 'INPUTS_VERIFIED', 'image': args.image,
                          'worlds': ['all_buggy', 'all_fixed'], 'repeat_count': 1,
                          'native_resources': image.get('evaluator_resources'), 'model_calls': 0}))
        return
    if iid == 'buildpkg-poetry-10606':
        if args.native_archives is None:
            raise ValueError('Restore the pinned evaluator-data image and pass --native-archives')
        for item in image['evaluator_resources']['files']:
            checked(args.native_archives / item['path'], item['sha256'])
    if iid == 'backend-fastapi-14186':
        if args.dependency_bundle is None:
            raise ValueError('Restore the pinned evaluator-data dependency-bundle and pass --dependency-bundle')
        for item in image['evaluator_resources']['files']:
            checked(args.dependency_bundle/item['path'],item['sha256'])
    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)
    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(), 'model_calls': 0, 'score_writes': 0,
              '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 / 'agent_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', '-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-poetry-10606':
                    assets = args.native_archives.resolve()
                    run(['docker', 'cp', str(assets), cid + ':/native-archives'], cell / 'inject-native-archives')
                if iid == 'backend-fastapi-14186':
                    run(['docker','cp',str(args.dependency_bundle.resolve()),cid+':/crossrepo-dependencies'],cell/'inject-native-dependencies')
                purelib = subprocess.check_output(['docker', 'exec', cid, 'python3', '-c', 'import sysconfig;print(sysconfig.get_paths()["purelib"])'], text=True).strip()
                run(['docker', 'cp', str(CODE / 'crossswe_case_capture.py'), cid + ':' + purelib + '/crossswe_case_capture.py'], cell / 'inject-reporter')
                if iid == 'backend-fastapi-13314':
                    run(['docker','cp',str(CODE/'unittest_capture.py'),cid+':'+purelib+'/crossswe_unittest_capture.py'],cell/'inject-unittest-reporter')
                    program='from pathlib import Path;Path('+repr(purelib+'/zz_crossswe_unittest.pth')+').write_text('+repr('import crossswe_unittest_capture\n')+')'
                    execute('python3 -c '+shlex.quote(program),cell/'enable-unittest-reporter')
                commands = contract['commands']
                environments = {}
                for command in commands:
                    env = {'PIP_NO_INDEX': '1', 'PIP_DISABLE_PIP_VERSION_CHECK': '1', 'PYTHONDONTWRITEBYTECODE': '1', **command.get('environment', {})}
                    if iid in BATCH02_IDS:env.update(PIP_NO_DEPS='1', PIP_NO_BUILD_ISOLATION='0')
                    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['repository'] == 'poetry'):
                    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']], 'PYTEST_PLUGINS': 'crossswe_case_capture', 'CROSSSWE_CASE_REPORT_DIR': report_dir, 'CROSSSWE_UNITTEST_REPORT_DIR':report_dir+'-unittest'}
                        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()
                        issues = []; rows = []
                        report_metadata={}
                        if iid in BATCH02_IDS:
                            if iid == 'backend-flask-6133':
                                reports=cell/(label+'-reports');reports.mkdir()
                                subprocess.run(['docker','cp',cid+':'+report_dir+'/.',str(reports)],capture_output=True)
                            if iid == 'backend-fastapi-13314':
                                reports=cell/(label+'-unittest-reports');reports.mkdir()
                                subprocess.run(['docker','cp',cid+':'+report_dir+'-unittest/.',str(reports)],capture_output=True)
                            rows,issues,report_metadata=parse_report(iid,command['repository'],kind,stdout,stderr,execution['returncode'],cell)
                        elif iid == 'buildpkg-poetry-11033':
                            mode = 'p2p' if kind == 'pass_to_pass' else 'f2p'; count = {('poetry','p2p'):3,('poetry_core','p2p'):3,('poetry','f2p'):3,('poetry_core','f2p'):2}[command['repository'], mode]
                            rows, issues = parse_contract_cases(stdout, count, execution['returncode'])
                            if stdout.count('IMPORT_EVIDENCE ') != count:issues.append('Missing actual source/vendor binding evidence')
                        elif iid == 'buildpkg-poetry-10606':
                            mode = 'p2p' if kind == 'pass_to_pass' else 'f2p'; count = {('poetry','p2p'):9,('pbs-installer','p2p'):6,('poetry','f2p'):11,('pbs-installer','f2p'):2}[command['repository'], mode]
                            rows, issues = parse_contract_cases(stdout, count, execution['returncode'])
                            summaries = [json.loads(x[len('CONTRACT_SUMMARY '):]) for x in stdout.splitlines() if x.startswith('CONTRACT_SUMMARY ')]
                            if not summaries or summaries[0].get('actual_native_flows') != 7 or summaries[0].get('actual_native_commands', 0) < 7:issues.append('Incomplete native flows')
                        elif iid == 'buildpkg-poetry-10672':
                            lines = [x for x in stdout.splitlines() if x.startswith('{')]
                            if execution['returncode'] == 0:
                                result = json.loads(lines[-1]) if lines else {}
                                if result.get('status') != 'passed' or not result.get('binding'):issues.append('Missing native public API/binding result')
                            else:
                                expected_frame = 'check_repository' if command['repository'] == 'poetry' else 'check_export'
                                if execution['returncode'] != 1 or expected_frame not in stderr or any(x in stderr for x in ['ModuleNotFoundError','ImportError','TimeoutExpired','ConnectionRefusedError','PermissionError']):issues.append('Failure is not established native behavior')
                            rows = [{'id': command['repository'] + '-' + kind, 'passed': execution['returncode'] == 0}]
                        else:
                            reports = cell / (label + '-reports'); reports.mkdir()
                            copied = subprocess.run(['docker','cp',cid + ':' + report_dir + '/.',str(reports)],capture_output=True)
                            sessions = [json.loads(p.read_text()) for p in sorted(reports.glob('*.json'))] if copied.returncode == 0 else []
                            if not sessions:issues.append('Missing pytest session reports')
                            for session in sessions:
                                issues += report_health(session)
                                rows += [{'id': r['nodeid'], 'passed': r['outcome'] == 'passed'} for r in session['reports'] if r['when'] == 'call']
                        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):
                            delta=approved_gold_addition(task,label,inventories[label],ids,inp)
                            if delta:record.setdefault('inventory_deltas',{})[label]=delta
                            else: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}
                        if iid in BATCH02_IDS:result['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-poetry-10606','backend-fastapi-14186']:
                        copied = subprocess.run(['docker','cp',cid+':/artifacts',str(cell/'native-artifacts')],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 status['state'] != 'LOCAL_VALIDATED':
        raise SystemExit(1)


if __name__ == '__main__':
    main()