hylix_publication.py
verification/tools/hylix_publication.py
1#!/usr/bin/env python32"""Source-bound Hylix context/dirty-range seed and actual native publication paths."""3from pathlib import Path4import argparse5import datetime6import fcntl7import hashlib8import json9import os10import resource11import subprocess12import sys13import tomllib14import uuid15import kani16import native_witness17import run_receipt18from rust_source import complete_item1920ROOT=kani.ROOT21SDK=ROOT/'cdk-rsx/crates'22WORKING=SDK/'cdk-rsx-engine-hylix/src/working_set.rs'23CONTEXT=WORKING.with_name('context.rs')24ARENA=WORKING.with_name('arena.rs')25PROOFS=ROOT/'verification/proofs/hylix/kani'26NATIVE=ROOT/'verification/proofs/hylix/native/publication.rs'27MANIFEST=Path(__file__).with_suffix('.toml')28COMPONENTS=[kani.PLATFORM/'memory.rs',*[kani.PLATFORM/('memory/'+n+'.rs') for n in ('error','region','page_pool')]]29STORAGE_ITEMS=('#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]\npub struct Block','impl Block {','pub trait Storage {')30SUITES={31 'context':('context_publication.rs',{'context::proofs::'+n for n in (32 'actual_update_finishes_after_normal_and_returned_error',33 'actual_query_discards_and_cannot_obtain_mutable_storage',34 'actual_constructed_loan_ends_before_finalization_and_next_epoch',35 'actual_epoch_check_and_drop_have_exact_conditional_scalar_effect')}),36 'err-negative':('context_negative.rs',{'context::proofs::negative_returned_error_discards_instead_of_finishing'}),37 'query-negative':('context_negative.rs',{'context::proofs::negative_query_calls_finish'}),38 'epoch-negative':('context_negative.rs',{'context::proofs::negative_stale_guard_can_publish'}),39 'dirty':('dirty_ranges.rs',{'working_set::proofs::actual_segment_dirty_union_empty_and_clear'}),40 'dirty-negative':('dirty_ranges_negative.rs',{'working_set::proofs::negative_later_edit_replaces_prior_dirty_interval'}),41 'cold-research':('publication_probe.rs',{'working_set::proofs::actual_working_set_frontend_probe'}),42}43NEGATIVES={'err-negative':'NEGATIVE_CONTROL_HYLIX_ERR_DISCARDS',44 'query-negative':'NEGATIVE_CONTROL_HYLIX_QUERY_FINISHES',45 'epoch-negative':'NEGATIVE_CONTROL_HYLIX_STALE_GUARD_ACCEPTED',46 'dirty-negative':'NEGATIVE_CONTROL_HYLIX_PRIOR_DIRTY_RANGE_LOST'}474849def register():50 for key,(_,harnesses) in SUITES.items():kani.EXPECTED_HARNESSES['hylix-publication-'+key]=harnesses51 for key,text in NEGATIVES.items():kani.NEGATIVE_CONTROLS['hylix-publication-'+key]=text525354def inputs():55 helpers=[p for p in (ROOT/'verification/tools').iterdir() if p.is_file() and p.suffix in ('.py','.toml','.nix','.patch')]56 return list(dict.fromkeys([WORKING,CONTEXT,ARENA,*COMPONENTS,*sorted(PROOFS.glob('*.rs')),NATIVE,MANIFEST,57 *helpers,ROOT/'cdk-rsx/rust-toolchain.toml']))585960def snapshot():return {str(p.relative_to(ROOT)):kani.sha(p) for p in inputs()}616263def local_manifest(before):64 source=MANIFEST.read_bytes()65 kani.require(hashlib.sha256(source).hexdigest()==before[str(MANIFEST.relative_to(ROOT))],66 'Hylix manifest changed after source capture')67 return tomllib.loads(source.decode())686970def storage_source():71 original=ARENA.read_text()72 fragments={marker:complete_item(original,marker) for marker in STORAGE_ITEMS}73 staged='use crate::{Error,Result};\n'+'\n'.join(fragments.values())+'\n'74 staged+='pub(crate) fn fixture_block()->Block { Block { offset:1,generation:1 } }\n'75 return staged,{key:hashlib.sha256(value.encode()).hexdigest() for key,value in fragments.items()}767778def stage(output,suite):79 (output/'memory').mkdir()80 (output/'memory.rs').write_bytes(COMPONENTS[0].read_bytes())81 for source in COMPONENTS[1:]:(output/'memory'/source.name).write_bytes(source.read_bytes())82 storage,fragments=storage_source();(output/'storage.rs').write_text(storage)83 working_tail=context_tail=''84 if suite=='native':85 (output/'native_publication.rs').write_bytes(NATIVE.read_bytes())86 working_tail='\n#[path="native_publication.rs"] pub mod native_cases;\n'87 else:88 filename,harnesses=SUITES[suite]89 selected=PROOFS/filename90 support=(PROOFS/'context_support.rs') if next(iter(harnesses)).startswith('context::') else None91 tail='\n#[cfg(kani)] mod proofs { '+('include!('+json.dumps(str(support))+'); ' if support else '')92 tail+='include!('+json.dumps(str(selected))+'); }\n'93 if support:context_tail=tail94 else:working_tail=tail95 (output/'working_set.rs').write_bytes(WORKING.read_bytes()+working_tail.encode())96 (output/'context.rs').write_bytes(CONTEXT.read_bytes()+context_tail.encode())97 entry='working_set::native_cases::run();' if suite=='native' else ''98 (output/'main.rs').write_text('#![allow(dead_code,unexpected_cfgs)]\nextern crate self as cdk_rsx_platform;\n'99 'pub mod memory; pub use memory::{MemoryError as Error,MemoryResult as Result};\n'100 'mod storage;pub use storage::{Storage,Block};mod context;mod working_set;\nfn main(){'+entry+'}\n')101 files={str(p.relative_to(output)):kani.sha(p) for p in output.rglob('*') if p.is_file()}102 return files,fragments103104105def output_dir(label):106 stamp=datetime.datetime.now(datetime.timezone.utc).strftime('%Y%m%dT%H%M%SZ')107 output=kani.TEMP/('hylix-publication-'+label+'-'+stamp+'-'+uuid.uuid4().hex[:8]);output.mkdir();return output108109110def unchanged(before,receipt,tools=None):111 receipt.verify();kani.require(snapshot()==before,'Hylix input changed')112 if tools is not None:kani.kani_install.verify(tools,kani.TEMP)113114115def run(suite,timeout):116 run_receipt.checkout(ROOT);key='hylix-publication-'+suite117 before=snapshot();manifest=local_manifest(before)118 kani.kani_obligations.required(key,SUITES[suite][1],manifest=manifest)119 tools=kani.kani_install.capture(kani.TEMP)120 output=output_dir(suite);staged,fragments=stage(output,suite)121 scope=('actual complete context source and actual Block/Storage declarations, one conditional 16-byte '122 'Storage image/trace with read-only discard and exact I/O; method-local epoch scalar premise '123 'separate from reached guard construction' if suite in ('context','err-negative','query-negative','epoch-negative') else124 'actual complete WorkingSet source, actual Segment scalar dirty interval effects with a real 512-byte '125 'scoped word owner; bounded valid edit ranges, no HashMap/Rc/cache-publication theorem')126 if suite=='cold-research':scope='unqualified actual cold WorkingSet 512-byte segment, one-slot cache, 1536-byte provider feasibility'127 receipt=run_receipt.write(ROOT,output,{'sources':before,'staged':staged,'toolIdentity':tools,128 'sourceFragments':fragments,'hostStackBytes':list(resource.getrlimit(resource.RLIMIT_STACK)),129 'scope':'native64; '+scope+'; std/raw/verifier premises explicit; not an IC/world/Arena/Store ownership theorem'})130 env=kani.environment();env['CARGO_HOME']=str(kani.TEMP/'hylix-cargo-home')131 env['RUSTFLAGS']='--edition=2024 -A dead_code --check-cfg=cfg(test)'132 argv=[kani.LAUNCHER/'kani',output/'main.rs','--target-dir',output/'target','-Z','unstable-options',133 '--harness-timeout',str(timeout)+'s','--exact','--export-json',output/'result.json']134 for harness in sorted(SUITES[suite][1]):argv+=['--harness',harness]135 print('Hylix '+suite+': '+str(output),flush=True)136 with (output/'run.log').open('w') as log:137 result=subprocess.run([str(x) for x in argv],cwd=ROOT,env=env,stdout=log,stderr=subprocess.STDOUT)138 unchanged(before,receipt,tools)139 summary=kani.validate_run(output,key,result.returncode,manifest=manifest)140 print(json.dumps({'suite':key,'status':kani.result_status(key),'summary':summary,'output':str(output)},indent=2),flush=True)141 return output142143144def native():145 run_receipt.checkout(ROOT);before,compiler=snapshot(),native_witness.compiler_identity()146 output=output_dir('native');staged,fragments=stage(output,'native')147 receipt=run_receipt.write(ROOT,output,{'sources':before,'staged':staged,'compiler':compiler,'sourceFragments':fragments,148 'scope':'native-only complete actual WorkingSet/context source; finite event/byte integration over '149 'exclusive owned 1536-byte provider and forwarding Storage fixture, no decoded Arena metadata; not formal engine ownership or IC rollback'})150 env=native_witness.environment(Path(compiler['path']));artifact=output/'witness'151 argv=[compiler['path'],'--edition=2024','--target',kani.PIN['target'],'-Cpanic=unwind',output/'main.rs','-o',artifact]152 with (output/'compile.log').open('wb') as log:153 compiled=subprocess.run([str(x) for x in argv],cwd=output,env=env,stdout=log,stderr=subprocess.STDOUT,timeout=120)154 unchanged(before,receipt);kani.require(native_witness.compiler_identity()==compiler,'Native compiler changed')155 kani.require(compiled.returncode==0 and native_witness.regular(artifact) and os.access(artifact,os.X_OK),'Hylix native fixture compilation failed')156 sealed={name:kani.sha(output/name) for name in ('compile.log','witness')}157 with (output/'run.stdout').open('wb') as stdout,(output/'run.stderr').open('wb') as stderr:158 ran=subprocess.run([str(artifact)],cwd=output,env=env,stdout=stdout,stderr=stderr,timeout=30)159 unchanged(before,receipt);kani.require(native_witness.compiler_identity()==compiler,'Native compiler changed')160 kani.require(all(native_witness.regular(output/name) and kani.sha(output/name)==digest for name,digest in sealed.items()),'Native artifact changed')161 kani.require(ran.returncode==0 and (output/'run.stdout').read_bytes()==b'hylix_actual_publication_context_ok\n','Hylix native context failed')162 files={**staged,**sealed,**{name:kani.sha(output/name) for name in ('run.stdout','run.stderr')}}163 record={'compiler':compiler,'sources':before,'files':files,'scope':'native finite integration only'}164 (output/'native.json').write_text(json.dumps(record,indent=2)+'\n')165 kani.require(all(native_witness.regular(output/name) and kani.sha(output/name)==digest for name,digest in files.items()),'Native context output changed')166 print(json.dumps({'suite':'hylix-publication-native','status':'PASS','output':str(output)},indent=2),flush=True)167 return output168169170def main():171 parser=argparse.ArgumentParser(description=__doc__);parser.add_argument('suite',nargs='?',default='all',choices=('all','native',*SUITES));parser.add_argument('--timeout',type=int,default=90)172 args=parser.parse_args();register()173 with (kani.TEMP/'.kani-runner.lock').open('w') as lock:174 fcntl.flock(lock,fcntl.LOCK_EX|fcntl.LOCK_NB)175 if args.suite in ('all','native'):native()176 for suite in [s for s in SUITES if not s.endswith('-research')] if args.suite=='all' else (() if args.suite=='native' else (args.suite,)):run(suite,args.timeout)177178179if __name__=='__main__':180 try:main()181 except (RuntimeError,subprocess.CalledProcessError,BlockingIOError) as error:182 print('Verification refused: '+str(error),file=sys.stderr);sys.exit(1)