equality_bridge.py
verification/tools/equality_bridge.py
1#!/usr/bin/env python32"""Qualify explicit native comparison/intrinsic imports; no cached approval."""3from pathlib import Path4import argparse5import fcntl6import json7import os8import re9import subprocess10import sys1112import kani13from verus import parse_report1415ROOT = kani.ROOT16PROOF_DIR = ROOT / 'verification/proofs/page-pool/creusot'17PRODUCT = kani.PLATFORM / 'memory/page_pool.rs'18TARGET = 'x86_64-unknown-linux-gnu'19LEAVES = ('owner_eq', 'owner_ne', 'run_eq', 'run_ne')20OPTION_LEAVES = ('option_run_eq', 'option_run_ne')21COUNT_LEAVES = ('count_ones', 'ceil32')22BRIDGE_SUITES = ('equality', 'equality-negative', 'option-equality', 'count-ones', 'count-ones-negative', 'ceil32', 'ceil32-negative')23STAGED_FILES = ('main.rs', 'page_pool.rs')24# A source change to a producer demands review of its oracle and assertions.25PRODUCERS = {26 'option_equality.rs': 'dba4a768ca35f42c94dd28466680455fab947914a785f5d155cf4adcd36845fa',27 'equality.rs': '8aea2d1505e3fc88382c13aa8357260e8c681a5a23996234496b3534830d4be0',28 'equality_negative.rs': 'c3b8624a33bf31e305712594f4fe0d0113436ad93f1aa13381789d3989d4e69f',29}30COUNT_PRODUCERS = {31 'verification/proofs/page-pool/kani/count_ones.rs': '93f10409c0b87924f8a9b421244084b0edf35038510be72361656ec14c420102',32 'verification/proofs/page-pool/kani/count_ones_negative.rs': 'fc0247c7bed66635be69a5a19d5c4b38800f75b37c73bcd2a10e7e9da4473ad0',33 'verification/proofs/page-pool/kani/ceil32.rs': 'd762a54f86da56898c852d78cd2546dc490f4998cae2e07d8fc1b76a468da5e2',34 'verification/proofs/page-pool/kani/ceil32_negative.rs': 'ddbc9d57172443567bbeba30e542764ca46162a1dbd7de4ddf5340c14f55ca1b',35 'verification/proofs/page-pool/shared/count_model.rs': '9f88dcfaf2d20bd679f45a18ea3a0ce81fc46ac76fed8f0e9d173b65b9641a92',36}37VERSIONS = {38 'kani': 'rustc 1.100.0-nightly (8925ea358 2026-08-20)',39 'creusot': 'rustc 1.99.0-nightly (11177f223 2026-08-02)',40 'production': 'rustc 1.101.0-nightly (7df81381d 2026-10-14)',41}424344def require(value, message):45 if not value:46 raise RuntimeError('Equality bridge: ' + message)474849def compact(source):50 return re.sub(r'\s+', '', source)515253def brace_block(source, start):54 begin = source.index('{', start)55 cursor, depth = begin + 1, 156 while depth:57 require(cursor < len(source), 'unclosed audited block')58 depth += (source[cursor] == '{') - (source[cursor] == '}')59 cursor += 160 return source[begin:cursor]616263def canonical_impl(expanded, ty):64 """Whitelist complete derive bodies, not a general Rust rewrite engine."""65 marker = 'impl ::core::cmp::PartialEq for ' + ty + ' {'66 require(expanded.count(marker) == 1, 'unexpected expanded ' + ty + ' impl set')67 body = compact(brace_block(expanded, expanded.index(marker)))68 # Self spelling changed between pinned rustc versions. Nothing else is renamed.69 body = body.replace('&Self', '&' + ty)70 if ty == 'Owner':71 direct = '{#[inline]fneq(&self,other:&Owner)->bool{::core::intrinsics::discriminant_value(self)==::core::intrinsics::discriminant_value(other)}}'72 lets = '{#[inline]fneq(&self,other:&Owner)->bool{let__self_discr=::core::intrinsics::discriminant_value(self);let__arg1_discr=::core::intrinsics::discriminant_value(other);__self_discr==__arg1_discr}}'73 # The only accepted inlining substitutes two single-use pure reads.74 require(body in (direct, lets), 'unreviewed Owner derive body')75 return direct76 direct = '{#[inline]fneq(&self,other:&Run)->bool{self.start==other.start&&self.count==other.count}}'77 require(body == direct, 'unreviewed Run derive body')78 return direct798081def audit_source():82 original = compact(PRODUCT.read_text())83 for declaration in (84 '#[derive(Clone,Copy,Debug,PartialEq,Eq)]#[repr(u8)]pubenumOwner{Runtime=1,Store=2,Control=3,}',85 '#[derive(Clone,Copy,Debug,PartialEq,Eq)]pubstructRun{pubstart:usize,pubcount:usize,}',86 ):87 require(original.count(declaration) == 1, 'unreviewed comparison type declaration')88 for name, expected in PRODUCERS.items():89 require(kani.sha(ROOT / 'verification/proofs/page-pool/kani' / name) == expected,90 'unreviewed producer: ' + name)91 for name, expected in COUNT_PRODUCERS.items():92 require(kani.sha(ROOT / name) == expected, 'unreviewed counting producer: ' + name)93 audit_count_wrapper((PROOF_DIR / 'counting.rs').read_text())94 audit_wrappers((PROOF_DIR / 'equality.rs').read_text())95 audit_option_wrappers((PROOF_DIR / 'option_equality.rs').read_text())969798def audit_wrappers(source):99 trusted = re.findall(r'#\[trusted\]', source)100 require(len(trusted) == 4, 'unexpected equality trusted-leaf count')101 blocks = []102 for ty, oracle in (('Owner', 'same_variant'), ('Run', 'same_fields')):103 for op in ('eq', 'ne'):104 name = ty.lower() + '_' + op105 expected = f'''#[trusted] #[check(terminates)]106 #[erasure(<{ty} as core::cmp::PartialEq>::{op})]107 #[ensures(result == {'!' if op == 'ne' else ''}{oracle}(*left, *right))]108 pub(super) fn {name}(left: &{ty}, right: &{ty}) -> bool {{109 <{ty} as core::cmp::PartialEq>::{op}(left, right)110 }}'''111 require(compact(source).count(compact(expected)) == 1,112 'comparison wrapper/contract differs from its qualified direct call: ' + name)113 blocks.append(expected)114 # No hidden additional attributes/preconditions/effects around these leaves.115 prefix = source[:source.index('#[logic(open(super))]')]116 prefix = re.sub(r'//[^\n]*', '', prefix)117 require(compact(prefix) == compact('use super::*;' + ''.join(blocks)),118 'unreviewed wrapper attributes or surrounding code')119 oracles = {120 'same_variant': '{match(left,right){(Owner::Runtime,Owner::Runtime)|(Owner::Store,Owner::Store)|(Owner::Control,Owner::Control)=>true,_=>false,}}',121 'same_fields': '{left.start==right.start&&left.count==right.count}',122 }123 for name, body in oracles.items():124 require(compact(brace_block(source, source.index('fn ' + name + '('))) == body,125 'oracle differs from reviewed Kani producer: ' + name)126127128129def audit_option_wrappers(source):130 require(source.count('#[trusted]') == 2, 'unexpected Option comparison leaves')131 blocks = []132 for op in ('eq', 'ne'):133 expected = f'''#[trusted] #[check(terminates)]134 #[erasure(<Option<Run> as core::cmp::PartialEq>::{op})]135 #[ensures(result == {'!' if op == 'ne' else ''}same_option_fields(*left, *right))]136 pub(super) fn option_run_{op}(left: &Option<Run>, right: &Option<Run>) -> bool {{137 <Option<Run> as core::cmp::PartialEq>::{op}(left, right)138 }}'''139 blocks.append(expected)140 prefix = re.sub(r'//[^\n]*', '', source[:source.index('#[logic(open(super))]')])141 require(compact(prefix) == compact('use super::*; use super::equality::same_fields;' + ''.join(blocks)),142 'unreviewed Option wrapper signature/attributes/body')143 expected = '{match(left,right){(None,None)=>true,(Some(a),Some(b))=>same_fields(a,b),_=>false,}}'144 require(compact(brace_block(source, source.index('fn same_option_fields('))) == expected,145 'Option oracle differs from reviewed Kani producer')146147def audit_count_wrapper(source):148 expected = """#[trusted] #[check(terminates)]149 #[erasure(u64::count_ones)]150 #[ensures(result@ == bit_population(word, 64))]151 pub(super) fn count_ones(word: u64) -> u32 { word.count_ones() }152 #[trusted] #[check(terminates)] #[erasure(usize::div_ceil)]153 #[requires(rhs == 32usize)]154 #[ensures(result@ == (value@ + 31) / 32)]155 pub(super) fn ceil32(value: usize, rhs: usize) -> usize { value.div_ceil(rhs) }"""156 prefix = re.sub(r'//[^\n]*', '', source[:source.index('#[logic(open(super))]')])157 require(compact(prefix) == compact('use super::*; use creusot_std::logic::ops::NthBitLogic;' + expected),158 'unreviewed count_ones wrapper signature/attributes/body')159160161def input_paths(extra=()):162 return [PRODUCT, Path(__file__), Path(kani.__file__), Path(kani.__file__).with_suffix('.toml'),163 Path(__file__).with_name('verus.py'), Path(__file__).with_name('verus.toml'),164 *kani.kani_obligations.INPUTS, *kani.kani_install.INPUTS,165 ROOT / 'cdk-rsx/rust-toolchain.toml', PROOF_DIR / 'equality.rs',166 PROOF_DIR / 'equality_targets.rs', PROOF_DIR / 'option_equality.rs',167 PROOF_DIR / 'option_equality_targets.rs',168 *[ROOT / 'verification/proofs/page-pool/kani' / n for n in PRODUCERS],169 *[ROOT / n for n in COUNT_PRODUCERS], PROOF_DIR / 'counting.rs', *extra]170171172def snapshot(paths):173 return {str(p.relative_to(ROOT)): kani.sha(p) for p in paths}174175176def producer_paths(suite):177 require(suite in BRIDGE_SUITES, 'unknown equality producer')178 paths = [PRODUCT, ROOT / 'verification/proofs/page-pool/kani' / kani.SUITES[suite][0]]179 if suite in ('count-ones', 'count-ones-negative', 'ceil32', 'ceil32-negative'):180 paths.append(ROOT / 'verification/proofs/page-pool/shared/count_model.rs')181 return [*paths, Path(kani.__file__), Path(kani.__file__).with_suffix('.toml'),182 *kani.kani_obligations.INPUTS, *kani.kani_install.INPUTS]183184185def producer_staging(suite):186 original = PRODUCT.read_bytes()187 proof = ROOT / 'verification/proofs/page-pool/kani' / kani.SUITES[suite][0]188 tail = ('\n#[cfg(kani)] mod proofs { include!(' + json.dumps(str(proof)) + '); }\n').encode()189 return {'main.rs': b'extern crate core;\nmod page_pool;\nfn main() {}\n',190 'page_pool.rs': original + tail}191192193def is_digest(value):194 return type(value) is str and re.fullmatch(r'[0-9a-f]{64}', value) is not None195196197def production_compiler():198 override = os.environ.get('EQUALITY_PRODUCTION_RUSTC')199 if override:200 return Path(override).resolve()201 # Worktrees share an installed SDK compiler read-only; their caches stay private.202 common = Path(kani.git(ROOT, 'rev-parse', '--git-common-dir'))203 if not common.is_absolute():204 common = ROOT / common205 return common.resolve().parent / ('cdk-rsx/.rustup/toolchains/'206 'nightly-2026-10-15-x86_64-unknown-linux-gnu/bin/rustc')207208209def compare_compilers(output, creusot_compiler):210 compilers = {'kani': kani.KANI / 'toolchain/bin/rustc',211 'creusot': creusot_compiler, 'production': production_compiler()}212 records, forms = {}, {}213 env = kani.environment()214 for label, compiler in compilers.items():215 require(compiler.is_file(), 'missing read-only compiler: ' + str(compiler))216 version = subprocess.check_output([str(compiler), '--version'], env=env, text=True).strip()217 require(version == VERSIONS[label], 'unexpected compiler: ' + version)218 path = output / (label + '-expanded.rs')219 with path.open('w') as out, (output / (label + '-expand.log')).open('w') as log:220 subprocess.run([str(compiler), '--edition=2024', '--crate-type=lib',221 '--target', TARGET, '-Zunpretty=expanded', str(PRODUCT)],222 env=env, cwd=output, stdout=out, stderr=log, check=True)223 forms[label] = {ty: canonical_impl(path.read_text(), ty) for ty in ('Owner', 'Run')}224 records[label] = {'version': version, 'rustc_sha256': kani.sha(compiler),225 'expanded_sha256': kani.sha(path), 'target': TARGET,226 'path': str(compiler.resolve())}227 require(forms['kani'] == forms['creusot'] == forms['production'],228 'compiler-derived comparison bodies differ')229 return records230231232def verify(ticket, consumer_output, paths):233 """Recheck source identity and full producer results immediately at consumption."""234 require(type(ticket) is dict and set(ticket) == {'consumer', 'target', 'sources', 'producers', 'compilers', 'toolIdentity'},235 'missing producer qualification')236 kani.kani_install.verify(ticket['toolIdentity'], kani.TEMP)237 require(ticket['consumer'] == str(consumer_output), 'producer belongs to a different consumer run')238 require(ticket['target'] == TARGET == kani.PIN['target'], 'producer/consumer target mismatch')239 require(ticket['sources'] == snapshot(paths), 'producer/consumer inputs changed')240 require(type(ticket['producers']) is dict and set(ticket['producers']) == set(BRIDGE_SUITES),241 'missing actual equality producer')242 factory = kani.git(ROOT, 'rev-parse', 'HEAD')243 sdk = kani.git(ROOT / 'cdk-rsx', 'rev-parse', 'HEAD')244 require(not kani.git(ROOT / 'cdk-rsx', 'status', '--porcelain'), 'SDK must be clean')245 for suite, record in ticket['producers'].items():246 require(type(record) is dict and set(record) == {'output', 'exit_code', 'result_sha256', 'log_sha256',247 'inputs_sha256', 'staged_sha256'},248 'missing producer report/diagnostic identity')249 require(type(record['output']) is str and type(record['exit_code']) is int250 and record['exit_code'] == int(suite in kani.NEGATIVE_CONTROLS)251 and all(is_digest(record[key]) for key in ('result_sha256', 'log_sha256', 'inputs_sha256'))252 and type(record['staged_sha256']) is dict and set(record['staged_sha256']) == set(STAGED_FILES)253 and all(is_digest(digest) for digest in record['staged_sha256'].values()),254 'invalid producer report/diagnostic identity')255 location = Path(record['output'])256 runs = kani.TEMP / 'runs'257 require(location.parent == runs and location.is_dir() and not location.is_symlink()258 and runs.is_dir() and not runs.is_symlink(),259 'missing producer output')260 files = {name: location / name for name in ('inputs.json', *STAGED_FILES)}261 require(all(path.is_file() and not path.is_symlink() for path in files.values()),262 'missing or symlinked producer metadata/staged file')263 require(kani.sha(files['inputs.json']) == record['inputs_sha256'], 'producer metadata changed')264 require(all(kani.sha(files[name]) == record['staged_sha256'][name] for name in STAGED_FILES),265 'producer staged source changed')266 staged = producer_staging(suite)267 require(all(files[name].read_bytes() == staged[name] for name in STAGED_FILES),268 'producer staged files differ from exact source/configuration')269 sources = snapshot(producer_paths(suite))270 require(all(is_digest(digest) and ticket['sources'].get(name) == digest271 for name, digest in sources.items()), 'producer source differs from consumer')272 expected = {'factory': factory, 'sdk': sdk, 'sdkStatus': '', 'sources': sources,273 'toolIdentity': ticket['toolIdentity'], 'staged': record['staged_sha256'],274 'exactProductionPrefixBytes': len(PRODUCT.read_bytes())}275 require(parse_report(files['inputs.json'].read_text()) == expected,276 'producer metadata/source/configuration differs')277 kani.validate_run(location, suite, record['exit_code'],278 expected_report_sha256=record['result_sha256'],279 expected_log_sha256=record['log_sha256'])280 require(set(ticket['compilers']) == set(VERSIONS), 'missing compiler equivalence check')281 require(all(record['target'] == TARGET and record['version'] == VERSIONS[label]282 for label, record in ticket['compilers'].items()), 'changed compiler target/version')283 require(all(Path(record['path']).is_file() and kani.sha(Path(record['path'])) == record['rustc_sha256']284 for record in ticket['compilers'].values()), 'compiler changed after qualification')285 audit_source()286287288def qualify(output, creusot_compiler, extra=()):289 audit_source()290 paths = input_paths(extra)291 before = snapshot(paths)292 tool_identity = kani.kani_install.capture(kani.TEMP)293 records = compare_compilers(output, creusot_compiler)294 with (kani.TEMP / '.kani-runner.lock').open('w') as lock:295 fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB)296 producers = {suite: kani.run(suite, 180) for suite in BRIDGE_SUITES}297 ticket = {'consumer': str(output), 'target': TARGET, 'sources': before,298 'producers': producers, 'compilers': records, 'toolIdentity': tool_identity}299 verify(ticket, output, paths)300 (output / 'equality-bridge.json').write_text(json.dumps(ticket, indent=2) + '\n')301 return ticket, paths302303304def main():305 parser = argparse.ArgumentParser(description=__doc__)306 parser.add_argument('action', choices=('run', 'controls'), nargs='?', default='run')307 options = parser.parse_args()308 import creusot309 creusot.TEMP.mkdir(exist_ok=True)310 with (creusot.TEMP / '.creusot-runner.lock').open('w') as lock:311 fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB)312 if options.action == 'controls':313 creusot.run(False, 'equality-model')314 creusot.run(False, 'option-equality-model')315 creusot.run(False, 'count-model')316 creusot.run(False, 'ceil-model')317 else:318 creusot.run(False)319320321if __name__ == '__main__':322 try:323 main()324 except (RuntimeError, subprocess.CalledProcessError, BlockingIOError) as error:325 print('Verification refused: ' + str(error), file=sys.stderr)326 sys.exit(1)