physical_theory_comparison.py
verification/tools/physical_theory_comparison.py
1#!/usr/bin/env python32"""Reconstruct Git sources and compare complete printed theories; never run SMT."""3from contextlib import ExitStack4from pathlib import Path5import argparse6import datetime7import fcntl8import hashlib9import json10import os11import subprocess12import sys13import tarfile14import uuid1516import creusot17import creusot_report18import run_receipt19import composition_checkpoint as checkpoints2021ROOT = creusot.ROOT22SDK = '16bbcc1f2f4a312631cad3ce74c6b2f044d09cd3'23BUDDY = '67a75a12e6096ad82134513578579e67f6b03182'24QUERY = 'f9c97ac7d2a50e378b1b660585dbee1ce98162da'25BASE = 'af6f967362a299ec973c89d5b7cfaec813c1a678'262728def require(condition, message):29 if not condition:30 raise RuntimeError('Physical theory comparison: ' + message)313233def manifest(root, suffix=None):34 """Record every path, including symlinks; theory trees must be regular files."""35 result = {}36 for path in sorted(root.rglob('*')):37 if path.is_symlink():38 require(suffix is None, 'Symlink in printed theory tree: ' + str(path))39 result[path.relative_to(root).as_posix()] = {'symlink': os.readlink(path)}40 elif path.is_file() and (suffix is None or path.suffix == suffix):41 result[path.relative_to(root).as_posix()] = creusot.sha(path)42 require(result, 'Empty input tree: ' + str(root))43 return result444546def compare(left, right):47 """Compare raw bytes over the union of all printed paths, without rewriting."""48 old, new = manifest(left, '.why'), manifest(right, '.why')49 common = old.keys() & new.keys()50 return {'before_files': len(old), 'after_files': len(new),51 'unchanged': sorted(name for name in common if (left / name).read_bytes() == (right / name).read_bytes()),52 'changed': {name: {'before_sha256': old[name], 'after_sha256': new[name]}53 for name in sorted(common) if (left / name).read_bytes() != (right / name).read_bytes()},54 'added': {name: new[name] for name in sorted(new.keys() - old.keys())},55 'removed': {name: old[name] for name in sorted(old.keys() - new.keys())}}565758def differences(comparison):59 return set(comparison['changed']) | set(comparison['added']) | set(comparison['removed'])606162def archive(repo, revision, path, destination):63 require(not destination.exists() and not path.exists(), 'Snapshot destination already exists')64 commit = creusot.git(repo, 'rev-parse', '--verify', revision + '^{commit}')65 tree = creusot.git(repo, 'rev-parse', commit + '^{tree}')66 with path.open('xb') as handle:67 subprocess.run(['git', '-C', str(repo), 'archive', '--format=tar', commit],68 stdout=handle, check=True)69 destination.mkdir()70 with tarfile.open(path) as handle:71 handle.extractall(destination, filter='data')72 return {'commit': commit, 'tree': tree, 'archive_sha256': creusot.sha(path)}737475def snapshot(output, label, revision):76 root = output / ('source-' + label)77 require(creusot.git(ROOT, 'rev-parse', revision + ':cdk-rsx') == SDK, 'Historical SDK gitlink differs')78 source = archive(ROOT, revision, output / (label + '-factory.tar'), root)79 # The archived gitlink has no contents; fill it from the exact SDK Git object.80 sdk_root = root / 'cdk-rsx'81 if sdk_root.exists():82 require(sdk_root.is_dir() and not any(sdk_root.iterdir()), 'Nonempty archived SDK gitlink')83 sdk_root.rmdir()84 source['sdk'] = archive(ROOT / 'cdk-rsx', SDK, output / (label + '-sdk.tar'), sdk_root)85 source['files'] = manifest(root)86 return root, source878889def stage(source, output, module):90 output.mkdir()91 script = '''import importlib, json, pathlib, sys92sys.path.insert(0, sys.argv[1])93module = importlib.import_module(sys.argv[2])94output = pathlib.Path(sys.argv[3])95module.stage(output)96expected = {**module.creusot_report.EXPECTED, **module.NEW} if sys.argv[2] == 'vec_bounds' else module.EXPECTED97data = {'expected': expected, 'original': {name: sorted(goals) for name, goals in getattr(module, 'ORIGINAL', getattr(module, 'ORIGINAL_GOALS', {})).items()},98 'selected': sorted(module.EXPECTED)}99(output / 'stage-manifest.json').write_text(json.dumps(data, indent=2) + '\\n')100'''101 with (output / 'stage.log').open('w') as log:102 subprocess.run([sys.executable, '-B', '-c', script, str(source / 'verification/tools'),103 module, str(output)], cwd=source, check=True, stdout=log, stderr=subprocess.STDOUT)104 return json.loads((output / 'stage-manifest.json').read_text())105106107def translate_and_print(output, module, metadata, verify):108 staged = {str(path.relative_to(output)): creusot.sha(path) for path in output.rglob('*')109 if path.is_file() and path.name != 'stage.log'}110 env = creusot.environment(output)111 command = [str(creusot.TOOL / 'bin/cargo-creusot'), 'creusot', '--erasure-check=error']112 if module == 'buddy_owner':113 command.append('proof')114 command += ['--only=coma', '-j', '4', '--', '--locked', '--offline']115 with (output / 'translation.log').open('w') as log:116 result = subprocess.run(command, cwd=output, env=env, stdout=log, stderr=subprocess.STDOUT)117 verify()118 run_receipt.verify_staged(output, staged)119 creusot.require_no_fatal_diagnostics((output / 'translation.log').read_text(), ())120 require(result.returncode == 0, 'Strict translation failed: ' + str(output / 'translation.log'))121 translation = output / 'verif/page_pool_creusot_rlib'122 prefix = {'vec_bounds': 'page_pool/proof', 'resize_entry': 'resize'}.get(module, 'proof')123 proof = translation / prefix124 inventory = creusot_report.goal_inventory(proof, metadata['expected'], creusot.TOOL / 'bin/why3',125 load_paths=[creusot.TOOL / 'share/why3find/packages/creusot'], config=creusot.TOOL / 'creusot_why3.conf',126 cwd=output, env=env, output_dir=output / 'theories', translation_root=translation,127 original_source_goals=metadata['original'])128 inventory.verify()129 verify()130 return {'staged': staged, 'printed': manifest(output / 'theories', '.why'),131 'checked_files': len(inventory.goals), 'checked_goals': sum(map(len, inventory.goals.values())),132 'original_files': len(inventory.original_source_goals),133 'original_goals': sum(map(len, inventory.original_source_goals.values())),134 'inventory_inputs': inventory.hashes, 'selected': metadata['selected']}, inventory135136137def run():138 checkout = run_receipt.checkout(ROOT)139 require(checkout['sdk'] == SDK, 'Unexpected SDK checkout')140 creusot.validate_source()141 binaries = creusot.validate_binaries()142 output = creusot.TEMP / ('physical-theories-' + datetime.datetime.now(datetime.timezone.utc).strftime('%Y%m%dT%H%M%SZ')143 + '-' + uuid.uuid4().hex[:8])144 output.mkdir()145 sources = {label: snapshot(output, label, revision) for label, revision in (146 ('buddy-historical', BUDDY), ('query-historical', QUERY), ('baseline', BASE), ('current', checkout['factory']))}147148 def verify():149 require(run_receipt.checkout(ROOT) == checkout, 'Invocation checkout changed')150 creusot.validate_source()151 require(creusot.validate_binaries() == binaries, 'Pinned tool/configuration changed')152 for label, (root, identity) in sources.items():153 require(manifest(root) == identity['files'], 'Git snapshot changed: ' + label)154 for kind, expected in (('factory', identity['archive_sha256']), ('sdk', identity['sdk']['archive_sha256'])):155 require(creusot.sha(output / (label + '-' + kind + '.tar')) == expected, 'Source archive changed')156157 receipt = {'invocation': checkout, 'tools': binaries,158 'scope': 'Git-source strict erasure translation and complete raw printed-theory comparison only; no SMT replay',159 'sources': {label: identity for label, (_, identity) in sources.items()}, 'cases': {}}160 (output / 'inputs.json').write_text(json.dumps(receipt, indent=2) + '\n')161 original = (output / 'inputs.json').read_bytes()162 inventories = []163 for label, source_label, module in (164 ('buddy-historical', 'buddy-historical', 'buddy_owner'), ('buddy-current', 'current', 'buddy_owner'),165 ('query-historical', 'query-historical', 'vec_bounds'), ('query-baseline', 'baseline', 'vec_bounds'),166 ('query-current', 'current', 'vec_bounds')):167 print('TRANSLATE_AND_PRINT', label, output, flush=True)168 case = output / label169 metadata = stage(sources[source_label][0], case, module)170 verify()171 receipt['cases'][label], inventory = translate_and_print(case, module, metadata, verify)172 inventories.append(inventory)173 for inventory in inventories:174 inventory.verify()175 for label, case in receipt['cases'].items():176 run_receipt.verify_staged(output / label, case['staged'])177 require(manifest(output / label / 'theories', '.why') == case['printed'], 'Printed theories changed: ' + label)178 comparisons = {name: compare(output / left / 'theories', output / right / 'theories')179 for name, left, right in (('buddy-historical-current', 'buddy-historical', 'buddy-current'),180 ('query-historical-current', 'query-historical', 'query-current'),181 ('query-baseline-current', 'query-baseline', 'query-current'))}182 selected = {'page_pool/proof/' + str(Path(name).parent) + '.why'183 for name in receipt['cases']['query-current']['selected']}184 comparisons['query-historical-current']['selected_differences'] = sorted(185 differences(comparisons['query-historical-current']) & selected)186 verify()187 require((output / 'inputs.json').read_bytes() == original, 'Original comparison metadata changed')188 receipt['comparisons'] = comparisons189 (output / 'comparison.json').write_text(json.dumps(receipt, indent=2) + '\n')190 require(not differences(comparisons['buddy-historical-current']), 'Buddy printed theories changed')191 checkpoints.candidate_delta(comparisons['query-baseline-current'])192 checkpoints.require_selected_unchanged(comparisons['query-historical-current']['selected_differences'])193 print('COMPARISON_ONLY_COMPLETE', output, flush=True)194195196def compare_core(comparison, references_path, references_sha):197 """Reconsume a completed comparison and the independently qualified core."""198 import vec_bounds199 checkout = run_receipt.checkout(ROOT)200 comparison = comparison.resolve()201 references = checkpoints.references(references_path, references_sha)202 checkpoint = Path(references['core']['path'])203 claim_checkpoint = Path(references['claim']['path'])204 original = (comparison / 'comparison.json').read_bytes()205 data = json.loads(original)206 require(data['invocation'] == checkout, 'Query comparison must use this exact combined source freeze')207 core_original = (checkpoint / 'inputs.json').read_bytes()208 core = json.loads(core_original)209 checkpoints.core_source_match(core, json.loads((claim_checkpoint / 'inputs.json').read_text()))210 creusot.validate_source()211 binaries = creusot.validate_binaries()212 require(data['tools'] == core['binaries'] == binaries, 'Core/query tools differ')213 require(core['factory'] == BASE and core['sdk'] == checkout['sdk'] == SDK214 and core['scope'] == 'all' and core['negative_control'] is None,215 'Wrong full-core checkpoint identity/scope')216 case = data['cases']['query-current']217 query = comparison / 'query-current'218 query_reference = references['query']219 query_metadata = json.loads((Path(query_reference['path']) / 'inputs.json').read_text())220 query_inputs_match(query_metadata, checkout['sdk'], binaries)221 query_delta = compare(Path(query_reference['path']) / 'goal-inventory', query / 'theories')222 require(not differences(query_delta), 'Fresh query proof context differs from combined translation')223 staged_source_match(case['staged'], query_metadata['staged'])224 run_receipt.verify_staged(query, case['staged'])225 require(manifest(query / 'theories', '.why') == case['printed'], 'Query printed inventory changed')226 require(all(creusot.sha(Path(path)) == digest for path, digest in case['inventory_inputs'].items()),227 'Query translation/import/tool input changed')228 checkpoints.candidate_delta(data['comparisons']['query-baseline-current'])229 checkpoints.require_selected_unchanged(data['comparisons']['query-historical-current']['selected_differences'])230 core_theories = checkpoint / 'goal-inventory'231 before = manifest(core_theories, '.why')232 expected_paths = {'page_pool/proof/' + str(Path(name).parent) + '.why': name233 for name in creusot_report.EXPECTED}234 originals = {str(Path(name).with_suffix('.why')) for name in creusot.ORIGINAL_SOURCE_GOALS}235 require(set(before) == set(expected_paths) | originals, 'Incomplete full-core theory tree')236 goals = {name: creusot_report.theory_goals((core_theories / path).read_text())237 for path, name in expected_paths.items()}238 reports = checkpoint / 'verif/page_pool_creusot_rlib/page_pool/proof'239 report_hashes = {str(path.relative_to(reports)): creusot.sha(path) for path in reports.rglob('proof.json')}240 summary = creusot_report.validate_directory(reports, goals, creusot_report.EXPECTED)241 result = compare(core_theories, query / 'theories')242 additions = {'page_pool/proof/' + str(Path(name).parent) + '.why' for name in vec_bounds.NEW}243 additions.add('page_pool/impl_Clone_for_VecBounds/clone.why')244 output = creusot.TEMP / ('physical-core-comparison-'245 + datetime.datetime.now(datetime.timezone.utc).strftime('%Y%m%dT%H%M%SZ') + '-' + uuid.uuid4().hex[:8])246 output.mkdir()247 record = {'invocation': checkout, 'scope': 'Raw printed-core comparison and report reconsumption only; no SMT',248 'comparison': str(comparison), 'comparison_sha256': hashlib.sha256(original).hexdigest(),249 'core_checkpoint': str(checkpoint), 'core_receipt_sha256': hashlib.sha256(core_original).hexdigest(),250 'core_source': {'factory': core['factory'], 'sdk': core['sdk']}, 'core_summary': summary,251 'core_theories': before, 'core_reports': report_hashes, 'comparison_result': result}252 require(run_receipt.checkout(ROOT) == checkout and binaries == creusot.validate_binaries(), 'Invocation changed')253 require((comparison / 'comparison.json').read_bytes() == original254 and (checkpoint / 'inputs.json').read_bytes() == core_original255 and manifest(core_theories, '.why') == before256 and manifest(query / 'theories', '.why') == case['printed']257 and report_hashes == {str(path.relative_to(reports)): creusot.sha(path) for path in reports.rglob('proof.json')},258 'Comparison inputs changed')259 (output / 'comparison.json').write_text(json.dumps(record, indent=2) + '\n')260 require(set(result['changed']) == {checkpoints.DELTA}261 and result['changed'][checkpoints.DELTA] == {'before_sha256': checkpoints.DELTA_BEFORE,262 'after_sha256': checkpoints.DELTA_AFTER}263 and not result['removed'] and set(result['added']) == additions,264 'Core/query theory delta requires affected-scope replay: ' + str(output))265 require((query / 'theories' / checkpoints.DELTA).read_bytes()266 == (claim_checkpoint / 'goal-inventory' / checkpoints.DELTA).read_bytes(),267 'Query owning caller differs from the qualified fb theory')268 record['claim_reference'] = references['claim']269 record['query_reference'] = query_reference270 record['query_input_reuse'] = {'producer_factory': query_metadata['factory'], 'sources': query_metadata['sources']}271 record['query_comparison'] = query_delta272 record['references_sha256'] = references_sha273 # All checked and original theories in the claim context must match the274 # current query context, not just the one overridden caller.275 claim_comparison = compare(claim_checkpoint / 'goal-inventory', query / 'theories')276 require(not claim_comparison['changed'] and not claim_comparison['removed']277 and set(claim_comparison['added']) == additions, 'Claim/query complete context differs')278 record['claim_comparison'] = claim_comparison279 record['components'] = {}280 component_inventories = []281 for role in ('buddy', 'slab', 'resize'):282 checkpoints.native_source_match(references[role])283 component = output / role284 metadata = stage(ROOT, component, checkpoints.MODULES[role])285 component_case, inventory = translate_and_print(component, checkpoints.MODULES[role], metadata,286 lambda: require(run_receipt.checkout(ROOT) == checkout, 'Combined source changed'))287 reference = Path(references[role]['path'])288 delta = compare(reference / 'goal-inventory', component / 'theories')289 require(not differences(delta), role + ' complete printed theory tree differs')290 previous = json.loads((reference / 'inputs.json').read_text())['staged']291 staged_source_match(component_case['staged'], previous)292 inventory.verify()293 component_inventories.append(inventory)294 record['components'][role] = {'reference': references[role], 'case': component_case, 'comparison': delta}295 checkpoints.references(references_path, references_sha)296 query_inputs_match(query_metadata, checkout['sdk'], binaries)297 for inventory in component_inventories:298 inventory.verify()299 for role, component in record['components'].items():300 run_receipt.verify_staged(output / role, component['case']['staged'])301 require(manifest(output / role / 'theories', '.why') == component['case']['printed'], 'Component theories changed')302 require(run_receipt.checkout(ROOT) == checkout and binaries == creusot.validate_binaries(), 'Combined inputs changed')303 (output / 'comparison.json').write_text(json.dumps(record, indent=2) + '\n')304 print('CORE_COMPARISON_ONLY_PASS', summary, output, flush=True)305306307def staged_source_match(current, previous):308 def source(staged):309 return {name: digest for name, digest in staged.items()310 if name.startswith('src/') or name in ('Cargo.toml', 'Cargo.lock', 'why3find.json')}311 require(source(current) == source(previous), 'Component staged source/contract bytes differ')312313314def query_inputs_match(metadata, sdk, tools):315 """Reuse a producer identity only when every captured proof input still matches."""316 require(metadata['sdk'] == sdk and metadata['binaries'] == tools and metadata['sources'],317 'Qualified query SDK/tool/input identity differs')318 for name, digest in metadata['sources'].items():319 relative = Path(name)320 require(not relative.is_absolute() and '..' not in relative.parts321 and (ROOT / relative).is_file() and creusot.sha(ROOT / relative) == digest,322 'Captured query proof input differs: ' + name)323324325if __name__ == '__main__':326 parser = argparse.ArgumentParser(description=__doc__)327 parser.add_argument('--comparison', type=Path)328 parser.add_argument('--references', type=Path)329 parser.add_argument('--references-sha256')330 parser.add_argument('--import-reference', choices=tuple(checkpoints.MODULES))331 parser.add_argument('--checkpoint', type=Path)332 parser.add_argument('--factory')333 parser.add_argument('--historical-core-audit', type=Path)334 parser.add_argument('--external-evidence', type=Path)335 parser.add_argument('--external-evidence-sha256')336 args = parser.parse_args()337 try:338 with creusot.cache_lease():339 require(bool(args.comparison) == bool(args.references) == bool(args.references_sha256), 'Reviewed comparison map required')340 require(bool(args.external_evidence) == bool(args.external_evidence_sha256), 'Both external evidence pins are required')341 with ExitStack() as stack:342 for name in ('.physical-theory-comparison.lock', '.creusot-runner.lock', '.buddy-owner.lock', '.vec-bounds.lock'):343 lease = stack.enter_context((creusot.TEMP / name).open('w'))344 fcntl.flock(lease, fcntl.LOCK_EX | fcntl.LOCK_NB)345 if args.import_reference:346 require(args.checkpoint and args.factory and not args.comparison, 'Historical checkpoint identity required')347 output = creusot.TEMP / ('composition-reference-' + args.import_reference + '-' + uuid.uuid4().hex[:8])348 output.mkdir()349 digest, summary = checkpoints.import_reference(args.checkpoint, args.import_reference, args.factory,350 output / 'checkpoint-seal.json', args.historical_core_audit,351 args.external_evidence, args.external_evidence_sha256)352 print('HISTORICAL_RECONSUMPTION_PENDING_OWNER_APPROVAL', digest, summary, output, flush=True)353 elif args.comparison:354 compare_core(args.comparison, args.references, args.references_sha256)355 else:356 run()357 except (RuntimeError, subprocess.CalledProcessError, BlockingIOError) as error:358 print(str(error), file=sys.stderr)359 sys.exit(1)