shared_tail.py
verification/tools/shared_tail.py
1#!/usr/bin/env python32"""Exact raw-origin shared-slice components, with an explicit allocator seam."""3import native_sdk4from pathlib import Path5import argparse6import datetime7import fcntl8import hashlib9import json10import subprocess11import sys12import tomllib13import uuid1415import checkpoint_seal16import creusot17import kani18import kani_obligations19import native_witness20import provider_resource21import run_receipt22import stable_authority23from rust_source import complete_item2425ROOT = kani.ROOT26PROOFS = ROOT / 'verification/proofs/shared-tail'27PIN_PATH = Path(__file__).with_suffix('.toml')28COLLECTIONS = ROOT / 'cdk-rsx/crates/cdk-rsx-collections/src/nyxus'29PRODUCTS = {'shared': COLLECTIONS / 'shared.rs', 'span': COLLECTIONS / 'span.rs'}30SUITES = {31 'origin': ('harnesses.rs', 'actual_raw_origin', ('raw_origin',)),32 'append': ('harnesses.rs', 'actual_append_live_prefix', ('append_live',)),33 'cleanup': ('harnesses.rs', 'actual_unpublished_cleanup', ('cleanup_destination',)),34 'partial': ('harnesses.rs', 'actual_partial_initialization', ('initialized_prefix',)),35 'prefix-negative': ('negative.rs', 'prefix_negative', ('append_live',)),36 'count-negative': ('negative.rs', 'count_negative', ('append_live',)),37 'reset-negative': ('negative.rs', 'reset_negative', ('cleanup_destination',)),38}39NEGATIVES = {'prefix-negative': 'NEGATIVE_CONTROL_SHARED_TAIL_PREFIX',40 'count-negative': 'NEGATIVE_CONTROL_SHARED_TAIL_COUNT',41 'reset-negative': 'NEGATIVE_CONTROL_SHARED_TAIL_RESET'}42SCOPE = ('native64 little-endian; exact production Header/layout/elements/Building/Release, '43 'zeroed_for_spans, len/range/strong_count/Clone/Drop, SharedBytes range, '44 'UnpublishedBytes Drop and complete SharedBytesBuilder; real Global allocation '45 'supplies an explicit lower allocator seam, NOT actual Nyxus Heap/provider refinement; '46 'capacity4 bytes and capacity3 non-Copy inline elements, fixed owning history; '47 'Kani memory checks do NOT establish Rust alias/provenance permissions; '48 'panic-unwind composition is native finite execution only; no IC/KEEP theorem')49NATIVE_SCOPE = 'finite native actual product allocator/public append unwinding and generic constructor/final Drop; ' + SCOPE50OPEN_SCOPE = ('OPEN attempted actual Header.elements pointer-origin permission bridge; '51 'no supplied origin axiom, no permission export admitted')52COHORT_SCOPE = SCOPE + '; two explicitly OPEN Creusot origin bridges, no permission export'53BASE_PATH = '/run/current-system/sw/bin:/usr/bin:/bin'54DECLARATION_KEYS = {'scope', 'commands', 'cwd', 'environment', 'target', 'execution_profile'}555657def pin(): return tomllib.loads(PIN_PATH.read_text())585960def fragments(sources=None):61 sources = {key: path.read_text() for key, path in PRODUCTS.items()} if sources is None else sources62 cfg = pin()63 kani.require({name: hashlib.sha256(text.encode()).hexdigest() for name, text in sources.items()}64 == cfg['products'], 'Strict source correspondence: complete production source changed')65 shared, span = sources['shared'], sources['span']66 select = complete_item67 result = {}68 for name, signature in (69 ('header', '#[repr(C)]\nstruct Header<T>'), ('layout', 'fn layout<T>'),70 ('elements', 'fn elements<T>'), ('building', 'struct Building<T:'),71 ('building_impl', 'impl<T: NyxusData> Building<T>'),72 ('building_drop', 'impl<T: NyxusData> Drop for Building<T>'),73 ('release', 'struct Release {'), ('release_drop', 'impl Drop for Release'),74 ('owner', '#[repr(transparent)]\npub struct SharedSlice<T:'),75 ('clone', 'impl<T: NyxusData> Clone for SharedSlice<T>'),76 ('owner_drop', 'impl<T: NyxusData> Drop for SharedSlice<T>')):77 result[name] = select(shared, signature)78 byte_impl = select(shared, 'impl SharedSlice<u8>')79 result['zeroed'] = 'impl SharedSlice<u8> {\n' + select(byte_impl, ' pub(super) fn zeroed_for_spans(') + '\n}'80 owner_impl = select(shared, 'impl<T: NyxusData> SharedSlice<T>')81 result['projections'] = 'impl<T: NyxusData> SharedSlice<T> {\n' + '\n'.join(82 select(owner_impl, signature) for signature in (' pub fn len(',83 ' pub(super) unsafe fn as_range_unchecked(', ' pub fn strong_count(')) + '\n}'84 for name, signature in (85 ('bytes', '#[repr(C)]\n#[derive(Clone)]\npub struct SharedBytes'),86 ('builder', 'pub struct SharedBytesBuilder'),87 ('unpublished', 'struct UnpublishedBytes'),88 ('unpublished_drop', 'impl Drop for UnpublishedBytes'),89 ('append', 'impl SharedBytesBuilder')):90 result[name] = select(span, signature)91 bytes_impl = select(span, 'impl SharedBytes {')92 result['byte_projection'] = 'impl SharedBytes {\n' + '\n'.join(93 select(bytes_impl, signature) for signature in (' pub fn as_slice(', ' pub fn len(')) + '\n}'94 digests = {name: hashlib.sha256(text.encode()).hexdigest() for name, text in result.items()}95 kani.require(digests == cfg['fragments'], 'Strict source correspondence: selected body changed')96 return result979899def inputs(native=False):100 # Broad, static source closure includes every imported verification helper101 # and its pins; imports cannot silently disappear from the receipt.102 paths = [*sorted(path for path in (ROOT / 'verification/tools').rglob('*')103 if path.is_file() and path.suffix in ('.py', '.toml', '.patch', '.nix')),104 *PRODUCTS.values(), *sorted(p for p in PROOFS.rglob('*') if p.is_file())]105 if native:106 paths += [ROOT / 'tools/env.sh', ROOT / 'cdk-rsx/tools/env.sh']107 names = subprocess.check_output(['git', '-C', str(ROOT / 'cdk-rsx'), 'ls-files', '.'], text=True).splitlines()108 paths += [ROOT / 'cdk-rsx' / name for name in names if name.endswith(('.rs', '.toml', '.lock'))]109 return list(dict.fromkeys(paths))110111112def snapshot(paths): return {str(path.relative_to(ROOT)): kani.sha(path) for path in paths}113114115def stage_sources(output, suite, moved=False):116 selected = fragments()117 files = {'fragments/' + name + '.rs': (source + '\n').encode() for name, source in selected.items()}118 body = '#![feature(allocator_api)]\n#![allow(dead_code)]\n'119 body += '#[cfg(not(all(target_pointer_width="64",target_endian="little")))] compile_error!("native64 little-endian required");\n'120 body += 'mod selected {\ninclude!(' + json.dumps(str(PROOFS / 'support.rs')) + ');\n'121 body += '\n'.join('include!(' + json.dumps(str(output / 'fragments' / (name + '.rs'))) + ');' for name in selected)122 body += '\ninclude!(' + json.dumps(str(PROOFS / 'callers.rs')) + ');\n'123 body += 'include!(' + json.dumps(str(PROOFS / ('moved.rs' if moved else SUITES[suite][0]))) + ');\n}\nfn main() {}\n'124 files['main.rs'] = body.encode()125 return files126127128def stage(output, suite, moved=False):129 files = stage_sources(output, suite, moved)130 (output / 'fragments').mkdir()131 for name, source in files.items(): (output / name).write_bytes(source)132 return {name: kani.sha(output / name) for name in files}133134135def verify_stage(output, suite=None, moved=False):136 for name, text in fragments().items():137 kani.require((output / 'fragments' / (name + '.rs')).read_text() == text + '\n',138 'Strict staged body correspondence changed')139 if suite is not None:140 kani.require(all((output / name).read_bytes() == content141 for name, content in stage_sources(output, suite, moved).items()),142 'Strict staged caller correspondence changed')143144145def manifest(suite):146 kani.require(suite in SUITES, 'Unknown shared-tail semantic population')147 declarations = {}148 for name, (filename, harness, helpers) in SUITES.items():149 selectors = ['shared-tail/callers.rs::' + helper for helper in helpers]150 if name == 'partial': selectors += ['shared-tail/support.rs::drop']151 declarations['shared-tail-' + name] = {152 'selected::' + harness: [*selectors, 'shared-tail/' + filename + '::' + harness]}153 return {'files': pin()['files'], 'suites': declarations}154155156def product_obligations(output, suite):157 # Enumerate source assertions independently before execution, from exactly158 # reconstructed complete source items. Layout's const offset assertion is159 # discharged by compilation; its debug assertion is a backend check.160 selectors = [('building_impl', 'finish')]161 if suite == 'partial': selectors += [('building_impl', 'push')]162 if suite not in ('origin', 'partial'): selectors += [('append', 'append_from_reader')]163 clauses = [clause for name, function in selectors for clause in kani_obligations.source_obligations(164 output / 'fragments' / (name + '.rs'), function)]165 layout = output / 'fragments/layout.rs'166 source = layout.read_text()167 items = kani_obligations.function_tokens(source, 'layout')168 positions = [index for index, token in enumerate(items) if token.text == 'debug_assert_eq']169 kani.require(len(positions) == 1, 'Layout debug assertion changed')170 index = positions[0]171 args = kani_obligations.arguments(items[index + 3:kani_obligations.closing(items, index + 2)])172 description = (kani_obligations.normalized('assertion failed:') + tuple(t.text for t in args[0])173 + ('=', '=') + tuple(t.text for t in args[1]))174 start = items[index].offset175 clauses.append(kani_obligations.Obligation(str(layout), source.count('\n', 0, start) + 1,176 start - source.rfind('\n', 0, start), 'assertion', description))177 return clauses178179180def new_output(action):181 output = kani.TEMP / ('shared-tail-' + datetime.datetime.now(datetime.timezone.utc).strftime('%Y%m%dT%H%M%SZ')182 + '-' + action + '-' + uuid.uuid4().hex[:8])183 output.mkdir()184 return output185186187def declaration(action, output):188 """Independent canonical execution meaning; never recover this from receipts."""189 output = Path(output)190 env = {'PATH': BASE_PATH, 'LC_ALL': 'C', 'LANG': 'C', 'TZ': 'UTC',191 'RUSTUP_AUTO_INSTALL': '0', 'PYTHONDONTWRITEBYTECODE': '1'}192 scope, cwd = SCOPE, ROOT193 if action in SUITES:194 toolchain = kani.KANI / 'toolchain/bin'195 env.update(PATH=str(toolchain) + ':' + BASE_PATH, KANI_HOME=str(kani.TEMP / kani.PIN['home_dir']),196 RUSTUP_HOME=str(kani.TEMP / 'rustup'), RUSTUP_TOOLCHAIN=kani.PIN['rust_toolchain'],197 RUSTC=str(toolchain / 'rustc'), CARGO=str(toolchain / 'cargo'),198 CARGO_HOME=str(kani.TEMP / 'shared-tail-kani-cargo-home'), CARGO_NET_OFFLINE='true',199 RUSTFLAGS='--edition=2024 -A dead_code --check-cfg=cfg(test)', CARGO_INCREMENTAL='0',200 TMPDIR=str(output / 'temp'))201 commands = [[str(kani.LAUNCHER / 'kani'), str(output / 'main.rs'), '--target-dir', str(output / 'target'),202 '-Z', 'unstable-options', '--harness-timeout', '90s', '--export-json', str(output / 'result.json'),203 '--jobs', '1', '--output-format', 'terse', '--exact', '--harness', 'selected::' + SUITES[action][1]]]204 profile = {'kind': 'kani', 'harness_seconds': 90, 'unwind': 10, 'jobs': 1,205 'safety_checks': 'all defaults', 'unwinding_assertions': True}206 elif action == 'body-control':207 python = Path('/run/current-system/sw/bin/python3').resolve()208 commands = [[str(python), str(Path(__file__)), '--probe-stage', str(output)]]209 profile = {'kind': 'source-correspondence-child'}210 elif action in ('moved', 'native'):211 compiler = native_witness.equality_bridge.production_compiler().resolve()212 env.update(PATH=str(compiler.parent) + ':' + BASE_PATH, RUSTC=str(compiler))213 if action == 'moved':214 commands = [[str(compiler), '--edition=2024', '--target', kani.PIN['target'],215 str(output / 'main.rs'), '-o', str(output / 'witness')]]216 profile = {'kind': 'consuming-owner-compiler-control'}217 else:218 scope, cwd = NATIVE_SCOPE, output / 'project'219 env.update(CARGO_HOME=str(kani.TEMP / 'product-cargo-home'), CARGO_TARGET_DIR=str(output / 'target'),220 TMPDIR=str(output / 'temp'), CARGO_NET_OFFLINE='true', CARGO_BUILD_TARGET=kani.PIN['target'],221 CARGO_UNSTABLE_CHECKSUM_FRESHNESS='true', CARGO_BUILD_FINGERPRINT='content',222 RUSTUP_HOME=str(compiler.parents[3]), RUSTDOC=str(compiler.parent / 'rustdoc'), RUSTFLAGS='-Cpanic=unwind')223 cargo, manifest = compiler.parent / 'cargo', cwd / 'Cargo.toml'224 commands = [[str(cargo), 'metadata', '--manifest-path', str(manifest), '--locked', '--offline', '--format-version', '1'],225 [str(cargo), 'build', '--manifest-path', str(manifest), '--locked', '--offline',226 '--target', kani.PIN['target'], '--bin', 'shared-tail-witness'],227 [str(output / 'target' / kani.PIN['target'] / 'debug/shared-tail-witness')]]228 profile = {'kind': 'native-finite-witness', 'panic': 'unwind',229 'process_seconds': {'metadata': 120, 'build': 180, 'run': 30}}230 elif action in ('permission-direct', 'permission-frontier'):231 scope, cwd = OPEN_SCOPE, output232 identity = creusot.TOOL.resolve().name233 env.update(PATH=str(creusot.TOOL / 'bin') + ':' + BASE_PATH,234 CARGO_HOME=str(creusot.INSTALL / 'cargo-home'),235 CARGO_TARGET_DIR=str(creusot.INSTALL / 'targets' / identity),236 XDG_CACHE_HOME=str(creusot.INSTALL / 'cache' / identity),237 XDG_CONFIG_HOME=str(creusot.INSTALL / 'config'), CARGO_NET_OFFLINE='true')238 commands = [[str(creusot.TOOL / 'bin/cargo-creusot'), 'creusot', '--erasure-check=error',239 '-j', '1', 'permission', '--only=coma', '--', '--locked', '--offline']]240 profile = {'kind': 'open-frontend-diagnostic', 'jobs': 1, 'why3_seconds': 5.0,241 'why3_depth': 6, 'solver_stage_reached': False}242 else:243 kani.require(action == 'cohort', 'Unknown canonical declaration')244 scope, commands, env = COHORT_SCOPE, [], {}245 profile = {'kind': 'artifact-aggregation'}246 return {'scope': scope, 'commands': commands, 'cwd': str(cwd), 'environment': env,247 'target': kani.PIN['target'], 'execution_profile': profile}248249250def permission_sources(direct):251 selected = fragments()252 source = ('use core::{cell::Cell, ptr::{self, NonNull}};\n' + selected['header']253 + '\n#[creusot_std::prelude::trusted]\n' + selected['elements'] + '\nmod permission;\n')254 return {'src/lib.rs': source.encode(),255 'src/permission.rs': (PROOFS / 'creusot' / ('direct.rs' if direct else 'permission.rs')).read_bytes(),256 **{name: (PROOFS / 'creusot' / name).read_bytes() for name in ('Cargo.toml', 'Cargo.lock', 'why3find.json')}}257258259def canonical_stage(action, output):260 if action in SUITES: return stage_sources(output, action)261 if action == 'moved': return stage_sources(output, 'origin', moved=True)262 if action == 'body-control':263 files = stage_sources(output, 'append')264 files['fragments/append.rs'] = files['fragments/append.rs'].replace(b'self.used = end;', b'self.used = 0;')265 return files266 if action == 'native':267 return {'project/' + name: data for name, data in stable_authority.native_sources(PROOFS / 'native').items()}268 if action in ('permission-direct', 'permission-frontier'):269 return permission_sources(action == 'permission-direct')270 kani.require(action == 'cohort', 'Unknown canonical staged inventory')271 mapping = json.loads((output / 'cohort-map.json').read_text())272 entries = []273 for item in mapping['results']:274 directory = Path(item['output'])275 metadata = json.loads((directory / 'inputs.json').read_text())276 record = checkpoint_seal.verify(directory, item['seal_sha256'], factory=mapping['factory'],277 sdk=mapping['sdk'], tools=metadata['binaries'])278 entries.append({**record['qualification'], 'output': str(directory), 'seal_sha256': item['seal_sha256']})279 expected = {'factory': mapping['factory'], 'sdk': mapping['sdk'], 'factory_status': '', 'sdk_status': '', 'results': entries}280 return {'cohort-map.json': (json.dumps(expected, indent=2) + '\n').encode()}281282283def validate_declaration(metadata, action, output):284 expected = declaration(action, output)285 present = set(metadata) & (DECLARATION_KEYS | {'command'})286 kani.require(present == DECLARATION_KEYS and all(metadata[key] == value for key, value in expected.items()),287 'Canonical execution declaration differs: ' + action)288 files = canonical_stage(action, output)289 expected_inventory = {name: hashlib.sha256(data).hexdigest() for name, data in files.items()}290 kani.require(metadata['staged'] == expected_inventory and all(run_receipt.regular(output / name)291 and (output / name).read_bytes() == data for name, data in files.items()),292 'Canonical complete staged inventory differs: ' + action)293294295def finish(output, record, external=None):296 (output / 'accepted.json').write_text(json.dumps(record, indent=2) + '\n')297 digest = checkpoint_seal.capture(output, kind='shared-tail-batch12', qualification=record, external=external)298 result = {**record, 'output': str(output), 'seal_sha256': digest}299 print(json.dumps(result), flush=True)300 return result301302303def validate(output, suite, code):304 authored = manifest(suite)305 harness = 'selected::' + SUITES[suite][1]306 required = kani_obligations.required('shared-tail-' + suite, {harness}, manifest=authored)307 key = 'shared-tail-' + suite308 kani.EXPECTED_HARNESSES[key] = {harness}309 if suite in NEGATIVES: kani.NEGATIVE_CONTROLS[key] = NEGATIVES[suite]310 summary = kani.validate_run(output, key, code, manifest=authored)311 reports = json.loads((output / 'result.json').read_text())['verification_results']['results']312 clauses = product_obligations(output, suite)313 kani_obligations.validate(reports[0]['checks'], clauses + required[harness], harness,314 negative=suite in NEGATIVES)315 if suite in NEGATIVES:316 failed = [c for c in reports[0]['checks'] if c['status'] == 'Failure']317 designated = [c for c in required[harness] if c.description == (json.dumps(NEGATIVES[suite]),)]318 kani.require(len(designated) == 1 and kani_obligations.check_identity(failed[0]) == designated[0],319 'Shared-tail negative failed at a different source assertion')320 return summary321322323def qualify(suite):324 original = run_receipt.checkout(ROOT) # Must precede tool authentication.325 paths = inputs()326 before = snapshot(paths)327 tool = kani.kani_install.capture(kani.TEMP)328 kani.require(original == run_receipt.checkout(ROOT), 'Checkout changed during tool authentication')329 output = new_output(suite)330 staged = stage(output, suite)331 clauses = product_obligations(output, suite)332 authored = manifest(suite)333 harness = 'selected::' + SUITES[suite][1]334 required = kani_obligations.required('shared-tail-' + suite, {harness}, manifest=authored)335 kani.environment() # Read-only readiness gate; execution uses the canonical declaration.336 (output / 'temp').mkdir()337 profile = declaration(suite, output)338 env, argv = profile['environment'], profile['commands'][0]339 receipt = run_receipt.write(ROOT, output, {**original, 'sources': before, 'staged': staged,340 'binaries': tool, 'suite': suite, **profile,341 'authored_inventory': authored, 'product_assertions': [clause.__dict__ for clause in clauses],342 'compile_time_assertions': ['layout: Header<T>.elements offset == Header<T> size']})343 def unchanged():344 receipt.verify()345 kani.require(before == snapshot(paths), 'Shared-tail source closure changed')346 verify_stage(output, suite)347 validate_declaration(json.loads(receipt.original), suite, output)348 unchanged()349 print('Shared tail', suite, output, flush=True)350 with (output / 'run.log').open('w') as log:351 proc = subprocess.run(argv, cwd=profile['cwd'], env=env, stdout=log, stderr=subprocess.STDOUT)352 (output / 'execution.json').write_text(json.dumps({'actual_exit': proc.returncode}) + '\n')353 unchanged()354 kani.kani_install.verify(tool, kani.TEMP)355 summary = validate(output, suite, proc.returncode)356 unchanged()357 return finish(output, {'suite': suite, 'actual_exit': proc.returncode, 'summary': summary,358 'authored_obligations': len(required[harness]), 'product_assertions': len(clauses)})359360361def body_control():362 original = run_receipt.checkout(ROOT)363 before = snapshot(inputs())364 output = new_output('body-control')365 staged = stage(output, 'append')366 path = output / 'fragments/append.rs'367 source = path.read_text()368 old = 'self.used = end;'369 kani.require(source.count(old) == 1, 'Body-control anchor changed')370 path.write_text(source.replace(old, 'self.used = 0;'))371 staged['fragments/append.rs'] = kani.sha(path)372 profile = declaration('body-control', output)373 env, argv = profile['environment'], profile['commands'][0]374 receipt = run_receipt.write(ROOT, output, {**original, 'sources': before, 'staged': staged,375 'binaries': {'python': {'path': argv[0], 'sha256': kani.sha(Path(argv[0]))}},376 'control': 'changed actual used publication body', **profile})377 validate_declaration(json.loads(receipt.original), 'body-control', output)378 with (output / 'run.log').open('w') as log:379 proc = subprocess.run(argv, cwd=profile['cwd'], env=env, stdout=log, stderr=subprocess.STDOUT)380 reason = 'Shared tail refused: Strict staged body correspondence changed\n'381 kani.require(proc.returncode == 1 and (output / 'run.log').read_text() == reason, 'Wrong body-control refusal')382 receipt.verify()383 validate_declaration(json.loads(receipt.original), 'body-control', output)384 kani.require(before == snapshot(inputs()), 'Body-control sources changed')385 return finish(output, {'suite': 'body-control', 'actual_exit': proc.returncode, 'expected_rejection': reason})386387388def native_compiler():389 compiler = native_witness.compiler_identity()390 root = Path(compiler['path']).parent.parent391 tree = kani.kani_install.rust_inventory(root, kani.PIN['target'])392 return {**compiler, 'native_sysroot': str(root), 'native_sysroot_sha256': kani.kani_install.digest(tree),393 'native_sysroot_entries': len(tree), 'target': kani.PIN['target']}394395396def moved():397 original = run_receipt.checkout(ROOT)398 paths = inputs()399 before = snapshot(paths)400 compiler = native_compiler()401 output = new_output('moved')402 staged = stage(output, 'origin', moved=True)403 profile = declaration('moved', output)404 env, argv = profile['environment'], profile['commands'][0]405 receipt = run_receipt.write(ROOT, output, {**original, 'sources': before, 'staged': staged,406 'binaries': {'compiler': compiler}, **profile})407 validate_declaration(json.loads(receipt.original), 'moved', output)408 with (output / 'compile.log').open('w') as log:409 proc = subprocess.run(argv, cwd=profile['cwd'], env=env, stdout=log, stderr=subprocess.STDOUT)410 text = (output / 'compile.log').read_text()411 kani.require(proc.returncode == 1 and text.count('error[E0382]: use of moved value: `building`') == 1412 and text.count('error[') == 1 and 'let duplicate = building.finish();' in text413 and str(PROOFS / 'moved.rs') + ':5:21' in text,414 'Building ownership move failed away from the designated use')415 receipt.verify()416 validate_declaration(json.loads(receipt.original), 'moved', output)417 verify_stage(output, 'origin', moved=True)418 kani.require(before == snapshot(paths) and compiler == native_compiler(), 'Move-control inputs changed')419 return finish(output, {'suite': 'moved', 'actual_exit': proc.returncode, 'diagnostic': 'E0382 building.finish'})420421422def native():423 original = run_receipt.checkout(ROOT)424 paths = inputs(native=True)425 before = snapshot(paths)426 compiler = native_compiler()427 output = new_output('native')428 project = output / 'project'429 project.mkdir()430 files = stable_authority.native_sources(PROOFS / 'native')431 for name, data in files.items(): (project / name).write_bytes(data)432 staged = {'project/' + name: kani.sha(project / name) for name in files}433 supplied, external = native_sdk.native_environment(output, Path(compiler['path']))434 profile = declaration('native', output)435 env, commands = profile['environment'], profile['commands']436 kani.require(all(supplied.get(key) == env[key] for key in ('RUSTC', 'RUSTDOC', 'RUSTUP_HOME',437 'CARGO_HOME', 'CARGO_TARGET_DIR', 'CARGO_BUILD_TARGET', 'TMPDIR', 'CARGO_NET_OFFLINE',438 'CARGO_UNSTABLE_CHECKSUM_FRESHNESS', 'CARGO_BUILD_FINGERPRINT', 'RUSTFLAGS')),439 'Supplied SDK environment differs from canonical native declaration')440 cargo = Path(compiler['path']).parent / 'cargo'441 cargo_sha = kani.sha(cargo)442 artifact = output / 'target' / kani.PIN['target'] / 'debug/shared-tail-witness'443 receipt = run_receipt.write(ROOT, output, {**original, 'sources': before, 'staged': staged,444 'binaries': {'compiler': compiler, 'cargo': {'path': str(cargo), 'sha256': cargo_sha}, 'environment': external},445 **profile})446 def unchanged():447 receipt.verify()448 validate_declaration(json.loads(receipt.original), 'native', output)449 kani.require(before == snapshot(paths) and compiler == native_compiler()450 and cargo_sha == kani.sha(cargo), 'Native source/compiler changed')451 kani.require(all(kani.sha(Path(path)) == digest for path, digest in external.items()), 'Native environment changed')452 unchanged()453 with (output / 'metadata.json').open('w') as stdout, (output / 'metadata.stderr').open('w') as stderr:454 meta = subprocess.run(commands[0], cwd=profile['cwd'], env=env, stdout=stdout, stderr=stderr, timeout=120)455 exits = {'metadata_exit': meta.returncode}456 (output / 'execution.json').write_text(json.dumps(exits) + '\n')457 kani.require(meta.returncode == 0, 'Native locked metadata failed')458 graph = json.loads((output / 'metadata.json').read_text())459 deps = native_sdk.dependency_snapshot(graph, project)460 (output / 'dependencies.json').write_text(json.dumps(deps, indent=2) + '\n')461 with (output / 'compile.stdout').open('w') as stdout, (output / 'compile.stderr').open('w') as stderr:462 compiled = subprocess.run(commands[1], cwd=profile['cwd'], env=env, stdout=stdout, stderr=stderr, timeout=180)463 exits['compile_exit'] = compiled.returncode464 (output / 'execution.json').write_text(json.dumps(exits) + '\n')465 unchanged()466 kani.require(compiled.returncode == 0, 'Actual product native build failed')467 creusot.require_no_fatal_diagnostics((output / 'compile.stderr').read_text(), ())468 artifact_sha = native_witness.executable_hash(artifact)469 with (output / 'run.stdout').open('w') as stdout, (output / 'run.stderr').open('w') as stderr:470 ran = subprocess.run(commands[2], cwd=profile['cwd'], env=env, stdout=stdout, stderr=stderr, timeout=30)471 exits['actual_exit'] = ran.returncode472 (output / 'execution.json').write_text(json.dumps(exits) + '\n')473 unchanged()474 kani.require(ran.returncode == 0 and (output / 'run.stdout').read_text() == 'SHARED_TAIL_ACTUAL_NATIVE_OK\n'475 and not (output / 'run.stderr').read_text(), 'Actual product native witness failed')476 kani.require(deps == native_sdk.dependency_snapshot(graph, project), 'Native dependencies changed')477 native_witness.executable_hash(artifact, artifact_sha)478 return finish(output, {'suite': 'native', 'metadata_exit': meta.returncode,479 'compile_exit': compiled.returncode, 'actual_exit': ran.returncode, 'artifact_sha256': artifact_sha})480481482def validate_permission_frontier(output, direct, code):483 log = (output / 'translate.log').read_text()484 if direct:485 reason = 'error: Dereference of a raw pointer is forbidden in creusot: use `creusot_std::ghost::perm::Perm<*const T>` instead'486 errors = [line for line in log.splitlines() if line.startswith(('error:', 'error[', 'Error:'))]487 kani.require(code == 1 and errors == [reason,488 'error: could not compile `shared-tail-creusot` (lib) due to 1 previous error; 3 warnings emitted',489 'Error: Compilation failed'] and 'src/permission.rs:13:14' in log,490 'Different direct raw-origin frontend boundary')491 creusot.require_no_fatal_diagnostics(log, errors)492 return 'OPEN_FRONTEND_RAW_DEREFERENCE'493 creusot.require_erasure_rejection(log, code, 'permission::elements_origin')494 kani.require('src/permission.rs:15:47' in log and 'Field { variant: 0, field: 2 }' in log,495 'Different permission-aware field-origin erasure boundary')496 return 'OPEN_PERMISSION_REBORROW_ERASURE'497498499def permission_frontier(direct=False):500 """Attempt the original address-of bridge without a trusted origin leaf."""501 original = run_receipt.checkout(ROOT)502 paths = inputs()503 before = snapshot(paths)504 creusot.validate_source()505 binaries = creusot.validate_binaries()506 kani.require(original == run_receipt.checkout(ROOT), 'Checkout changed during Creusot authentication')507 label = 'permission-direct' if direct else 'permission-frontier'508 output = new_output(label)509 # The trusted original is solely an erasure target, never a callee. The510 # origin bridge itself retains its raw operation and is wholly untrusted.511 files = permission_sources(direct)512 for name, data in files.items():513 path = output / name514 path.parent.mkdir(parents=True, exist_ok=True)515 path.write_bytes(data)516 staged = {name: kani.sha(output / name) for name in files}517 profile = declaration(label, output)518 env, commands = profile['environment'], profile['commands']519 receipt = run_receipt.write(ROOT, output, {**original, 'sources': before, 'staged': staged,520 'binaries': binaries, **profile, 'intended_goal': 'vc_elements_origin', 'no_solver_stage_reached': True,521 'original_source_goals': {}, 'budgets': {'time': 5.0, 'depth': 6}})522 def unchanged():523 receipt.verify()524 validate_declaration(json.loads(receipt.original), label, output)525 kani.require(before == snapshot(paths) and binaries == creusot.validate_binaries(), 'Permission-frontier inputs changed')526 creusot.validate_source()527 unchanged()528 with (output / 'translate.log').open('w') as log:529 translated = subprocess.run(commands[0], cwd=profile['cwd'], env=env, stdout=log, stderr=subprocess.STDOUT)530 (output / 'translation-exit.json').write_text(json.dumps({'actual_exit': translated.returncode}) + '\n')531 unchanged()532 status = validate_permission_frontier(output, direct, translated.returncode)533 kani.require(not list((output / 'verif').rglob('*.coma')) if (output / 'verif').exists() else True,534 'Unexpected generated proof population for rejected frontend')535 return finish(output, {'suite': label, 'status': status, 'actual_exit': translated.returncode,536 'generated_goals': 0, 'permission_export': False})537538539def cohort(results):540 original = run_receipt.checkout(ROOT)541 output = new_output('cohort')542 tools = {}543 external = {}544 for result in results:545 directory = Path(result['output'])546 metadata = json.loads((directory / 'inputs.json').read_text())547 kani.require(metadata['factory'] == original['factory'] and metadata['sdk'] == original['sdk'],548 'Cohort contains a different producer source identity')549 tools[result['suite']] = metadata['binaries']550 external[str(directory / checkpoint_seal.NAME)] = result['seal_sha256']551 (output / 'cohort-map.json').write_text(json.dumps({**original, 'results': results}, indent=2) + '\n')552 receipt = run_receipt.write(ROOT, output, {**original, 'sources': snapshot(inputs(native=True)),553 'staged': {'cohort-map.json': kani.sha(output / 'cohort-map.json')}, 'binaries': tools,554 **declaration('cohort', output)})555 receipt.verify()556 validate_declaration(json.loads(receipt.original), 'cohort', output)557 return finish(output, {'suite': 'cohort', 'components': len(results), 'actual_driver_exit': 0,558 'permission_export': False}, external)559560561def audit(output, digest, *, factory, sdk):562 """Reconsume originals against independently supplied identities and seal."""563 output = Path(output)564 metadata = json.loads((output / 'inputs.json').read_text())565 record = checkpoint_seal.verify(output, digest, factory=factory, sdk=sdk, tools=metadata['binaries'])566 kani.require(metadata['sources'] == snapshot(inputs(native=record['qualification']['suite'] in ('native', 'cohort'))),567 'Audit source/import closure differs from original producer')568 suite = record['qualification']['suite']569 validate_declaration(metadata, suite, output)570 if suite == 'cohort':571 mapping = json.loads((output / 'cohort-map.json').read_text())572 kani.require(mapping['factory'] == factory and mapping['sdk'] == sdk, 'Different cohort source identity')573 kani.require({item['suite'] for item in mapping['results']} ==574 {*SUITES, 'body-control', 'moved', 'native', 'permission-direct', 'permission-frontier'},575 'Incomplete/extra cohort population')576 kani.require(len(mapping['results']) == len({item['suite'] for item in mapping['results']}), 'Duplicate cohort component')577 return [audit(item['output'], item['seal_sha256'], factory=factory, sdk=sdk) for item in mapping['results']]578 if suite in SUITES:579 verify_stage(output, suite)580 expected_stage = {name: hashlib.sha256(content).hexdigest()581 for name, content in stage_sources(output, suite).items()}582 kani.require(expected_stage == metadata['staged'], 'Original Kani stage inventory differs')583 kani.kani_install.verify(metadata['binaries'], kani.TEMP)584 code = json.loads((output / 'execution.json').read_text())['actual_exit']585 kani.require(code == record['qualification']['actual_exit'], 'Recorded actual Kani exit differs')586 validate(output, suite, code)587 elif suite in ('permission-direct', 'permission-frontier'):588 creusot.validate_source()589 kani.require(creusot.validate_binaries() == metadata['binaries'], 'Original Creusot tools differ')590 code = json.loads((output / 'translation-exit.json').read_text())['actual_exit']591 status = validate_permission_frontier(output, suite == 'permission-direct', code)592 kani.require(status == record['qualification']['status'] and not record['qualification']['permission_export'],593 'An open frontier was relabeled as a permission theorem')594 source = 'direct.rs' if suite == 'permission-direct' else 'permission.rs'595 kani.require((output / 'src/permission.rs').read_bytes() == (PROOFS / 'creusot' / source).read_bytes(),596 'Different original permission reproducer')597 elif suite == 'moved':598 verify_stage(output, 'origin', moved=True)599 kani.require(metadata['binaries']['compiler'] == native_compiler(), 'Different native compiler/sysroot')600 text = (output / 'compile.log').read_text()601 kani.require(record['qualification']['actual_exit'] == 1 and text.count('error[') == 1602 and 'error[E0382]: use of moved value: `building`' in text603 and str(PROOFS / 'moved.rs') + ':5:21' in text, 'Different owning move diagnostic')604 elif suite == 'native':605 kani.require(metadata['binaries']['compiler'] == native_compiler(), 'Different native compiler/sysroot')606 kani.require(all(kani.sha(Path(path)) == digest for path, digest in metadata['binaries']['environment'].items()),607 'Different original SDK environment sources')608 project = output / 'project'609 kani.require(all((project / name).read_bytes() == data610 for name, data in stable_authority.native_sources(PROOFS / 'native').items()),611 'Different complete SDK native client stage')612 deps = json.loads((output / 'dependencies.json').read_text())613 kani.require(deps == native_sdk.dependency_snapshot(json.loads((output / 'metadata.json').read_text()), project),614 'Different native dependency closure')615 kani.require(json.loads((output / 'execution.json').read_text()) ==616 {'metadata_exit': 0, 'compile_exit': 0, 'actual_exit': 0}617 and (output / 'run.stdout').read_text() == 'SHARED_TAIL_ACTUAL_NATIVE_OK\n'618 and not (output / 'run.stderr').read_text(), 'Different actual native outcomes')619 artifact = output / 'target' / kani.PIN['target'] / 'debug/shared-tail-witness'620 native_witness.executable_hash(artifact, record['qualification']['artifact_sha256'])621 else:622 kani.require(suite == 'body-control' and record['qualification']['actual_exit'] == 1623 and (output / 'run.log').read_text() == 'Shared tail refused: Strict staged body correspondence changed\n',624 'Different correspondence refusal')625 expected = stage_sources(output, 'append')626 expected['fragments/append.rs'] = expected['fragments/append.rs'].replace(b'self.used = end;', b'self.used = 0;')627 kani.require(all((output / name).read_bytes() == data for name, data in expected.items()),628 'Different exact source mutation control')629 return {'suite': suite, 'source': factory, 'seal_sha256': digest, 'reconsumed': True}630631632def main():633 parser = argparse.ArgumentParser(description=__doc__)634 parser.add_argument('action', choices=('all', *SUITES, 'body-control', 'moved', 'native', 'permission-direct', 'permission-frontier'), default='all', nargs='?')635 parser.add_argument('--probe-stage', type=Path, help=argparse.SUPPRESS)636 args = parser.parse_args()637 if args.probe_stage:638 verify_stage(args.probe_stage)639 raise RuntimeError('Changed product body admitted')640 with (kani.TEMP / '.shared-tail.lock').open('w') as lock:641 fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB)642 actions = (*SUITES, 'body-control', 'moved', 'native', 'permission-direct', 'permission-frontier') if args.action == 'all' else (args.action,)643 result = [qualify(action) if action in SUITES else body_control() if action == 'body-control'644 else moved() if action == 'moved' else native() if action == 'native'645 else permission_frontier(action == 'permission-direct') for action in actions]646 mapping = cohort(result) if args.action == 'all' else None647 print(json.dumps({'actual_driver_exit': 0, 'cohort': mapping, 'results': result}), flush=True)648649650if __name__ == '__main__':651 try:652 with creusot.cache_lease():653 main()654 except (RuntimeError, subprocess.SubprocessError, BlockingIOError) as error:655 print('Shared tail refused:', error, file=sys.stderr)656 sys.exit(1)