buddy_partition.py

verification/tools/buddy_partition.py

buddy_partition.py176 lines← SDK documentation
1#!/usr/bin/env python32"""Qualify buddy source steps and a separate conditional partition-induction model."""3from pathlib import Path4import argparse5import datetime6import fcntl7import json8import os9import re10import subprocess11import uuid1213import buddy_induction14import kani15import run_receipt16import verus1718ROOT = kani.ROOT19PROOF = ROOT / 'verification/proofs/allocator/verus/buddy_partition.rs'20PROOFS = (21    'live_push_count', 'live_remove_count', 'live_member_positive', 'two_live_members_count',22    'unique_live_cover', 'live_excludes_reserved', 'live_spans_do_not_overlap',23    'initial_partition', 'acquire_preserves_partition', 'begin_release_preserves_partition',24    'coalesce_preserves_partition', 'finish_release_preserves_partition',25    'step_preserves_partition', 'finite_history_partition', 'merge_chain_bound',26    'nonempty_history_exists',27)28EXPECTED_OBLIGATIONS = len(PROOFS) + 1  # recursive live_at also checks termination29NEGATIVE = '''30pub proof fn negative_reserved_alias() {31    let bad = State {32        free: Seq::new(256, |p: int| if p < 2 { 0nat } else { 1nat }),33        live: seq![Span { first: 0, cells: 1 }], pending: None,34    };35    let negative_control_buddy_reserved_alias = partition(bad);36    assert(negative_control_buddy_reserved_alias);37}38'''394041def audit_source(source):42    kani.require(tuple(re.findall(r'^pub proof fn (\w+)\(', source, re.MULTILINE)) == PROOFS,43                 'Partition proof inventory changed')44    kani.require(not re.search(r'\b(?:assume|admit)\s*\(|external_body|\btrusted\b', source),45                 'Unchecked partition assumption/body is not allowed')46    kani.require(source.endswith('\n}\n'), 'Partition macro boundary changed')474849def validate_report(report, exit_code, negative):50    verus.validate_version(report)51    result = report.get('verification-results', {})52    kani.require(result.get('is-verifying-entire-crate') is True53                 and result.get('encountered-vir-error') is False,54                 'Partial/incomplete partition verification')55    kani.require(type(result.get('verified')) is int and type(result.get('errors')) is int,56                 'Invalid partition result counters')57    kani.require(exit_code == (1 if negative else 0)58                 and result.get('success') is (not negative)59                 and result.get('encountered-error') is negative60                 and result['verified'] == EXPECTED_OBLIGATIONS61                 and result['errors'] == (1 if negative else 0),62                 'Unexpected partition result or missing obligations')63    details = report.get('func-details')64    expected = set(PROOFS) | {'live_at'} | ({'negative_reserved_alias'} if negative else set())65    kani.require(isinstance(details, dict) and all('buddy_partition::' + name in details for name in expected),66                 'Missing partition theorem identity')67    for name, detail in details.items():68        kani.require(isinstance(detail, dict) and isinstance(detail.get('failed_proof_notes'), list),69                     'Malformed partition function result')70        if not negative:71            kani.require(not detail['failed_proof_notes'], 'Failed partition proof notes')72    return result737475def validate_negative(stderr, source):76    headers = re.findall(r'^error(?:\[[^\]]+\])?: (.+)$', stderr, re.MULTILINE)77    kani.require(headers == ['assertion failed', 'aborting due to 1 previous error'],78                 'Partition negative failed for an unrelated reason')79    expected_line = str(source.read_text().splitlines().index('    assert(negative_control_buddy_reserved_alias);') + 1)80    locations = re.findall(r'^\s*--> (.+):(\d+):(\d+)\s*$', stderr, re.MULTILINE)81    kani.require(locations and Path(locations[0][0]).resolve() == source.resolve()82                 and locations[0][1] == expected_line83                 and 'assert(negative_control_buddy_reserved_alias)' in stderr,84                 'Partition negative did not identify the exact reserved-alias assertion')858687def run(timeout):88    checkout = run_receipt.checkout(ROOT)89    # The wrapper may otherwise provision a missing Rust pin implicitly. Require90    # a private home with existing read-only distribution links before invoking it.91    home = kani.TEMP / 'rustup'92    kani.require(home.is_dir() and not home.is_symlink(), 'Partition verifier needs a private Rustup home')93    kani.require((home / 'toolchains' / verus.PIN['rust_toolchain'] / 'bin/rustc').is_file(),94                 'Required existing Verus Rust distribution is missing; do not auto-install')95    os.environ['RUSTUP_HOME'] = str(home)96    verus.validate_install()97    source = PROOF.read_text()98    audit_source(source)99    paths = [PROOF, Path(__file__), *run_receipt.INPUTS, Path(buddy_induction.__file__),100             Path(kani.__file__), Path(kani.__file__).with_suffix('.toml'),101             Path(verus.__file__), Path(verus.__file__).with_suffix('.toml'),102             kani.PLATFORM / 'transient.rs', kani.PLATFORM / 'allocation.rs',103             buddy_induction.PROOFS / 'buddy_iteration.rs',104             buddy_induction.PROOFS / 'buddy_iteration_negative.rs',105             buddy_induction.PROOFS / 'buddy_support.rs',106             buddy_induction.PROOFS.parent / 'shared/coverage.rs',107             Path(__file__).with_name('buddy_fragments.py'), *kani.kani_obligations.INPUTS, *kani.kani_install.INPUTS]108    before = {str(p.relative_to(ROOT)): kani.sha(p) for p in paths}109    # These remain separate results. No axiom imports the source producer's110    # theorem into the mathematical model or vice versa.111    producer = [buddy_induction.run('buddy-iteration', 90),112                buddy_induction.run('buddy-iteration-negative', 30)]113    stamp = datetime.datetime.now(datetime.timezone.utc).strftime('%Y%m%dT%H%M%SZ')114    output = kani.TEMP / 'runs' / (stamp + '-buddy-partition-' + uuid.uuid4().hex[:8])115    output.mkdir(parents=True)116    producer_hashes = {str(Path(record['output']) / name): digest117                       for record in producer for name, digest in {118                           'inputs.json': record['inputs_sha256'], 'result.json': record['result_sha256'],119                           'run.log': record['log_sha256'], **record['staged_sha256']}.items()}120    kani.require(all(Path(path).is_file() and not Path(path).is_symlink()121                     and kani.sha(Path(path)) == digest for path, digest in producer_hashes.items()),122                 'Source-step metadata/staged/report files changed before model proof')123    kani.require(before == {str(p.relative_to(ROOT)): kani.sha(p) for p in paths},124                 'Partition/source producer inputs changed')125    staged_inputs = {}126    for negative in (False, True):127        directory = output / ('negative' if negative else 'positive')128        directory.mkdir()129        staged = directory / 'buddy_partition.rs'130        staged.write_text(source[:-3] + NEGATIVE + '\n}\n' if negative else source)131        staged_inputs[str(staged.relative_to(output))] = kani.sha(staged)132    metadata = {**checkout, 'staged': staged_inputs,133                'sources': before, 'requiredProofs': list(PROOFS),134                'sourceStepRuns': [record['output'] for record in producer],135                'sourceStepHashes': producer_hashes,136                'scope': 'conditional mathematical partition/history model; NOT actual whole-method or resource refinement'}137    receipt = run_receipt.write(ROOT, output, metadata)138    env = verus.environment()139    env['RUSTUP_HOME'] = str(home)140    print('Partition model: ' + str(output), flush=True)141    for negative in (False, True):142        directory = output / ('negative' if negative else 'positive')143        staged = directory / 'buddy_partition.rs'144        argv = [verus.TOOL / 'verus', staged, '--crate-type', 'lib', '--crate-name', 'buddy_partition',145                '--output-json', '--no-cheating', '--num-threads', '4',146                '--log-dir', directory / 'solver-logs']147        with (directory / 'result.json').open('w') as out, (directory / 'stderr.log').open('w') as err:148            process = subprocess.run([str(x) for x in argv], cwd=ROOT, env=env,149                                     stdout=out, stderr=err, timeout=timeout)150        receipt.verify()151        verus.validate_install()152        kani.require(before == {str(p.relative_to(ROOT)): kani.sha(p) for p in paths}, 'Partition inputs changed')153        kani.require(all(Path(path).is_file() and not Path(path).is_symlink()154                         and kani.sha(Path(path)) == digest for path, digest in producer_hashes.items()),155                     'Completed source-step metadata/staged/report changed during model proof')156        stderr = (directory / 'stderr.log').read_text()157        kani.require('required rust toolchain' not in stderr, 'Verus runtime was not admitted')158        result = validate_report(verus.parse_report((directory / 'result.json').read_text()),159                                 process.returncode, negative)160        if negative:161            validate_negative(stderr, staged)162        print(('EXPECTED_REJECTION' if negative else 'MODEL_PASS') + ': ' + json.dumps(result), flush=True)163    return output164165166def main():167    parser = argparse.ArgumentParser(description=__doc__)168    parser.add_argument('--timeout', type=int, default=90)169    options = parser.parse_args()170    with (kani.TEMP / '.buddy-induction.lock').open('w') as lock:171        fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB)172        run(options.timeout)173174175if __name__ == '__main__':176    main()