creusot_report.py

verification/tools/creusot_report.py

creusot_report.py469 lines← SDK documentation
1"""Reject incomplete Why3find reports for the checked page-control scope."""2from pathlib import Path3from dataclasses import dataclass, field4from concurrent.futures import ThreadPoolExecutor5import hashlib6import json7import math8import re9import subprocess101112BASE_METHODS = (13    'word', 'set', 'header', 'committed_pages', 'installed', 'install_store',14    'owner', 'bit', 'boundary', 'free_summary', 'owners',15)16METHODS = BASE_METHODS + ('contains', 'first_occupied', 'mark', 'next_free', 'adjacent_boundary', 'containing', 'release', 'initialize', 'validate', 'recover_runtime', 'attach', 'into_backing', 'allocated_pages', 'claim')17EXPECTED = {18    f'impl_Pool_B/{name}_proof/proof.json': f'vc_{name}_proof_B'19    for name in BASE_METHODS20} | {21    'initialize/initialization_prefix_write/proof.json': 'vc_initialization_prefix_write',22    'initialize/header_format_written/proof.json': 'vc_header_format_written',23    'initialize/header_format_preserved/proof.json': 'vc_header_format_preserved',24    **{f'claim/{name}/proof.json': f'vc_{name}' for name in (25        'rounded_alignment', 'candidate_arithmetic', 'padded_result', 'subtracted_result',26        'unbase_candidate', 'search_progress', 'payload_geometry', 'claim_owner',27        'header_advance', 'marked_valid', 'free_interval_frame', 'claim_effects',28        'prefix_choice', 'claim_positive_witness', 'chain_alignment_one', 'chain_singleton_run',29        'payload_result', 'cleared_prefix', 'minimum_normal_form', 'zero_trace_reflexive', 'old_payload_window',30    )},31    **{f'claim/search/{name}/proof.json': f'vc_{name}' for name in (32        'committed_admit', 'committed_request', 'committed_free_choice', 'aligned_ceiling_bound',33        'committed_rounding_safe', 'committed_rounding_keeps_candidate',34        'committed_cursor_bound', 'committed_skip_occupied',35    )},36    **{f'claim/completeness/{name}/proof.json': f'vc_{name}' for name in (37        'complete_unbase_candidate', 'complete_search_progress', 'complete_prefix_choice',38    )},39    'claim/completeness/impl_Pool_B/claim_committed_proof/proof.json': 'vc_claim_committed_proof_B',40    'claim/impl_Pool_B/claim_proof/proof.json': 'vc_claim_proof_B',41    'claim/claim_committed_without_growth/proof.json': 'vc_claim_committed_without_growth_B',42    'claim/claim_without_growth/proof.json': 'vc_claim_without_growth_B',43    'claim/claim_invalid_client/proof.json': 'vc_claim_invalid_client_B',44    'provider/borrow_control/proof.json': 'vc_borrow_control',45    'claim/store_claim_handoff/proof.json': 'vc_store_claim_handoff_B',46    'claim/fresh_store_admitted/proof.json': 'vc_fresh_store_admitted',47    'provider/handoff_payload/proof.json': 'vc_handoff_payload',48    'provider/initialized_bytes/proof.json': 'vc_initialized_bytes_B',49    'provider/initialized_byte/proof.json': 'vc_initialized_byte_B',50    'provider/metadata_frame/proof.json': 'vc_metadata_frame_B',51    'provider/forget_bound/proof.json': 'vc_forget_bound_B',52    'provider/borrowed_zero/impl_BorrowedBacking/cleared_payload/proof.json': 'vc_cleared_payload',53    'provider/handed_out_payload_is_dirty/proof.json': 'vc_handed_out_payload_is_dirty',54    'provider/impl_PhysicalState/control/proof.json': "vc_control'0",55    'provider/impl_PhysicalState/control_mut/proof.json': 'vc_control_mut',56    'initialize/impl_Pool_B/initialize_proof/proof.json': 'vc_initialize_proof_B',57    'initialize/blank_tables_valid/proof.json': 'vc_blank_tables_valid',58    'initialize/assemble_initialized/proof.json': 'vc_assemble_initialized',59    'initialize/initialize_without_growth/proof.json': 'vc_initialize_without_growth_B',60    'lifecycle/initialized_is_saved_valid/proof.json': 'vc_initialized_is_saved_valid',61    'owner_chunk/proof.json': 'vc_owner_chunk',62    'admitted_owner_update_exists/proof.json': 'vc_admitted_owner_update_exists',63    'install_client/proof.json': 'vc_install_client_B',64    'owner_step_geometry/proof.json': 'vc_owner_step_geometry',65    'owner_word_effect/proof.json': 'vc_owner_word_effect',66    'owner_region_frame/proof.json': 'vc_owner_region_frame',67    'table_write_frame/proof.json': 'vc_table_write_frame',68    'summary_bit_update/proof.json': 'vc_summary_bit_update',69    'free_summary_step/proof.json': 'vc_free_summary_step',70    'free_summary_invariant_reachable/proof.json': 'vc_free_summary_invariant_reachable',71    'queries/impl_Pool_B/contains_proof/proof.json': 'vc_contains_proof_B',72    'queries/impl_Pool_B/first_occupied_proof/proof.json': 'vc_first_occupied_proof_B',73    'queries/query_geometry/proof.json': 'vc_query_geometry',74    'queries/range_match_correspondence/proof.json': 'vc_range_match_correspondence',75    'queries/occupied_chunk_correspondence/proof.json': 'vc_occupied_chunk_correspondence',76    'queries/query_cases/proof.json': 'vc_query_cases',77    'queries/contains_client/proof.json': 'vc_contains_client_B',78    'bit_queries/chunk_matches/proof.json': 'vc_chunk_matches',79    'bit_queries/first_set_bit/proof.json': 'vc_first_set_bit',80    'bit_queries/chunk_first_occupied/proof.json': 'vc_chunk_first_occupied',81    'updates/owner_code_range/proof.json': 'vc_owner_code_range',82    'updates/owner_update_keeps_boundaries/proof.json': 'vc_owner_update_keeps_boundaries',83    'updates/boundary_update_effect/proof.json': 'vc_boundary_update_effect',84    'updates/boundary_summary_bits/proof.json': 'vc_boundary_summary_bits',85    'updates/mark_table_frame/proof.json': 'vc_mark_table_frame',86    'updates/boundary_summaries_reachable/proof.json': 'vc_boundary_summaries_reachable',87    'updates/impl_Pool_B/mark_proof/proof.json': 'vc_mark_proof_B',88    'partition/mark_keeps_partition/proof.json': 'vc_mark_keeps_partition',89    'partition/mark_preserves_partition/proof.json': 'vc_mark_preserves_partition_B',90    'partition/empty_partition_reachable/proof.json': 'vc_empty_partition_reachable',91    'partition/partition_examples/proof.json': 'vc_partition_examples',92    'free_bits/free_pair_facts/proof.json': 'vc_free_pair_facts',93    'free_bits/first_set_in_suffix/proof.json': 'vc_first_set_in_suffix',94    'free_bits/first_free_in_word/proof.json': 'vc_first_free_in_word',95    'free_queries/free_word_correspondence/proof.json': 'vc_free_word_correspondence',96    'free_queries/summary_geometry/proof.json': 'vc_summary_geometry',97    'free_queries/summary_choice_correspondence/proof.json': 'vc_summary_choice_correspondence',98    'free_queries/summary_prefix_full/proof.json': 'vc_summary_prefix_full',99    'free_queries/free_query_cases/proof.json': 'vc_free_query_cases',100    'free_queries/impl_Pool_B/next_free_proof/proof.json': 'vc_next_free_proof_B',101    'free_queries/next_free_limit_client/proof.json': 'vc_next_free_limit_client_B',102    'boundary_bits/last_set_bit/proof.json': 'vc_last_set_bit',103    'boundary_bits/boundary_in_word/proof.json': 'vc_boundary_in_word',104    'boundary_bits/boundary_bit_cases/proof.json': 'vc_boundary_bit_cases',105    'lookup/boundary_geometry/proof.json': 'vc_boundary_geometry',106    'lookup/boundary_word_correspondence/proof.json': 'vc_boundary_word_correspondence',107    'lookup/boundary_summary_geometry/proof.json': 'vc_boundary_summary_geometry',108    'lookup/boundary_summary_correspondence/proof.json': 'vc_boundary_summary_correspondence',109    'lookup/clear_words_pages/proof.json': 'vc_clear_words_pages',110    'lookup/boundary_candidate/proof.json': 'vc_boundary_candidate',111    'lookup/live_head/proof.json': 'vc_live_head',112    'lookup/live_end/proof.json': 'vc_live_end',113    'lookup/nearest_unique/proof.json': 'vc_nearest_unique',114    'lookup/lookup_full_cases/proof.json': 'vc_lookup_full_cases',115    'lookup/lookup_adjacent_cases/proof.json': 'vc_lookup_adjacent_cases',116    'lookup/impl_Pool_B/adjacent_boundary_proof/proof.json': 'vc_adjacent_boundary_proof_B',117    'lookup/impl_Pool_B/containing_proof/proof.json': 'vc_containing_proof_B',118    **{f'equality/{name}/proof.json': f'vc_{name}' for name in (119        'owner_model_matches_oracle', 'run_model_matches_oracle',120        'owner_eq_client', 'owner_ne_client', 'run_eq_client', 'run_ne_client',121    )},122    'validation_helpers/scanned_owner_range/proof.json': 'vc_scanned_owner_range',123    'validation_helpers/scan_step/proof.json': 'vc_scan_step',124    'validation_helpers/scan_complete/proof.json': 'vc_scan_complete',125    'validation_helpers/scan_examples/proof.json': 'vc_scan_examples',126    'validation_helpers/partition_scan_accepts/proof.json': 'vc_partition_scan_accepts',127    'validation_helpers/partition_scan_closed/proof.json': 'vc_partition_scan_closed',128    'validation_helpers/saved_image_witness/proof.json': 'vc_saved_image_witness',129    **{f'option_equality/{name}/proof.json': f'vc_{name}' for name in (130        'option_model_matches_oracle', 'option_run_eq_client', 'option_run_ne_client',131    )},132    'release/exact_run_candidates_unique/proof.json': 'vc_exact_run_candidates_unique',133    'release/release_exact_client/proof.json': 'vc_release_exact_client_B',134    'validation_helpers/coverage_step/proof.json': 'vc_coverage_step',135    'validation_helpers/control_guard/proof.json': 'vc_control_guard',136    'validation_helpers/free_scan_step/proof.json': 'vc_free_scan_step',137    'validation_helpers/boundary_scan_step/proof.json': 'vc_boundary_scan_step',138    'validation/impl_Pool_B/validate_proof/proof.json': 'vc_validate_proof_B',139    'release/release_table_frame/proof.json': 'vc_release_table_frame',140    'release/release_keeps_partition/proof.json': 'vc_release_keeps_partition',141    'release/impl_Pool_B/release_proof/proof.json': 'vc_release_proof_B',142    **{f'recovery/{name}/proof.json': f'vc_{name}' for name in (143        'header_frame', 'prefix_start', 'prefix_no_runtime', 'skip_non_runtime',144        'run_starts_at_cursor', 'prefix_after_release', 'valid_after_release',145        'retained_run_preserved', 'prefix_complete', 'all_retained_runs_preserved',146        'recovery_cases',147    )},148    **{f'recovery/impl_Pool_B/{name}_proof/proof.json': f'vc_{name}_proof_B'149       for name in ('recover_runtime', 'attach', 'into_backing')},150    **{f'counting/{name}/proof.json': f'vc_{name}' for name in (151        'bit_population', 'bit_count_checked', 'ceil32_model_checked',152        'pair_population', 'matching_pair', 'matching_population',153        'owner_population', 'word_slot', 'word_count_step', 'free_padding',154        'owner_cast', 'rounded_value', 'counting_cases', 'bit_population_anchor',155    )},156    'counting/impl_Pool_B/allocated_pages_proof/proof.json': 'vc_allocated_pages_proof_B',157    'counting/validated_count_client/proof.json': 'vc_validated_count_client_B',158    **{f'provider/resource_admission/impl_BorrowedBacking/{name}/proof.json': f'vc_{name}'159       for name in ('page_observation', 'base_observation', 'fixed_growth')},160    **{f'provider/resource_admission/{name}/proof.json': f'vc_{name}' for name in (161        'receiver_count_is_required', 'initialize_and_install_borrowed_image', 'installation_frame',162        'metadata_word', 'metadata_join', 'payload_join', 'decode_window', 'decoded_low_byte', 'complement_low_byte',163        'actual_owner_witness', 'actual_store_owner_witness',164        'committed_claim_borrowed_image', 'actual_committed_owner_witness',165    )},166}167PROVERS = frozenset(('alt-ergo', 'z3', 'cvc4', 'cvc5'))168TACTICS = frozenset(('compute_specified', 'split_vc'))169# Reviewed structural branch/move/fallback/identity operations in the current170# checked translation. Full names only; another helper requires source review.171OWNED_PROGRAM_HELPERS = frozenset((172    'branch_Result_Pool_BorrowedBacking_PoolError',173    'branch_Result_Run_PoolError',174    'branch_Result_bool_PoolError',175    'branch_Result_unit_PoolError',176    'branch_Result_usize_PoolError',177    'from_PoolError',178    'from_residual_Option_Run',179    'from_residual_Result_Run_PoolError',180    'from_residual_Result_unit_PoolError',181    'is_some_Run',182    'ok_or_Run',183    'unwrap_or_Run',184))185186187def require(condition, message):188    if not condition:189        raise RuntimeError(message)190191192def parse_report(raw):193    def unique(pairs):194        result = {}195        for key, value in pairs:196            require(key not in result, 'Duplicate result key: ' + key)197            result[key] = value198        return result199200    def invalid(value):201        raise RuntimeError('Nonfinite JSON constant: ' + value)202203    try:204        return json.loads(raw, object_pairs_hook=unique, parse_constant=invalid)205    except (TypeError, ValueError, RecursionError) as error:206        raise RuntimeError('Malformed Why3find report') from error207208209def proof_counts(node, depth=0, allow_open=False):210    require(depth <= 64, 'Unexpected proof-tree depth')211    if node is None and allow_open:212        return 0, 1213    require(isinstance(node, dict), 'Unproved or malformed proof node')214    if set(node) == {'prover', 'time'}:215        require(isinstance(node['prover'], str) and node['prover'] in PROVERS,216                'Unexpected prover')217        elapsed = node['time']218        require(type(elapsed) in (int, float) and math.isfinite(elapsed) and elapsed >= 0,219                'Invalid prover time')220        return 1, 0221    require(set(node) == {'tactic', 'children'}, 'Unknown proof outcome')222    require(isinstance(node['tactic'], str) and node['tactic'] in TACTICS,223            'Unexpected proof tactic')224    children = node['children']225    require(isinstance(children, list) and len(children) > 0, 'Empty proof decomposition')226    counts = [proof_counts(child, depth + 1, allow_open) for child in children]227    return sum(count[0] for count in counts), sum(count[1] for count in counts)228229230def proved_leaves(node, depth=0):231    return proof_counts(node, depth)[0]232233234def report_goals(report, main_goal, *, allow_refines=False):235    require(isinstance(report, dict) and set(report) == {'profile', 'proofs'},236            'Unexpected Why3find report format')237    require(report['profile'] == [], 'Unexpected prover profile format')238    proofs = report['proofs']239    require(isinstance(proofs, dict) and set(proofs) == {'Coma'},240            'Missing or unexpected verification module')241    goals = proofs['Coma']242    require(isinstance(goals, dict) and main_goal in goals, 'Missing required main goal')243    require(not allow_refines or main_goal == 'refines', 'Refinement admission requires its exact declared main')244    require(all(isinstance(name, str) and (name.startswith('vc_')245                or (allow_refines and name == 'refines')) for name in goals),246            'Unexpected verification goal')247    return goals248249250def validate_report(report, main_goal, expected_goals, *, allow_refines=False):251    goals = report_goals(report, main_goal, allow_refines=allow_refines)252    require(main_goal in expected_goals and set(goals) == set(expected_goals),253            'Missing or unexpected verification goals: missing='254            + str(sorted(set(expected_goals) - set(goals))) + ', unexpected='255            + str(sorted(set(goals) - set(expected_goals))))256    leaves = sum(proved_leaves(node) for node in goals.values())257    require(leaves > 0, 'No prover result')258    return {'goal_count': len(goals), 'prover_leaves': leaves}259260261def validate_expected_rejection(report, main_goal, expected_goals, *, allow_refines=False):262    goals = report_goals(report, main_goal, allow_refines=allow_refines)263    require(main_goal in expected_goals and set(goals) == set(expected_goals),264            'Unexpected negative-control goals')265    leaves, open_goals = proof_counts(goals[main_goal], allow_open=True)266    leaves += sum(proved_leaves(node) for name, node in goals.items() if name != main_goal)267    require(leaves > 0 and open_goals == 1,268            'Negative control must leave exactly its designated subgoal unproved')269    return {'prover_leaves': leaves, 'open_goals': open_goals}270271272def validate_directory(proof_root, inventory, expected=EXPECTED):273    proof_root = Path(proof_root)274    require(proof_root.is_dir(), 'Missing proof directory')275    if isinstance(inventory, GoalInventory):276        inventory.verify()277        inventory = inventory.goals278    require(set(inventory) == set(expected), 'Missing or unexpected source goal inventories')279    found = {path.relative_to(proof_root).as_posix(): path280             for path in proof_root.rglob('proof.json')}281    require(set(found) == set(expected),282            'Missing or unexpected proof files: missing=' + str(sorted(set(expected) - set(found)))283            + ', unexpected=' + str(sorted(set(found) - set(expected))))284    summary = {'files': len(found), 'goal_count': 0, 'prover_leaves': 0}285    for name, main_goal in expected.items():286        path = found[name]287        require(not path.is_symlink(), 'Proof-report symlink refused')288        result = validate_report(parse_report(path.read_text()), main_goal, inventory[name],289                                 allow_refines=main_goal == 'refines')290        summary['goal_count'] += result['goal_count']291        summary['prover_leaves'] += result['prover_leaves']292    return summary293294295def validate_negative_directory(proof_root, inventory, expected, negative_file):296    """Require every scoped goal, allowing one open main leaf in one file."""297    proof_root = Path(proof_root)298    if isinstance(inventory, GoalInventory):299        inventory.verify()300        inventory = inventory.goals301    require(negative_file in expected and set(expected) <= set(inventory),302            'Missing designated negative goal inventory')303    found = {p.relative_to(proof_root).as_posix(): p for p in proof_root.rglob('proof.json')}304    require(set(found) == set(expected), 'Missing or unexpected negative proof files')305    result = {'files': len(found), 'goal_count': 0, 'prover_leaves': 0, 'open_goals': 0}306    for relative, path in found.items():307        require(not path.is_symlink(), 'Proof-report symlink refused')308        goals = report_goals(parse_report(path.read_text()), expected[relative],309                             allow_refines=expected[relative] == 'refines')310        require(set(goals) == set(inventory[relative]), 'Missing or unexpected negative verification goals')311        result['goal_count'] += len(goals)312        for name, node in goals.items():313            designated = relative == negative_file and name == expected[relative]314            leaves, opened = proof_counts(node, allow_open=designated)315            require(not designated or opened == 1, 'Designated negative must leave exactly one open leaf')316            result['prover_leaves'] += leaves317            result['open_goals'] += opened318    require(result['prover_leaves'] > 0 and result['open_goals'] == 1,319            'Unexpected negative proof outcome')320    return result321322323def theory_goals(text, *, extra_names=()):324    """Read the pinned Why3 printer's *generated* Coma theory, not Coma syntax.325326    Why3 has already resolved imports and generated their VCs. Only the current327    single-Coma-theory format is admitted. No hand parser tries to infer VCs from328    Rust contracts or Coma `let`s. A changed printer grammar requires review.329    """330    # Why3 comments nest. Keep newlines so declaration anchors stay meaningful.331    output, cursor, depth = [], 0, 0332    while cursor < len(text):333        if text.startswith('(*', cursor):334            depth += 1335            cursor += 2336        elif text.startswith('*)', cursor):337            require(depth > 0, 'Malformed Why3 printer comment')338            depth -= 1339            cursor += 2340        else:341            char = text[cursor]342            output.append(char if depth == 0 or char == '\n' else ' ')343            cursor += 1344    require(depth == 0, 'Unterminated Why3 printer comment')345    text = ''.join(output)346    require(re.findall(r'^\s*theory\s+(\S+)', text, re.M) == ['Coma']347            and text.rstrip().endswith('\nend'),348            'Unexpected Why3 theory set')349    require(not re.search(r'^\s*(?:module|lemma)\b', text, re.M),350            'Unreviewed Why3 proof declaration')351    names = re.findall(r"^\s*goal\s+([A-Za-z_][A-Za-z0-9_']*)\s*:", text, re.M)352    require(len(names) == len(re.findall(r'^\s*goal\b', text, re.M)),353            'Unrecognized generated goal identity')354    require(all(re.fullmatch(r"vc_[A-Za-z0-9_']+", name) or name in extra_names for name in names),355            'Unrecognized generated goal identity')356    require(len(names) == len(set(names)), 'Duplicate generated goal identity')357    return frozenset(names)358359360def audit_checked_coma(source, *, source_path=None):361    """Admit this finite reviewed translation's crate-local type program helpers.362363    Source/stage and whole-crate hashes bind the exact helper manifest. Pinned364    helper naming can omit later generic arguments: this is not a general365    instantiation or call-graph proof. Logical DeepModel definitions are separate.366    The authenticated owner_eq/run_eq/option_run_eq wrappers have distinct names.367    """368    # VecBounds has an extra unproved query-crate Clone derive; none of its369    # derived program/trait helpers may enter a checked client.370    owned = re.compile(r"(?:^|_)(?:Config|Owner|PoolError|Run|VecBounds)(?:_|'|$)")371    programs = re.findall(r"^[ \t]*let[ \t]+([A-Za-z_][A-Za-z0-9_']*)", source, re.M)372    leaked = {name for name in programs if owned.search(name) and name not in OWNED_PROGRAM_HELPERS}373    constructors = re.findall(r"\bdyn_(?:Debug|PartialEq|Eq|Clone)_[A-Za-z0-9_']+", source)374    leaked.update(name for name in constructors if owned.search(name))375    location = '' if source_path is None else ' at ' + str(source_path)376    require(not leaked, 'Unchecked original-derived helper in checked Coma' + location + ': ' + str(sorted(leaked)))377378379def input_hashes(roots, files):380    paths = set(Path(path) for path in files)381    for root in roots:382        require(root.is_dir(), 'Missing translation/import directory: ' + str(root))383        paths.update(path for path in root.rglob('*')384                     if path.is_file() and path.suffix in ('.coma', '.why', '.mlw'))385    require(all(path.is_file() for path in paths), 'Missing inventory input')386    return {str(path): hashlib.sha256(path.read_bytes()).hexdigest() for path in sorted(paths)}387388389@dataclass(frozen=True)390class GoalInventory:391    goals: dict392    roots: tuple393    files: tuple394    hashes: dict395    original_source_goals: dict = field(default_factory=dict)396397    def verify(self):398        require(input_hashes(self.roots, self.files) == self.hashes,399                'Translation, imports or Why3 changed after goal enumeration')400401402def goal_inventory(proof_root, expected, why3_binary, *, load_paths, config, cwd, env, output_dir,403                   translation_root, original_source_goals=None):404    """Print every crate Coma before proof search; never learn scope from proof.json.405406    Call after translation-only and before prove-only. `load_paths` must contain407    the same pinned package imports as Why3find. The caller authenticates the408    pinned Why3/Coma implementation; its default standard library remains part409    of that tool trust boundary. All explicitly supplied imports, translations,410    configuration and the Why3 executable are content-rechecked after proving.411    Outside the checked proof subtree, only the exact explicit original-source412    file/goal classification is admitted. Those goals remain unproved and may413    not supply unchecked derived helpers to the checked clients.414    """415    proof_root, output_dir = Path(proof_root), Path(output_dir)416    translation_root = Path(translation_root)417    original_source_goals = {} if original_source_goals is None else original_source_goals418    require(proof_root.is_dir(), 'Missing fresh Coma translation directory')419    require(proof_root.is_relative_to(translation_root) and translation_root.is_dir(),420            'Proof scope escapes crate translation root')421    require(not any(translation_root.rglob('proof.json')), 'Goal enumeration must precede proof reports')422    sources = sorted(translation_root.rglob('*.coma'))423    require(sources and all(not path.is_symlink() for path in sources),424            'Missing or symlinked Coma translation')425    roots = tuple(dict.fromkeys((translation_root, *(Path(path) for path in load_paths))))426    files = (Path(why3_binary), Path(config))427    before = input_hashes(roots, files)428    output_dir.mkdir(parents=True, exist_ok=False)429430    def enumerate_file(source):431        checked = source.is_relative_to(proof_root)432        relative = source.relative_to(translation_root)433        if checked:434            audit_checked_coma(source.read_text(), source_path=source)435        printed = output_dir / relative.with_suffix('.why')436        printed.parent.mkdir(parents=True, exist_ok=True)437        args = [str(why3_binary), 'prove', '--print-theory', '--config=' + str(config),438                '--warn-off=unused_variable,axiom_abstract,clone_not_abstract']439        for path in load_paths:440            args += ['-L', str(path)]441        args.append(str(source))442        with printed.open('w') as out, printed.with_suffix('.log').open('w') as err:443            process = subprocess.run(args, cwd=cwd, env=env, stdout=out, stderr=err)444        require(process.returncode == 0, 'Why3 goal enumeration failed: ' + str(printed.with_suffix('.log')))445        name = ((source.relative_to(proof_root).with_suffix('') / 'proof.json').as_posix()446                if checked else relative.as_posix())447        # Only an exact source-known checked path/main can admit a refinement.448        # Original-derived classification remains explicit and separate below.449        extra = ('refines',) if not checked or expected.get(name) == 'refines' else ()450        goals = theory_goals(printed.read_text(), extra_names=extra)451        return checked, name, goals452453    with ThreadPoolExecutor(max_workers=4) as workers:454        enumerated = list(workers.map(enumerate_file, sources))455    goals = {name: names for checked, name, names in enumerated if checked and names}456    originals = {name: names for checked, name, names in enumerated if not checked}457    require(set(originals) == set(original_source_goals),458            'Unregistered original-source Coma files: missing=' + str(sorted(set(original_source_goals) - set(originals)))459            + ', unexpected=' + str(sorted(set(originals) - set(original_source_goals))))460    require(all(originals[name] == frozenset(required) for name, required in original_source_goals.items()),461            'Original-source goal classification differs')462    require(set(goals) == set(expected),463            'Generated goal-file scope differs: missing=' + str(sorted(set(expected) - set(goals)))464            + ', unexpected=' + str(sorted(set(goals) - set(expected))))465    require(all(main in goals[name] for name, main in expected.items()),466            'Fresh translation lacks a required main goal')467    inventory = GoalInventory(goals, roots, files, before, originals)468    inventory.verify()469    return inventory