minima_pages.py
verification/tools/minima_pages.py
1#!/usr/bin/env python32"""Actual Minima owning wrappers over one supplied genuine initialized byte image."""3import native_sdk4from pathlib import Path5import argparse6import datetime7import fcntl8import hashlib9import json10import re11import subprocess12import sys13import tomllib14import uuid1516import checkpoint_seal17import kani18import minima_owner19import native_witness20import run_receipt21import stable_authority22from rust_source import complete_item2324ROOT = kani.ROOT25SDK = ROOT / 'cdk-rsx'26PRODUCT = SDK / 'crates/cdk-rsx-engine-minima/src/storage.rs'27LIB = PRODUCT.with_name('lib.rs')28PROOFS = ROOT / 'verification/proofs/minima-pages'29MANIFEST = Path(__file__).with_suffix('.toml')30MEMORY = [kani.PLATFORM / 'memory.rs', *[kani.PLATFORM / ('memory/' + name + '.rs')31 for name in ('error', 'region', 'page_pool')]]32SUITES = {33 'history': ('history.rs', {'storage::proofs::projected_directory_retirement_reuses_same_real_page_resource'}),34 'drop': ('drop.rs', {'storage::proofs::projected_nonempty_collection_drop_releases_only_its_owned_page'}),35 'borrow': ('borrow.rs', {'storage::proofs::actual_raw_block_borrow_validates_live_or_retired_owner'}),36}37NEGATIVES = {38 'transfer-negative': ('negative_disarmed_transfer_releases_its_page', 'NEGATIVE_CONTROL_MINIMA_TRANSFER_RELEASE'),39 'owner-negative': ('negative_retired_directory_owner_remains_live', 'NEGATIVE_CONTROL_MINIMA_DIRECTORY_OWNER'),40 'generation-negative': ('negative_directory_reuse_accepts_old_generation', 'NEGATIVE_CONTROL_MINIMA_DIRECTORY_GENERATION'),41 'neighbor-negative': ('negative_directory_retirement_releases_linear_neighbor', 'NEGATIVE_CONTROL_MINIMA_DIRECTORY_NEIGHBOR'),42}43for name,(function,_) in NEGATIVES.items():44 SUITES[name] = ('negative.rs', {'storage::proofs::' + function})45NATIVE_TESTS = ('positive', 'duplicate-view')46NATIVE = PROOFS / 'native'4748SCOPE = ('native64 source-selected ownership algorithms with explicit exclusive-Authority receiver/resource projection; '49 'actual Authority/CollectionId/Owner/Slot/Page/PageDirectory/Vec types, Global for Nyxus; '50 'one fresh real initialized4-page exclusive slice split into header/raw/directory/linear resources; '51 'supplied2-owner/3-live-page embedding and concrete independent generations; consumed raw transfer/disarm, '52 'actual directory mutation, selected truncation/retirement and dirty unpublished physical reservation; '53 'address identity stands for supplied same Root, proof-only resource wrappers/threaded Authority and explicit Drop-body calls; '54 'no actual Block/Collection representation, mutating Rc/RefCell refinement, clear/publication, startup/fresh growth, '55 'Nyxus origin, arbitrary histories, final provider teardown or Wasm/IC rollback theorem')5657BORROW_SCOPE = ('native64 unchanged actual Root/Block/BlockRef with Rc/RefCell/Vec, Global for Nyxus; '58 'one supplied genuine initialized4-page sole byte image and admitted2-owner/3-live-slot/linear embedding; '59 'one actual retained addressable Root/Block/byte owner, concrete generations with live-or-retired owner state; '60 'actual Block::borrow/private geometry and complete Root::validate_block read-only behavior; '61 'no Arena/Shared mutation, constructor/retirement execution, mutating Rc/RefCell refinement, '62 'Nyxus origin, arbitrary histories, provider teardown, physical stable-world construction or Wasm/IC theorem')63NATIVE_SCOPE = ('finite complete-SDK actual2-owner/directory/raw Block/linear ownership and provider lifetime history; '64 'native host witness, no IC rollback or formal whole-engine ownership theorem')656667def scope(suite):68 return BORROW_SCOPE if suite == 'borrow' else SCOPE6970PROOF_ENVIRONMENT_KEYS = ('CARGO_HOME', 'RUSTFLAGS', 'RUSTUP_HOME', 'RUSTUP_TOOLCHAIN',71 'RUSTUP_AUTO_INSTALL', 'RUSTC', 'CARGO', 'KANI_HOME', 'PATH',72 'PYTHONDONTWRITEBYTECODE')73NATIVE_ENVIRONMENT_KEYS = ('CARGO_HOME', 'CARGO_TARGET_DIR', 'TMPDIR', 'RUSTFLAGS', 'RUSTUP_HOME',74 'RUSTUP_AUTO_INSTALL', 'CARGO_BUILD_TARGET', 'CARGO_UNSTABLE_CHECKSUM_FRESHNESS',75 'CARGO_BUILD_FINGERPRINT', 'RUSTC', 'RUSTDOC', 'CARGO_NET_OFFLINE', 'PATH')767778def inputs(native=False):79 paths = [PRODUCT, LIB, *MEMORY, SDK / 'rust-toolchain.toml', MANIFEST,80 *[p for p in (ROOT / 'verification/tools').iterdir()81 if p.is_file() and p.suffix in ('.py', '.toml', '.nix', '.patch')],82 *[p for p in PROOFS.rglob('*') if p.is_file()]]83 if native:84 paths += [ROOT / 'tools/env.sh', SDK / 'tools/env.sh', SDK / '.cargo/config.toml']85 names = subprocess.check_output(['git', '-C', str(ROOT / 'cdk-rsx'), 'ls-files', '.'], text=True).splitlines()86 paths += [ROOT / 'cdk-rsx' / name for name in names if name.endswith(('.rs', '.toml', '.lock'))]87 return list(dict.fromkeys(paths))888990def manifest():91 data = tomllib.loads(MANIFEST.read_text())92 files = {str(path.relative_to(ROOT / 'verification/proofs')): path93 for path in (PROOFS / 'kani').glob('*.rs')}94 kani.require(set(data['files']) == set(files), 'Minima pages proof input inventory changed')95 for name, path in files.items():96 kani.require(kani.sha(path) == data['files'][name], 'Minima pages proof/support pin changed: ' + name)97 text = path.read_text()98 if path.name in ('resources.rs', 'borrow.rs'):99 assumption = 'kani::assume(bytes.len() == 4 * BLOCK_BYTES as usize);'100 kani.require(text.count(assumption) == 1, 'Minima supplied byte-resource shape changed')101 text = text.replace(assumption, '')102 kani.require(re.search(r'\bkani\s*::\s*(?:assume|stub|stub_verified|requires|ensures|modifies)\b', text) is None,103 'Minima pages unchecked algorithm assumption/stub or contract instrumentation')104 return data105106107def replace_exact(text, old, new, count=1):108 kani.require(count > 0 and text.count(old) == count, 'Minima receiver projection anchor changed: ' + old)109 positions = [match.start() for match in re.finditer(re.escape(old), text)]110 mapped = text.replace(old, new)111 restored = mapped112 for index in reversed(range(len(positions))):113 at = positions[index] + index * (len(new) - len(old))114 kani.require(restored[at:at + len(new)] == new, 'Minima projected edit moved')115 restored = restored[:at] + old + restored[at + len(new):]116 kani.require(restored == text, 'Minima projection is not reversible')117 return mapped118119120def selected_storage():121 source, library = PRODUCT.read_text(), LIB.read_text()122 constants = [line for text in (source, library) for line in text.splitlines()123 if any(line.startswith(prefix + name + ':') for prefix in ('const ', 'pub const ')124 for name in ('LIVE', 'INLINE_PAGES', 'NODE_BYTES', 'BLOCK_BYTES', 'NODES_PER_BLOCK'))]125 kani.require(len(constants) == 5, 'Minima projection geometry changed')126 declarations = [minima_owner.declaration(source, marker) for marker in (127 'pub struct CollectionId {', 'struct Owner {', 'struct Slot {', 'struct Page {')]128 declarations += [complete_item(source, marker) for marker in (129 'impl Page {', 'struct Authority {', '#[repr(C)]\nstruct PageDirectory',130 'impl PageDirectory {', 'impl core::ops::Index<usize> for PageDirectory')]131 original, projected = {}, {}132 root = complete_item(source, 'impl Root {')133 for name, signature, mutable in (134 ('owner', 'fn selected_owner(authority: &mut Authority, domain:u64) -> Result<CollectionId>', True),135 ('validate', 'fn selected_validate(authority: &Authority, domain:u64, id:CollectionId) -> Result<()>', False),136 ('release', 'fn selected_release(authority: &mut Authority, page:Page)', True),137 ('retire_owner', 'fn selected_retire_owner(authority: &mut Authority, id:CollectionId)', True)):138 item = complete_item(root, 'fn ' + name + '(')139 body = item[item.index('{')+1:item.rfind('}')]140 binding = ' let ' + ('mut ' if mutable else '') + 'authority = self.inner.authority.borrow' + ('_mut' if mutable else '') + '();\n'141 kani.require(body.count(binding) == 1, 'Minima exclusive borrow boundary changed')142 mapped = body.replace(binding, '')143 if name in ('owner', 'validate'):144 mapped = replace_exact(mapped, 'self.inner.domain', 'domain')145 kani.require('self.' not in mapped, 'Unbound projected Root receiver')146 original[name], projected[name] = item, signature + ' {' + mapped + '}\n'147 operations = (148 ('into_page', complete_item(complete_item(source, 'impl Block {'), 'fn into_page('),149 'fn selected_into_page(page:&mut Page, supplied_root:*const Authority, supplied_owner:CollectionId, root:*const Authority, owner:CollectionId) -> Result<Page>',150 [('root.same(&self.authority.root)', 'core::ptr::eq(root, supplied_root)'),151 ('self.authority.owner', 'supplied_owner'), ('&mut self.page', 'page')]),152 ('block_drop', complete_item(source, 'impl Drop for Block {'),153 'fn selected_block_drop(authority:&mut Authority, page:Page)',154 [('self.page', 'page'), ('self.authority.root.release(page)', 'selected_release(authority, page)')]),155 ('collection_drop', complete_item(source, 'impl Drop for Collection {'),156 'fn selected_collection_drop(blocks:&mut PageDirectory, authority:&mut Authority, owner:CollectionId)',157 [('self.blocks', 'blocks'), ('self.authority.root.release(blocks[index])', 'selected_release(authority, blocks[index])'),158 ('self.authority.root.retire_owner(self.authority.owner)', 'selected_retire_owner(authority, owner)')]),159 ('truncate', complete_item(complete_item(source, 'impl Collection {'), 'pub fn truncate_nodes('),160 'fn selected_truncate(directory:&mut PageDirectory, authority:&mut Authority, nodes:u64) -> Result<()>',161 [(' self.validate(storage)?;\n', ''), ('self.blocks', 'directory'),162 ('self.authority.root.release(directory[index])', 'selected_release(authority, directory[index])')]),163 )164 for name, item, signature, changes in operations:165 method = complete_item(item, 'fn drop(') if name.endswith('_drop') else item166 body = method[method.index('{')+1:method.rfind('}')]167 for old, new in changes:168 if new:169 body = replace_exact(body, old, new, body.count(old))170 else:171 kani.require(body.count(old) == 1, 'Minima projected same-authority validation boundary changed')172 body = body.replace(old, '')173 kani.require('self.' not in body and 'storage' not in body, 'Unbound projected ownership receiver')174 original[name], projected[name] = item, signature + ' {' + body + '}\n'175 shared = complete_item(source, 'impl<M: Memory> Shared<M>')176 claim = complete_item(shared, 'fn claim(&self)')177 a = claim.index(' let reused = authority.free != 0;')178 b = claim.index(' let mut memory = self.memory.borrow_mut();')179 planning = claim[a:b]180 a = claim.index(' authority.free = authority.slots[(physical - 1) as usize].next_free;')181 b = claim.index(' Self::clear(&mut *memory, physical);')182 update = claim[a:b]183 original['claim_prefix'], original['reuse_metadata'] = planning, update184 projected['claim_prefix'] = 'fn selected_claim_prefix(authority:&Authority)->Result<(bool,u64,u64)> {\n' + planning + '\nOk((reused,physical,generation))\n}'185 projected['reuse_metadata'] = 'fn selected_reuse_metadata(authority:&mut Authority,physical:u64,generation:u64) {\n' + update + '\n}'186 prefix = ('use crate::{Error,Result};\nuse std::alloc::Global as Nyxus;\n'187 'type RetainedVec<T> = std::vec::Vec<T, Nyxus>;\n')188 body = prefix + '\n'.join(constants + declarations + list(projected.values())) + '\n'189 fragments = {'original_' + key: hashlib.sha256(value.encode()).hexdigest() for key,value in original.items()}190 fragments.update({'projected_' + key: hashlib.sha256(value.encode()).hexdigest() for key,value in projected.items()})191 fragments.update({'declaration' + str(i):hashlib.sha256(value.encode()).hexdigest() for i,value in enumerate(constants + declarations)})192 return body, fragments193194195def actual_borrow_storage():196 source, library = PRODUCT.read_text(), LIB.read_text()197 declarations = minima_owner.fragments(source)198 constants = [line for text in (source,library) for line in text.splitlines()199 if line.startswith(('const LIVE:', 'pub const BLOCK_BYTES:'))]200 kani.require(len(constants) == 2, 'Actual raw borrow geometry changed')201 prefix = ('use crate::{Error,Result};\nuse std::alloc::Global as Nyxus;\n'202 'use std::rc::Rc; use core::cell::{Cell,RefCell};\n'203 'type RetainedVec<T> = std::vec::Vec<T, Nyxus>;\n')204 fragments = {'actual_borrow_' + str(i):hashlib.sha256(value.encode()).hexdigest()205 for i,value in enumerate(constants + declarations)}206 return prefix + '\n'.join(constants + declarations), fragments207208209def staged(suite):210 source, fragments = actual_borrow_storage() if suite == 'borrow' else selected_storage()211 tail = '\n#[cfg(kani)] mod proofs { use super::*;\n'212 for name in ((SUITES[suite][0],) if suite == 'borrow' else ('resources.rs', SUITES[suite][0])):213 tail += 'include!(' + json.dumps(str(PROOFS / 'kani' / name)) + ');\n'214 tail += '}\n'215 files = {'main.rs': ('#![feature(allocator_api)]\n#![allow(dead_code,unexpected_cfgs)]\n'216 'mod error; pub use error::{MemoryError as Error,MemoryResult as Result};\nmod storage;\nfn main() {}\n').encode(),217 'storage.rs': (source + tail).encode(), 'error.rs': MEMORY[1].read_bytes()}218 return files, fragments219220221def stage(output, suite):222 files, fragments = staged(suite)223 for name, data in files.items():224 path = output / name225 path.parent.mkdir(parents=True, exist_ok=True)226 path.write_bytes(data)227 return {name: kani.sha(output / name) for name in files}, fragments228229230def verify_stage(output, suite):231 files, _ = staged(suite)232 kani.require(all(run_receipt.regular(output / name) and (output / name).read_bytes() == data233 for name, data in files.items()), 'Minima pages canonical source changed')234235236def register():237 for suite, (_, names) in SUITES.items():238 kani.EXPECTED_HARNESSES['minima-pages-' + suite] = names239 for suite, (_, marker) in NEGATIVES.items():240 kani.NEGATIVE_CONTROLS['minima-pages-' + suite] = marker241242def snapshot(paths):243 return {str(path.relative_to(ROOT)): kani.sha(path) for path in paths}244245def directory(label):246 output = kani.TEMP / ('minima-pages-' + datetime.datetime.now(datetime.timezone.utc).strftime('%Y%m%dT%H%M%SZ')247 + '-' + label + '-' + uuid.uuid4().hex[:8])248 output.mkdir()249 return output250251def proof_environment():252 env = kani.environment()253 env['CARGO_HOME'] = str(kani.TEMP / 'minima-pages-kani-cargo-home')254 env['RUSTFLAGS'] = '--edition=2024 -A dead_code --check-cfg=cfg(test)'255 return env, {name: env[name] for name in PROOF_ENVIRONMENT_KEYS}256257def proof_command(output, suite):258 argv = [kani.LAUNCHER / 'kani', output / 'main.rs', '--target-dir', output / 'target',259 '-Z', 'unstable-options', '--harness-timeout', '90s', '--exact', '--export-json', output / 'result.json']260 for name in sorted(SUITES[suite][1]): argv += ['--harness', name]261 return list(map(str, argv))262263def validate_proof_declaration(metadata, output, suite):264 _, settings = proof_environment()265 kani.require(metadata['command'] == proof_command(output, suite)266 and metadata['environment'] == settings267 and metadata['manifest_sha256'] == kani.sha(MANIFEST),268 'Minima pages proof command/settings differ from canonical declaration')269270def validate_report(report, suite, code, manifest):271 key = 'minima-pages-' + suite272 result = kani.validate_report(report, key, code, manifest=manifest)273 if suite in NEGATIVES:274 rows = kani.kani_obligations.required(key, SUITES[suite][1], manifest=manifest)275 marker = kani.kani_obligations.normalized(json.dumps(NEGATIVES[suite][1]))276 expected = [item for values in rows.values() for item in values277 if item.category == 'assertion' and item.description == marker]278 failed = [check for row in report['verification_results']['results'] for check in row['checks']279 if check['status'] == 'Failure']280 kani.require(len(expected) == len(failed) == 1281 and kani.kani_obligations.check_identity(failed[0]) == expected[0],282 'Minima pages negative failed away from designated source assertion')283 return result284285def check_sources(paths, before, receipt, suite, output, tools):286 receipt.verify()287 kani.require(snapshot(paths) == before, 'Minima pages source changed')288 verify_stage(output, suite)289 kani.kani_install.verify(tools, kani.TEMP)290291def run(suite):292 register()293 run_receipt.checkout(ROOT)294 paths = inputs()295 before = snapshot(paths)296 inventory = manifest()297 kani.kani_obligations.required('minima-pages-' + suite, SUITES[suite][1], manifest=inventory)298 tools = kani.kani_install.capture(kani.TEMP)299 output = directory(suite)300 files, fragments = stage(output, suite)301 env, settings = proof_environment()302 argv = proof_command(output, suite)303 receipt = run_receipt.write(ROOT, output, {'sources': before, 'staged': files, 'binaries': tools,304 'scope': scope(suite), 'sourceFragments': fragments, 'suite': suite, 'command': list(map(str, argv)),305 'manifest_sha256': kani.sha(MANIFEST), 'environment': settings})306 print('MINIMA_PAGES_RUN', suite, output, flush=True)307 with (output / 'run.log').open('w') as log:308 result = subprocess.run(argv, cwd=ROOT, env=env, stdout=log, stderr=subprocess.STDOUT)309 (output / 'run.exit').write_text(str(result.returncode) + '\n')310 check_sources(paths, before, receipt, suite, output, tools)311 summary = kani.validate_run(output, 'minima-pages-' + suite, result.returncode, manifest=inventory)312 validate_report(json.loads((output / 'result.json').read_text()), suite, result.returncode, inventory)313 seal = checkpoint_seal.capture(output, kind='minima-pages-kani', qualification={'suite': suite, 'summary': summary})314 print('MINIMA_PAGES_PASS', suite, output, seal, flush=True)315 return output, seal316317def native_case(stdout, stderr, code, name):318 if name == 'positive':319 kani.require(type(code) is int and code == 0 and not stderr320 and stdout == 'STABLE_AUTHORITY_NATIVE_OK\n', 'Native complete owning history failed')321 else:322 kani.require(name == 'duplicate-view' and type(code) is int and code == 101 and not stdout323 and stderr.count('panicked at') == 1 and stderr.count('Hylix virtual memory already leased') == 1324 and 'unreachable' not in stderr, 'Native virtual-lease rejection moved')325326327def native_artifact(output, rows):328 project = output / 'project'329 artifacts = [row for row in rows if row.get('reason') == 'compiler-artifact'330 and row.get('executable') and row.get('manifest_path') == str(project / 'Cargo.toml')331 and row['target']['name'] == 'stable-authority-witness'332 and row['target']['src_path'] == str(project / 'main.rs')333 and row['target']['kind'] == ['bin'] and row['profile']['test'] is False]334 kani.require(len(artifacts) == 1, 'Native history lacks one exact full-SDK owning binary')335 artifact = Path(artifacts[0]['executable'])336 prefix = output / 'target' / kani.PIN['target'] / 'debug'337 kani.require(artifact.is_relative_to(prefix), 'Native owning binary leaves its private target')338 kani.require(artifact.name == 'stable-authority-witness', 'Native owning executable identity changed')339 return artifact340341342def native_commands(cargo, output):343 project = output / 'project'344 metadata = [str(cargo), 'metadata', '--manifest-path', str(project / 'Cargo.toml'),345 '--locked', '--offline', '--format-version', '1']346 build = [str(cargo), 'build', '--manifest-path', str(project / 'Cargo.toml'), '--locked', '--offline',347 '--target', kani.PIN['target'], '--bin', 'stable-authority-witness', '--message-format=json']348 return metadata, build349350351def native_stage(output):352 files = stable_authority.native_sources(NATIVE)353 for name,data in files.items():354 path = output / 'project' / name355 path.parent.mkdir(parents=True, exist_ok=True)356 path.write_bytes(data)357 return {'project/' + name:kani.sha(output / 'project' / name) for name in files}358359360def verify_native_stage(output):361 files = stable_authority.native_sources(NATIVE)362 kani.require(all(run_receipt.regular(output / 'project' / name)363 and (output / 'project' / name).read_bytes() == data for name,data in files.items()),364 'Native owning canonical source relocation changed')365366367def validate_native_declaration(metadata, data, cargo, env, sources, output):368 metadata_command, build_command = native_commands(cargo, output)369 kani.require(data['metadata_command'] == metadata_command and data['build_command'] == build_command370 and metadata['environment'] == {name: env[name] for name in NATIVE_ENVIRONMENT_KEYS}371 and metadata['environmentSources'] == sources,372 'Minima pages native command/settings differ from canonical declaration')373374def native():375 run_receipt.checkout(ROOT)376 paths, output = inputs(native=True), directory('native')377 before = snapshot(paths)378 compiler = native_witness.compiler_identity()379 cargo = (Path(compiler['path']).parent / 'cargo').resolve()380 binaries = {'compiler': compiler, 'cargo': {'path': str(cargo),381 'sha256': native_witness.executable_hash(cargo)}}382 env, env_sources = native_sdk.native_environment(output, Path(compiler['path']))383 environment = {name: env[name] for name in NATIVE_ENVIRONMENT_KEYS}384 staged = native_stage(output)385 declared = output / 'native-tests.json'386 declared.write_text(json.dumps(NATIVE_TESTS, indent=2) + '\n')387 receipt = run_receipt.write(ROOT, output, {'sources': before,388 'staged': {**staged, 'native-tests.json': kani.sha(declared)}, 'binaries': binaries,389 'scope': NATIVE_SCOPE,390 'tests': list(NATIVE_TESTS), 'environment': environment, 'environmentSources': env_sources})391 print('MINIMA_PAGES_NATIVE', output, flush=True)392 metadata_command, build_command = native_commands(cargo, output)393 metadata = subprocess.run(metadata_command, env=env, cwd=output / 'project', capture_output=True, text=True, timeout=120)394 (output / 'metadata.stdout').write_text(metadata.stdout)395 (output / 'metadata.stderr').write_text(metadata.stderr)396 (output / 'metadata.exit').write_text(str(metadata.returncode) + '\n')397 kani.require(metadata.returncode == 0, 'Native SDK locked metadata failed: ' + metadata.stderr)398 graph = json.loads(metadata.stdout)399 dependencies = native_sdk.dependency_snapshot(graph, output / 'project')400 sealed = {name: kani.sha(output / name) for name in ('metadata.stdout', 'metadata.stderr', 'metadata.exit')}401402 def unchanged():403 receipt.verify()404 verify_native_stage(output)405 kani.require(snapshot(paths) == before, 'Native ownership SDK/source changed')406 kani.require(native_witness.compiler_identity() == compiler, 'Native ownership compiler changed')407 native_witness.executable_hash(cargo, binaries['cargo']['sha256'])408 kani.require(all(run_receipt.regular(Path(path)) and kani.sha(Path(path)) == digest409 for path, digest in env_sources.items()), 'Native ownership environment source changed')410 kani.require(native_sdk.dependency_snapshot(graph, output / 'project') == dependencies,411 'Native ownership registry dependency changed')412 kani.require(all(run_receipt.regular(output / name) and kani.sha(output / name) == digest413 for name, digest in sealed.items()), 'Earlier native pages artifact changed')414415 unchanged()416 with (output / 'build.stdout').open('w') as stdout, (output / 'build.stderr').open('w') as stderr:417 built = subprocess.run(build_command, env=env, cwd=output / 'project', stdout=stdout, stderr=stderr, timeout=180)418 (output / 'build.exit').write_text(str(built.returncode) + '\n')419 unchanged()420 kani.require(built.returncode == 0, 'Native full-SDK Minima test compilation failed: ' + str(output))421 rows = [json.loads(line) for line in (output / 'build.stdout').read_text().splitlines()]422 artifact = native_artifact(output, rows)423 sealed.update({name: kani.sha(output / name) for name in ('build.stdout', 'build.stderr', 'build.exit')})424 sealed[str(artifact.relative_to(output))] = native_witness.executable_hash(artifact)425 tests = {}426 for index, name in enumerate(NATIVE_TESTS):427 unchanged()428 command = [str(artifact)] + ([] if name == 'positive' else [name])429 case = subprocess.run(command, env=env, cwd=output / 'project', capture_output=True, text=True, timeout=30)430 prefix = 'case-' + str(index)431 for suffix, content in (('stdout', case.stdout), ('stderr', case.stderr), ('exit', str(case.returncode) + '\n')):432 (output / (prefix + '.' + suffix)).write_text(content)433 native_case(case.stdout, case.stderr, case.returncode, name)434 sealed.update({prefix + '.' + suffix: kani.sha(output / (prefix + '.' + suffix))435 for suffix in ('stdout', 'stderr', 'exit')})436 tests[name] = {'command': command, 'prefix': prefix, 'exit': case.returncode}437 unchanged()438 record = {'metadata_command': metadata_command, 'metadata_exit': metadata.returncode,439 'build_command': build_command, 'build_exit': built.returncode, 'tests': tests,440 'artifact': str(artifact.relative_to(output)), 'dependencies': dependencies}441 (output / 'native.json').write_text(json.dumps(record, indent=2) + '\n')442 external = {**dependencies, **env_sources, compiler['path']: compiler['sha256'],443 str(cargo): binaries['cargo']['sha256']}444 seal = checkpoint_seal.capture(output, kind='minima-pages-native', qualification={'cases': len(tests)},445 external=external)446 print('MINIMA_PAGES_NATIVE_PASS', output, seal, flush=True)447 return output, seal448449def audit_native(output, metadata, seal):450 current = run_receipt.checkout(ROOT)451 record = checkpoint_seal.verify(output, seal, factory=current['factory'], sdk=current['sdk'], tools=metadata['binaries'])452 kani.require(record['kind'] == 'minima-pages-native' and metadata['scope'] == NATIVE_SCOPE453 and metadata['sources'] == snapshot(inputs(native=True)),454 'Native ownership source closure changed')455 compiler = native_witness.compiler_identity()456 cargo = (Path(compiler['path']).parent / 'cargo').resolve()457 kani.require(metadata['binaries'] == {'compiler': compiler, 'cargo': {'path': str(cargo),458 'sha256': native_witness.executable_hash(cargo)}}, 'Native ownership tool identity changed')459 env, sources = native_sdk.native_environment(output, Path(compiler['path']))460 data = json.loads((output / 'native.json').read_text())461 validate_native_declaration(metadata, data, cargo, env, sources, output)462 verify_native_stage(output)463 graph = json.loads((output / 'metadata.stdout').read_text())464 deps = native_sdk.dependency_snapshot(graph, output / 'project')465 kani.require(data['dependencies'] == deps and record['external'] == {**deps, **sources,466 compiler['path']: compiler['sha256'], str(cargo): metadata['binaries']['cargo']['sha256']},467 'Native ownership external input closure differs')468 kani.require(data['metadata_exit'] == data['build_exit'] == 0469 and (output / 'metadata.exit').read_text() == (output / 'build.exit').read_text() == '0\n'470 and set(data['tests']) == set(NATIVE_TESTS) and metadata['tests'] == list(NATIVE_TESTS)471 and json.loads((output / 'native-tests.json').read_text()) == list(NATIVE_TESTS),472 'Native ownership execution inventory changed')473 artifact = native_artifact(output, [json.loads(line) for line in (output / 'build.stdout').read_text().splitlines()])474 kani.require(artifact == output / data['artifact'], 'Native ownership selected binary changed')475 native_witness.executable_hash(artifact)476 for index, name in enumerate(NATIVE_TESTS):477 case = data['tests'][name]478 prefix = 'case-' + str(index)479 kani.require(case == {'command': [str(artifact)] + ([] if name == 'positive' else [name]),480 'prefix': prefix, 'exit': 0 if name == 'positive' else 101}, 'Native ownership test command changed')481 code = int((output / (prefix + '.exit')).read_text())482 native_case((output / (prefix + '.stdout')).read_text(),483 (output / (prefix + '.stderr')).read_text(), code, name)484485def audit(output, seal):486 register()487 output = Path(output).resolve()488 metadata = json.loads((output / 'inputs.json').read_text())489 current = run_receipt.checkout(ROOT)490 if 'tests' in metadata:491 audit_native(output, metadata, seal)492 print('MINIMA_PAGES_AUDIT_PASS', output, seal, flush=True)493 return494 kind = 'minima-pages-kani' if 'suite' in metadata else 'minima-pages-body-control'495 record = checkpoint_seal.verify(output, seal, factory=current['factory'], sdk=current['sdk'], tools=metadata['binaries'])496 kani.require(record['kind'] == kind, 'Wrong pages artifact kind')497 paths = inputs()498 kani.require(metadata['sources'] == snapshot(paths), 'Minima pages audit input closure changed')499 if kind == 'minima-pages-kani':500 suite = metadata['suite']501 validate_proof_declaration(metadata, output, suite)502 verify_stage(output, suite)503 _, fragments = staged(suite)504 kani.require(metadata['sourceFragments'] == fragments and metadata['scope'] == scope(suite),505 'Minima pages source fragments/scope changed')506 kani.kani_install.verify(metadata['binaries'], kani.TEMP)507 code = int((output / 'run.exit').read_text())508 inventory = manifest()509 kani.validate_run(output, 'minima-pages-' + suite, code, manifest=inventory)510 validate_report(json.loads((output / 'result.json').read_text()), suite, code, inventory)511 else:512 files, _ = staged('history')513 files['storage.rs'] = files['storage.rs'].replace(b'Ok(core::mem::replace(page, Page::EMPTY))', b'Ok(*page)', 1)514 kani.require(all(run_receipt.regular(output / name) and (output / name).read_bytes() == data515 for name, data in files.items()), 'Body-control exact mutation changed')516 print('MINIMA_PAGES_AUDIT_PASS', output, seal, flush=True)517518def main():519 parser = argparse.ArgumentParser(description=__doc__)520 parser.add_argument('suite', choices=('all', 'native', 'body-control', 'audit', *SUITES), nargs='?', default='all')521 parser.add_argument('--output', type=Path)522 parser.add_argument('--seal-sha256')523 args = parser.parse_args()524 with (kani.TEMP / '.minima-pages.lock').open('w') as lock:525 fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB)526 if args.suite == 'audit':527 kani.require(args.output is not None and args.seal_sha256 is not None, 'Audit needs output and original seal SHA256')528 audit(args.output, args.seal_sha256)529 return530 artifacts = []531 if args.suite in ('all', 'native'): artifacts.append(native())532 if args.suite in ('all', 'body-control'): artifacts.append(body_control())533 for suite in SUITES if args.suite == 'all' else (() if args.suite in ('native', 'body-control') else (args.suite,)):534 artifacts.append(run(suite))535 for output, seal in artifacts: audit(output, seal)536 print('MINIMA_PAGES_COHORT', json.dumps({str(output): seal for output, seal in artifacts}), flush=True)537538539def body_control():540 run_receipt.checkout(ROOT)541 paths, output = inputs(), directory('body-control')542 before = snapshot(paths)543 files, _ = stage(output, 'history')544 path = output / 'storage.rs'545 source = path.read_text()546 anchor = 'Ok(core::mem::replace(page, Page::EMPTY))'547 kani.require(source.count(anchor) == 1, 'Minima move/disarm source anchors changed')548 path.write_text(source.replace(anchor, 'Ok(*page)', 1))549 files['storage.rs'] = kani.sha(path)550 receipt = run_receipt.write(ROOT, output, {'sources': before, 'staged': files, 'binaries': {},551 'control': 'resealed omitted raw Block disarm'})552 try:553 verify_stage(output, 'history')554 except RuntimeError as error:555 kani.require(str(error) == 'Minima pages canonical source changed', 'Unrelated pages body rejection')556 receipt.verify()557 kani.require(snapshot(paths) == before, 'Page control inputs changed')558 seal = checkpoint_seal.capture(output, kind='minima-pages-body-control', qualification={'status': 'EXPECTED_REJECTION'})559 print('MINIMA_PAGES_BODY_REJECTED', output, seal, flush=True)560 return output, seal561 raise RuntimeError('Missing raw Block disarm was admitted')562563564if __name__ == '__main__':565 try: main()566 except (RuntimeError,subprocess.CalledProcessError,BlockingIOError,ValueError,KeyError) as error:567 print(str(error),file=sys.stderr)568 raise SystemExit(1)