"""Pinned S3-B(a) geometry-only inputs and fail-closed I/O for prediction.""" import hashlib import json import os from pathlib import Path import sys ROOT = Path('artifacts/s3b-a-ten-part-2026-11-15') RULE = '1794741236.468009' def sha(path): h = hashlib.sha256() with open(path, 'rb') as f: for b in iter(lambda: f.read(1024*1024), b''): h.update(b) return h.hexdigest() def read(path): return json.loads(Path(path).read_text()) def checked(path, expected): if sha(path) != expected: raise ValueError('Pinned file changed: '+str(path)) return Path(path) def contract(root): c = read(Path(root)/'contract.json') for p, h in {**c['code_sha256'], **c['source_sha256']}.items(): checked(p, h) freeze = read(Path(root)/'code-freeze.json') if freeze['contract_sha256'] != sha(Path(root)/'contract.json') or not freeze.get('git_commit'): raise ValueError('Implementation/contract not Git-frozen') if c['authorizing_ruling'] != RULE or c['limits']['total_worker_CPU_s'] != 72000: raise ValueError('Wrong scope/budget') return c def restrict_prediction_io(allowed_files, output_root): """Python audit guard: exact data-file allowlist, no truth/cache/VTU access. This is an audited-worker I/O barrier, not a hostile-code OS sandbox. The pinned code neither invokes subprocesses nor accesses files via ctypes. """ allowed = {str(Path(p).resolve()) for p in allowed_files} output = str(Path(output_root).resolve()) runtimes = [str(Path(sys.prefix).resolve()), str(Path(__file__).resolve().parent)] def inside(path, directory): return path == directory or path.startswith(directory+os.sep) def audit(event, args): if event == 'open': name, mode, flags = args if isinstance(name, int): return path = str(Path(os.fsdecode(name)).resolve()) writing = bool(flags & (os.O_WRONLY | os.O_RDWR | os.O_CREAT | os.O_TRUNC | os.O_APPEND)) if writing: if not inside(path, output): raise PermissionError('Prediction output outside own directory') elif path not in allowed and not inside(path, output) and not any(inside(path, v) for v in runtimes): raise PermissionError('Prediction input outside geometry allowlist: '+path) elif event in ('subprocess.Popen', 'os.system', 'os.exec', 'socket.connect'): raise PermissionError('Prediction subprocess/network forbidden') sys.addaudithook(audit) def reserve_ok(spent, part_cap, stage_cap): return spent >= 0 and spent+part_cap <= stage_cap