"""Portable99 PNPM-only 64GiB resource derivative; no task or case changes.""" import ast from contextlib import contextmanager import datetime import hashlib import json import os from pathlib import Path import re import shutil import stat import sys import tempfile import types sys.dont_write_bytecode = True PINS = {'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'} BASE_SHA = '99bfbe785ff03efa19a02c1755839847dfda57e9e5e93f52d7ff19381798a523' DERIVED_SHA = 'fdba81fb6014662bd099102278b6d06c59953c13524b61e4f4a748946eede0cf' IID = 'buildpkg-pnpm-11330' MEMORY = 64 * 1024 ** 3 MIN_AVAILABLE = 80_000_000_000 MIN_DISK = 35_000_000_000 + 256 * 1024 ** 2 def require(value, message): if not value: raise ValueError(message) def regular(path): require(not any(p.is_symlink() for p in (path, *path.parents)) and stat.S_ISREG(path.lstat().st_mode), 'Unsafe portable baseline source: ' + str(path)) return path def derive_baseline(data): require(hashlib.sha256(data).hexdigest() == BASE_SHA, 'Original99 source SHA mismatch') before = b"'24g' if iid == 'buildpkg-pnpm-11330'" after = b"'64g' if iid == 'buildpkg-pnpm-11330'" require(data.count(before) == 1 and data.count(after) == 0, 'Ambiguous portable99 derivation') derived = data.replace(before, after, 1) require(hashlib.sha256(derived).hexdigest() == DERIVED_SHA and derived.replace(after, before, 1) == data, 'Derived source SHA mismatch') original_ast = ast.parse(data); derived_ast = ast.parse(derived) originals = list(ast.walk(original_ast)); changes = [] for left, right in zip(originals, ast.walk(derived_ast)): if ast.dump(left) != ast.dump(right) and isinstance(left, ast.Constant): require(isinstance(right, ast.Constant) and left.value == '24g' and right.value == '64g', 'Non-resource AST mutation') changes.append(right) require(len(changes) == 1, 'Expected exactly one memory literal AST mutation') changes[0].value = '24g' require(ast.dump(original_ast) == ast.dump(derived_ast), 'Frozen command AST changed') return derived @contextmanager def verified_baseline(root): scoped = root / 'scripts/candidate_batch06_support_v1' captured = {} for name, digest in PINS.items(): data = regular(scoped / name).read_bytes() require(hashlib.sha256(data).hexdigest() == digest, 'Scoped support SHA mismatch: ' + name) captured[name] = data derived = derive_baseline(captured['evaluate_reusable_batch06_image.py']) with tempfile.TemporaryDirectory(prefix='crossswe-pnpm-portable64-') as directory: snapshot = Path(directory) for name, data in captured.items(): target = snapshot / name; target.parent.mkdir(parents=True, exist_ok=True) with target.open('xb') as stream: stream.write(data) # Import only the verified private support snapshot, even in an embedded # caller with preexisting modules of the same names. names = [Path(name).stem for name in PINS if name.startswith('reusable_support/')] previous = {name: sys.modules.pop(name) for name in names if name in sys.modules} previous_path = sys.path[:] try: path = snapshot / 'evaluate_reusable_batch06_image.py' module = types.ModuleType('crossswe_portable99_pnpm_mem64_v1'); module.__file__ = str(path) exec(compile(derived, str(path), 'exec'), module.__dict__) module.ROOT = root; module.CODE = snapshot / 'reusable_support' yield module finally: sys.path[:] = previous_path for name in names: sys.modules.pop(name, None) sys.modules.update(previous) def durable(path, data): require(path.parent.is_dir() and not any(p.is_symlink() for p in (path.parent, *path.parent.parents)), 'Unsafe admission evidence directory') with path.open('xb') as stream: stream.write(data); stream.flush(); os.fsync(stream.fileno()) descriptor = os.open(path.parent, os.O_RDONLY | os.O_DIRECTORY) try: os.fsync(descriptor) finally: os.close(descriptor) def json_data(value): return (json.dumps(value, indent=2, sort_keys=True) + '\n').encode() def observe_host(cell): # Linux host, not container/cgroup observations. Any read or parse failure # propagates before create. Each world gets fresh, separately durable RAW. raw = Path('/proc/meminfo').read_bytes() rows = re.findall(rb'^MemAvailable:[ \t]+([0-9]+)[ \t]+kB[ \t]*$', raw, re.MULTILINE) require(len(rows) == 1, 'Unreadable Linux host MemAvailable') available = int(rows[0]) * 1024 free = shutil.disk_usage(cell).free return raw, {'observed_utc': datetime.datetime.now(datetime.timezone.utc).isoformat(), 'memory_source': '/proc/meminfo', 'memory_available_bytes': available, 'disk_path': str(cell), 'disk_free_bytes': free, 'minimum_memory_available_bytes': MIN_AVAILABLE, 'minimum_disk_free_bytes': MIN_DISK, 'admitted': available >= MIN_AVAILABLE and free >= MIN_DISK} def install_mem64_guard(module, root, wrapper_sha): original_run = module.run pending = {} def guarded(argv, target, timeout=180, check=True): target = Path(target) if argv[:2] == ['docker', 'create'] and 'crossswe.instance=' + IID in argv: name = argv[argv.index('--name') + 1] image = json.loads(regular(root / 'environments' / IID / 'image.json').read_text()) expected = ['docker', 'create', '--name', name, '--network', 'none', '--cpus', '8', '--memory', '64g', '--memory-swap', '64g', '--label', 'crossswe.owner=docker171-20261015', '--label', 'crossswe.instance=' + IID, image['image_ref'], 'sleep', 'infinity'] require(argv == expected and re.fullmatch(r'[^@\s]+@sha256:[0-9a-f]{64}', image['image_ref']) and re.fullmatch(r'sha256:[0-9a-f]{64}', image['config_digest']), 'Unexpected PNPM create identity/resource argv') cell = target.parent raw, observation = observe_host(cell) observation['world'] = cell.parent.name observation['create_argv'] = argv observation['meminfo_sha256'] = hashlib.sha256(raw).hexdigest() observation['derivation'] = {'base_sha256': BASE_SHA, 'derived_sha256': DERIVED_SHA, 'wrapper_sha256': wrapper_sha, 'support_sha256': PINS, 'change': "PNPM memory literal '24g' -> '64g'; all other original99 AST unchanged"} durable(cell / 'portable-mem64-host-meminfo.raw', raw) durable(cell / 'portable-mem64-admission.json', json_data(observation)) require(observation['admitted'], 'Host admission refused before PNPM create') pending[name] = (cell, image, target) result = original_run(argv, target, timeout=timeout, check=check) if argv[:2] == ['docker', 'start'] and len(argv) == 3 and argv[2] in pending: cell, image, create_target = pending.pop(argv[2]) # Original main has already set cid; failures here use its finally. inspected = cell / 'portable-mem64-container-inspect' original_run(['docker', 'inspect', argv[2]], inspected, timeout=180, check=True) cid = create_target.with_suffix('.stdout.log').read_text().strip() require(re.fullmatch(r'[0-9a-f]{64}', cid), 'Create did not return a full container ID') rows = json.loads(inspected.with_suffix('.stdout.log').read_text()) require(isinstance(rows, list) and len(rows) == 1, 'Expected one actual container inspect') info = rows[0]; host = info['HostConfig'] require(info['Id'] == cid and info['Name'] == '/' + argv[2] and info['Config']['Image'] == image['image_ref'] and info['Image'] in {image['config_digest'], image['registry_digest'], image['amd64_manifest_digest']} and host['NanoCpus'] == 8_000_000_000 and host['Memory'] == MEMORY and host['MemorySwap'] == MEMORY and host['NetworkMode'] == 'none' and info['Mounts'] == [], 'Actual PNPM container identity/resource/isolation mismatch') return result module.run = guarded def main(): root = Path(__file__).resolve().parents[1] wrapper_sha = hashlib.sha256(regular(Path(__file__)).read_bytes()).hexdigest() with verified_baseline(root) as module: install_mem64_guard(module, root, wrapper_sha) module.main() if __name__ == '__main__': main()