migration_commit.py

verification/tools/migration_commit.py

migration_commit.py258 lines← SDK documentation
1#!/usr/bin/env python32"""Source-bound installed migration publication/rollback qualification."""3import native_sdk4from pathlib import Path5import argparse, datetime, fcntl, hashlib, json, os, shlex, shutil, subprocess, sys, tomllib, uuid6import kani, native_witness, run_receipt, stable_authority, startup_admission as startup7from rust_source import complete_item8ROOT=kani.ROOT9PROOFS=ROOT/'verification/proofs/migration-commit'10MANIFEST=Path(__file__).with_suffix('.toml')11HARNESS='actual_emitted_restore_publishes_only_after_callback_success'12NEGATIVE='negative_callback_error_publishes_target'13BODY='negative_emitted_restore_discards_callback_error'14NODE=Path('/nix/store/zv7jk9knz9g176az3rcm8wyxc68nms8a-nodejs-slim-24.22.1/bin/node')15NODE_SHA='fa212ff7a43ae43fd69ff0bbb40a5dea37a26f952e4af79cb4b0ff60b5d3a2b5'16IC_CHECKS=(17 'populated V1 KEEP preserves all mixed-engine rows and the exact shared stable image',18 'two late failures after owner conversion, app save and completed dirty frame restore V1 values, identities and every stable byte',19 'V1 to V2 preserves every key, scalar and nested byte owner while adding specified fields and removing obsolete owners',20 'successful target catalog publication rejects V1 and preserves the installed V2 state',21 'converted V2 survives populated KEEP and remains writable with stable owner identity and query purity')22IC_REFUSALS=('late migration failure 1','late migration failure 2','published V2 rejects downgrade')23GUARDS={24 'store-convert':('cdk-rsx-store/src/scope.rs','    fn convert<M: ModuleMemory, N: ModuleMemory>('),25 'store-write':('cdk-rsx-store/src/scope.rs','pub(crate) fn execute_write<R>('),26 'store-finish':('cdk-rsx-store/src/scope.rs','    fn finish(&self)'),27 'actor-upgrade':('cdk-rsx-store/src/lib.rs','    pub fn upgrade<N: ModuleMemory>('),28 'store-root-upgrade':('cdk-rsx-store/src/backend.rs','    pub(crate) fn upgrade_root<M: ModuleMemory, N: ModuleMemory>('),29 'store-hylix-write':('cdk-rsx-store/src/backend.rs','    fn hylix_write<R>('),30 'native-quarantine':('cdk-rsx-store/src/backend.rs',"impl Drop for ConversionGuard<'_>"),31 'records-finish':('cdk-rsx-store/src/hylix.rs','    pub(crate) fn finish(&self)'),32 'provider-using':('cdk-rsx-engine-hylix/src/context.rs','pub fn using<R>('),33 'provider-working':('cdk-rsx-engine-hylix/src/context.rs','struct WorkingFrame'),34 'provider-discard':('cdk-rsx-engine-hylix/src/context.rs','impl Drop for WorkingFrame'),35 'root-post-upgrade':('cdk-rsx/src/lib.rs','        pub extern "C" fn __cdk_rsx_post_upgrade()'),36 'root-checked-fatal':('cdk-rsx-macros/src/root.rs','            fn __cdk_rsx_checked<R>('),37}38def digest(text):return hashlib.sha256(text.encode()).hexdigest()39def source_fragments():40    result={}41    for name,(path,signature) in GUARDS.items():42        result[name]=complete_item((ROOT/'cdk-rsx/crates'/path).read_text(),signature)43    return result4445def validate_guards(fragments):46    expected=tomllib.loads(MANIFEST.read_text())['source_guards']47    kani.require(set(expected)==set(GUARDS)==set(fragments),'Migration source guard inventory changed')48    kani.require(all(digest(value)==expected[name] for name,value in fragments.items()),'Migration source body guard changed')4950def validate_ic_result(record):51    kani.require(type(record) is dict and set(record)=={'status','checks','failures','snapshots','boundary','stable','server','ownedInstance','artifacts','runner_sha256'}52        and record['status']=='PASS' and record['checks']==list(IC_CHECKS),'Migration installed exact check inventory changed')53    failures=record['failures']54    kani.require(type(failures) is list and len(failures)==len(IC_REFUSALS) and all(type(f) is dict and set(f)=={'name','message'}55        and f['name']==name and type(f['message']) is str and f['message'] for f,name in zip(failures,IC_REFUSALS)), 'Migration installed refusal inventory changed')56    kani.require([s['phase'] for s in record['snapshots']]==['old-populated','converted','fresh-work'],'Migration installed snapshot inventory changed')5758def sources():59    paths=startup.sources()60    paths += [p for p in PROOFS.rglob('*') if p.is_file()]61    paths += [p for p in (ROOT/'tests/canisters/engine-composition-probe').rglob('*') if p.is_file()]62    paths += [ROOT/'verification/docs/workstreams/migration-commit-batch10.md']63    return list(dict.fromkeys(paths))6465def native(out,unchanged):66    compiler=native_witness.compiler_identity();cargo=Path(compiler['path']).parent/'cargo'67    env,environment_sources=native_sdk.native_environment(out,Path(compiler['path']));env['CARGO_BUILD_JOBS']='2'68    cargo_sha=native_witness.executable_hash(cargo)69    project=out/'project';project.mkdir();staged={}70    for p in (PROOFS/'native').iterdir():71        if p.name=='main.rs':continue72        body=p.read_text()73        if p.name=='generate.rs':body=body.replace('../../../../cdk-rsx/',str(ROOT/'cdk-rsx')+'/')74        (project/p.name).write_text(body);staged['project/'+p.name]=kani.sha(project/p.name)75    receipt=run_receipt.write(ROOT,out,{'sources':unchanged.sources,'staged':staged,'compiler':compiler,'cargo':{'path':str(cargo),'sha256':cargo_sha},'environmentSources':environment_sources})76    sealed={};commands=[]77    def verify():78        unchanged();receipt.verify();kani.require(native_witness.compiler_identity()==compiler,'Migration compiler changed');native_witness.executable_hash(cargo,cargo_sha)79        kani.require(all(run_receipt.regular(Path(p)) and kani.sha(Path(p))==h for p,h in environment_sources.items()),'Migration environment source changed')80        kani.require(all(run_receipt.regular(out/p) and kani.sha(out/p)==h for p,h in sealed.items()),'Migration staged output changed')81    def command(label,args,expected=0,cwd=ROOT):82        verify()83        with(out/(label+'.stdout')).open('w') as stdout,(out/(label+'.stderr')).open('w') as stderr:84            result=subprocess.run(list(map(str,args)),cwd=cwd,env=env,stdout=stdout,stderr=stderr,timeout=180)85        verify();sealed.update({label+s:kani.sha(out/(label+s)) for s in ('.stdout','.stderr')})86        commands.append({'name':label,'command':list(map(str,args)),'exit':result.returncode})87        kani.require(result.returncode==expected,'Migration '+label+' failed: '+str(out/(label+'.stderr')))88    command('metadata',[cargo,'metadata','--manifest-path',project/'Cargo.toml','--locked','--offline','--format-version','1'])89    graph=json.loads((out/'metadata.stdout').read_text());dependencies=native_sdk.dependency_snapshot(graph,project)90    command('generator-build',[cargo,'build','--manifest-path',project/'Cargo.toml','--locked','--offline','--target',kani.PIN['target']])91    generator=out/'target'/kani.PIN['target']/'debug/migration-generate';sealed[str(generator.relative_to(out))]=native_witness.executable_hash(generator)92    generated=out/'generated';command('generate',[generator,generated])93    kani.require((out/'generate.stdout').read_text()=='MIGRATION_GENERATED_OK\n','Migration generator sentinel changed')94    (generated/'context.rs').write_bytes((PROOFS/'kani/context.rs').read_bytes())95    (generated/'main.rs').write_bytes((PROOFS/'native/main.rs').read_bytes())96    fragments=source_fragments();validate_guards(fragments)97    for name,text in {'finish':"impl Context<'_> {\n"+fragments['store-finish']+'\n}','write':fragments['store-write'],98        'working':fragments['provider-working']+'\n'+fragments['provider-discard'],'using':fragments['provider-using']}.items():99        (generated/(name+'.rs')).write_text(text+'\n')100    for p in generated.iterdir():sealed[str(p.relative_to(out))]=kani.sha(p)101    command('native-compile',[compiler['path'],'--edition=2024','-Cpanic=unwind',generated/'main.rs','-o',generated/'native'])102    sealed[str((generated/'native').relative_to(out))]=native_witness.executable_hash(generated/'native')103    command('native-run',[generated/'native'])104    kani.require((out/'native-run.stdout').read_text()=='MIGRATION_NATIVE_OK\n' and not (out/'native-run.stderr').read_text(),'Migration native sentinel/diagnostics changed')105    kani.require(native_sdk.dependency_snapshot(graph,project)==dependencies,'Migration generator dependency source changed')106    verify()107    return generated,verify,{'commands':commands,'compiler':compiler,'cargo_sha256':cargo_sha,'dependencies':dependencies,'environmentSources':environment_sources,'artifacts':sealed}108109def kani_source(generated,suite):110    lifecycle=(generated/'lifecycle.rs').read_text()111    anchor='reopen () ? ;'112    if suite=='body':113        kani.require(lifecycle.count(anchor)==1,'Migration generated body anchor changed')114        lifecycle=lifecycle.replace(anchor,'let _ = reopen () ;')115    return 'include!('+json.dumps(str(PROOFS/'kani/context.rs'))+');\n'+lifecycle+'\ninclude!('+json.dumps(str(PROOFS/'kani/commit.rs'))+');\nfn main(){}\n'116117def formal(out,generated,verify,suite):118    out.mkdir();(out/'main.rs').write_text(kani_source(generated,suite));main_sha=kani.sha(out/'main.rs')119    key='migration-commit-'+suite;harness=NEGATIVE if suite=='semantic' else BODY if suite=='body' else HARNESS120    kani.EXPECTED_HARNESSES[key]={harness}121    marker='NEGATIVE_CALLBACK_ERROR_PUBLISHED' if suite=='semantic' else 'NEGATIVE_EMITTED_RESTORE_LOST_CALLBACK_ERROR'122    if suite!='positive':kani.NEGATIVE_CONTROLS[key]=marker123    manifest=tomllib.loads(MANIFEST.read_text())124    if suite!='semantic':125        # Explicit independent helper inventory: the actual emitted app guard126        # plus the controlled digest leaf must both remain reachable assertions.127        emitted=str(out/'main.rs')128        manifest['files'][emitted]=main_sha129        manifest['suites'][key][harness].append(emitted+'::__cdk_rsx_publish_root')130    required=kani.kani_obligations.required(key,{harness},manifest=manifest)131    tool=kani.kani_install.capture(kani.TEMP);env=kani.environment();env['CARGO_HOME']=str(kani.TEMP/'migration-kani-cargo-home');env['RUSTFLAGS']='--edition=2024 -A dead_code'132    cmd=[kani.LAUNCHER/'kani',out/'main.rs','--target-dir',out/'kani-target','-Z','unstable-options','--exact','--harness',harness,'--harness-timeout','90s','--export-json',out/'result.json']133    with(out/'kani.log').open('w') as log:ran=subprocess.run(list(map(str,cmd)),cwd=ROOT,env=env,stdout=log,stderr=subprocess.STDOUT)134    verify();kani.kani_install.verify(tool,kani.TEMP);kani.require(kani.sha(out/'main.rs')==main_sha,'Migration formal input changed')135    kani.validate_diagnostics((out/'kani.log').read_text());report=json.loads((out/'result.json').read_text());summary=kani.validate_report(report,key,ran.returncode,manifest=manifest)136    if suite!='positive':137        designated=[o for obligations in required.values() for o in obligations if o.category=='assertion' and o.description==kani.kani_obligations.normalized(json.dumps(marker))]138        failures=[c for result in report['verification_results']['results'] for c in result['checks'] if c['status']=='Failure']139        kani.require(len(designated)==len(failures)==1 and kani.kani_obligations.check_identity(failures[0])==designated[0],'Migration formal control failed away from designated assertion')140    return {'child_exit':ran.returncode,'summary':summary,'toolIdentity':tool,'command':list(map(str,cmd)),'main_sha256':main_sha}141142def ic(out,unchanged,pocket_ic):143    native_witness.executable_hash(NODE,NODE_SHA)144    binary=pocket_ic.resolve(strict=True)145    kani.require(kani.sha(binary)=='9930ca48c613a019fb8d9bda9ffb39c204907e9244ca960508a84eee9e9af1f4','Unexpected provisioned PocketIC binary')146    runtime=kani.TEMP/'pocketic-runtime';packet=runtime/'runtime.json'147    kani.require(run_receipt.regular(packet),'Root-provisioned PocketIC runtime packet required')148    runtime_record=json.loads(packet.read_text());library_path=runtime/'lib'149    kani.require(runtime_record['binary']=={'path':str(binary),'sha256':kani.sha(binary)}150        and runtime_record['libraryPath']==str(library_path) and not library_path.is_symlink()151        and {p.name for p in library_path.iterdir()}=={'libunwind.so.8'}152        and kani.sha(library_path/'libunwind.so.8')==runtime_record['copiedFrom']['sha256'],153        'PocketIC runtime selection changed')154    runtime_files={str(p):kani.sha(p) for p in runtime.rglob('*') if p.is_file()}155    runtime_files.update(runtime_record['libraries']);runtime_files[runtime_record['copiedFrom']['path']]=runtime_record['copiedFrom']['sha256']156    shell=Path('/bin/sh').resolve(strict=True);runtime_files[str(shell)]=native_witness.executable_hash(shell)157    launcher=out/'pocketic-launcher'158    server_stderr=out/'pocketic-server.stderr'159    launcher_body='#!/bin/sh\nexport LD_LIBRARY_PATH='+shlex.quote(str(library_path))+'\nexec '+shlex.quote(str(binary))+' "$@" 2>'+shlex.quote(str(server_stderr))+'\n'160    launcher.write_text(launcher_body);launcher.chmod(0o755);launcher_sha=native_witness.executable_hash(launcher)161    def verify_runtime():162        startup.verify_runtime_files(runtime_files);native_witness.executable_hash(binary,runtime_record['binary']['sha256'])163        native_witness.executable_hash(launcher,launcher_sha)164        kani.require(launcher.read_text()==launcher_body,'PocketIC child-only launcher changed')165    verify_runtime()166    dependencies=(ROOT/'tests/pocketic/node_modules').resolve(strict=True);dep_sha=startup.minima_targets.tree_hash(dependencies)167    compiler=Path(native_witness.compiler_identity()['path']);env,environment_sources=native_sdk.native_environment(out,compiler)168    env['CARGO_BUILD_JOBS']='2'169    node_settings=startup.clear_node_options(env)170    pic_settings=startup.isolate_pic_state(env,out)171    def verify_host_environment():172        kani.require({name:env.get(name) for name in startup.NODE_SETTINGS}==node_settings173            and {name:env.get(name) for name in pic_settings}==pic_settings and env.get('LD_LIBRARY_PATH') is None,174            'Isolated IC host environment changed')175    verify_host_environment()176    invocation_environment={name:env.get(name) for name in startup.ENV_SETTINGS}177    version_command=[str(launcher),'--version']178    with(out/'pic-version.stdout').open('w') as stdout,(out/'pic-version.stderr').open('w') as stderr:179        preflight=subprocess.run(version_command,cwd=ROOT,env=env,stdout=stdout,stderr=stderr,timeout=30)180    verify_runtime();verify_host_environment()181    kani.require(preflight.returncode==0 and (out/'pic-version.stdout').read_text()=='pocket-ic-server 16.1.0\n'182        and not (out/'pic-version.stderr').read_text(),'Pinned PocketIC isolated launcher preflight failed')183    smoke_command=[str(NODE),str(startup.PROOFS/'smoke.mjs'),str(ROOT),str(launcher),str(out/'server-smoke'),str(Path(pic_settings['RRT_PIC_STATE_DIR'])/'smoke')]184    with(out/'server-smoke.stdout').open('w') as stdout,(out/'server-smoke.stderr').open('w') as stderr:185        smoke=subprocess.run(smoke_command,cwd=ROOT,env=env,stdout=stdout,stderr=stderr,timeout=300)186    verify_runtime();verify_host_environment()187    shutil.copyfile(server_stderr,out/'smoke-server.stderr')188    kani.require(smoke.returncode==0,'Owned PocketIC create/tearDown preflight failed')189    smoke_result=json.loads((out/'server-smoke/diagnostic.json').read_text())190    kani.require(smoke_result['created'] is True and smoke_result['deleted'] is True and smoke_result['error'] is None,191        'Owned PocketIC preflight did not create and tear down its instance')192    artifacts=out/'artifacts';artifacts.mkdir();exits=[]193    for name,features in [('v1',None),('v2','v2'),('fail-migration','fail-migration')]:194        cmd=[sys.executable,str(ROOT/'cdk-rsx/tools/build-app.py'),'--manifest-path',str(ROOT/'tests/Cargo.toml'),'--package','engine-composition-probe-canister','--out-dir',str(artifacts),'--name',name,'--wasm-target','wasm64-unknown-unknown','--offline','--locked']195        if features:cmd+=['--features',features]196        print('MIGRATION_IC_BUILD',name,flush=True)197        with(out/('ic-build-'+name+'.stdout')).open('w') as stdout,(out/('ic-build-'+name+'.stderr')).open('w') as stderr:198            built=subprocess.run(cmd,cwd=ROOT,env=env,stdout=stdout,stderr=stderr,timeout=600)199        unchanged();kani.require(built.returncode==0,'Canonical IC build boundary: '+str(out/('ic-build-'+name+'.stderr')))200        exits.append({'name':name,'child_exit':built.returncode,'command':cmd})201    result=ROOT/'tests/tmp'/('migration-commit-'+uuid.uuid4().hex[:8]);result.parent.mkdir(exist_ok=True)202    node=NODE;node_sha=native_witness.executable_hash(node)203    helper=ROOT/'cdk-rsx/tools/wire_runtime.py';helper_sha=kani.sha(helper)204    tool=artifacts/'v1.wasm-tool';tool_sha=native_witness.executable_hash(tool)205    generated_host=ROOT/'tests/pocketic/.generated'206    generation=[sys.executable,str(helper),'--wasm-tool',str(tool),'--out-dir',str(generated_host),'--node',str(node)]207    with(out/'host-runtime.stdout').open('w') as stdout,(out/'host-runtime.stderr').open('w') as stderr:208        prepared=subprocess.run(generation,cwd=ROOT,env=env,stdout=stdout,stderr=stderr,timeout=30)209    unchanged();kani.require(prepared.returncode==0,'Generic IC host runtime generation failed')210    producer=json.loads((out/'host-runtime.stdout').read_text())211    kani.require(producer['node']['path']==str(node) and producer['node']['sha256']==node_sha212        and producer['outputs']==[str(generated_host/'wire-runtime.mjs'),str(generated_host/'wire-codec.mjs')],213        'Generic IC host producer identity changed')214    host_files=startup.host_runtime_snapshot(generated_host)215    def verify_host():216        startup.verify_host_runtime(generated_host,host_files);native_witness.executable_hash(tool,tool_sha)217        native_witness.executable_hash(node,node_sha);kani.require(kani.sha(helper)==helper_sha,'IC host generator source changed')218    verify_host();verify_runtime();verify_host_environment()219    cmd=[str(node),str(ROOT/'tests/pocketic/engine-composition-migration.mjs'),'--source-root='+str(ROOT),'--output='+str(result),'--pocket-ic='+str(launcher)]220    for name in ('v1','v2','fail-migration'):cmd+=['--'+name+'='+str(artifacts/name)]221    print('MIGRATION_POCKETIC',result,flush=True)222    with(out/'ic.stdout').open('w') as stdout,(out/'ic.stderr').open('w') as stderr:223        ran=subprocess.run(cmd,cwd=ROOT,env=env,stdout=stdout,stderr=stderr,timeout=300)224    unchanged();verify_host();verify_runtime();verify_host_environment();startup.minima_targets.verify_dependencies(ROOT/'tests/pocketic/node_modules',dependencies,dep_sha)225    native_witness.executable_hash(node,node_sha)226    kani.require(ran.returncode==0,'Matching-target root lifecycle failed: '+str(out/'ic.stderr'))227    record=json.loads((result/'result.json').read_text());validate_ic_result(record)228    kani.require(record['runner_sha256']==kani.sha(ROOT/'tests/pocketic/engine-composition-migration.mjs') and record['server']=={'path':str(launcher),'sha256':launcher_sha},'Matching-target runner/server identity changed')229    return {'builds':exits,'run_exit':ran.returncode,'command':cmd,'output':str(result),'result_sha256':kani.sha(result/'result.json'),'node':{'path':str(node),'sha256':node_sha},'nodeSettings':node_settings,'nodeModules':{'path':str(dependencies),'sha256':dep_sha},'pocketIc':{'path':str(binary),'sha256':kani.sha(binary)},'environmentSources':environment_sources,'invocationEnvironment':invocation_environment,'canonicalRustupHome':str(ROOT/'cdk-rsx/.rustup'),230        'wireRuntime':{'generator':{'path':str(helper),'sha256':helper_sha},'tool':{'path':str(tool),'sha256':tool_sha},'node':producer['node'],'directory':str(generated_host),'files':host_files,'command':generation,'child_exit':prepared.returncode},231        'runtime':{'packet':str(packet),'files':runtime_files,'selection':runtime_record,'launcher':{'path':str(launcher),'body':launcher_body,'sha256':launcher_sha},'serverStderr':{'path':str(server_stderr),'sha256':kani.sha(server_stderr)},'shell':str(shell),'preflight':{'command':version_command,'child_exit':preflight.returncode},'serverSmoke':{'command':smoke_command,'child_exit':smoke.returncode,'result':smoke_result}},'pocketIcSettings':pic_settings,232        'stateOwnership':json.loads((out/'pocketic-state.json').read_text())}233234def run(action,pocket_ic):235    run_receipt.checkout(ROOT);out=kani.TEMP/('migration-commit-'+datetime.datetime.now(datetime.timezone.utc).strftime('%Y%m%dT%H%M%SZ')+'-'+uuid.uuid4().hex[:8]);out.mkdir();(out/'temp').mkdir()236    paths=sources();before=startup.snapshot(paths);identity=run_receipt.checkout(ROOT)237    def unchanged():238        kani.require(startup.snapshot(paths)==before,'Migration source changed during qualification')239        kani.require(run_receipt.checkout(ROOT)==identity,'Migration checkout changed during qualification')240    unchanged.sources=before241    fragments=source_fragments();validate_guards(fragments)242    generated,verify,native_record=native(out,unchanged)243    result={'checkout':identity,'sources':before,'source_guards':{name:digest(value) for name,value in fragments.items()},'native':native_record}244    if action in ('all','formal'):result['formal']={suite:formal(out/('kani-'+suite),generated,verify,suite) for suite in ('positive','semantic','body')}245    if action in ('all','ic'):246        kani.require(pocket_ic is not None,'Explicit existing --pocket-ic required')247        result['ic']=ic(out,verify,pocket_ic)248    verify()249    result['artifacts']={str(p.relative_to(out)):kani.sha(p) for p in out.rglob('*') if p.is_file() and not p.is_relative_to(out/'target') and 'kani-target' not in p.parts}250    (out/'qualification.json').write_text(json.dumps(result,indent=2)+'\n')251    print('MIGRATION_QUALIFIED',action,out,'record_sha256='+kani.sha(out/'qualification.json'),flush=True)252if __name__=='__main__':253    parser=argparse.ArgumentParser(description=__doc__);parser.add_argument('action',choices=('native','formal','ic','all'),default='all',nargs='?');parser.add_argument('--pocket-ic',type=Path);args=parser.parse_args()254    try:255        with(kani.TEMP/'.migration-commit.lock').open('w') as lock:256            fcntl.flock(lock,fcntl.LOCK_EX|fcntl.LOCK_NB);run(args.action,args.pocket_ic)257    except (RuntimeError,subprocess.CalledProcessError,BlockingIOError,ValueError,KeyError) as error:258        print('Migration refused:',error,file=sys.stderr);sys.exit(1)