"""Evaluate one submitted multi-repository candidate against frozen batch06 tests. No gold selection, endpoint expectations, model calls, baseline/score writes, or publication. Help/import/check-only do not access Docker or create outputs. """ import argparse import collections import datetime import hashlib import importlib.util import json import os from pathlib import Path, PurePosixPath import re import shlex import shutil import subprocess import sys from types import SimpleNamespace import uuid sys.dont_write_bytecode = True from batch06_candidate_case_reports_v1 import parse_report HERE = Path(__file__).resolve().parent DEFAULT_SUPPORT = HERE if (HERE / 'evaluate_reusable_batch06_image.py').is_file() else HERE.parents[1] / 'batch06/publication' OWNER = 'native-candidate-batch06-v1' SUPPORT_SHA256 = { 'evaluate_reusable_batch06_image.py': '99bfbe785ff03efa19a02c1755839847dfda57e9e5e93f52d7ff19381798a523', 'reusable_support/batch06_case_reports.py': '71be1b571260f84a250dd6c1e4689bde8d80a4f71f6926d0103e18272145f675', 'reusable_support/batch06_git_state.py': '87b2720ada6307f55e8550661ffff21267c69b547e89d254e0b82d5f2935af32', 'reusable_support/batch06_runtime_resources.py': 'f68535cdf3feeb9435129649c04020ca5361a2d86aa08359ca2dccf957ecb486', 'reusable_support/batch06_source_audit.py': 'fe8dcb35ca7d9fb28d4ddf484e17fa02a706d13aa928d392be708e6d499c12fd', 'reusable_support/batch06_source_files.py': 'a9ccfb607e04ade3d165cf14e2fc2579326d220f93539c1e09e9ce4fbe7dab95', 'reusable_support/execution_io.py': 'fca4f9c2a2fe83af2203257c1155af2db45bb065080ae47fb23378affd3cf407', 'reusable_support/image_identity.py': '82764a71a677364e7dbbe40023885ca3f15bf8f307a98dd8378bfb80966decf0', 'reusable_support/validation_policy.py': '42dee62ae6ac69fd6fecfa1e04530ad598e1b230fe3fd67e81047d9c44f067ea', } # Verified read-only against control/inputs//binding.json and all bound # current files on 2026-10-16. Image configs come from hash-verified OCI manifests # (Conda) and the repair build metadata (Meson v2 / PNPM v2), never a mutable tag. PROFILES = { 'buildpkg-conda-14674': { 'task_sha256': 'daf906a285d6990dd6c378ec5f3a376814c11ad4362ce620326da132ea07fe83', 'contract_sha256': '2aeef1122c363c444dd6569b5b714b12cdbe8a1059da15108fe04ab599df05f9', 'registry_digest': 'sha256:d2745804b21528b350187e18ac32ffb773faef87e28b7d6327df18d6fbc91d00', 'config_digest': 'sha256:ad74c088d5215e3dbbb9e25b2010192d1dfcbee09b4af2dc561a7e72a75a46bc'}, 'buildpkg-conda-16510': { 'task_sha256': 'b30fcf076b486b203a8c4b8c22107f00f4dbdb37a812e152a9b7cfe7c6658b9f', 'contract_sha256': '3ec3d42e43282535358d0dd65693f0d2af99cc3f996316b23ea644b02e62416c', 'registry_digest': 'sha256:26d1b76d1f0c27ebd3cafb61a2d58e466f73dce534057681f46725f4e74d078d', 'config_digest': 'sha256:06eecf1a7bf9fb40a201c9a48a09a6046cbbdb93c4cc3933e88750ba700cbc94'}, 'buildpkg-conda-16555': { 'task_sha256': 'c26374c00e6c0631b58ecad2f4f138a6f46c9ba5386cb255481db35b6b353d72', 'contract_sha256': '96153bfb8fb68b9392dd84e1e3aa2da614ddd0b90b2209675e41594b8907006b', 'registry_digest': 'sha256:f9442940872ee8ff677cab6e19a548a8bb1e5f7a6447b4dcc8f443e6aa03fb0b', 'config_digest': 'sha256:3137b95a0d6e3e466e5b08b8fc826db7c1dcad598b611459e6c151b3bdd0b2da'}, 'buildpkg-meson-15997': { 'task_sha256': 'dbd9f3daf089cc222ffe04837a733ce08193079ed83a8aeccdfc1dd91a8bfcf0', 'contract_sha256': 'cc25cf2c67a01f65e92f91734c79dac67480e0c00479c1ea06985918a7bab5d5', 'registry_digest': 'sha256:749c9f2969287b45357c2497f8e3390fb3daa40266ed263b79319c97d03c0626', 'config_digest': 'sha256:9db08b84b4903472b10cd4d43b9c81d86dd4e3d6bae51d01a524cd3cd98da21c'}, 'buildpkg-pnpm-11330': { 'task_sha256': '0043628f0223fe1d4312e94db372d2342dc2c1978591ecabde672f250ab6471b', 'contract_sha256': '425db49bef334d759f5f2c7825966042ddc0fd9d53350bcafb781f49784d4bf0', 'registry_digest': 'sha256:e6c20a1727d4eb758737a9c2710a2e0a805bc534fc056929d7ddb2279b55437c', 'config_digest': 'sha256:e3812fc8855ddd21aa20648162571a834da9c2e776157decd0a07aa7c350601c'}, } PNPM_RESOURCE_IMAGE = 'silinchen0617/crossrepo-bench@sha256:1563086d39cbdf087f748c0e845fb33921e307e605bf639393fe552c9a271372' PNPM_RESOURCE_MANIFEST_SHA256 = '292b80ad4a806df8e425a7ad92545534a4a7c782514e18353a2504c6e1375931' ENVIRONMENT = {'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'} def require(value, message): if not value: raise ValueError(message) def digest(path): h = hashlib.sha256() with Path(path).open('rb') as stream: for block in iter(lambda: stream.read(1024 * 1024), b''): h.update(block) return h.hexdigest() def regular(path): path = Path(path).absolute() require(path.is_file() and not path.is_symlink() and path == path.resolve(), 'Missing or symlinked input: ' + str(path)) return path def read_json(path): def unique(pairs): result = {} for key, value in pairs: require(key not in result, 'Duplicate JSON key: ' + key) result[key] = value return result return json.loads(regular(path).read_text(), object_pairs_hook=unique, parse_constant=lambda value: (_ for _ in ()).throw(ValueError('Invalid JSON constant: ' + value))) def import_file(name, path): spec = importlib.util.spec_from_file_location(name, path) module = importlib.util.module_from_spec(spec) spec.loader.exec_module(module) return module def load_support(directory): """Load exact reviewed portable support, without running its endpoint main.""" directory = Path(directory).resolve() for name, expected in SUPPORT_SHA256.items(): require(digest(regular(directory / name)) == expected, 'Frozen support SHA drift: ' + name) names = ('batch06_case_reports', 'batch06_runtime_resources', 'image_identity', 'validation_policy', 'execution_io') modules = {name: import_file('_candidate_frozen_' + name, directory / 'reusable_support' / (name + '.py')) for name in names} previous = {name: sys.modules.get(name) for name in names} old_path = sys.path[:] try: sys.modules.update(modules) baseline = import_file('_candidate_frozen_batch06', directory / 'evaluate_reusable_batch06_image.py') finally: sys.path[:] = old_path for name, module in previous.items(): if module is None: sys.modules.pop(name, None) else: sys.modules[name] = module return SimpleNamespace(root=directory, code=directory / 'reusable_support', baseline=baseline, reports=modules['batch06_case_reports'], runtime=modules['batch06_runtime_resources'], identity=modules['image_identity'], io=modules['execution_io']) def safe_patch_path(name): rel = PurePosixPath(name) require(name and not rel.is_absolute() and '..' not in rel.parts and '.git' not in rel.parts and '\x00' not in name, 'Candidate patch escapes repository: ' + name) return name def git_quoted_token(data): """Decode Git's C-quoted path bytes, including octal UTF-8, without shlex.""" require(data.startswith(b'"'), 'Expected Git quoted path') result = bytearray(); index = 1 escapes = {ord('a'): 7, ord('b'): 8, ord('t'): 9, ord('n'): 10, ord('v'): 11, ord('f'): 12, ord('r'): 13, ord('\\'): 92, ord('"'): 34} while index < len(data): value = data[index]; index += 1 if value == 34: return bytes(result), index if value == 92: require(index < len(data), 'Unterminated Git path escape') value = data[index]; index += 1 if value in escapes: result.append(escapes[value]) elif 48 <= value <= 55: octal = bytes([value]) while index < len(data) and len(octal) < 3 and 48 <= data[index] <= 55: octal += bytes([data[index]]); index += 1 number = int(octal, 8); require(number <= 255, 'Invalid Git octal path escape') result.append(number) else: raise ValueError('Unsupported Git path escape') else: result.append(value) raise ValueError('Unterminated Git quoted path') def git_single_path(data, *, unified=False): # Git emits one empty timestamp delimiter after space-bearing ---/+++ paths. if unified and data.endswith(b'\t'): data = data[:-1] if data.startswith(b'"'): path, end = git_quoted_token(data) require(end == len(data), 'Extra data after Git quoted path') else: require(b'\t' not in data, 'Unsupported timestamp/tab in unquoted Git header path') path = data return path.decode('utf-8', errors='surrogateescape') def git_header_pairs(data): if data.startswith(b'"'): old, end = git_quoted_token(data) require(data[end:end + 1] == b' ', 'Missing Git path separator') return [(old.decode('utf-8', errors='surrogateescape'), git_single_path(data[end + 1:]))] pairs = [] for index, value in enumerate(data): if value == 32 and (data[index + 1:].startswith(b'b/') or data[index + 1:].startswith(b'"b/')): try: pairs.append((git_single_path(data[:index]), git_single_path(data[index + 1:]))) except ValueError: continue require(pairs, 'Cannot decode both Git diff header paths') return pairs def validate_patch_headers(data, numstat_paths): """Bind BOTH sides of every Git/rename/copy/unified header to Git numstat. Supported input is standard `git diff` (including binary, rename/copy, mode-only and C-quoted paths). Bare traditional/combined/ambiguous formats are explicitly unsupported rather than guessing their path semantics. """ lines = data.split(b'\n') require(not any(line.startswith((b'diff --cc ', b'diff --combined ')) for line in lines), 'Combined Git diffs are unsupported') starts = [index for index, line in enumerate(lines) if line.startswith(b'diff --git ')] require(starts, 'Only standard git diff patches are supported; bare unified diffs are unsupported') require(not any(line.startswith((b'--- ', b'+++ ', b'rename from ', b'copy from ')) for line in lines[:starts[0]]), 'Path header outside a Git diff block') expected_numstat = []; inventory = [] for position, start in enumerate(starts): end = starts[position + 1] if position + 1 < len(starts) else len(lines) metadata = {}; operation = 'change' for line in lines[start + 1:end]: if line.startswith((b'@@', b'GIT binary patch')): break # Hunk content may itself start with ---/+++; not metadata. require(not line.startswith(b'Binary files '), 'Binary diffs require git diff --binary') for prefix, key in ((b'--- ', 'old'), (b'+++ ', 'new'), (b'rename from ', 'rename_old'), (b'rename to ', 'rename_new'), (b'copy from ', 'copy_old'), (b'copy to ', 'copy_new')): if line.startswith(prefix): require(key not in metadata, 'Duplicate Git path header: ' + key) value = git_single_path(line[len(prefix):], unified=key in ('old', 'new')) if key in ('old', 'new'): if value == '/dev/null': value = None else: side = 'a/' if key == 'old' else 'b/' require(value.startswith(side), 'Unsupported Git unified path prefix') value = safe_patch_path(value[2:]) else: value = safe_patch_path(value) metadata[key] = value break bound = None for kind in ('rename', 'copy'): if kind + '_old' in metadata or kind + '_new' in metadata: require(bound is None and kind + '_old' in metadata and kind + '_new' in metadata, 'Incomplete/conflicting Git rename/copy headers') bound = (metadata[kind + '_old'], metadata[kind + '_new']); operation = kind if 'old' in metadata or 'new' in metadata: require('old' in metadata and 'new' in metadata, 'Incomplete Git unified path headers') old, new = metadata['old'], metadata['new'] require(old is not None or new is not None, 'Two null Git paths') marker_pair = (old if old is not None else new, new if new is not None else old) require(bound is None or marker_pair == bound, 'Git rename/copy and unified headers disagree') bound = marker_pair if old is None: operation = 'create' elif new is None: operation = 'delete' candidates = [] for old, new in git_header_pairs(lines[start][len(b'diff --git '):]): if old.startswith('a/') and new.startswith('b/'): pair = (old[2:], new[2:]) if (bound is not None and pair == bound) or (bound is None and pair[0] == pair[1]): candidates.append(pair) require(len(candidates) == 1, 'Ambiguous or inconsistent Git diff header paths') old, new = (safe_patch_path(value) for value in candidates[0]) expected_numstat.append(old if operation == 'delete' else new) inventory.append({'old_path': old, 'new_path': new, 'operation': operation}) require(collections.Counter(expected_numstat) == collections.Counter(numstat_paths), 'Git numstat and full path-header inventories disagree') return inventory def validate_candidate_patches(task, mapping_file): """Read patch paths and use Git's read-only numstat parser for decoded paths.""" mapping_file = regular(mapping_file) mapping = read_json(mapping_file) require(isinstance(mapping, dict), 'Candidate mapping must be a JSON object') keys = {repo['key'] for repo in task['repositories']} require(set(mapping).issubset(keys), 'Unknown candidate repository key') result = {} for key, value in mapping.items(): require(isinstance(value, str) and value, 'Candidate patch path must be a nonempty string') supplied = Path(value) path = regular(supplied if supplied.is_absolute() else mapping_file.parent / supplied) data = path.read_bytes() require(data, 'Empty candidate patch file; omit an unchanged repository') argv = ['git', 'apply', '--numstat', '-z', '--'] parsed = subprocess.run(argv, input=data, capture_output=True, timeout=30, env={**os.environ, 'GIT_CONFIG_NOSYSTEM': '1', 'GIT_CONFIG_GLOBAL': os.devnull}) require(parsed.returncode == 0 and parsed.stdout, 'Invalid candidate patch: ' + parsed.stderr.decode(errors='replace')) paths = [] for row in parsed.stdout.split(b'\0'): if not row: continue fields = row.split(b'\t', 2) require(len(fields) == 3, 'Malformed Git patch path inventory') name = fields[2].decode('utf-8', errors='surrogateescape') paths.append(safe_patch_path(name)) require(paths, 'Candidate patch has no changed repository paths') header_paths = validate_patch_headers(data, paths) result[key] = {'path': str(path), 'sha256': hashlib.sha256(data).hexdigest(), 'bytes': len(data), 'changed_paths': paths, 'validated_header_paths': header_paths, 'validation': {'argv': argv, 'returncode': parsed.returncode, 'stdout_sha256': hashlib.sha256(parsed.stdout).hexdigest(), 'stderr_sha256': hashlib.sha256(parsed.stderr).hexdigest()}} return result def prepare_inputs(bench_root, iid, mapping_file, output_dir, support_dir=DEFAULT_SUPPORT, evaluator_resource_dir=None): require(iid in PROFILES, 'Unsupported candidate instance') bench_root = Path(bench_root).resolve() out = Path(output_dir).absolute() require(out == out.resolve() and not out.exists(), 'Output must be a new non-symlink path') require(not out.is_relative_to(bench_root), 'Output must be outside the release checkout') support = load_support(support_dir) support.baseline.ROOT = bench_root inp = bench_root / 'instances' / iid profile = PROFILES[iid] require(digest(regular(inp / 'task.json')) == profile['task_sha256'], 'Frozen task SHA drift') task = read_json(inp / 'task.json') contract_path = support.baseline.checked_reference(inp, task['evaluation']) require(digest(contract_path) == profile['contract_sha256'], 'Frozen contract SHA drift') # Reuse the exact published loader and its checked_reference/source/resource checks. inp, task, contract, image, resource = support.baseline.load_inputs(iid) regular(bench_root / 'environments' / iid / 'image.json') if iid == 'buildpkg-pnpm-11330': require(resource['image_ref'] == PNPM_RESOURCE_IMAGE and resource['manifest_sha256'] == PNPM_RESOURCE_MANIFEST_SHA256, 'Original PNPM runtime image/manifest binding changed') for key, expected in profile.items(): require(image.get(key) == expected, 'Unsupported image/input profile: ' + key) require(image.get('amd64_manifest_digest') == profile['registry_digest'], 'Unreviewed image manifest') require(image['image_ref'] == 'silinchen0617/crossrepo-bench@' + profile['registry_digest'], 'Unapproved image reference') repositories = {repo['key']: repo for repo in task['repositories']} require(len(repositories) == len(task['repositories']) == 2, 'Expected two distinct repositories') require(collections.Counter(command['repository'] for command in contract['commands']) == collections.Counter(repositories.keys()), 'Frozen command repository inventory mismatch') for command in contract['commands']: require(command['container_path'] == repositories[command['repository']]['container_path'], 'Command source path mismatch') require(all(isinstance(command[kind], str) and command[kind] for kind in ('pass_to_pass', 'fail_to_pass')), 'Missing frozen command') for artifact in contract.get('test_files', []): support.baseline.checked_reference(inp, artifact) rel = PurePosixPath(artifact.get('original_path', Path(artifact['path']).name)) require(not rel.is_absolute() and '..' not in rel.parts, 'Escaping evaluator injection path') for repo in repositories.values(): for ref in repo['test_patches']: support.baseline.checked_reference(inp, ref) provided = Path(evaluator_resource_dir).absolute() if evaluator_resource_dir is not None else None if provided is not None: require(provided == provided.resolve() and not provided.is_symlink(), 'Symlinked evaluator resource directory') if resource is None: require(provided is None, 'This instance has no evaluator resource') elif provided is not None: support.runtime.verify_runtime_files(provided, resource) patches = validate_candidate_patches(task, mapping_file) source = support.baseline.checked_reference(bench_root / 'environments' / iid, image['source_manifest'], read_json=True) input_files = {'task': inp / 'task.json', 'contract': inp / task['evaluation']['path'], 'image': bench_root / 'environments' / iid / 'image.json', 'source_manifest': support.baseline.checked_reference(bench_root / 'environments' / iid, image['source_manifest'])} provenance = {'bench_root': str(bench_root), 'output_dir': str(out), **{key: {'path': str(regular(path)), 'bytes': path.stat().st_size, 'sha256': digest(path)} for key, path in input_files.items()}} return {'iid': iid, 'bench_root': bench_root, 'inp': inp, 'task': task, 'contract': contract, 'image': image, 'resource': resource, 'provided_resource': provided, 'source': source, 'support': support, 'patches': patches, 'mapping_file': regular(mapping_file), 'out': out, 'image_json_sha256': digest(bench_root / 'environments' / iid / 'image.json'), 'mapping_sha256': digest(mapping_file), 'input_provenance': provenance} def validate_git_state(task, state, label, *, expected=None, clean=False): """Validate the unchanged helper's tracked HEAD/diff report for both roots. The staged report includes candidate + frozen test patch changes. Frozen setup may create ignored/untracked build/install outputs; those are not in git diff HEAD. No equality of staged/pre-test source-file inventories is imposed. The tracked diff and base HEAD must remain unchanged by setup/tests. """ roots = {repo['container_path']: repo['base_commit'] for repo in task['repositories']} require(isinstance(state, dict) and set(state) == set(roots), 'Git ' + label + ': paired root inventory mismatch') for root, base in roots.items(): row = state[root] require(isinstance(row, dict) and set(row) == {'head', 'diff_sha256'}, 'Git ' + label + ': malformed state schema') require(isinstance(row['head'], str) and re.fullmatch('[0-9a-f]{40}', row['head']) and row['head'] == base, 'Git ' + label + ': HEAD differs from frozen base: ' + root) require(isinstance(row['diff_sha256'], str) and re.fullmatch('[0-9a-f]{64}', row['diff_sha256']), 'Git ' + label + ': malformed tracked diff SHA: ' + root) if clean: require(row['diff_sha256'] == hashlib.sha256(b'').hexdigest(), 'Git ' + label + ': base tracked diff is not empty') if expected is not None: require(state == expected, 'Git ' + label + ': tracked candidate/test source state changed') return state def classify(commands, repository_keys): expected = {(repo, kind) for repo in repository_keys for kind in ('pass_to_pass', 'fail_to_pass')} actual = [(row['repository'], row['kind']) for row in commands] issues = [str(issue) for row in commands for issue in row.get('issues', [])] if len(actual) != len(expected) or set(actual) != expected or any(not row.get('cases') for row in commands): issues.append('Incomplete candidate command/case inventory') regressions = [] p2p_total = f2p_total = f2p_passed = 0 for command in commands: cases = command.get('cases', []) if command['kind'] == 'pass_to_pass': p2p_total += len(cases) regressions.extend({'repository': command['repository'], 'kind': command['kind'], **row} for row in cases if not row['passed']) else: f2p_total += len(cases); f2p_passed += sum(row['passed'] for row in cases) state = ('EVALUATION_ERROR' if issues else 'P2P_REGRESSION' if regressions else 'RESOLVED' if f2p_total and f2p_passed == f2p_total else 'UNRESOLVED') return {'state': state, 'resolved': state == 'RESOLVED', 'issues': issues, 'p2p_total': p2p_total, 'p2p_regressions': regressions, 'f2p_total': f2p_total, 'f2p_passed': f2p_passed, 'f2p_failed': f2p_total - f2p_passed} class Runner: """Execute first; remember raw results before best-effort receipt writes.""" def invoke(self, argv, *, input_bytes, timeout, target): return subprocess.run(argv, input=input_bytes, capture_output=True, timeout=timeout) def run(self, argv, target, timeout=180, check=True, input_bytes=None, on_result=None): started = datetime.datetime.now(datetime.timezone.utc).isoformat() timed_out = False try: result = self.invoke(argv, input_bytes=input_bytes, timeout=timeout, target=Path(target)) stdout, stderr, rc = result.stdout, result.stderr, result.returncode timed_out = bool(getattr(result, 'timed_out', False)) except subprocess.TimeoutExpired as exc: stdout, stderr, rc = exc.stdout or b'', exc.stderr or b'', -9 timed_out = True except OSError as exc: stdout, stderr, rc = b'', (type(exc).__name__ + ': ' + str(exc)).encode(), 127 target = Path(target) record = {'argv': argv, 'returncode': rc, 'timed_out': timed_out, 'timeout_seconds': timeout, 'started_utc': started, 'ended_utc': datetime.datetime.now(datetime.timezone.utc).isoformat(), 'stdout_sha256': hashlib.sha256(stdout).hexdigest(), 'stderr_sha256': hashlib.sha256(stderr).hexdigest(), 'persistence_errors': []} if input_bytes is not None: record['stdin_sha256'] = hashlib.sha256(input_bytes).hexdigest() # The caller records full IDs/ownership and raw streams before any I/O. if on_result is not None: on_result(record, stdout, stderr) for suffix, data in (('.stdout.log', stdout), ('.stderr.log', stderr)): try: target.with_suffix(suffix).write_bytes(data) except Exception as exc: record['persistence_errors'].append(suffix + ': ' + type(exc).__name__ + ': ' + str(exc)) try: atomic_write(target.with_suffix('.execution.json'), record) except Exception as exc: record['persistence_errors'].append('.execution.json: ' + type(exc).__name__ + ': ' + str(exc)) if check and (rc or timed_out or record['persistence_errors']): raise RuntimeError(target.name + ': ' + ('timeout' if timed_out else 'exit ' + str(rc)) + ('; receipt persistence failed' if record['persistence_errors'] else '')) return record def atomic_write(path, value): path = Path(path) temporary = path.with_suffix(path.suffix + '.tmp') with temporary.open('w') as stream: json.dump(value, stream, indent=2, sort_keys=True); stream.write('\n'); stream.flush(); os.fsync(stream.fileno()) temporary.replace(path) def observe_host_resources(output_directory): """Read Linux host availability; an unreadable/ambiguous observation fails closed.""" raw = Path('/proc/meminfo').read_bytes() available = [re.fullmatch(rb'MemAvailable:[ \t]+([0-9]+)[ \t]+kB', line) for line in raw.splitlines() if line.startswith(b'MemAvailable:')] require(len(available) == 1 and available[0] is not None, 'Expected exactly one Linux MemAvailable kB value') free = shutil.disk_usage(output_directory).free require(type(free) is int and free >= 0, 'Invalid host disk free bytes') return {'meminfo_raw': raw, 'memory_available_bytes': int(available[0].group(1)) * 1024, 'disk_free_bytes': free} def record_pnpm_host_admission(cell): """Persist actual host evidence immediately before the PNPM candidate create.""" observed = observe_host_resources(cell) minimum_memory = 80_000_000_000 disk_floor = 35_000_000_000 disk_margin = 256 * 1024**2 admitted = (observed['memory_available_bytes'] >= minimum_memory and observed['disk_free_bytes'] >= disk_floor + disk_margin) raw = observed['meminfo_raw'] (cell / 'host-meminfo.txt').write_bytes(raw) receipt = {'schema_version': 1, 'resource_only_revision': 'pnpm11330-mem64-a01', 'state': 'ADMITTED' if admitted else 'INSUFFICIENT_HOST_RESOURCES', 'admitted': admitted, 'observed_utc': datetime.datetime.now(datetime.timezone.utc).isoformat(), 'meminfo': {'source': '/proc/meminfo', 'path': 'candidate/host-meminfo.txt', 'bytes': len(raw), 'sha256': hashlib.sha256(raw).hexdigest()}, 'disk_path': str(cell.resolve()), 'observed': {key: observed[key] for key in ('memory_available_bytes', 'disk_free_bytes')}, 'required': {'memory_available_bytes': minimum_memory, 'disk_free_bytes': disk_floor + disk_margin, 'disk_floor_bytes': disk_floor, 'disk_margin_bytes': disk_margin}, 'container_profile': {'cpus': '8', 'memory': '64g', 'memory_swap': '64g'}} atomic_write(cell / 'host-resource-admission.json', receipt) return receipt def evaluate(prepared, runner=None): """One fresh candidate container; dependency injection is for offline traces.""" p = prepared; runner = runner or Runner(); out = p['out']; out.mkdir(parents=True, exist_ok=False) support = p['support']; task = p['task']; contract = p['contract']; image = p['image']; iid = p['iid'] cell = out / 'candidate'; cell.mkdir() nonce = uuid.uuid4().hex name = 'crossswe-candidate-' + iid + '-' + nonce status = {'schema_version': 1, 'adapter': OWNER, 'instance_id': iid, 'world': 'candidate', 'repeat': 1, 'state': 'RUNNING', 'complete_case_inventory': False, 'image_digest': image['registry_digest'], 'config_digest': image['config_digest'], 'task_sha256': image['task_sha256'], 'contract_sha256': image['contract_sha256'], 'started_utc': datetime.datetime.now(datetime.timezone.utc).isoformat(), 'image': image, 'image_json_sha256': p['image_json_sha256'], 'source_manifest': p['source'], 'support_sha256': SUPPORT_SHA256, 'operator_sha256': {name: digest(HERE / name) for name in ('evaluate_candidate_batch06_v1.py', 'batch06_candidate_case_reports_v1.py')}, 'input_provenance': p['input_provenance'], 'model_calls': 0, 'score_writes': 0, 'baseline_writes': 0, 'candidate_inputs': p['patches'], 'candidate_mapping': {'path': str(p['mapping_file']), 'sha256': p['mapping_sha256']}, 'patches': [], 'commands': [], 'git_captures': {}, 'issues': [], 'logging_errors': [], 'ownership_errors': [], 'cleanup': {'attempted': False, 'removed': False}, 'container_name': name, 'ownership_nonce': nonce} cid = None; identity = None; environments = {}; setup_started = False; create_attempted = False memory = {}; owner_confirmed = False def fail(message): status.setdefault('primary_error', message) if message not in status['issues']: status['issues'].append(message) status['state'] = 'EVALUATION_ERROR'; status['resolved'] = False; status['complete_case_inventory'] = False def logging_error(message): status['logging_errors'].append(message) fail('Receipt persistence: ' + message) def persist_status(label, strict=True): try: atomic_write(out / 'status.json', status) return True except Exception as exc: logging_error(label + ': ' + type(exc).__name__ + ': ' + str(exc)) if strict: raise RuntimeError(label + ': status receipt persistence failed') from exc return False def observe(label, argv, record, stdout, stderr): nonlocal cid, identity, owner_confirmed memory[label] = {'record': record, 'stdout': stdout, 'stderr': stderr} if record['returncode'] or record.get('timed_out'): return try: if argv[:3] == ['docker', 'image', 'inspect']: actual = json.loads(stdout)[0] support.identity.validate_image(actual, image) identity = actual; status['engine_image_identity'] = actual elif argv[:2] == ['docker', 'create']: value = stdout.decode().strip() require(re.fullmatch('[0-9a-f]{64}', value), 'Docker create did not return a full immutable container ID') cid = value; status['container_id'] = cid elif argv[:2] == ['docker', 'inspect'] and label != 'removed-container-inspect': actual = json.loads(stdout)[0] labels = actual['Config'].get('Labels') or {} require(identity is not None and re.fullmatch('[0-9a-f]{64}', actual['Id']) and (cid is None or actual['Id'] == cid) and actual['Image'] == identity['Id'] and labels.get('crossswe.owner') == OWNER and labels.get('crossswe.attempt') == nonce and labels.get('crossswe.instance') == iid, 'Container ownership mismatch; refusing to operate/clean up') cid = actual['Id']; status['container_id'] = cid; owner_confirmed = True status['last_ownership_proof'] = {'label': label, 'container_id': cid, 'image_id': actual['Image'], 'labels': labels, 'stdout_sha256': record['stdout_sha256']} except Exception as exc: record['observation_error'] = type(exc).__name__ + ': ' + str(exc) if argv[:2] == ['docker', 'inspect']: status['ownership_errors'].append(record['observation_error']) owner_confirmed = False fail(label + ': ' + record['observation_error']) def run(argv, label, check=True, tolerate_logging=False, **kwargs): nonlocal owner_confirmed if argv[:2] == ['docker', 'inspect'] and label != 'removed-container-inspect': owner_confirmed = False record = runner.run(argv, cell / label, check=False, on_result=lambda row, stdout, stderr: observe(label, argv, row, stdout, stderr), **kwargs) for error in record.get('persistence_errors', []): logging_error(label + ': ' + error) if record.get('observation_error'): if not tolerate_logging: raise RuntimeError(label + ': ' + record['observation_error']) if record.get('persistence_errors') and not tolerate_logging: raise RuntimeError(label + ': receipt persistence failed') if check and (record['returncode'] or record.get('timed_out')): raise RuntimeError(label + ': ' + ('timeout' if record.get('timed_out') else 'exit ' + str(record['returncode']))) return record def read_output(label): return memory[label]['stdout'] def execute(command, label, cwd='/testbed', env=None, check=True, timeout=14400, tolerate_logging=False): argv = ['docker', 'exec', '-w', cwd] for key, value in (env or {}).items(): argv += ['-e', key + '=' + value] return run(argv + [cid, 'bash', '-lc', command], label, check=check, timeout=timeout, tolerate_logging=tolerate_logging) def capture(script, label, filename): data = (support.code / script).read_bytes() require(hashlib.sha256(data).hexdigest() == SUPPORT_SHA256['reusable_support/' + script], 'Support changed during execution') result = run(['docker', 'exec', '-i', cid, 'python3', '-'], label, input_bytes=data, timeout=300) if script == 'batch06_git_state.py': try: state = support.reports.decode(read_output(label).decode('utf-8', errors='strict')) expected = None if label == 'git-before': expected = status['git_captures']['staged-git-state']['state'] elif label.endswith('-git-after'): expected = status['git_captures']['git-before']['state'] validate_git_state(task, state, label, expected=expected, clean=label == 'base-git-state') status['git_captures'][label] = {'state': state, 'stdout_sha256': result['stdout_sha256']} except Exception as exc: raise ValueError('Git capture ' + label + ': ' + str(exc)) from exc try: (cell / filename).write_bytes(read_output(label)) except Exception as exc: logging_error(label + ': ' + filename + ': ' + type(exc).__name__ + ': ' + str(exc)) raise def inspect(label, tolerate_logging=False): record = run(['docker', 'inspect', cid], label, check=False, tolerate_logging=tolerate_logging) require(record['returncode'] == 0 and not record.get('timed_out') and owner_confirmed and not status['ownership_errors'], 'Owned container inspection failed or ownership is blocked') return json.loads(read_output(label))[0] try: persist_status('initial') # Snapshot every submitted patch before Docker, then apply this immutable # copy. Frozen artifacts are checked again at the point of injection. require(digest(regular(p['bench_root'] / 'environments' / iid / 'image.json')) == p['image_json_sha256'], 'Image descriptor SHA drift after preparation') require(digest(regular(p['inp'] / 'task.json')) == image['task_sha256'], 'Frozen task SHA drift after preparation') require(digest(regular(p['inp'] / task['evaluation']['path'])) == image['contract_sha256'], 'Frozen contract SHA drift after preparation') require(digest(regular(p['mapping_file'])) == p['mapping_sha256'], 'Candidate mapping SHA drift after preparation') snapshots = out / 'candidate-inputs'; snapshots.mkdir() (snapshots / 'patches.json').write_bytes(p['mapping_file'].read_bytes()) for key, patch in p['patches'].items(): require(digest(regular(patch['path'])) == patch['sha256'], 'Candidate patch SHA drift') snapshot = snapshots / (key + '.patch'); snapshot.write_bytes(Path(patch['path']).read_bytes()) require(digest(snapshot) == patch['sha256'], 'Candidate patch changed while snapshotting') run(['docker', 'pull', '--platform', 'linux/amd64', image['image_ref']], 'image-pull', timeout=1800) run(['docker', 'image', 'inspect', image['image_ref']], 'image-inspect') identity = json.loads(read_output('image-inspect'))[0]; support.identity.validate_image(identity, image) status['engine_image_identity'] = identity assets = support.runtime.materialize_runtime(p['resource'], out / 'evaluator-resources', p['provided_resource']) if p['resource'] is not None: status['resource_materialization'] = { 'mode': 'provided-verified-directory' if p['provided_resource'] is not None else 'pinned-helper-managed-private-image', 'provided_dir': str(p['provided_resource']) if p['provided_resource'] is not None else None, 'helper_sha256': SUPPORT_SHA256['reusable_support/batch06_runtime_resources.py'], 'default_resource_container_commands_logged': False, 'verified_files': [{'path': str(path.relative_to(out)), 'bytes': path.stat().st_size, 'sha256': digest(path)} for path in sorted(assets.rglob('*')) if path.is_file()]} persist_status('resource-materialization') cpus, memory_limit = ('8', '64g') if iid == 'buildpkg-pnpm-11330' else ('2', '3g') if iid == 'buildpkg-pnpm-11330': status['host_resource_admission'] = record_pnpm_host_admission(cell) persist_status('host-resource-admission') require(status['host_resource_admission']['admitted'], 'Insufficient host resources for PNPM 64GiB candidate') create_attempted = True run(['docker', 'create', '--name', name, '--network', 'none', '--cpus', cpus, '--memory', memory_limit, '--memory-swap', memory_limit, '--label', 'crossswe.owner=' + OWNER, '--label', 'crossswe.attempt=' + nonce, '--label', 'crossswe.instance=' + iid, image['image_ref'], 'sleep', 'infinity'], 'create') cid = read_output('create').decode().strip() require(re.fullmatch('[0-9a-f]{64}', cid), 'Docker create did not return a full immutable container ID') status['container_id'] = cid run(['docker', 'start', cid], 'start') info = inspect('initial-container-inspect') require(not info['Mounts'] and info['HostConfig']['NetworkMode'] == 'none', 'Container isolation mismatch') require(info['HostConfig']['NanoCpus'] == int(cpus) * 10**9 and info['HostConfig']['Memory'] == int(memory_limit[:-1]) * 1024**3 and info['HostConfig']['MemorySwap'] == info['HostConfig']['Memory'], 'Container resource budget mismatch') status['container_isolation'] = {'mounts': info['Mounts'], 'network': info['HostConfig']['NetworkMode'], 'cpus': cpus, 'memory': memory_limit} capture('batch06_source_audit.py', 'base-source-audit', 'agent-source-audit.json') audited = json.loads((cell / 'agent-source-audit.json').read_text())['manifest'] support.baseline.validate_source_manifest(audited, task) require(audited == p['source'], 'Agent source manifest differs from published image binding') capture('batch06_git_state.py', 'base-git-state', 'git-state-base.json') # All caller candidates precede every frozen test patch and hidden file. for repo in task['repositories']: execute('git diff --exit-code HEAD && test -z "$(git status --porcelain)"', repo['key'] + '-clean', repo['container_path']) for repo in task['repositories']: key = repo['key']; patch = p['patches'].get(key) if patch is None: continue snapshot = snapshots / (key + '.patch'); dst = '/tmp/crossswe-candidate-' + key + '.patch' run(['docker', 'cp', str(snapshot), cid + ':' + dst], key + '-candidate-copy') execution = execute('git apply --check ' + shlex.quote(dst) + ' && git apply ' + shlex.quote(dst), key + '-candidate-apply', repo['container_path']) status['patches'].append({'repository': key, 'kind': 'candidate', **patch, 'snapshot': str(snapshot.relative_to(out)), 'container_path': dst, 'application': execution}) for repo in task['repositories']: for index, patch in enumerate(repo['test_patches'], 1): source = support.baseline.checked_reference(p['inp'], patch) dst = '/tmp/crossswe-frozen-test-' + repo['key'] + '-' + str(index) + '.patch' label = repo['key'] + '-frozen-test-' + str(index) run(['docker', 'cp', str(source), cid + ':' + dst], label + '-copy') execution = execute('git apply --check ' + shlex.quote(dst) + ' && git apply ' + shlex.quote(dst), label + '-apply', repo['container_path']) status['patches'].append({'repository': repo['key'], 'kind': 'frozen_test', **patch, 'application': execution}) capture('batch06_source_files.py', 'staged-source', 'source-files-staged.json') capture('batch06_git_state.py', 'staged-git-state', 'git-state-staged.json') execute('mkdir -p /crossrepo-patches /artifacts', 'evaluator-dirs') for number, artifact in enumerate(contract.get('test_files', [])): source = support.baseline.checked_reference(p['inp'], artifact) rel = PurePosixPath(artifact.get('original_path', source.name)) execute('mkdir -p ' + shlex.quote('/crossrepo-patches/' + str(rel.parent)), 'evaluator-parent-' + str(number)) run(['docker', 'cp', str(source), cid + ':/crossrepo-patches/' + str(rel)], 'inject-' + str(number)) if p['resource'] is not None: support.runtime.verify_runtime_files(assets, p['resource']) for number, mapping in enumerate(p['resource']['injections']): source = assets / mapping['source']; require(source.is_dir() and not source.is_symlink(), 'Missing runtime injection') execute('mkdir -p ' + shlex.quote(str(PurePosixPath(mapping['destination']).parent)), 'runtime-parent-' + str(number)) run(['docker', 'cp', str(source), cid + ':' + mapping['destination']], 'runtime-copy-' + str(number)) status['evaluator_resource'] = p['resource'] commands = contract['commands'] environments = {command['repository']: {**ENVIRONMENT, **command.get('environment', {})} for command in commands} setup_started = True for command in sorted(commands, key=lambda row: row.get('setup_order') or 0): if command.get('setup_command'): execute(command['setup_command'], command['repository'] + '-source-setup', command['container_path'], environments[command['repository']]) for command in sorted(commands, key=lambda row: row.get('evaluation_setup_order') or 0): if command.get('evaluation_setup_command'): execute(command['evaluation_setup_command'], 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'], command['repository'] + '-ready', command['container_path'], environments[command['repository']]) capture('batch06_source_files.py', 'source-before', 'source-files.json') capture('batch06_git_state.py', 'git-before', 'git-state.json') for command in commands: for kind in ('pass_to_pass', 'fail_to_pass'): label = command['repository'] + '-' + kind execution = execute(command[kind], label, command.get('test_cwd') or command['container_path'], environments[command['repository']], check=False) native = cell / 'native-artifacts'; native.mkdir(exist_ok=True) run(['docker', 'cp', cid + ':/artifacts/.', str(native)], label + '-capture-native-artifacts') capture('batch06_source_files.py', label + '-source-after', 'source-files-after.json') capture('batch06_git_state.py', label + '-git-after', 'git-state-after.json') stdout = read_output(label).decode('utf-8', errors='strict') stderr = memory[label]['stderr'].decode('utf-8', errors='strict') rows, issues, metadata = parse_report(iid, command['repository'], kind, stdout, stderr, execution['returncode'], cell, frozen=support.reports) if execution.get('timed_out'): issues.append('Native command timed out') status['commands'].append({'repository': command['repository'], 'kind': kind, 'command': command[kind], 'cwd': command.get('test_cwd') or command['container_path'], 'environment': environments[command['repository']], 'returncode': execution['returncode'], 'passed': sum(row['passed'] for row in rows), 'failed': sum(not row['passed'] for row in rows), 'cases': rows, 'issues': issues, 'report_metadata': metadata, 'raw_receipt': str((cell / (label + '.execution.json')).relative_to(out))}) persist_status(label) if execution.get('timed_out'): raise RuntimeError('Native command timed out; stop before dispatching another command') outcome = classify(status['commands'], [repo['key'] for repo in task['repositories']]) status.update({key: value for key, value in outcome.items() if key != 'state'}) if outcome['issues']: status.setdefault('primary_error', outcome['issues'][0]) status['candidate_outcome'] = outcome['state'] status['complete_case_inventory'] = outcome['state'] != 'EVALUATION_ERROR' status['state'] = 'VALID_CANDIDATE_EVALUATION' if status['complete_case_inventory'] else 'EVALUATION_ERROR' status['p2p'] = {'total': outcome['p2p_total'], 'passed': outcome['p2p_total'] - len(outcome['p2p_regressions']), 'failed': len(outcome['p2p_regressions']), 'regressions': outcome['p2p_regressions']} status['f2p'] = {'total': outcome['f2p_total'], 'passed': outcome['f2p_passed'], 'failed': outcome['f2p_failed']} except Exception as exc: fail(type(exc).__name__ + ': ' + str(exc)) finally: if create_attempted and cid is None and identity and not status['ownership_errors']: try: run(['docker', 'inspect', name], 'recover-owned-container', check=False, tolerate_logging=True) except Exception as exc: fail('Failed-create ownership recovery: ' + type(exc).__name__ + ': ' + str(exc)) if cid and identity and not status['ownership_errors']: try: info = inspect('final-container-inspect', tolerate_logging=True) status['final_container_state'] = info.get('State', {}) if info.get('State', {}).get('OOMKilled'): fail('Container OOMKilled') except Exception as exc: fail('Owned container cleanup inspection: ' + type(exc).__name__ + ': ' + str(exc)) if owner_confirmed and not status['ownership_errors']: # Independent cleanup steps: receipt failure never skips stop or # remove after fresh ownership proof has been saved in memory. if setup_started: for command in reversed(contract['commands']): if command.get('evaluation_teardown_command'): try: execute(command['evaluation_teardown_command'], command['repository'] + '-teardown', command['container_path'], environments[command['repository']], tolerate_logging=True) except Exception as exc: fail('Teardown: ' + type(exc).__name__ + ': ' + str(exc)) steps = [(['docker', 'cp', cid + ':/artifacts', str(cell / 'native-artifacts-final')], 'final-native-artifacts', 180), (['docker', 'stop', '--time', '1', cid], 'stop', 30), (['docker', 'rm', cid], 'remove', 30), (['docker', 'inspect', cid], 'removed-container-inspect', 180)] status['cleanup'].update(attempted=True, container_id=cid) for argv, label, timeout in steps: try: result = run(argv, label, check=False, timeout=timeout, tolerate_logging=True) if label != 'removed-container-inspect' and (result['returncode'] or result.get('timed_out')): fail(label + ': ' + ('timeout' if result.get('timed_out') else 'exit ' + str(result['returncode']))) except Exception as exc: fail(label + ': ' + type(exc).__name__ + ': ' + str(exc)) removed = memory.get('remove', {}).get('record', {}) absent = memory.get('removed-container-inspect', {}).get('record', {}) missing_message = memory.get('removed-container-inspect', {}).get('stderr', b'').decode(errors='replace') status['cleanup']['removed'] = (removed.get('returncode') == 0 and not removed.get('timed_out') and absent.get('returncode') == 1 and not absent.get('timed_out') and re.search(r'No such (?:object|container)', missing_message, re.I) is not None) if not status['cleanup']['removed']: fail('Owned container cleanup was not verified') if status['ownership_errors']: fail('Sticky ownership errors prohibit cleanup of a foreign/unverified container') if status['issues']: status['state'] = 'EVALUATION_ERROR'; status['resolved'] = False; status['complete_case_inventory'] = False status['ended_utc'] = datetime.datetime.now(datetime.timezone.utc).isoformat() status['receipt_persisted'] = True if not persist_status('final', strict=False): status['receipt_persisted'] = False return status def main(argv=None): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument('--bench-root', type=Path, required=True, help='Portable Bench checkout with instances/ and published environments/') parser.add_argument('--support-dir', type=Path, default=DEFAULT_SUPPORT, help='Pinned batch06 publication runner and reusable_support/') parser.add_argument('--instance-id', required=True, choices=sorted(PROFILES)) parser.add_argument('--candidate-patches', type=Path, required=True, help='JSON repository-key to patch-path object; omitted key leaves its base unchanged') parser.add_argument('--output-dir', type=Path, required=True) parser.add_argument('--evaluator-resource-dir', type=Path) parser.add_argument('--check-only', action='store_true') args = parser.parse_args(argv) try: prepared = prepare_inputs(args.bench_root, args.instance_id, args.candidate_patches, args.output_dir, args.support_dir, args.evaluator_resource_dir) if args.check_only: print(json.dumps({'instance_id': args.instance_id, 'state': 'INPUTS_VERIFIED', 'world': 'candidate', 'image': prepared['image']['image_ref'], 'patches': prepared['patches'], 'evaluator_resources': prepared['resource'], 'model_calls': 0, 'score_writes': 0, 'runtime_validation': 'NOT_RUN'})) return 0 status = evaluate(prepared) print(json.dumps({'instance_id': args.instance_id, 'state': status['state'], 'resolved': status.get('resolved', False), 'receipt': str(prepared['out'] / 'status.json'), 'receipt_persisted': status.get('receipt_persisted', False), 'issues': status['issues'], 'logging_errors': status['logging_errors']})) return 2 if status['state'] == 'EVALUATION_ERROR' else 0 except (ValueError, OSError, KeyError, TypeError) as exc: print(type(exc).__name__ + ': ' + str(exc), file=sys.stderr) return 2 if __name__ == '__main__': raise SystemExit(main())