vec_bounds.py
verification/tools/vec_bounds.py
1#!/usr/bin/env python32"""Qualify the actual read-only VecBounds adapter; no payload/growth model."""3from pathlib import Path4import argparse5import datetime6import fcntl7import json8import re9import subprocess10import sys11import uuid1213import creusot14import creusot_report15import equality_bridge16import native_callbacks17import native_witness18import provider_resource19import run_receipt20import checkpoint_seal21import composition_checkpoint2223ROOT = creusot.ROOT24MEMORY = provider_resource.MEMORY25REGION = MEMORY.parent / 'memory/region.rs'26QUERY = ROOT / 'verification/proofs/provider/creusot/vec_bounds_query.rs'27WITNESS = QUERY.with_name('vec_bounds_witness.rs')28DIRECT = QUERY.with_name('direct_bytes_frontend.rs')29BINDING = QUERY.with_name('vec_bounds_binding.rs')30NATIVE = ROOT / 'verification/proofs/provider/native/direct_bytes.rs'31PREFIX = 'queries/vec_bounds_query/'32NEW = {PREFIX + 'config_query/proof.json': 'vc_config_query',33 PREFIX + 'installation_owner_frame/proof.json': 'vc_installation_owner_frame',34 PREFIX + 'rejecting_page/proof.json': 'vc_rejecting_page',35 PREFIX + 'single_store_page/proof.json': 'vc_single_store_page',36 PREFIX + 'admitted_client/proof.json': 'vc_admitted_client',37 'claim/vec_bounds_witness/owned_queries/proof.json': 'vc_owned_queries',38 'provider/vec_bounds_binding/expose/proof.json': 'vc_expose'}39NEW.update({PREFIX + 'impl_VecBounds/' + name + '/proof.json': 'vc_' + name40 for name in ('base_query', 'pages_query', 'pool_query', 'contains_query')})41NEW.update({PREFIX + 'impl_Pool_VecBounds/' + name + '/proof.json': 'vc_' + name42 for name in ('attach_query', 'word_query', 'committed_query', 'contains_query')})43SUPPORT = ('lifecycle/initialized_is_saved_valid', 'owner_region_frame', 'queries/query_geometry', 'queries/range_match_correspondence',44 'owner_step_geometry', 'bit_queries/chunk_matches', 'bit_queries/first_set_bit',45 'initialize/impl_Pool_B/initialize_proof', 'updates/impl_Pool_B/mark_proof',46 'claim/marked_valid', 'validation/impl_Pool_B/validate_proof',47 'impl_Pool_B/install_store_proof', 'recovery/impl_Pool_B/into_backing_proof',48 'provider/borrow_control', 'provider/impl_PhysicalState/control',49 'provider/impl_PhysicalState/control_mut')50EXPECTED = dict(NEW)51PROVE_PATHS = ('queries/vec_bounds_query', 'claim/vec_bounds_witness', 'provider/vec_bounds_binding')52ORIGINAL = {**creusot.ORIGINAL_SOURCE_GOALS,53 'page_pool/impl_Clone_for_VecBounds/clone.coma': frozenset(('vc_clone_VecBounds',))}54SCOPE = ('actual Copy VecBounds read-only metadata binding and exact native64 sparse byte query; '55 'separate real metadata permission, no ResourceBacking/payload/growth implementation')565758def annotate(text):59 marker = '#[creusot_std::prelude::trusted]'60 creusot.require(marker not in text, 'Product target already annotated')61 staged = re.sub(r'(?m)^([ \t]*)((?:pub(?:\([^)]*\))? )?(?:unsafe )?fn )',62 lambda m: m[1] + marker + '\n' + m[1] + m[2], text)63 recovered = re.sub(r'(?m)^[ \t]*#\[creusot_std::prelude::trusted\]\n', '', staged)64 creusot.require(recovered == text, 'Vec bounds target staging changed source')65 return staged666768def audit(query):69 creusot.require(re.findall(r'#\[(?:[a-z_:]+::)?trusted\][\s\S]*?\bfn ([a-z_]+)', query) == ['read_query'],70 'The only trusted query function must be read_query')71 ceil = '''extern_spec! {72 impl usize {73 #[requires(rhs > 0usize)]74 #[ensures(result@ == (self@ + rhs@ - 1) / rhs@)]75 const fn div_ceil(self, rhs: usize) -> usize;76 }77}'''78 creusot.require(query.count('extern_spec!') == 179 and provider_resource.complete_item(query, 'extern_spec!') == ceil,80 'Unexpected standard arithmetic contract')81 creusot.require(query.count('#[trusted]') == 1 and 'Ghost::conjure' not in query82 and not re.search(r'\b(?:assume|admit)\s*!?\(', query), 'Unexpected query trust')83 creusot.require('impl ResourceBacking for VecBounds' not in query,84 'Copy query view cannot implement payload authority')85 ordinary = re.sub(r'#\[erasure\([^\n]*\)\]', '', query)86 creusot.require(not re.search(r'\.\s*(?:pool|contains|read|word|committed_pages)\s*\(', ordinary),87 'Checked query called an unchecked original method')88 creusot.require(creusot.function_body(query, 'read_query') ==89 creusot.function_body(provider_resource.POOL.read_text(), 'read'),90 'Raw read differs from the admitted primitive')919293def audit_witness(witness):94 creusot.require(not re.search(r'#\[[^\]\n]*\b(?:requires|trusted|ignore|external_body)\b', witness)95 and 'Ghost::conjure' not in witness and not re.search(r'\b(?:assume|admit)\s*!?\(', witness),96 'Owning witness must be unconditional and checked')97 creusot.require('let pages = image.len() / PAGE_BYTES;' in witness98 and 'Perm::from_mut(&mut image[..])' in witness, 'Page bounds must come from the real owner')99100101def stage(output, control=None):102 creusot.stage(output)103 crate = output / 'src/lib.rs'104 crate.write_text(crate.read_text() + '\n#[cfg(not(all(target_pointer_width="64", target_endian="little")))]\ncompile_error!("VecBounds proof requires native64 little endian");\n')105 memory = MEMORY.read_text()106 pieces = [107 '#[derive(Clone, Copy)]\n' + provider_resource.complete_item(memory, 'struct VecBounds'),108 provider_resource.complete_item(memory, 'unsafe impl page_pool::Backing for VecBounds'),109 provider_resource.complete_item(memory, 'impl VecBounds'),110 provider_resource.complete_item(memory, 'unsafe impl RetainedBounds for VecBounds'),111 provider_resource.complete_item(memory, 'fn native_pool_config()'),112 ]113 trait = provider_resource.complete_item(REGION.read_text(), 'pub unsafe trait RetainedBounds')114 target = output / 'src/page_pool.rs'115 target.write_text(target.read_text() + '\nuse crate::page_pool;\n' + trait + '\n'116 + '\n'.join(annotate(piece) for piece in pieces) + '\n')117 query, witness = QUERY.read_text(), WITNESS.read_text()118 audit(query)119 audit_witness(witness)120 if control == 'erasure':121 old = 'if bytes.end <= page_pool::ROOT_BYTES {\n return true;'122 creusot.require(query.count(old) == 1, 'Erasure control changed')123 query = query.replace(old, old.replace('return true;', 'return false;'))124 elif control == 'derive':125 old = 'bounds.contains_query(bytes, metadata)'126 creusot.require(query.count(old) == 1, 'Clone control changed')127 query = query.replace(old, 'bounds.clone().contains_query(bytes, metadata)')128 elif control == 'boundary':129 old = 'assert!(view.contains_query(0..ROOT_BYTES, metadata));'130 creusot.require(witness.count(old) == 1, 'Boundary control changed')131 witness = witness.replace(old, old.replace('assert!(view', 'assert!(!view'))132 elif control == 'origin':133 old = 'let view = VecBounds { pointer: base as *mut u8, pages };'134 creusot.require(witness.count(old) == 1, 'Origin control changed')135 witness = witness.replace(old, 'let view = VecBounds { pointer: payload_start, pages };')136 elif control == 'frame':137 old = 'assert!(image[0] == 0xa5u8);'138 creusot.require(witness.count(old) == 1, 'Frame control changed')139 witness = witness.replace(old, 'assert!(image[0] == 0x5au8);')140 (output / 'src/vec_bounds_query.rs').write_text(query)141 (output / 'src/vec_bounds_witness.rs').write_text(witness)142 binding = BINDING.read_text()143 creusot.require(not re.search(r'#\[[^\]\n]*\b(?:trusted|ignore|external_body)\b', binding)144 and 'Ghost::conjure' not in binding and not re.search(r'\b(?:assume|admit)\s*!?\(', binding),145 'Image admission must be checked, without permission fabrication')146 (output / 'src/vec_bounds_binding.rs').write_text(binding)147 for name, module in (('queries.rs', 'vec_bounds_query'), ('claim.rs', 'vec_bounds_witness'),148 ('provider.rs', 'vec_bounds_binding')):149 path = output / 'src' / name150 path.write_text(path.read_text() + '\n#[path="' + module + '.rs"] pub(in crate::page_pool) mod ' + module + ';\n')151 return {str(p.relative_to(output)): creusot.sha(p) for p in output.rglob('*') if p.is_file()}152153154def byte_frontend_stage(output):155 stage(output)156 source = MEMORY.read_text()157 item = provider_resource.complete_item158 trait = item(source, 'pub unsafe trait Memory')159 implementation = item(source, 'unsafe impl Memory for VecMemory')160 names = ('with_retained_bytes', 'with_retained_bytes_mut')161 narrowed_trait = 'pub unsafe trait Memory {\n' + '\n'.join(162 item(trait, 'fn ' + n + '<T>') for n in names) + '\n}'163 narrowed_impl = 'unsafe impl Memory for VecMemory {\n' + '\n'.join(164 item(implementation, 'fn ' + n + '<T>') for n in names) + '\n}'165 helpers = 'impl VecMemory {\n' + item(source, 'fn bounds(&self)') + '\n' + item(166 source, 'fn check_range(&self,') + '\n}'167 target = output / 'src/page_pool.rs'168 target.write_text(target.read_text() + '\n#[path="direct_bytes_native.rs"] mod direct_bytes_native;\n')169 (output / 'src/direct_bytes_native.rs').write_text('use crate::page_pool;\n'170 'use super::{VecBounds, RetainedBounds};\n#[path="byte_error.rs"] mod byte_error;\n'171 'use byte_error::{MemoryError as Error, MemoryResult as Result};\n'172 + item(source, 'pub struct VecMemory') + '\n' + annotate(narrowed_trait) + '\n'173 + annotate(narrowed_impl) + '\n' + annotate(helpers)174 + '\n#[path="direct_bytes_frontend.rs"] mod direct_bytes_frontend;\n')175 error = (MEMORY.parent / 'memory/error.rs').read_text()176 old = '#[derive(Debug, Clone, PartialEq, Eq)]'177 creusot.require(error.count(old) == 1, 'MemoryError derive changed')178 (output / 'src/byte_error.rs').write_text(error.replace(old,179 '#[derive(Debug, Clone, PartialEq, Eq, creusot_std::prelude::DeepModel)]'))180 (output / 'src/direct_bytes_frontend.rs').write_bytes(DIRECT.read_bytes())181182183def complement(frontend):184 """Explicit frontend/native complement, never a formal producer ticket."""185 run_receipt.checkout(ROOT)186 before_paths = tuple(dict.fromkeys([QUERY, WITNESS, BINDING, DIRECT, NATIVE, Path(__file__),187 Path(native_callbacks.__file__), *native_callbacks.sources(),188 *native_witness.INPUTS, *creusot.proof_inputs()]))189 before = native_witness.snapshot(before_paths)190 label = 'byte-frontend' if frontend else 'byte-native'191 output = creusot.TEMP / ('vec-bounds-' + label + '-' + uuid.uuid4().hex[:8])192 output.mkdir()193 if frontend:194 identity = creusot.validate_binaries()195 byte_frontend_stage(output)196 command = [creusot.TOOL / 'bin/cargo-creusot', 'creusot', '--erasure-check=error',197 '--only=coma', '-j', '4', '--', '--locked', '--offline']198 env = creusot.environment(output)199 else:200 identity = native_witness.compiler_identity()201 native_callbacks.stage(output)202 (output / 'main.rs').write_bytes(NATIVE.read_bytes())203 command = [identity['path'], '--edition=2024', '--target', equality_bridge.TARGET,204 '-Cpanic=unwind', output / 'main.rs', '-o', output / 'witness']205 env = native_witness.environment(Path(identity['path']))206 staged = {str(p.relative_to(output)): creusot.sha(p) for p in output.rglob('*') if p.is_file()}207 receipt = run_receipt.write(ROOT, output, {'sources': before, 'staged': staged,208 'tool': identity, 'scope': label + '; explicitly not a formal physical callback theorem'})209 with (output / 'run.log').open('w') as log:210 result = subprocess.run(list(map(str, command)), cwd=output, env=env,211 stdout=log, stderr=subprocess.STDOUT, timeout=120)212 receipt.verify()213 creusot.require(before == native_witness.snapshot(before_paths), 'Complement source changed')214 creusot.require(identity == (creusot.validate_binaries() if frontend215 else native_witness.compiler_identity()), 'Complement tool changed')216 creusot.require(result.returncode == 0, 'Complement failed: ' + str(output / 'run.log'))217 if frontend:218 creusot.require_no_fatal_diagnostics((output / 'run.log').read_text(), ())219 print('UNQUALIFIED_DIRECT_BYTES_FRONTEND_ONLY', output)220 else:221 artifact = native_witness.executable_hash(output / 'witness')222 with (output / 'native.log').open('w') as log:223 result = subprocess.run([str(output / 'witness')], cwd=output, env=env,224 stdout=log, stderr=subprocess.STDOUT, timeout=30)225 creusot.require(result.returncode == 0 and (output / 'native.log').read_text()226 == 'actual_direct_byte_callbacks_ok\n', 'Native byte callback context failed')227 receipt.verify()228 creusot.require(before == native_witness.snapshot(before_paths), 'Native source changed')229 creusot.require(native_witness.compiler_identity() == identity, 'Native compiler changed')230 native_witness.executable_hash(output / 'witness', artifact)231 print('PASS_FINITE_NATIVE_COMPLEMENT', output)232 return output233234235def run(control=None, translate=False, frontend=False, upstream=None, upstream_sha256=None):236 run_receipt.checkout(ROOT)237 proves = not translate and not frontend and control not in ('erasure', 'derive')238 creusot.require(bool(upstream) == bool(upstream_sha256), 'Both upstream map pins are required')239 creusot.require(not proves or upstream is not None, 'Local query proof requires the exact core/claim upstream map')240 upstream_record = None if upstream is None else {'path': str(Path(upstream).resolve()), 'sha256': upstream_sha256}241 if proves:242 composition_checkpoint.upstream(upstream_record['path'], upstream_sha256)243 creusot.validate_source()244 binaries = creusot.validate_binaries()245 inputs = tuple(dict.fromkeys([QUERY, WITNESS, BINDING, MEMORY, REGION, Path(__file__),246 Path(provider_resource.__file__), Path(composition_checkpoint.__file__),247 *creusot.proof_inputs(), *equality_bridge.input_paths()]))248 before = {str(p.relative_to(ROOT)): creusot.sha(p) for p in inputs}249 output = creusot.TEMP / ('vec-bounds-' + datetime.datetime.now(datetime.timezone.utc).strftime('%Y%m%dT%H%M%SZ')250 + '-' + (control or 'positive') + '-' + uuid.uuid4().hex[:8])251 output.mkdir()252 bridge, bridge_paths = (None, ()) if frontend else equality_bridge.qualify(output, creusot.TOOL / 'bin/rustc', inputs)253 staged = stage(output, control)254 receipt = run_receipt.write(ROOT, output, {'sources': before, 'staged': staged, 'binaries': binaries,255 'scope': SCOPE, 'control': control, 'reused_support': SUPPORT, 'upstream': upstream_record,256 'local_reports': sorted(EXPECTED), 'frontend_only': frontend})257258 def verify():259 receipt.verify()260 creusot.require(before == {str(p.relative_to(ROOT)): creusot.sha(p) for p in inputs}, 'Bounds source changed')261 creusot.require(binaries == creusot.validate_binaries(), 'Bounds tool changed')262 if bridge is not None:263 equality_bridge.verify(bridge, output, bridge_paths)264265 env = creusot.environment(output)266 command = [creusot.TOOL / 'bin/cargo-creusot', 'creusot', '--erasure-check=error',267 '--only=coma', '-j', '4', '--', '--locked', '--offline']268 print('VecBounds checkpoint:', output, flush=True)269 with (output / 'run.log').open('w') as log:270 result = subprocess.run(list(map(str, command)), cwd=output, env=env, stdout=log, stderr=subprocess.STDOUT)271 verify()272 log = (output / 'run.log').read_text()273 if control == 'erasure':274 creusot.require_erasure_rejection(log, result.returncode,275 'page_pool::proof::queries::vec_bounds_query::<impl page_pool::VecBounds>::contains_query')276 print('EXPECTED_ERASURE_REJECTION', output)277 return output278 creusot.require_no_fatal_diagnostics(log, ())279 creusot.require(result.returncode == 0, 'VecBounds translation failed: ' + str(output / 'run.log'))280 if frontend:281 print('UNQUALIFIED_FRONTEND_TRANSLATION_ONLY', output)282 return output283 root = output / 'verif/page_pool_creusot_rlib/page_pool/proof'284 all_expected = {**creusot_report.EXPECTED, **NEW}285 try:286 inventory = creusot_report.goal_inventory(root, all_expected, creusot.TOOL / 'bin/why3',287 load_paths=[creusot.TOOL / 'share/why3find/packages/creusot'], config=creusot.TOOL / 'creusot_why3.conf',288 cwd=output, env=env, output_dir=output / 'goal-inventory', translation_root=root.parent.parent,289 original_source_goals=ORIGINAL)290 except RuntimeError as error:291 if control != 'derive':292 raise293 expected = ('Unchecked original-derived helper in checked Coma at '294 + str(root / 'queries/vec_bounds_query/admitted_client.coma') + ": ['clone_VecBounds']")295 creusot.require(str(error) == expected, 'Clone control failed for an unrelated reason: ' + str(error))296 verify()297 print('EXPECTED_UNPROVED_VECBOUNDS_CLONE_REJECTION', output)298 return output299 creusot.require(control != 'derive', 'Unproved VecBounds Clone reached the checked inventory')300 verify()301 print('UNPROVED_ORIGINAL_SOURCE:', json.dumps({'files': len(inventory.original_source_goals),302 'goals': sum(map(len, inventory.original_source_goals.values()))}), flush=True)303 if translate:304 print('TRANSLATED_ONLY', len(inventory.goals), output)305 return output306 creusot.require(sum(len(inventory.goals[name]) for name in EXPECTED) == 86,307 'Local query obligation scope differs from the reviewed 15-report scope')308 parents, upstream_bindings = composition_checkpoint.query_upstream(output / 'goal-inventory',309 upstream_record['path'], upstream_sha256)310 verify(); inventory.verify()311 command = [creusot.TOOL / 'bin/cargo-creusot', 'creusot', '--only=prove', '-j', '8',312 *['page_pool/proof/' + p for p in PROVE_PATHS], '--', '--locked', '--offline']313 with (output / 'run.log').open('a') as log:314 result = subprocess.run(list(map(str, command)), cwd=output, env=env, stdout=log, stderr=subprocess.STDOUT)315 verify()316 inventory.verify()317 after_parents, after_bindings = composition_checkpoint.query_upstream(output / 'goal-inventory',318 upstream_record['path'], upstream_sha256)319 creusot.require(parents == after_parents and upstream_bindings == after_bindings,320 'Qualified upstream/query context changed during local SMT')321 log = (output / 'run.log').read_text()322 goals = {name: inventory.goals[name] for name in EXPECTED}323 if control:324 designated = 'claim/vec_bounds_witness/owned_queries/proof.json'325 creusot.require_logical_rejection(log, result.returncode, EXPECTED[designated])326 summary = creusot_report.validate_negative_directory(root, goals, EXPECTED, designated)327 status = 'EXPECTED_REJECTION'328 else:329 creusot.require_no_fatal_diagnostics(log, ())330 creusot.require(result.returncode == 0, 'VecBounds proof failed: ' + str(output / 'run.log'))331 summary = creusot_report.validate_directory(root, goals, EXPECTED)332 digest = checkpoint_seal.capture(output, kind='ordinary-positive',333 qualification={'role': 'query', 'scope': 'query-local-15-with-checked-core', 'summary': summary,334 'upstream': upstream_record},335 external={**inventory.hashes, **checkpoint_seal.bridge_artifacts(bridge), **upstream_bindings})336 print('CHECKPOINT_SEAL_SHA256 ' + digest, flush=True)337 status = 'PASS'338 print(json.dumps({'status': status, 'summary': summary, 'output': str(output)}), flush=True)339 return output340341342if __name__ == '__main__':343 parser = argparse.ArgumentParser(description=__doc__)344 parser.add_argument('action', choices=('positive', 'origin', 'boundary', 'frame', 'erasure', 'derive', 'byte-frontend', 'native', 'validator', 'all'), nargs='?', default='positive')345 parser.add_argument('--translate-only', action='store_true')346 parser.add_argument('--frontend-only', action='store_true', help='type/erasure feasibility only; no producer or proof admission')347 parser.add_argument('--upstream', type=Path, help='owner-pinned exact core/claim proof map')348 parser.add_argument('--upstream-sha256')349 args = parser.parse_args()350 try:351 with creusot.cache_lease():352 creusot.require(not (args.translate_only or args.frontend_only) or args.action == 'positive', 'Translation requires positive')353 with (creusot.TEMP / '.vec-bounds.lock').open('w') as lease:354 fcntl.flock(lease, fcntl.LOCK_EX | fcntl.LOCK_NB)355 if args.action == 'validator':356 scope = 'vec-bounds-validator'357 creusot.require(scope not in creusot.PROOF_SCOPES, 'Duplicate local validator scope')358 creusot.PROOF_SCOPES[scope] = ('validation/impl_Pool_B/validate_proof/',)359 creusot.run(False, scope=scope, extra_inputs=(Path(__file__),))360 sys.exit(0)361 if args.action in ('byte-frontend', 'native'):362 complement(args.action == 'byte-frontend')363 sys.exit(0)364 for control in (None, 'origin', 'boundary', 'frame', 'erasure', 'derive') if args.action == 'all' else (None if args.action == 'positive' else args.action,):365 run(control, args.translate_only, args.frontend_only, args.upstream, args.upstream_sha256)366 except (RuntimeError, subprocess.CalledProcessError, BlockingIOError) as error:367 print('VecBounds refused: ' + str(error), file=sys.stderr)368 sys.exit(1)