buddy_induction.py
verification/tools/buddy_induction.py
1#!/usr/bin/env python32"""Check a byte-identical production coalescing iteration and initial partition."""3from pathlib import Path4import argparse5import datetime6import fcntl7import hashlib8import json9import subprocess10import uuid1112import kani13import run_receipt14from buddy_fragments import unique_between1516ROOT = kani.ROOT17PROOFS = ROOT / 'verification/proofs/allocator/kani'18EXPECTED = {19 'buddy-iteration': {'transient::proofs::' + name for name in (20 'coalesce_iteration_exact_effect', 'coalesce_iteration_free_pending_conservation',21 'initial_reserved_free_partition', 'final_free_insertion_conservation',22 'coalesce_geometry_for_all_coordinates')},23 'buddy-iteration-negative': {'transient::proofs::negative_consumed_buddy_remains_free'},24}25262728def stage(source):29 release = unique_between(source, b' unsafe fn release_span(', b' unsafe fn rebin_page(')30 loop = unique_between(release, b' while order + 1 < ORDERS {',31 b' set_free(page, offset, order);')32 opening = b' while order + 1 < ORDERS {\n'33 closing = b' }\n'34 kani.require(loop.startswith(opening) and loop.endswith(closing), 'Coalescing loop boundary changed')35 body = loop[len(opening):-len(closing)]36 kani.require(body.endswith(b' order += 1;\n'), 'Iteration accounting boundary changed')37 kani.require(body.count(b'break;') == 1, 'Iteration break decision changed')38 wrapper = (b'\n#[cfg(kani)] unsafe fn proof_coalesce_iteration('39 b'page: *mut PageHeader, mut offset: usize, mut order: usize) -> Option<(usize, usize)> {\n'40 b' unsafe {\n loop {\n' + body41 + b' return Some((offset, order));\n }\n None\n }\n}\n')42 kani.require(wrapper.count(body) == 1, 'Iteration bytes were not preserved')43 return wrapper, {'bytes': len(body), 'sha256': hashlib.sha256(body).hexdigest(),44 'scope': 'one loop-body iteration; order+1<8 is a caller premise; no final free insertion'}4546474849def run(suite, timeout):50 checkout = run_receipt.checkout(ROOT)51 kani.kani_obligations.required(suite, EXPECTED[suite])52 tool_identity = kani.kani_install.capture(kani.TEMP)53 suffix = datetime.datetime.now(datetime.timezone.utc).strftime('%Y%m%dT%H%M%SZ')54 output = kani.TEMP / 'runs' / (suffix + '-' + suite + '-' + uuid.uuid4().hex[:8])55 output.mkdir(parents=True)56 proof = PROOFS / ('buddy_iteration_negative.rs' if suite.endswith('negative') else 'buddy_iteration.rs')57 sources = [kani.PLATFORM / 'transient.rs', kani.PLATFORM / 'allocation.rs',58 proof, PROOFS / 'buddy_support.rs', PROOFS.parent / 'shared/coverage.rs', Path(__file__), *run_receipt.INPUTS, Path(kani.__file__),59 Path(kani.__file__).with_suffix('.toml'), Path(__file__).with_name('buddy_fragments.py'),60 *kani.kani_obligations.INPUTS, *kani.kani_install.INPUTS]61 before = {str(p.relative_to(ROOT)): kani.sha(p) for p in sources}62 original = sources[0].read_bytes()63 wrapper, fragment = stage(original)64 tail = wrapper + ('\n#[cfg(kani)] mod proofs { include!(' + json.dumps(str(proof)) + '); }\n').encode()65 (output / 'transient.rs').write_bytes(original + tail)66 (output / 'main.rs').write_text('extern crate core;\n#[path=' + json.dumps(str(sources[1]))67 + '] mod allocation;\nmod transient;\nfn main() {}\n')68 staged = {p.name: kani.sha(p) for p in output.iterdir() if p.is_file()}69 inputs = {**checkout,70 'sources': before, 'toolIdentity': tool_identity, 'staged': staged, 'fragment': fragment,71 'scope': 'native64, actual iteration in one-iteration loop receiver context; no whole-method claim'}72 receipt = run_receipt.write(ROOT, output, inputs)73 metadata_sha = kani.sha(output / 'inputs.json')74 env = kani.environment()75 env['RUSTFLAGS'] = '--edition=2024 -A dead_code --check-cfg=cfg(test)'76 result = output / 'result.json'77 argv = [kani.LAUNCHER / 'kani', output / 'main.rs', '--target-dir', output / 'target',78 '-Z', 'unstable-options', '--harness-timeout', str(timeout) + 's', '--export-json', result]79 print('Running ' + suite + ': ' + str(output), flush=True)80 with (output / 'run.log').open('w') as log:81 process = subprocess.run([str(x) for x in argv], cwd=ROOT, env=env,82 stdout=log, stderr=subprocess.STDOUT)83 receipt.verify()84 kani.require(before == {str(p.relative_to(ROOT)): kani.sha(p) for p in sources}, 'Iteration inputs changed')85 kani.require((output / 'transient.rs').read_bytes() == original + tail, 'Production prefix/iteration changed')86 kani.require(result.is_file(), 'No complete iteration report: inspect run.log')87 kani.EXPECTED_HARNESSES.update(EXPECTED)88 kani.NEGATIVE_CONTROLS['buddy-iteration-negative'] = 'NEGATIVE_CONTROL_COALESCE_BUDDY_REMAINS_FREE'89 kani.kani_install.verify(tool_identity, kani.TEMP)90 summary = kani.validate_run(output, suite, process.returncode)91 print(json.dumps({'suite': suite, 'status': kani.result_status(suite),92 'summary': summary, 'output': str(output)}, indent=2))93 return {'output': str(output), 'exit_code': process.returncode,94 'result_sha256': kani.sha(result), 'log_sha256': kani.sha(output / 'run.log'),95 'inputs_sha256': metadata_sha, 'staged_sha256': staged}969798def main():99 parser = argparse.ArgumentParser(description=__doc__)100 parser.add_argument('--timeout', type=int, default=90)101 args = parser.parse_args()102 with (kani.TEMP / '.buddy-induction.lock').open('w') as lock:103 fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB)104 run('buddy-iteration', args.timeout)105 run('buddy-iteration-negative', args.timeout)106107108if __name__ == '__main__':109 main()