store_completion.py
verification/tools/store_completion.py
1#!/usr/bin/env python32"""Source-exact Store natural cleanup components and retained provider diagnostics."""3import native_sdk4from pathlib import Path5import argparse6import fcntl7import hashlib8import json9import re10import subprocess11import sys12import tomllib13import uuid14import kani15import run_receipt16import store_conversion as lower17from rust_source import complete_item18ROOT = kani.ROOT19SDK = lower.SDK20STORE = lower.STORE21PROOFS = ROOT / 'verification/proofs/store-completion'22MANIFEST = Path(__file__).with_suffix('.toml')23SUITES = {'natural-research': ('positive.rs', 'actual_single_snapshot_natural_context_cleanup'), 'destructor': ('drop.rs', 'actual_nonempty_context_destructor'), 'query-research': ('query.rs', 'actual_public_query_natural_cleanup'), 'dual': ('dual.rs', 'actual_dual_erased_owner_cleanup'), 'single-query-research': ('single.rs', 'actual_single_public_query_cleanup'), 'borrowed-query-research': ('borrowed.rs', 'actual_borrowed_provider_query_cleanup'), 'anchor-research': ('anchor.rs', 'actual_seeded_vtable_public_query_cleanup'), 'vtable-research': ('single.rs', 'actual_single_public_query_cleanup'), 'read-context': ('read_context.rs', 'actual_read_context_natural_completion')}24SUITES.update({'active-negative': ('negative.rs','negative_read_context_stays_active'),25 'provider-negative': ('negative.rs','negative_provider_owner_survives')})26NEGATIVES = {'active-negative':'NEGATIVE_CONTROL_STORE_COMPLETION_ACTIVE',27 'provider-negative':'NEGATIVE_CONTROL_STORE_COMPLETION_PROVIDER_DROP'}28SCOPE = ('Conditional native64 exact retained-directory Store projection and supplied decoded clean Row/liveness; '29 'Global/std/Any/compiler/verifier and native TLS are leaves. No native Core/BTreeMap, general module tree, '30 'complete write/record flush, Nyxus allocator, Wasm ABI or IC theorem. ')31SCOPES = {'natural-research': 'One supplied decoded clean Row and valid distinct record identity; complete actual execute_write '32 'and FrameRecords.finish with natural owning cleanup; no provider required or entered, no miss decode/public guards; unwind4.'}3334SCOPES['destructor'] = 'One actual nonempty Context natural destructor without calling finish; supplied decoded clean Row, actual owning Box/Vec/RefCell and retained directory destruction, no Active entry or provider; unwind4.'35SCOPES['query-research'] = 'Actual public Store.read, retained Hylix provider dispatch, complete using_read/enter/Reset/WorkingFrame, complete execute_read/Active and natural nonempty Context destruction; one supplied initialized decoded clean Row, successful and ordinary Err query then empty second frame, provider destruction; unwind4.'36SCOPES['dual'] = 'Actual attached Box<dyn Storage> and nonempty Context Box<dyn BufferedValue> natural cleanup without entering Store/provider TLS or finish; unwind4.'37SCOPES['single-query-research'] = 'One complete actual public query with attached provider and one supplied decoded clean snapshot; ordinary result, Store/provider TLS exit and natural owning cleanup; unwind4.'38SCOPES['borrowed-query-research'] = 'Complete actual engine using_read and Store execute_read with caller-owned Image provider, one supplied decoded clean snapshot, ordinary result, actual TLS exit and natural owning cleanup; Store.hylix_read provider owner bridge excluded; unwind4.'39SCOPES['anchor-research'] = SCOPES['single-query-research'] + ' Additional independent actual erased Buffered<Row> create/drop seeds the exact destructor call graph; experimental only.'40SCOPES['vtable-research'] = SCOPES['single-query-research'] + ' Conservative no-restrict-vtable diagnostic, unqualified even if successful.'41SCOPES['read-context'] = 'Complete actual execute_read/Active and natural nonempty Context destruction with supplied decoded clean Row; no provider or public Store provider dispatch, no finish; unwind4.'42SCOPES['active-negative'] = SCOPES['read-context'] + ' Exact false retained Active claim, shared positive helper.'43SCOPES['provider-negative'] = SCOPES['dual'] + ' Exact false surviving provider claim, shared positive helper.'4445def scope_for(suite):46 return SCOPE + SCOPES[suite]47484950def context():51 import store_records52 source, fragments = store_records.context()53 source = replace_once(source, 'include!(' + json.dumps(str(store_records.PROOFS/'kani/scope.rs')) + ');',54 'include!(' + json.dumps(str(PROOFS/'kani/scope.rs')) + ');')55 source = replace_once(source, 'pub use context::{using,using_read,with_storage,with_storage_read,check_no_loans};', 'pub use context::{using,using_read,with_storage,with_storage_read,check_no_loans,context_id};')56 backend_source = (STORE/'backend.rs').read_text()57 items = [complete_item(backend_source, anchor) for anchor in (58 'pub fn with_hylix<S:', 'fn hylix(&self)', 'fn hylix_read<R>', 'pub fn read<R>')]59 fragments += items60 method = items[1]61 method = replace_once(method, ' #[cfg(not(target_family = "wasm"))]\n {\n &self.core.hylix\n }\n', '')62 method = replace_once(method, ' #[cfg(target_family = "wasm")]\n', '')63 backend_module = complete_item(source, 'mod backend {')64 backend_module_new = backend_module[:-1] + '\nimpl Store {\n' + '\n'.join([items[0],method,*items[2:]]) + '\n}\n}'65 source = replace_once(source, backend_module, backend_module_new)66 source = replace_once(source, 'use scope::{Access,Scope,Upgrade,Detached};', 'use scope::{Access,Scope,ReadScope,Upgrade,Detached};')67 return source, fragments686970def sources():71 import store_records72 return list(dict.fromkeys([*store_records.sources(),73 *sorted(path for path in PROOFS.rglob('*') if path.is_file())]))747576def staged(suite):77 source, fragments = context()78 tail = '\n#[cfg(kani)] mod proofs {use super::*; use cdk_rsx_engine_hylix::{Error as EngineError,Result as EngineResult};\n'79 for file in ('storage.rs','support.rs',SUITES[suite][0]):80 tail += 'include!(' + json.dumps(str(PROOFS/'kani'/file)) + ');\n'81 tail += '}\n'82 old = complete_item(source, 'mod hylix {')83 new = old[:-1] + tail + '}\n'84 source = replace_once(source, old, new)85 source += '\nfn main() {}\n'86 return {'main.rs': source.encode()}, fragments878889CONTROLS = {90 'body': ('read-context',' ACTIVE.set(std::ptr::null());',' // mutation: Store TLS exit omitted'),91 'erasure': ('dual',' &self.hylix',' &self.core.hylix'),92}939495def body_files(kind='body'):96 suite, old, new = CONTROLS[kind]97 files, _ = staged(suite)98 files['main.rs'] = replace_once(files['main.rs'].decode(),old,new).encode()99 return files100101102def expected_command(output, suite):103 command = list(map(str, [kani.LAUNCHER/'kani',output/'main.rs','--target-dir',output/'target',104 '-Z','unstable-options','--harness-timeout','90s','--exact','--export-json',output/'result.json',105 '--harness','hylix::proofs::'+SUITES[suite][1]]))106 if suite == 'vtable-research': command += ['-Z','restrict-vtable','--no-restrict-vtable']107 return command108109110def body_control(kind='body'):111 checkout = run_receipt.checkout(ROOT)112 before = snapshot(sources())113 output = directory(kind)114 files = body_files(kind)115 for name, contents in files.items(): (output/name).write_bytes(contents)116 require(run_receipt.checkout(ROOT)==checkout,'checkout changed before source admission')117 receipt=run_receipt.write(ROOT,output,{'sources':before,118 'staged':{name:kani.sha(output/name) for name in files},'control':kind,'suite':CONTROLS[kind][0]})119 try:120 verify_stage(output,CONTROLS[kind][0])121 except RuntimeError as error:122 require(str(error)=='Store completion: exact selected source changed','unrelated source rejection')123 receipt.verify()124 require(snapshot(sources())==before,'source control input changed')125 digest=seal(output,{'kind':'body','control':kind,'suite':CONTROLS[kind][0],126 'status':'EXPECTED_SOURCE_REJECTION'})127 print('STORE_COMPLETION_SOURCE_REJECTION',kind,output,digest,flush=True)128 return output,digest129 raise RuntimeError('designated source change admitted')130131132def require(ok, message):133 kani.require(ok, 'Store completion: ' + message)134135def register():136 for suite, (_, name) in SUITES.items():137 kani.EXPECTED_HARNESSES['store-completion-' + suite] = {'hylix::proofs::' + name}138 for suite, marker in NEGATIVES.items():139 kani.NEGATIVE_CONTROLS['store-completion-' + suite] = marker140141def replace_once(source, old, new):142 require(source.count(old) == 1, 'source anchor changed: ' + old)143 return source.replace(old, new)144145def snapshot(paths):146 return {str(path.relative_to(ROOT)): kani.sha(path) for path in paths}147148def stage(output, suite):149 files, fragments = staged(suite)150 for name, contents in files.items():151 (output / name).write_bytes(contents)152 return {name: kani.sha(output / name) for name in files}, fragments153154def verify_stage(output, suite):155 files, _ = staged(suite)156 require(all(run_receipt.regular(output / name) and (output / name).read_bytes() == contents157 for name, contents in files.items()), 'exact selected source changed')158159def validate_report(report, suite, code, manifest):160 key = 'store-completion-' + suite161 summary = kani.validate_report(report, key, code, manifest=manifest)162 if suite in NEGATIVES:163 required = kani.kani_obligations.required(key, kani.EXPECTED_HARNESSES[key], manifest=manifest)164 marker = kani.kani_obligations.normalized(json.dumps(NEGATIVES[suite]))165 designated = [item for rows in required.values() for item in rows166 if item.category == 'assertion' and item.description == marker]167 failed = [check for row in report['verification_results']['results'] for check in row['checks']168 if check['status'] == 'Failure']169 require(len(designated) == len(failed) == 1 and170 kani.kani_obligations.check_identity(failed[0]) == designated[0], 'negative failed away from designated assertion')171 return summary172173def directory(label):174 output = kani.TEMP / ('store-completion-' + label + '-' + uuid.uuid4().hex[:8])175 output.mkdir()176 return output177178def seal(output, record):179 require(not (output / 'completed.json').exists(), 'completion already exists')180 artifacts = {str(path.relative_to(output)): kani.sha(path) for path in output.iterdir() if path.is_file()}181 (output / 'completed.json').write_text(json.dumps({**record, 'artifacts': artifacts}, indent=2) + '\n')182 return kani.sha(output / 'completed.json')183184def recorded_environment():185 kani.environment() # Existing installation readiness only; never inherit its ambient environment.186 return {'CARGO_HOME': str(kani.TEMP / 'store-completion-kani-cargo-home'),187 'RUSTFLAGS': '--edition=2024 -A dead_code --check-cfg=cfg(test)',188 'RUSTUP_HOME': str(kani.TEMP / 'rustup'), 'RUSTUP_TOOLCHAIN': kani.PIN['rust_toolchain'],189 'RUSTUP_AUTO_INSTALL': '0', 'CARGO_BUILD_JOBS': '1', 'CARGO_NET_OFFLINE': 'true',190 'KANI_HOME': str(kani.TEMP / kani.PIN['home_dir']),191 'RUSTC': str(kani.KANI / 'toolchain/bin/rustc'),192 'CARGO': str(kani.KANI / 'toolchain/bin/cargo'),193 'PATH': str(kani.KANI / 'toolchain/bin') + ':/run/current-system/sw/bin:/usr/bin:/bin',194 'PYTHONDONTWRITEBYTECODE': '1', 'LANG': 'C', 'LC_ALL': 'C', 'TZ': 'UTC'}195196def run(suite):197 register()198 checkout = run_receipt.checkout(ROOT)199 paths = sources()200 before = snapshot(paths)201 manifest = tomllib.loads(MANIFEST.read_text())202 key = 'store-completion-' + suite203 kani.kani_obligations.required(key, kani.EXPECTED_HARNESSES[key], manifest=manifest)204 tools = kani.kani_install.capture(kani.TEMP)205 require(run_receipt.checkout(ROOT) == checkout, 'checkout changed during authentication')206 output = directory(suite)207 files, fragments = stage(output, suite)208 env = recorded_environment()209 command = expected_command(output, suite)210 receipt = run_receipt.write(ROOT, output, {'sources': before, 'staged': files, 'toolIdentity': tools,211 'sourceFragments': [hashlib.sha256(item.encode()).hexdigest() for item in fragments], 'scope': scope_for(suite),212 'suite': suite, 'command': command, 'cwd':str(ROOT), 'manifest_sha256': kani.sha(MANIFEST),213 'environment': {name: env[name] for name in recorded_environment()}})214 print('Store completion', suite, output, flush=True)215 with (output / 'run.log').open('w') as log:216 result = subprocess.run(command, cwd=ROOT, env=env, stdout=log, stderr=subprocess.STDOUT)217 (output / 'process.json').write_text(json.dumps({'command': command, 'cwd':str(ROOT), 'child_exit_code': result.returncode}, indent=2) + '\n')218 receipt.verify()219 require(snapshot(paths) == before, 'input changed')220 verify_stage(output, suite)221 kani.kani_install.verify(tools, kani.TEMP)222 require(all(run_receipt.regular(output / name) for name in ('result.json', 'run.log')), 'missing formal output')223 kani.validate_diagnostics((output / 'run.log').read_text())224 report = json.loads((output/'result.json').read_text())225 if suite.endswith('-research'):226 summary = report['verification_results']['summary']227 digest = seal(output,{'kind':'research','suite':suite,'child_exit_code':result.returncode,228 'summary':summary,'status':'EXPERIMENTAL_UNQUALIFIED'})229 print('STORE_COMPLETION_UNQUALIFIED',suite,output,digest,flush=True)230 return output,digest231 summary = validate_report(report, suite, result.returncode, manifest)232 digest = seal(output, {'kind': 'kani', 'child_exit_code': result.returncode, 'summary': summary,233 'status': kani.result_status(key)})234 print(json.dumps({'suite': suite, 'output': str(output), 'completion_sha256': digest,235 'child_exit_code': result.returncode, 'summary': summary, 'status': kani.result_status(key)}), flush=True)236 return output, digest237238def reconsume(output, expected_seal):239 output = Path(output)240 require(run_receipt.regular(output / 'completed.json') and kani.sha(output / 'completed.json') == expected_seal,241 'completion seal changed')242 record = json.loads((output / 'completed.json').read_text())243 expected_artifacts = {'main.rs','inputs.json'} if record['kind']=='body' else {'main.rs','inputs.json','run.log','result.json','process.json'}244 if record['kind']=='native':245 expected_artifacts = {'main.rs','inputs.json','compile.stdout','compile.stderr','witness','process.json'}246 expected_artifacts |= {case['name']+suffix for case in native_cases(output) for suffix in ('.stdout','.stderr')}247 require(set(record['artifacts']) == expected_artifacts, 'artifact inventory changed')248 require(all(run_receipt.regular(output / name) and kani.sha(output / name) == value249 for name, value in record['artifacts'].items()), 'sealed artifact changed')250 inputs = json.loads((output / 'inputs.json').read_text())251 require(run_receipt.checkout(ROOT) == {key: inputs[key] for key in ('factory', 'sdk', 'factory_status', 'sdk_status')},252 'checkout changed')253 require(snapshot(sources()) == inputs['sources'], 'source changed')254 run_receipt.verify_staged(output, inputs['staged'])255 if record['kind']=='native':256 return audit_native(output,record,inputs)257 if record['kind']=='body':258 kind = record['control']259 require(kind in CONTROLS and record['suite']==inputs['suite']==CONTROLS[kind][0]260 and record['status']=='EXPECTED_SOURCE_REJECTION' and inputs['control']==kind,'source control changed')261 require(all((output/name).read_bytes()==contents for name,contents in body_files(kind).items()),262 'source control is not exact designated mutation')263 try:264 verify_stage(output,record['suite'])265 except RuntimeError as error:266 require(str(error)=='Store completion: exact selected source changed','wrong source rejection')267 return record268 raise RuntimeError('source control admitted')269 require(record['kind'] in ('kani','research'),'unknown completion kind')270 register()271 key = 'store-completion-' + inputs['suite']272 expected_status = 'EXPERIMENTAL_UNQUALIFIED' if inputs['suite'].endswith('-research') else kani.result_status(key)273 require(record['status']==expected_status,'result scope/status changed')274 _, fragments = staged(inputs['suite'])275 require(inputs['scope'] == scope_for(inputs['suite']) and inputs['manifest_sha256'] == kani.sha(MANIFEST)276 and inputs['sourceFragments'] == [hashlib.sha256(item.encode()).hexdigest() for item in fragments],277 'scope/fragment/manifest binding changed')278 require(inputs['cwd'] == str(ROOT) and inputs['command'] == expected_command(output, inputs['suite']), 'recorded command/profile changed')279 require(inputs['environment'] == recorded_environment(), 'recorded environment/profile changed')280 verify_stage(output, inputs['suite'])281 kani.kani_install.verify(inputs['toolIdentity'], kani.TEMP)282 kani.validate_diagnostics((output / 'run.log').read_text())283 process = json.loads((output / 'process.json').read_text())284 require(process['cwd'] == str(ROOT) and process['command'] == inputs['command'] and process['child_exit_code'] == record['child_exit_code'],285 'actual process differs')286 if record['kind']=='research':287 summary=json.loads((output/'result.json').read_text())['verification_results']['summary']288 require(summary==record['summary'] and inputs['suite'].endswith('-research'),'research diagnostic changed')289 return {'status':'EXPERIMENTAL_UNQUALIFIED','summary':summary}290 summary = validate_report(json.loads((output / 'result.json').read_text()), inputs['suite'],291 record['child_exit_code'], tomllib.loads(MANIFEST.read_text()))292 require(summary == record['summary'], 'recorded summary differs from original report')293 return summary294295def native_cases(output):296 return [{'name':mode+'-'+str(value)+'-'+str(error).lower(),297 'command':[str(output/'witness'),mode,str(value),str(error).lower()],298 'cwd':str(ROOT),'child_exit_code':0}299 for mode in ('single','double') for value in (0,1,255) for error in (False,True)]300301302def native_tools(compiler):303 root = Path(compiler['path']).parent.parent304 paths = [*sorted((root/'lib').glob('*.so')),305 *sorted((root/'lib/rustlib'/kani.PIN['target']/'lib').iterdir())]306 require(paths and all(run_receipt.regular(path) for path in paths),'native sysroot input missing')307 return {str(path):kani.sha(path) for path in paths}308309310def audit_native(output, record, inputs):311 compiler = lower.native_witness.compiler_identity()312 require(inputs['compiler']==record['compiler']==compiler,'native compiler changed')313 require(inputs['compiler_inputs']==native_tools(compiler),'native sysroot changed')314 env, imports = lower.native_sdk.native_environment(output,Path(compiler['path']))315 require(inputs['environment']==native_fixed(env) and inputs['imports']==imports,'native environment/import changed')316 source, fragments = native_source()317 require((output/'main.rs').read_text()==source and inputs['scope']==NATIVE_SCOPE318 and inputs['sourceFragments']==[hashlib.sha256(item.encode()).hexdigest() for item in fragments],319 'native source/scope fragments changed')320 command = native_command(output,compiler)321 require(inputs['command']==command and inputs['cwd']==str(ROOT),'native command/cwd changed')322 process = json.loads((output/'process.json').read_text())323 require(process==record['process']=={'compile_command':command,'cwd':str(ROOT),324 'compile_exit_code':0,'cases':native_cases(output)},'native actual exits/case inventory changed')325 lower.native_witness.executable_hash(output/'witness',record['binary_sha256'])326 for case in process['cases']:327 require((output/(case['name']+'.stdout')).read_text()=='STORE_COMPLETION_NATIVE_OK\n'328 and not (output/(case['name']+'.stderr')).read_text(),'native case diagnostics changed')329 return {'kind':'native','compile_exit_code':0,'cases':len(process['cases'])}330331332NATIVE_SCOPE = ('Finite pinned production-compiler native exact selected retained Store public query caller; '333 'single and two successive nonempty/empty queries, values0/1/255 and ordinary Err/success. '334 'No formal, Nyxus/Wasm or IC theorem.')335336337def native_source():338 source, fragments = context()339 original = (PROOFS/'kani/single.rs').read_text()340 prefix = '#[kani::proof]\n#[kani::unwind(4)]\n'341 require(original.count(prefix) == 1, 'native proof attributes changed')342 selected = replace_once(original, prefix, '')343 selected = replace_once(selected, 'fn actual_single_public_query_cleanup()',344 'fn actual_single_public_query_cleanup(scalar: u8, ordinary_error: bool)')345 for line in (' let scalar: u8 = kani::any();\n', ' let ordinary_error: bool = kani::any();\n'):346 selected = replace_once(selected, line, '')347 selected, count = re.subn(r'(?m)^(\s*)kani::cover!\((.*), "[^"]*"\);$', r'\1let _ = \2;', selected)348 require(count == 2 and 'kani::' not in selected, 'native cover erasure changed')349 module = '\npub(crate) mod native { use super::*; use cdk_rsx_engine_hylix::{Error as EngineError,Result as EngineResult};\n'350 for file in ('storage.rs','support.rs'):351 module += 'include!(' + json.dumps(str(PROOFS/'kani'/file)) + ');\n'352 module += selected353 module += '''354pub(crate) fn run() {355 let mode = std::env::args().nth(1).unwrap();356 let scalar: u8 = std::env::args().nth(2).unwrap().parse().unwrap();357 let ordinary_error: bool = std::env::args().nth(3).unwrap().parse().unwrap();358 match mode.as_str() {359 "single" => actual_single_public_query_cleanup(scalar, ordinary_error),360 "double" => { query_completion(scalar, ordinary_error); },361 _ => panic!("unknown native mode"),362 }363 println!("STORE_COMPLETION_NATIVE_OK");364}365}366'''367 old = complete_item(source, 'mod hylix {')368 source = replace_once(source, old, old[:-1] + module + '}\n')369 source += '\nfn main() { hylix::native::run(); }\n'370 return source, fragments371372373def native_command(output, compiler):374 return [compiler['path'], '--edition=2024', '--target', kani.PIN['target'], '-Cpanic=unwind',375 str(output/'main.rs'), '-o', str(output/'witness')]376377378def native_fixed(env):379 keys = ('RUSTC','RUSTFLAGS','RUSTUP_HOME','RUSTUP_AUTO_INSTALL','CARGO_HOME',380 'CARGO_TARGET_DIR','TMPDIR','CARGO_NET_OFFLINE','PATH')381 return {**{name:env[name] for name in keys if name in env},382 'PATH': str(Path(env['RUSTC']).parent) + ':/run/current-system/sw/bin:/usr/bin:/bin',383 'RUSTUP_AUTO_INSTALL': '0', 'PYTHONDONTWRITEBYTECODE': '1',384 'LANG': 'C', 'LC_ALL': 'C', 'TZ': 'UTC'}385386387def native():388 checkout = run_receipt.checkout(ROOT)389 paths, before = sources(), snapshot(sources())390 output = directory('native')391 (output/'temp').mkdir()392 compiler = lower.native_witness.compiler_identity()393 env, imports = lower.native_sdk.native_environment(output, Path(compiler['path']))394 env = native_fixed(env)395 require(run_receipt.checkout(ROOT) == checkout, 'checkout changed during native authentication')396 source, fragments = native_source()397 (output/'main.rs').write_text(source)398 command = native_command(output,compiler)399 receipt = run_receipt.write(ROOT,output,{'sources':before,'staged':{'main.rs':kani.sha(output/'main.rs')},400 'compiler':compiler,'compiler_inputs':native_tools(compiler),'environment':native_fixed(env),'imports':imports,'command':command,'cwd':str(ROOT),401 'sourceFragments':[hashlib.sha256(item.encode()).hexdigest() for item in fragments],402 'scope':NATIVE_SCOPE})403 print('Store completion native',output,flush=True)404 with (output/'compile.stdout').open('w') as stdout,(output/'compile.stderr').open('w') as stderr:405 built = subprocess.run(command,cwd=ROOT,env=env,stdout=stdout,stderr=stderr,timeout=120)406 cases = []407 process = {'compile_command':command,'cwd':str(ROOT),'compile_exit_code':built.returncode,'cases':cases}408 (output/'process.json').write_text(json.dumps(process,indent=2)+'\n')409 receipt.verify()410 require(snapshot(paths)==before,'native source changed')411 require(built.returncode==0,'native exact-source compilation failed')412 binary_sha = lower.native_witness.executable_hash(output/'witness')413 for mode in ('single','double'):414 for value in (0,1,255):415 for ordinary_error in (False,True):416 name = mode+'-'+str(value)+'-'+str(ordinary_error).lower()417 argv = [str(output/'witness'),mode,str(value),str(ordinary_error).lower()]418 with (output/(name+'.stdout')).open('w') as stdout,(output/(name+'.stderr')).open('w') as stderr:419 ran = subprocess.run(argv,cwd=ROOT,env=env,stdout=stdout,stderr=stderr,timeout=30)420 cases.append({'name':name,'command':argv,'cwd':str(ROOT),'child_exit_code':ran.returncode})421 (output/'process.json').write_text(json.dumps(process,indent=2)+'\n')422 require(ran.returncode==0 and (output/(name+'.stdout')).read_text()=='STORE_COMPLETION_NATIVE_OK\n'423 and not (output/(name+'.stderr')).read_text(),'native exact-source case failed: '+name)424 receipt.verify()425 require(snapshot(paths)==before and (output/'main.rs').read_text()==native_source()[0],'native inputs changed')426 require(lower.native_witness.compiler_identity()==compiler,'native compiler changed')427 lower.native_witness.executable_hash(output/'witness',binary_sha)428 digest = seal(output,{'kind':'native','binary_sha256':binary_sha,'compiler':compiler,'process':process})429 reconsume(output,digest)430 print('STORE_COMPLETION_NATIVE_PASS',output,digest,flush=True)431 return output,digest432433434def main():435 parser = argparse.ArgumentParser(description=__doc__)436 parser.add_argument('suite', choices=('all', *CONTROLS, 'audit', 'native', *SUITES), nargs='?', default='all')437 parser.add_argument('--output', type=Path)438 parser.add_argument('--seal-sha256')439 args = parser.parse_args()440 with (kani.TEMP / '.store-completion.lock').open('w') as lease:441 fcntl.flock(lease, fcntl.LOCK_EX | fcntl.LOCK_NB)442 if args.suite == 'audit':443 require(args.output is not None and args.seal_sha256 is not None, 'audit needs output and seal')444 print('STORE_COMPLETION_AUDIT_PASS', reconsume(args.output, args.seal_sha256))445 return446 outputs = []447 if args.suite == 'native':448 native()449 return450 if args.suite in ('all',*CONTROLS):451 for kind in CONTROLS if args.suite=='all' else (args.suite,): outputs.append(body_control(kind))452 selected = [suite for suite in SUITES if not suite.endswith('-research')]453 for suite in selected if args.suite == 'all' else ((args.suite,) if args.suite in SUITES else ()):454 outputs.append(run(suite))455 if args.suite=='all': outputs.append(native())456 print(json.dumps([{'output': str(path), 'seal_sha256': value} for path, value in outputs], indent=2))457458if __name__ == '__main__':459 try:460 main()461 except (RuntimeError,subprocess.CalledProcessError,subprocess.TimeoutExpired,BlockingIOError,ValueError,KeyError) as error:462 print('Store completion refused:',error,file=sys.stderr)463 sys.exit(1)