global_bins.py

verification/tools/global_bins.py

global_bins.py247 lines← SDK documentation
1#!/usr/bin/env python32"""Qualify native bin effects/counters and a separate global representation theorem."""3from pathlib import Path4import argparse5import datetime6import fcntl7import json8import re9import subprocess10import sys11import uuid1213import bin_live_count14import kani15import run_receipt16import verus1718ROOT = kani.ROOT19PROOF = ROOT / 'verification/proofs/allocator/verus/global_bins.rs'20PROOFS = (21    'bin_key_encoding','empty_bins','unique_member','linked_is_unique','linked_placement',22    'unlinked_is_unique','unlinked_placement','link_encoded_effects','empty_link_encoded_effects',23    'unlink_encoded_effects','sole_unlink_encoded_effects','reciprocal_neighbors',24    'forward_rank_excludes_cycle','live_count_increment','live_count_decrement',25    'concrete_nonempty_witness','forget_exception','changed_target_exception',26    'rebin_preserves_global','step_preserves_global','arbitrary_finite_histories',27    'concrete_rebin_witness','nonempty_state_transition',28)29# A reviewed contract correspondence, not a theorem exchange between kernels.30# Updating native clauses requires revisiting the model's encoding lemmas.31PRODUCER_SHA = '17b4ac182d20a033cd5c1c1669b3e7af09fa71a4d0c2b04229ce189ce8e44757'32NATIVE_SUITES = ('buddy-bins','buddy-bins-negative','buddy-bins-heap-negative')33COUNTER_SUITES = tuple(bin_live_count.EXPECTED)34STAGED_FILES = ('main.rs','transient.rs')35NEGATIVES = {36    'duplicate': ('negative_duplicate_membership', '''37pub proof fn negative_duplicate_membership() {38    let negative_control_duplicate = unique(seq![seq![1int],seq![1int]]);39    assert(negative_control_duplicate);40}41''', '    assert(negative_control_duplicate);'),42    'wrong-bin': ('negative_wrong_bin', '''43pub proof fn negative_wrong_bin() {44    let negative_control_wrong_bin = placement(seq![seq![1int]],map![1int=>1int],None);45    assert(negative_control_wrong_bin);46}47''', '    assert(negative_control_wrong_bin);'),48}495051def audit(source):52    kani.require(tuple(re.findall(r'^pub proof fn (\w+)\(',source,re.M)) == PROOFS,53                 'Global bin proof inventory changed')54    kani.require(not re.search(r'\b(?:assume|admit)\s*\(|external_body|\btrusted\b',source),55                 'Unchecked global-bin assumption/body')56    kani.require(source.endswith('\n}\n'), 'Global model macro boundary changed')57    native = ROOT/'verification/proofs/allocator/kani/buddy_bins.rs'58    kani.require(kani.sha(native) == PRODUCER_SHA, 'Native bin postconditions changed; review representation bridge')596061def validate_model(report, exit_code, negative=None):62    kani.require(type(exit_code) is int and (negative is None or negative in NEGATIVES), 'Invalid model result mode')63    verus.validate_version(report)64    result = report.get('verification-results',{})65    kani.require(result.get('is-verifying-entire-crate') is True and result.get('encountered-vir-error') is False,66                 'Partial/incomplete global model proof')67    kani.require(type(result.get('verified')) is int and type(result.get('errors')) is int,68                 'Invalid global model counters')69    kani.require(exit_code == (1 if negative else 0) and result.get('success') is (not bool(negative))70        and result.get('encountered-error') is bool(negative)71        and result['verified'] == len(PROOFS) and result['errors'] == (1 if negative else 0),72        'Global model missing proofs or unexpected result')73    details = report.get('func-details')74    expected = set(PROOFS) | ({NEGATIVES[negative][0]} if negative else set())75    kani.require(isinstance(details,dict) and all('global_bins::'+name in details for name in expected),76                 'Missing local global-bin theorem identity')77    for value in details.values():78        kani.require(isinstance(value,dict) and isinstance(value.get('failed_proof_notes'),list),79                     'Malformed global function detail')80        if not negative: kani.require(not value['failed_proof_notes'], 'Failed global proof notes')81    return result828384def validate_negative(stderr, source, negative):85    headers = re.findall(r'^error(?:\[[^\]]+\])?: (.+)$',stderr,re.M)86    kani.require(headers == ['assertion failed','aborting due to 1 previous error'],87                 'Unrelated global-bin negative failure')88    assertion = NEGATIVES[negative][2]89    line = str(source.read_text().splitlines().index(assertion)+1)90    locations = re.findall(r'^\s*--> (.+):(\d+):(\d+)\s*$',stderr,re.M)91    kani.require(locations and Path(locations[0][0]).resolve() == source.resolve()92        and locations[0][1] == line and assertion.strip() in stderr,93        'Wrong global-bin negative assertion')949596def producer_inputs():97    return [PROOF,Path(__file__),*run_receipt.INPUTS,Path(bin_live_count.__file__),Path(verus.__file__),98        Path(verus.__file__).with_suffix('.toml'),Path(kani.__file__),Path(kani.__file__).with_suffix('.toml'),99        Path(__file__).with_name('buddy_fragments.py'),kani.PLATFORM/'transient.rs',kani.PLATFORM/'allocation.rs',100        *[ROOT/'verification/proofs/allocator/kani'/n for n in ('buddy_bins.rs','buddy_bins_negative.rs','buddy_bins_heap_negative.rs','buddy_bins_negative_support.rs',101            'buddy_live_count.rs','buddy_live_count_negative.rs','buddy_support.rs')],102        *kani.kani_obligations.INPUTS,*kani.kani_install.INPUTS]103104105def producer_paths(suite):106    """Independent, complete input admission for each native producer."""107    kani.require(suite in (*NATIVE_SUITES,*COUNTER_SUITES), 'Unknown bin producer')108    proofs=ROOT/'verification/proofs/allocator/kani'109    if suite in NATIVE_SUITES:110        paths=[kani.PLATFORM/'allocation.rs',kani.PLATFORM/'transient.rs',proofs/kani.SUITES[suite][0],111               proofs/'buddy_support.rs']112        if suite.endswith('-negative'):paths.append(proofs/'buddy_bins_negative_support.rs')113    else:114        paths=[kani.PLATFORM/'transient.rs',kani.PLATFORM/'allocation.rs',115               proofs/('buddy_live_count_negative.rs' if suite.endswith('-negative') else 'buddy_live_count.rs'),116               proofs/'buddy_support.rs',Path(bin_live_count.__file__),Path(__file__).with_name('buddy_fragments.py')]117    return [*paths,Path(kani.__file__),Path(kani.__file__).with_suffix('.toml'),118            *kani.kani_obligations.INPUTS,*kani.kani_install.INPUTS]119120121def producer_staging(suite):122    """Reconstruct both compiled files, including exact native/prefix bytes."""123    original=(kani.PLATFORM/'transient.rs').read_bytes()124    proof=(ROOT/'verification/proofs/allocator/kani'/kani.SUITES[suite][0] if suite in NATIVE_SUITES125           else bin_live_count.PROOFS/('buddy_live_count_negative.rs' if suite.endswith('-negative') else 'buddy_live_count.rs'))126    wrapper,fragment=(b'',None) if suite in NATIVE_SUITES else bin_live_count.stage(original)127    tail=wrapper+('\n#[cfg(kani)] mod proofs { include!('+json.dumps(str(proof))+'); }\n').encode()128    main=('extern crate core;\n#[path='+json.dumps(str(kani.PLATFORM/'allocation.rs'))129          +'] mod allocation;\nmod transient;\nfn main() {}\n').encode()130    return {'main.rs':main,'transient.rs':original+tail},len(original),fragment131132133def producer_files(output):134    """Fresh producer artifacts must be direct, regular files in our run root."""135    output=Path(output)136    runs=kani.TEMP/'runs'137    kani.require(output.parent==runs and output.is_dir() and not output.is_symlink()138        and runs.is_dir() and not runs.is_symlink(),'Wrong source result location')139    files={name:output/name for name in ('inputs.json','result.json','run.log',*STAGED_FILES)}140    kani.require(all(path.is_file() and not path.is_symlink() for path in files.values()),141                 'Missing or symlinked native metadata/staged/result file')142    return files143144145def is_digest(value):146    return type(value) is str and re.fullmatch(r'[0-9a-f]{64}',value) is not None147148149def verify_producers(producers, source_before, paths, tool, sdk, factory):150    kani.require(type(producers) is dict and set(producers) == set((*NATIVE_SUITES,*COUNTER_SUITES)),151                 'Missing source bin/counter producer')152    _verify_records(producers, source_before, paths, tool, sdk, factory)153154155def verify_bins(producers, source_before, paths, tool, sdk, factory):156    """Consume only the fixed complete native link/unlink/rebin family."""157    kani.require(type(producers) is dict and set(producers) == set(NATIVE_SUITES),158                 'Missing or extra source bin producer; duplicate suite collections are refused')159    _verify_records(producers, source_before, paths, tool, sdk, factory)160161162def _verify_records(producers, source_before, paths, tool, sdk, factory):163    kani.require(source_before == {str(p.relative_to(ROOT)):kani.sha(p) for p in paths},164                 'Global/native inputs changed')165    kani.require(sdk==kani.git(ROOT/'cdk-rsx','rev-parse','HEAD')166        and not kani.git(ROOT/'cdk-rsx','status','--porcelain')167        and factory==kani.git(ROOT,'rev-parse','HEAD')168        and not kani.git(ROOT,'status','--porcelain'),'Global/native checkout identity changed')169    kani.kani_install.verify(tool,kani.TEMP)170    for suite,record in producers.items():171        kani.require(type(record) is dict and set(record)=={'output','exit_code','result_sha256','log_sha256',172            'inputs_sha256','staged_sha256'} and type(record['output']) is str173            and type(record['exit_code']) is int and record['exit_code']==int(suite.endswith('-negative'))174            and all(is_digest(record[key]) for key in ('result_sha256','log_sha256','inputs_sha256'))175            and type(record['staged_sha256']) is dict and set(record['staged_sha256'])==set(STAGED_FILES)176            and all(is_digest(value) for value in record['staged_sha256'].values()),'Incomplete source qualification')177        output=Path(record['output']);files=producer_files(output)178        kani.require(kani.sha(files['inputs.json'])==record['inputs_sha256'],'Native producer metadata changed')179        kani.require(all(kani.sha(files[name])==record['staged_sha256'][name] for name in STAGED_FILES),180                     'Native producer staged files changed')181        staged,prefix,fragment=producer_staging(suite)182        kani.require(all(files[name].read_bytes()==staged[name] for name in STAGED_FILES),183                     'Native staged files differ from exact source/configuration')184        sources={str(p.relative_to(ROOT)):kani.sha(p) for p in producer_paths(suite)}185        kani.require(all(is_digest(digest) and source_before.get(name)==digest for name,digest in sources.items()),186                     'Native producer source differs from global consumer')187        expected={'factory':factory,'sdk':sdk,'sdkStatus':'','sources':sources,'toolIdentity':tool}188        if suite in NATIVE_SUITES:189            expected.update(staged=record['staged_sha256'],exactProductionPrefixBytes=prefix)190        else:191            expected.update(staged=record['staged_sha256'],sourceFragment=fragment)192        kani.require(verus.parse_report(files['inputs.json'].read_text())==expected,193                     'Native producer metadata/source/configuration differs')194        kani.validate_run(output,suite,record['exit_code'],expected_report_sha256=record['result_sha256'],195            expected_log_sha256=record['log_sha256'])196197198def run(timeout):199    checkout=run_receipt.checkout(ROOT)200    source=PROOF.read_text();audit(source);verus.validate_install()201    paths=producer_inputs();before={str(p.relative_to(ROOT)):kani.sha(p) for p in paths}202    sdk=checkout['sdk'];factory=checkout['factory']203    tool=kani.kani_install.capture(kani.TEMP)204    with (kani.TEMP/'.kani-runner.lock').open('w') as lock:205        fcntl.flock(lock,fcntl.LOCK_EX|fcntl.LOCK_NB)206        producers={suite:kani.run(suite,90) for suite in NATIVE_SUITES}207        producers['buddy-live-count']=bin_live_count.run(False)208        producers['buddy-live-count-negative']=bin_live_count.run(True)209    verify_producers(producers,before,paths,tool,sdk,factory)210    output=kani.TEMP/'runs'/(datetime.datetime.now(datetime.timezone.utc).strftime('%Y%m%dT%H%M%SZ')211        +'-global-bins-'+uuid.uuid4().hex[:8]);output.mkdir(parents=True)212    staged_inputs={}213    for negative in (None,*NEGATIVES):214        directory=output/(negative or 'positive');directory.mkdir()215        staged=directory/'global_bins.rs'216        staged.write_text(source if negative is None else source[:-3]+NEGATIVES[negative][1]+'\n}\n')217        staged_inputs[str(staged.relative_to(output))]=kani.sha(staged)218    receipt=run_receipt.write(ROOT,output,{**checkout,'staged':staged_inputs,219        'sources':before,'nativeProducers':producers,'toolIdentity':tool,'requiredProofs':PROOFS,220        'scope':'separate canonical list representation/induction theorem; native/model correspondence is reviewed, not shared-kernel proof'})221    for negative in (None,*NEGATIVES):222        directory=output/(negative or 'positive')223        staged=directory/'global_bins.rs'224        argv=[verus.TOOL/'verus',staged,'--crate-type','lib','--crate-name','global_bins',225            '--output-json','--no-cheating','--num-threads','4','--log-dir',directory/'solver-logs']226        with (directory/'result.json').open('w') as out,(directory/'stderr.log').open('w') as err:227            result=subprocess.run([str(x) for x in argv],cwd=ROOT,env=verus.environment(),stdout=out,stderr=err,timeout=timeout)228        receipt.verify()229        verify_producers(producers,before,paths,tool,sdk,factory)230        verus.validate_install()231        summary=validate_model(verus.parse_report((directory/'result.json').read_text()),result.returncode,negative)232        if negative:validate_negative((directory/'stderr.log').read_text(),staged,negative)233        print(('EXPECTED_'+negative.upper().replace('-','_')+'_REJECTION' if negative else 'GLOBAL_MODEL_PASS')+': '+json.dumps(summary),flush=True)234    return output235236237def main():238    parser=argparse.ArgumentParser(description=__doc__);parser.add_argument('--timeout',type=int,default=90)239    options=parser.parse_args()240    with (kani.TEMP/'.global-bins.lock').open('w') as lock:241        fcntl.flock(lock,fcntl.LOCK_EX|fcntl.LOCK_NB);run(options.timeout)242243244if __name__=='__main__':245    try:main()246    except (RuntimeError,subprocess.CalledProcessError,subprocess.TimeoutExpired,BlockingIOError) as error:247        print('Global bin qualification refused: '+str(error),file=sys.stderr);sys.exit(1)