slab_release_representation.py

verification/tools/slab_release_representation.py

slab_release_representation.py193 lines← SDK documentation
1#!/usr/bin/env python32"""Check the corrected Kani representation matrix; never an SDK theorem."""3from pathlib import Path4import argparse5import datetime6import fcntl7import json8import subprocess9import sys10import uuid1112import kani13import native_witness14import slab_release1516SUITE = 'slab-release-representation-research'17PROOF = slab_release.PROOFS / 'slab_release_representation.rs'18EXPECTED = {'transient::proofs::' + name for name in (19    'typed_header_and_heap', 'byte_header_and_typed_heap', 'byte_header_and_heap',20    'false_property_typed_header_and_heap', 'false_property_byte_header_and_typed_heap',21    'false_property_byte_header_and_heap')}22EXPECTED_FAILURES = {23    'transient::proofs::false_property_typed_header_and_heap': 'FALSE_PROPERTY_TYPED_BIN_RETAINED',24    'transient::proofs::false_property_byte_header_and_typed_heap': 'FALSE_PROPERTY_MIXED_BIN_RETAINED',25    'transient::proofs::false_property_byte_header_and_heap': 'FALSE_PROPERTY_BYTE_BIN_RETAINED',26}27SENTINEL = 'SLAB_RELEASE_REPRESENTATIONS_NATIVE_PASS\n'282930def validate(report, exit_code):31    """Accept only the documented diagnostic pattern; export no proof ticket."""32    kani.require(report['tools']['kani'] == kani.PIN['version']33        and report['tools']['rustc'] == kani.PIN['rustc_version']34        and report['tools']['cbmc'].startswith(kani.PIN['cbmc_version'] + ' ')35        and report['metadata']['target'] == kani.PIN['target'], 'Representation tool/target mismatch')36    summary = report['verification_results']['summary']37    kani.require(type(exit_code) is int and exit_code == 138        and summary['status'] == 'completed' and summary['executed'] == 639        and summary['total_harnesses'] == 6 and summary['successful'] == 340        and summary['failed'] == 3, 'Changed or incomplete representation diagnostic')41    results = report['verification_results']['results']42    kani.require(len(results) == 6 and {r['harness_id'] for r in results} == EXPECTED,43                 'Representation harness population changed')44    obligations = kani.kani_obligations.required(SUITE, EXPECTED)45    failures = []46    for result in results:47        negative = result['harness_id'] in EXPECTED_FAILURES48        kani.require(result['status'] == ('Failure' if negative else 'Success'),49                     'Representation status changed')50        checks = result['checks']51        kani.kani_obligations.validate(checks, obligations[result['harness_id']],52                                       result['harness_id'], negative=negative)53        for check in checks:54            if check['category'] == 'cover':55                kani.require(check['status'] == 'Satisfied', 'Representation witness unreachable')56            else:57                kani.require(check['status'] in ('Success', 'Unreachable', 'Failure'),58                             'Unsupported representation result')59                if check['status'] == 'Failure':60                    failures.append((result['harness_id'], check))61    kani.require(len(failures) == 3 and {name for name, _ in failures} == set(EXPECTED_FAILURES)62        and all(check['category'] == 'assertion' and check['description'].strip('"') == EXPECTED_FAILURES[name]63                for name, check in failures),64        'Representation diagnostic failed somewhere else')656667def native(output):68    """Run identical authored clients on production and Kani's native compilers."""69    product = (kani.PLATFORM / 'transient.rs').read_bytes()70    production = native_witness.compiler_identity()71    compilers = {'production': Path(production['path']),72                 'kani-native': (kani.KANI / 'toolchain/bin/rustc').resolve()}73    records = {}74    for name, compiler in compilers.items():75        directory = output / name76        directory.mkdir()77        env = native_witness.environment(compiler)78        identity = {'path': str(compiler), 'sha256': kani.sha(compiler)}79        version = subprocess.run([str(compiler), '--version'], env=env,80                                 capture_output=True, text=True, timeout=30)81        expected_version = production['version'] if name == 'production' else kani.PIN['rustc_version']82        kani.require(version.returncode == 0 and version.stdout.strip() == expected_version,83                     'Wrong native representation compiler')84        identity['version'] = version.stdout.strip()85        tail = ('\npub mod proofs { include!(' + json.dumps(str(PROOF)) + '); }\n').encode()86        (directory / 'transient.rs').write_bytes(product + tail)87        (directory / 'main.rs').write_text('extern crate core;\n#[path='88            + json.dumps(str(kani.PLATFORM / 'allocation.rs'))89            + '] mod allocation;\nmod transient;\nfn main() { transient::proofs::native_all(); }\n')90        staged = {p.name: kani.sha(p) for p in directory.iterdir() if p.is_file()}91        artifact = directory / 'native'92        with (directory / 'compile.stdout').open('w') as stdout, (directory / 'compile.stderr').open('w') as stderr:93            compiled = subprocess.run([str(compiler), '--edition=2024', '--target', kani.PIN['target'],94                '-Adead_code', '-Aunexpected_cfgs', str(directory / 'main.rs'), '-o', str(artifact)],95                cwd=kani.ROOT, env=env, stdout=stdout, stderr=stderr, timeout=120)96        kani.require(compiled.returncode == 0, 'Native representation compile failed')97        artifact_sha = native_witness.executable_hash(artifact)98        with (directory / 'run.stdout').open('w') as stdout, (directory / 'run.stderr').open('w') as stderr:99            ran = subprocess.run([str(artifact)], cwd=kani.ROOT, env=env,100                                 stdout=stdout, stderr=stderr, timeout=30)101        native_witness.executable_hash(artifact, artifact_sha)102        kani.require(ran.returncode == 0 and (directory / 'run.stdout').read_text() == SENTINEL,103                     'Native representation assertion differs')104        opposite = {}105        for mode, marker in (('false-typed', 'FALSE_PROPERTY_TYPED_BIN_RETAINED'),106                             ('false-mixed', 'FALSE_PROPERTY_MIXED_BIN_RETAINED'),107                             ('false-byte', 'FALSE_PROPERTY_BYTE_BIN_RETAINED')):108            native_witness.executable_hash(artifact, artifact_sha)109            with (directory / (mode + '.stdout')).open('w') as stdout, (directory / (mode + '.stderr')).open('w') as stderr:110                failed = subprocess.run([str(artifact), mode], cwd=kani.ROOT, env=env,111                                        stdout=stdout, stderr=stderr, timeout=30)112            native_witness.executable_hash(artifact, artifact_sha)113            kani.require(failed.returncode == 101 and marker in (directory / (mode + '.stderr')).read_text(),114                         'Native compiler did not reject the exact false retained-head property')115            opposite[mode] = failed.returncode116        kani.require(staged == {n: kani.sha(directory / n) for n in staged}117            and kani.sha(compiler) == identity['sha256'], 'Native representation input/compiler changed')118        records[name] = {'compiler': identity, 'compile_exit': compiled.returncode,119                         'run_exit': ran.returncode, 'false_property_exits': opposite,120                         'files': {p.name: kani.sha(p) for p in directory.iterdir() if p.is_file()}}121        kani.require(records[name]['files']['native'] == artifact_sha, 'Native executable changed')122    for name, record in records.items():123        directory = output / name124        native_witness.executable_hash(directory / 'native', record['files']['native'])125        kani.require(all((directory / n).is_file() and not (directory / n).is_symlink()126                         and kani.sha(directory / n) == digest for n, digest in record['files'].items()),127                     'Native representation artifacts changed')128        kani.require(kani.sha(Path(record['compiler']['path'])) == record['compiler']['sha256'],129                     'Native representation compiler changed')130    return records131132133def run(timeout):134    checkout = {name: kani.git(where, 'rev-parse', 'HEAD') for name, where in135                (('factory', kani.ROOT), ('sdk', kani.ROOT / 'cdk-rsx'))}136    kani.require(not kani.git(kani.ROOT, 'status', '--porcelain'),137                 'Representation comparison requires a clean factory')138    kani.require(not kani.git(kani.ROOT / 'cdk-rsx', 'status', '--porcelain'),139                 'Representation comparison requires a clean SDK')140    tool = kani.kani_install.capture(kani.TEMP)141    kani.kani_obligations.required(SUITE, EXPECTED)142    paths = [PROOF, Path(__file__), Path(slab_release.__file__), Path(slab_release.slab_release_fragment.__file__),143        kani.PLATFORM / 'transient.rs', kani.PLATFORM / 'allocation.rs', Path(kani.__file__),144        Path(native_witness.creusot.__file__),145        Path(kani.__file__).with_suffix('.toml'), *kani.kani_obligations.INPUTS,146        *kani.kani_install.INPUTS, *native_witness.INPUTS]147    before = {str(p.relative_to(kani.ROOT)): kani.sha(p) for p in paths}148    stamp = datetime.datetime.now(datetime.timezone.utc).strftime('%Y%m%dT%H%M%SZ')149    output = kani.TEMP / 'runs' / (stamp + '-slab-release-representation-' + uuid.uuid4().hex[:8])150    output.mkdir(parents=True)151    original, tail, fragment, staged = slab_release.stage(output, PROOF.name)152    identities = {**checkout,153                  'sources': before, 'toolIdentity': tool, 'staged': staged,154                  'status': 'EXPERIMENTAL_UNQUALIFIED', 'sourceFragment': fragment}155    (output / 'inputs.json').write_text(json.dumps(identities, indent=2) + '\n')156    metadata_sha = kani.sha(output / 'inputs.json')157    def verify():158        slab_release.verify_inputs(output, before, identities, metadata_sha, original, tail, tool)159    env = kani.environment()160    env['CARGO_HOME'] = str(kani.TEMP / 'slab-release-cargo-home')161    env['RUSTFLAGS'] = '--edition=2024 -A dead_code --check-cfg=cfg(test)'162    print('Representation diagnostic (no SDK theorem): ' + str(output), flush=True)163    argv = [kani.LAUNCHER / 'kani', output / 'main.rs', '--target-dir', output / 'target',164            '-Z', 'unstable-options', '--harness-timeout', str(timeout) + 's',165            '--export-json', output / 'result.json', '--output-format', 'terse']166    with (output / 'run.log').open('w') as log:167        result = subprocess.run([str(x) for x in argv], cwd=kani.ROOT, env=env,168                                stdout=log, stderr=subprocess.STDOUT)169    verify()170    kani.require(all((output / n).is_file() and not (output / n).is_symlink()171                     for n in ('result.json', 'run.log')), 'Missing representation report/log')172    kani.validate_diagnostics((output / 'run.log').read_text())173    validate(json.loads((output / 'result.json').read_text()), result.returncode)174    recorded = {n: kani.sha(output / n) for n in ('result.json', 'run.log')}175    records = native(output)176    verify()177    kani.require(recorded == {n: kani.sha(output / n) for n in recorded}, 'Representation evidence changed')178    (output / 'native.json').write_text(json.dumps(records, indent=2) + '\n')179    print('EXPERIMENTAL_UNQUALIFIED: corrected Kani and both native compilers agree on '180          'three true and three independent false properties; all covers reachable; no SDK theorem', flush=True)181182183if __name__ == '__main__':184    parser = argparse.ArgumentParser(description=__doc__)185    parser.add_argument('--timeout', type=int, default=90)186    args = parser.parse_args()187    try:188        with (kani.TEMP / '.kani-runner.lock').open('w') as lock:189            fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB)190            run(args.timeout)191    except (RuntimeError, subprocess.CalledProcessError, BlockingIOError) as error:192        print('Representation comparison refused: ' + str(error), file=sys.stderr)193        sys.exit(1)