From 7d5dd6f5b2e639b700198ac53d14292fba24cd04 Mon Sep 17 00:00:00 2001 From: Amaury Chamayou Date: Fri, 4 Dec 2026 12:10:55 +0000 Subject: [PATCH] Add Lean specification coverage masks, mapping docs, and CI checks Port the four anchor-validated Lean coverage masks, the specification-to-C++ coverage mapping documentation, and scripts/lean_coverage_report.py (with unit tests) to main, re-anchored and updated for recent main changes including #8490, #8785, #8791, #8888, #8894, #8905, and #8921. Add --check-masks to scripts/lean_coverage_report.py and wire scripts/lean-coverage-masks-checks.sh into scripts/ci-checks.sh so CI validates mask anchors, brace balance, and cross-spec disjointness on every PR. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: 679d732f8eac4c0aa07824aa725ebde6 --- .../skills/formatting-and-linting/SKILL.md | 1 + lean/COVERAGE_MAPPING.md | 168 ++ lean/consensus/coverage_mask.json | 155 ++ lean/consistency/coverage_mask.json | 120 + lean/disaster-recovery/coverage_mask.json | 123 + lean/kv/coverage_mask.json | 588 +++++ scripts/ci-checks.sh | 1 + scripts/lean-coverage-masks-checks.sh | 17 + scripts/lean_coverage_report.py | 2109 +++++++++++++++++ scripts/tests/lean_coverage_report_test.py | 513 ++++ 10 files changed, 3795 insertions(+) create mode 100644 lean/COVERAGE_MAPPING.md create mode 100644 lean/consensus/coverage_mask.json create mode 100644 lean/consistency/coverage_mask.json create mode 100644 lean/disaster-recovery/coverage_mask.json create mode 100644 lean/kv/coverage_mask.json create mode 100755 scripts/lean-coverage-masks-checks.sh create mode 100755 scripts/lean_coverage_report.py create mode 100755 scripts/tests/lean_coverage_report_test.py diff --git a/.github/skills/formatting-and-linting/SKILL.md b/.github/skills/formatting-and-linting/SKILL.md index a4f2a4fa59dc..45cc5829872e 100644 --- a/.github/skills/formatting-and-linting/SKILL.md +++ b/.github/skills/formatting-and-linting/SKILL.md @@ -35,6 +35,7 @@ Each command below is under `scripts/`. This table is a routing guide; the scrip | `prettier-checks.sh` | TS, JS, Markdown, YAML, JSON (excluding `.github/**/*.md` and `tests/sandbox/`) | prettier | `-f` | | `doc-newline-checks.sh` | Markdown and RST prose | Mid-sentence newline policy | `-f` | | `builtin-maps-checks.sh` | Built-in map names in `include/` or `src/`, and `doc/audit/builtin_maps.rst` | Every `public:ccf.gov.*` and `public:ccf.internal.*` map is documented | No | +| `lean-coverage-masks-checks.sh` | `lean/COVERAGE_MAPPING.md`, `lean//coverage_mask.json`, `scripts/lean_coverage_report.py`, or mapped C++ files | Validates coverage mask anchors, brace balance, cross-spec disjointness, and report script tests | No | | `cmake-format-checks.sh` | CMake files | gersemi | `-f` | | `release-notes-checks.sh` | `CHANGELOG.md`, `.changes/*.md` (also run prettier) | extract-release-notes.py | `-f` (changelog links only) | | `shellcheck-checks.sh` | Shell scripts outside `3rdparty/` | shellcheck | No | diff --git a/lean/COVERAGE_MAPPING.md b/lean/COVERAGE_MAPPING.md new file mode 100644 index 000000000000..8177dd77f99e --- /dev/null +++ b/lean/COVERAGE_MAPPING.md @@ -0,0 +1,168 @@ +# Lean Specification to Implementation Coverage Mapping + +This document defines the mapping between CCF's four formal specifications under `lean/` and the C++ implementation source files that realize them, together with what each specification's `coverage_mask.json` includes and excludes. +[`scripts/lean_coverage_report.py`](../scripts/lean_coverage_report.py) parses this document together with each specification's anchor-validated `lean//coverage_mask.json` file to compute C++ code LoC, Lean specification LoC, and CI line/branch coverage over the modeled sections, alongside matching whole-file, removed-region, and trace-validated metrics from `llvm-cov` JSON exports. + +Two packages under `lean/` are support libraries rather than protocol specifications and have no C++ implementation mapping: + +- [`lean/common/`](common/README.md) (`ccf_common`): protocol-independent Lean transition-system, execution, finset, sequence, function, and parser infrastructure shared across specifications (only `CCF.TxID` mirrors the primitive type in `include/ccf/tx_id.h`). +- [`lean/mathlib-equivalence/`](mathlib-equivalence/README.md): proofs that the lightweight definitions in `lean/common/` are equivalent to their Mathlib counterparts. + +## Scope methodology and taxonomy + +The mapping partitions the modeled C++ surface strictly across the four specifications: every C++ line belongs to at most one specification (`scripts/lean_coverage_report.py` enforces cross-spec disjointness), so per-specification counts sum directly to the unique total without double-counting. + +### What is in scope + +A C++ file or function is mapped to a specification when it directly implements: + +1. **Modeled state and protocol types**: core state structures, enums, tables, and message payloads mirrored by `Model/` (including companion headers of exclude-masked component files so C++ type declarations are counted alongside Lean's `Types.lean`/`Messages.lean`). +2. **Modeled transitions, guards, and observables**: functions implementing `Model.step` state transitions, quorum/conflict/freshness/status checks, and client-visible responses or notifications. +3. **Admission and boundary guards enforcing model assumptions**: validation checks that uphold a model's input preconditions (such as quote/certificate pinning for `Validation.rejected`, `/timeout` primary-certificate authentication enforcing local `Input.timeout`, session-view checks, and `try`/`catch` error cleanup preventing false `TxID` emission). +4. **Defensive invariants and LLVM artifacts**: unreachable `std::logic_error` checks, documented semantic discrepancies (such as `Store::compact` backward compaction), and LLVM closing-brace coverage artifacts remain unmasked in scope. + +### What is out of scope + +The following kinds of C++ code are excluded uniformly across all four specifications: + +1. **Trace instrumentation, tests, and replay drivers**: `CCF_KV_TRACING` (`#ifdef` blocks and `src/kv/trace.{h,cpp}`), `RDP_TRACE` (`AdvanceTrace` and trace helpers), `cft_trace_msgpack.h`, `trace_retired_committed_tx`, `get_state_for_trace`, test harnesses, and Python trace runners. +2. **Network transport, persistence framing, and host task scheduling**: node-to-node channels, `Forwarder` transport, `libcurl` HTTP/TLS clients (`dispatch_authenticated_message`, `start_failover_timers`), ledger enclave framing, `JobBoard` periodic registration, KV local-write role-lock permit helpers, and backpressure/batch-size heuristics. +3. **Cryptography, attestation internals, sealing, and Merkle receipts**: quote verification internals (`quote.cpp`), SNP local sealing, KV encryption/claims, `TxHistory`, `/receipt`, and `/receipt/cose`. +4. **Explicitly unmodeled features**: snapshots and snapshot import, ledger deserialization, `ReservedTx`, `MaterialisedReadOnly` historical/replicated-state reads, signature-table access control, `TxFlag`, `TxDiff`/`MapDiff`, KV hooks, disaster-recovery-only consensus hooks (`remove_deleted_nodes`, 4-arg `force_become_primary`, `enable_all_domains`), HTTP 307 redirection, `/commit`, OpenAPI generation, URI path-template routing, client authentication policies, and request metrics. +5. **Cross-cutting containers, callers, wrappers, and generic libraries**: node lifecycle (`node_state.h`, `node_frontend.h`), shared interface/primitive headers (`kv_types.h`, `tx_id.h`, `consensus_types.h`, `src/node/configuration.h`), typed C++ serializer wrappers, QuickJS bindings, governance wrappers, `champ_map.h`, and `dl_list.h`. + +### Masking discipline and format + +- Predominantly modeled component files (`consensus`, `disaster-recovery`, `kv`) use **`exclude`** masks so newly added code is counted by default and every exclusion carries a justification. +- Sparse multi-purpose RPC/endpoint files (`consistency`) use whole-function **`include`** masks rather than excluding hundreds of unrelated lines. +- Each `lean//coverage_mask.json` file specifies `spec`, a top-level `description`, and a `files` map of repo-relative paths to `include` or `exclude` range lists. + Every range entry requires 1-based inclusive `start` and `end` line numbers, an identifier-bearing `start_anchor`, a matching `end_anchor`, and a `reason`. +- Every mask range is validated by [`scripts/lean_coverage_report.py`](../scripts/lean_coverage_report.py) for non-empty identifier-bearing start anchors, matching end anchors, lexical `{`/`}` brace balance, non-overlap, and cross-spec disjointness. +- Bare `catch` blocks, authentication/validation guards, and defensive error arms of modeled functions are never masked out. + +### Methodological caveats + +- **Total CI test coverage vs trace-validated coverage**: Total columns measure how thoroughly CCF's full CI test suite (`coverage.yml`, artifact `coverage-export-json`) exercises the mapped C++ regions, whereas Trace-validated columns (artifact `coverage-trace-validated-json`) measure only the subset of CI tests whose execution traces are checked against each specification's Lean model. +- **No C++ refinement proof**: code LoC, CI coverage, trace replay, and Lean proofs over abstract models provide complementary assurance rather than a machine-checked C++ refinement proof. +- **Service-level vs component-level mapping**: `lean/consistency` specifies an external client-visible contract whose guarantees depend on consensus and KV code accounted under `lean/consensus` and `lean/kv` to keep rows disjoint; its current replayer validates writes and status reports, not client reads. +- **Uniform `llvm-cov export` branch deduplication**: kept, whole-file unmasked, and removed-region metrics are all computed from the same `llvm-cov` JSON export, which deduplicates branches per source coordinate across C++ template instantiations (taking the maximum hit count per outcome). +- **Declaration-only headers**: companion headers with zero instrumented lines contribute to Code LoC (balancing Lean type/message declarations) and contribute `0/0` to line/branch denominators. + +## Validating masks and computing reports + +CI validates all four masks on every pull request through [`scripts/lean-coverage-masks-checks.sh`](../scripts/lean-coverage-masks-checks.sh) (invoked by [`scripts/ci-checks.sh`](../scripts/ci-checks.sh)). +When modifying any mapped C++ file, run the validator locally and update shifted line numbers, anchors, or exclusions in the affected `lean//coverage_mask.json`: + +```bash +./scripts/lean_coverage_report.py --check-masks +``` + +To compute live Total and Trace-validated coverage tables against the latest `main` Coverage workflow run (or a specific `--run-id`, or local `--export-json` / `--trace-validated-dir` exports): + +```bash +./scripts/lean_coverage_report.py --show-removed +./scripts/lean_coverage_report.py --no-masks +./scripts/lean_coverage_report.py --per-file +``` + +## Consensus (`lean/consensus`) + +Specification: [`lean/consensus/README.md`](consensus/README.md). +Line-range mask: [`lean/consensus/coverage_mask.json`](consensus/coverage_mask.json). +Models the CCF CFT/AFT consensus protocol, including elections, pre-vote, log replication, signature-gated commitment, reconfiguration quorums, retirement phases, successor nomination, CheckQuorum step-down, rollback, and backup initialization from a committed prefix. + +### In-scope implementation files + +- [`src/consensus/aft/cft.h`](../src/consensus/aft/cft.h) (masked in [`lean/consensus/coverage_mask.json`](consensus/coverage_mask.json)): main `aft::Aft` consensus state machine implementing elections, pre-vote, `AppendEntries` replication and conflict resolution, quorum checks across active configurations, commit advancement (`update_commit`), reconfiguration (`add_configuration`), retirement (`set_retired_committed`, successor nomination), `periodic` (CheckQuorum majority step-down and election/heartbeat dispatch), `recv_message` (including error arms), leadership transitions and rollback (`set_leadership_state`, `update_local_writes`, `rollback`), bootstrap (`force_become_primary()`), and `init_as_backup`. +- [`src/consensus/aft/impl/state.h`](../src/consensus/aft/impl/state.h) (masked in [`lean/consensus/coverage_mask.json`](consensus/coverage_mask.json)): `aft::State`, `aft::ViewHistory`, and `aft::AtomicLeadershipState` storing term/view, log and commit indices, committable indices, leadership/membership state, and retirement indices. +- [`src/consensus/aft/cft_types.h`](../src/consensus/aft/cft_types.h) (masked in [`lean/consensus/coverage_mask.json`](consensus/coverage_mask.json)): consensus wire message types (`AppendEntries`, `AppendEntriesResponse`, `RequestVote`, `RequestVoteResponse`, `RequestPreVote`, `RequestPreVoteResponse`, `ProposeRequestVote`, `CftMsgType`) and `starting_view_change`. +- [`src/node/hooks.h`](../src/node/hooks.h) (masked in [`lean/consensus/coverage_mask.json`](consensus/coverage_mask.json)): `ConfigurationChangeHook`, which translates `public:ccf.gov.nodes.info` writes (`PENDING`, `TRUSTED`, `RETIRED`, deletions) into consensus configuration deltas passed to `add_configuration` during replication and follower apply (implementing `TransactionMetadata.configuration` in `Consensus/Model/NodeState.lean`). + +### Out-of-scope subsystems and abstractions + +- **Masked out of the in-scope consensus files**: + - `JobBoard` periodic task registration (`register_periodic_tasks`), ledger-backlog and uncommitted-transaction backpressure (`should_apply_backpressure`, `ledger->is_backlogged()` drop in `recv_message`), byte-size batching heuristics (`update_batch_size`), periodic signature scheduling (`get_signature_disposition`, `can_sign_unsafe`), and KV local-write role-lock permit accessors (`acquire_local_write_permit`, `local_writes_enabled`). + - Disaster-recovery-only paths outside `lean/consensus`: `remove_deleted_nodes` (node deletion without retirement and identity reuse), four-argument `force_become_primary`, and `enable_all_domains`. + - External RPC/snapshot view-history queries unused by consensus transitions (`get_view_history`, `get_view_history_since`, `ViewHistory::get_history_until`, `ViewHistory::get_history_since`), read-only status diagnostics (`get_details`), `CommitObserver` callbacks, and trace-capture helpers (`trace_retired_committed_tx`, `get_state_for_trace`, and `ConfigurationChangeHook`'s `trace_retired_committed_tx` call in `src/node/hooks.h`). + - The KV `aft::Store`/`aft::Adaptor` bridge (abstracted by `NodeState.log`) and `std::formatter` logging formatter in `cft_types.h`. +- **Excluded external files**: + - Node lifecycle and retirement-transaction drivers (`src/node/node_state.h`, `src/node/retired_nodes_cleanup.h`, `src/node/rpc/node_frontend.h`): the join protocol, snapshot transport/deserialization, crash recovery, and background retirement-confirmation scheduling are outside `lean/consensus`. + - Transport, ledger framing, and observers (`src/consensus/consensus_types.h`, `src/consensus/aft/consensus_channels.h`, `src/consensus/aft/commit_observer.h`, `src/consensus/ledger_enclave.h`, `src/consensus/ledger_enclave_types.h`, `src/node/node_to_node.h`, `src/node/node_to_node_channel_manager.h`, `src/node/channels.h`, `src/node/node_transport.h`): message delivery, loss, and ledger persistence are abstracted by `CCF.MultiNodeTransitionSystem` and `NodeState.log`. + - Trace instrumentation and shared vocabulary headers (`src/consensus/aft/cft_trace_msgpack.h`, `src/kv/kv_types.h`, `include/ccf/tx_id.h`). + +## Consistency (`lean/consistency`) + +Specification: [`lean/consistency/README.md`](consistency/README.md). +Line-range mask: [`lean/consistency/coverage_mask.json`](consistency/coverage_mask.json). +Models CCF's externally visible consistency contract (serializability and real-time ordering of committed writes, forwarded reads, elections, and `Committed`/`Invalid` status reporting) for an abstract append-and-read application. + +### In-scope implementation files + +- [`include/ccf/tx_status.h`](../include/ccf/tx_status.h): defines `ccf::TxStatus`, `ccf::FinalTxStatus`, `tx_status_to_str`, and `ccf::evaluate_tx_status(...)`, which computes `Unknown`, `Pending`, `Committed`, and `Invalid` from `(target_view, target_seqno)`, local view history, and `(committed_view, committed_seqno)`. +- [`src/endpoints/base_endpoint_registry.cpp`](../src/endpoints/base_endpoint_registry.cpp) (`include`-masked in [`lean/consistency/coverage_mask.json`](consistency/coverage_mask.json)): `get_status_for_txid_v1`, delegating status evaluation to consensus. +- [`src/endpoints/common_endpoint_registry.cpp`](../src/endpoints/common_endpoint_registry.cpp) (`include`-masked in [`lean/consistency/coverage_mask.json`](consistency/coverage_mask.json)): `GetTxStatus` and the `/tx` client endpoint handler that returns transaction status observations. +- [`src/endpoints/endpoint_registry.cpp`](../src/endpoints/endpoint_registry.cpp) (`include`-masked in [`lean/consistency/coverage_mask.json`](consistency/coverage_mask.json)): `default_locally_committed_func` (populating `x-ms-ccf-transaction-id` on initial client responses), default forwarding policies in `make_endpoint`/`make_read_only_endpoint`/`make_command_endpoint`, `execute_*_endpoint`, and `set_consensus`. +- [`src/node/rpc/frontend.h`](../src/node/rpc/frontend.h) (`include`-masked in [`lean/consistency/coverage_mask.json`](consistency/coverage_mask.json)): `RpcFrontend` request execution (`process`, `process_forwarded`, `process_command_inner` including exception cleanup), session-consistency view checks (`check_session_consistency`), backup forwarding (`redirect_or_forward`, `forward`), and transaction commit/retry (`commit_transaction`). + +### Out-of-scope subsystems and abstractions + +- **Excluded from the `include`-masked RPC/endpoint files**: + - Unmodeled client/registry endpoints and APIs: `/commit`, `get_last_committed_txid_v1`, `get_view_history_v1`/`v2`, `get_view_for_seqno_v1` (absent from `consistency/Model`, which models per-write final status observations rather than commit-frontier or view-history queries), OpenAPI generation (`/api`, `build_api`, `generate_openapi_document_v1`), historical Merkle/COSE receipts (`/receipt`, `/receipt/cose`), and node/user/member lookups. + - HTTP routing, access control, redirection, and operational plumbing: URI path-template regex parsing and lookup, HTTP 404/405/`OPTIONS` formatting, operator-feature/unsecured-interface allowlists, HTTP 307 redirection helpers (`resolve_redirect_location`, `check_redirect`, `get_redirections_config`), client authentication policies, forwarding timeout config, latency metrics, pre-KV command handling, uncommitted-tx backpressure, proposal Merkle-root injection, and periodic ticks. +- **Excluded external files**: + - Sparse registry declaration headers (`include/ccf/base_endpoint_registry.h`, `include/ccf/common_endpoint_registry.h`, `include/ccf/endpoint_registry.h`): omitted because their `.cpp` counterparts use targeted `include` masks and the remaining header lines are predominantly unrelated declarations and prototypes. + - Underlying consensus and KV engines (`src/consensus/aft/*`, `src/kv/*`): accounted under `lean/consensus` and `lean/kv` to keep specifications strictly disjoint (note that the `/tx` call chain crosses one unmapped 9-line pass-through in `src/kv/kv_types.h`, `Consensus::evaluate_tx_status`, into `ccf::evaluate_tx_status`). + - Forwarding transport, deferred commit callbacks, and thin API surfaces (`src/node/rpc/forwarder.h`, `src/node/rpc/forwarder_types.h`, `src/node/commit_callback_subsystem.h`, `src/node/commit_callback_interface.h`, `src/node/gov/handlers/transactions.h`, `src/js/extensions/ccf/consensus.cpp`, `src/node/rpc/user_frontend.h`, `src/node/rpc/member_frontend.h`, `src/endpoints/endpoint.cpp`, `src/consensus/aft/cft_trace_msgpack.h`, `include/ccf/tx_id.h`): forwarding network transport, hold-until-commit deferred responses, non-forwarded backup reads, HTTP redirection overrides, governance/JS wrappers, and trace definitions are outside `lean/consistency`. + +## Disaster Recovery (`lean/disaster-recovery`) + +Specification: [`lean/disaster-recovery/README.md`](disaster-recovery/README.md). +Line-range mask: [`lean/disaster-recovery/coverage_mask.json`](disaster-recovery/coverage_mask.json). +Models CCF's self-healing open recovery decision protocol: per-node phases (`Gossiping`, `Voting`, `Opening`, `Joining`, `Open`), independent timeout lane, deterministic gossip selection by `(view, seqno, location)`, quorum vs failover opening, retries, validation rejection, and restart notifications. + +### In-scope implementation files + +- [`src/node/recovery_decision_protocol.cpp`](../src/node/recovery_decision_protocol.cpp) (masked in [`lean/disaster-recovery/coverage_mask.json`](disaster-recovery/coverage_mask.json)): `RecoveryDecisionProtocolSubsystem` implementing `reset_state`, `try_start` (including post-commit `GOSSIPING` timer start and `JOINING` restart notification), `advance`, gossip/vote/IAmOpen/timeout transitions, deterministic maximum selection, retry-phase dispatch (`start_message_retry_timers`, `stop_timers`), message builders (`get_node_info`, `get_iamopen_request`), and message fanout (`send_gossip_unsafe`, `send_vote_unsafe`, `send_iamopen_unsafe`). +- [`src/node/recovery_decision_protocol.h`](../src/node/recovery_decision_protocol.h) (masked in [`lean/disaster-recovery/coverage_mask.json`](disaster-recovery/coverage_mask.json)): `RecoveryDecisionProtocolSubsystem` declaration and protocol request payloads (`TaggedWithNodeInfo`, `GossipRequest`, `IAmOpenRequest`). +- [`src/node/rpc/self_healing_open_handlers.h`](../src/node/rpc/self_healing_open_handlers.h) (masked in [`lean/disaster-recovery/coverage_mask.json`](disaster-recovery/coverage_mask.json)): inbound endpoints `/recovery_decision_protocol/{gossip,vote,iamopen,timeout}`, including subsystem/configuration admission guards, quote verification and certificate-pinning rejection (`Validation.rejected`), `/timeout` primary-certificate authentication (enforcing the local `Input.timeout` assumption), gossip freeze and deduplication, vote insertion, `IAmOpen` handling (including `OPEN`/`JOINING` guards), and `advance()`. +- [`include/ccf/service/tables/self_healing_open.h`](../include/ccf/service/tables/self_healing_open.h): protocol enums (`StateMachine`, `OpenKinds`), `Location`, `RequestNodeInfo`, `NodeInfo`, `service_fingerprint_from_pem`, and the `RECOVERY_DECISION_PROTOCOL_*` KV tables. + +### Out-of-scope subsystems and abstractions + +- **Masked out of the in-scope disaster-recovery files**: + - `RDP_TRACE` instrumentation (`tracing_enabled`, `trace_safely`, `emit_trace`, `record_trace_send`, `prepare_trace_step`, `trace_committed_step`, `AdvanceTrace`, `trace_on_commit`, and inline `trace_safely` blocks). + - Wall-clock failover timer scheduling with cURL self-HTTP dispatch (`start_failover_timers`) and cURL HTTP/TLS message transport (`dispatch_authenticated_message`): timeouts and network delivery are abstracted as `Input.timeout` and `CCF.MultiNodeTransitionSystem` envelopes in `DisasterRecovery/Model.lean`. +- **Excluded external files**: + - TEE attestation cryptography and SNP local sealing (`src/node/quote.cpp`, `include/ccf/node/quote.h`, `src/node/rpc/node_frontend_utils.h`, `src/node/local_sealing.h`, `src/node/local_sealing.cpp`, `src/service/tables/local_sealing.h`, `include/ccf/service/local_sealing.h`): `Local.lean` abstracts quote cryptography as `Validation.accepted | .rejected` and does not model key sealing. + - Downstream service opening, process restart, and host lifecycle wiring (`src/node/node_state.h`, `src/node/rpc/node_frontend.h`, `src/node/rpc/node_interface.h`, `src/node/rpc/node_operation.h`, `src/node/rpc/node_operation_interface.h`, `src/node/open_service.h`, `src/node/recovered_service_opening_task.h`, `src/node/runtime_control.h`, `src/node/configuration.h`): `Local.step` stops at emitting `Notification.opening` and `Notification.restart`. + - HTTP/TLS client transport and shared primitive types (`src/http_client/curl.h`, `include/ccf/tx_id.h`). + +## Key-Value Store (`lean/kv`) + +Specification: [`lean/kv/README.md`](kv/README.md) and [`doc/build_apps/kv/semantics.rst`](../doc/build_apps/kv/semantics.rst). +Line-range mask: [`lean/kv/coverage_mask.json`](kv/coverage_mask.json). +Models the observable single-node semantics of CCF's transactional KV store: lazy current-snapshot metadata capture, lazy per-map local and globally committed view capture, point and map-wide reads/writes/iteration, optimistic concurrency control, atomic multi-map local application, compaction, and rollback. + +### In-scope implementation files + +- [`src/kv/store.h`](../src/kv/store.h) (masked in [`lean/kv/coverage_mask.json`](kv/coverage_mask.json)): `ccf::kv::Store` and `StoreState` lifecycle, `current_txid_and_commit_term`, `next_version` (including stale-term and non-writable rejection), `get_map`/`add_dynamic_map`, `commit` replication result handling, `compact`, and `rollback`. +- [`src/kv/untyped_map.h`](../src/kv/untyped_map.h) (masked in [`lean/kv/coverage_mask.json`](kv/coverage_mask.json)): `ccf::kv::untyped::Map`, `Roll`, `LocalCommit`, `HandleCommitter` (`prepare` OCC conflict checks on per-key reads, whole-map `read_version`, and `rollback_counter`; `commit` frame publication), `create_change_set` (per-map local and globally committed view capture and compacted-version checks), and map-level `compact` and `rollback`. +- [`src/kv/untyped_change_set.h`](../src/kv/untyped_change_set.h) (masked in [`lean/kv/coverage_mask.json`](kv/coverage_mask.json)): `ccf::kv::untyped::ChangeSet` holding pinned `state`, pinned `committed` view, `start_version`, `rollback_counter`, `read_version`, `reads`, and `writes`. +- [`src/kv/untyped_map_handle.cpp`](../src/kv/untyped_map_handle.cpp) (masked in [`lean/kv/coverage_mask.json`](kv/coverage_mask.json)) and [`include/ccf/kv/untyped_map_handle.h`](../include/ccf/kv/untyped_map_handle.h): `ccf::kv::untyped::MapHandle` implementing `get`, `has`, `put`, `remove`, `clear`, `get_version_of_previous_write`, `get_globally_committed`, `has_globally_committed`, `foreach`, `size`, `range`, `read_key`, and `foreach_state_and_writes`. +- [`src/kv/apply_changes.h`](../src/kv/apply_changes.h) (masked in [`lean/kv/coverage_mask.json`](kv/coverage_mask.json)): `apply_changes(...)` implementing ordered map locking, atomic multi-map `prepare()`, dynamic new-map conflict checks, version resolution, and atomic `commit()`. +- [`src/kv/tx.cpp`](../src/kv/tx.cpp) (masked in [`lean/kv/coverage_mask.json`](kv/coverage_mask.json)), [`src/kv/tx_pimpl.h`](../src/kv/tx_pimpl.h) (masked in [`lean/kv/coverage_mask.json`](kv/coverage_mask.json)), and [`include/ccf/kv/tx.h`](../include/ccf/kv/tx.h) (masked in [`lean/kv/coverage_mask.json`](kv/coverage_mask.json)): `BaseTx`, `ReadOnlyTx`, and `Tx` implementing lazy initial snapshot capture (`read_txid`, `commit_view`), lazy per-map `ChangeSet` acquisition and dynamic map creation, handle reuse over a shared `ChangeSet`, and `CompactedVersionConflict` reporting. +- [`src/kv/committable_tx.h`](../src/kv/committable_tx.h) (masked in [`lean/kv/coverage_mask.json`](kv/coverage_mask.json)): `CommittableTx::commit(...)` handling read-only commits, invoking `apply_changes`, returning `FAIL_CONFLICT` or stale-term `FAIL_NO_REPLICATE`, and submitting applied writes to `Store::commit`. +- [`src/kv/compacted_version_conflict.h`](../src/kv/compacted_version_conflict.h): `CompactedVersionConflict` exception corresponding to `map_unavailable`. +- [`src/kv/version_v.h`](../src/kv/version_v.h) and [`include/ccf/kv/version.h`](../include/ccf/kv/version.h): `Version`, `NoVersion`, and `VersionV` pairing stored values with their write version. + +### Out-of-scope subsystems and abstractions + +- **Masked out of the in-scope KV files** (documented in [`doc/build_apps/kv/semantics.rst`](../doc/build_apps/kv/semantics.rst) and flagged with `trace::unsupported(...)` in `src/kv/`): + - Snapshot creation, serialization, and import (`Snapshot`, `SnapshotChangeSet`, `SnapshotHandleCommitter`, `deserialise_snapshot*`, `SnapshotPublicMaps`), ledger deserialization (`fill_maps`, `deserialize`, `commit_deserialised`), and wire serialization helpers. + - `ReservedTx` (including the `Reserved` guard in `CommittableTx::commit`), `MaterialisedReadOnly` historical/replicated-state reads (`materialised_read_state`, `create_read_only_tx_at_replicated_state`, `is_historical` branches, `MaterialisedReadOnlyTag`, rollback-invalidation guard), signature-table and role access control (`BaseTx::check_map_access`, `AccessMode`, `PrivateImpl::Role`), `set_read_txid`, `TxFlag`/`StoreFlag` (ledger chunking and snapshot flags), `WriteSetObserver`, `swap_private_maps`, `StoreState::clear`, `Map::clear` outside a transaction, and `TxDiff`/`MapDiff` (`track_deletes_on_missing_keys`). + - Consensus role-lock permit helpers (`acquire_local_write_permit`, `local_writes_enabled`), map and global hooks (`set_map_hook`, `set_global_hook`, `post_commit`, `post_compact`, `ConsensusHook` collection), `StoreReadiness`, `TxHistory`/`ILedgerChunker`/`Encryptor` plumbing, and compiled-out `#ifdef CCF_KV_TRACING` instrumentation blocks. + - Note: backward compaction in `Store::compact` (which lowers the cutoff if given a smaller version, whereas `lean/kv` treats it as a no-op and rejects backward traces) remains unmasked as a documented domain restriction. +- **Excluded external files**: + - Serialization, encryption, claims, snapshots, chunking, diffs, hooks, access-control types, and shared interfaces: `src/kv/kv_types.h`, `src/kv/kv_serialiser.h`, `src/kv/raw_serialise.h`, `src/kv/deserialise.h`, `src/kv/generic_serialise_wrapper.h`, `src/kv/serialised_entry_format.h`, `include/ccf/kv/serialisers/{blit_serialiser,json_serialiser,serialised_entry}.h`, `src/kv/encryptor.h`, `src/kv/null_encryptor.h`, `src/kv/claims.h`, `src/kv/snapshot.h`, `src/kv/ledger_chunker.h`, `src/kv/ledger_chunker_interface.h`, `src/kv/untyped_map_diff.cpp`, `include/ccf/kv/{untyped_map_diff,map_diff,hooks}.h`, `src/kv/internal_table_names.h`, and `src/kv/map_access_denied.h`. + - Typed C++ serializer handles and wrappers (`include/ccf/kv/{map,set,value,unit_value}_handle.h`, `include/ccf/kv/{map,set,value,unit_value,unit,untyped,abstract_handle,get_name,read_only_store}.h`) and JavaScript bindings (`src/js/extensions/ccf/kv.cpp`, `include/ccf/js/extensions/ccf/kv.h`): `lean/kv` models untyped byte-key/value maps without type serializers or JS bindings. + - Generic persistent data structures (`src/ds/champ_map.h`, `src/ds/dl_list.h`), caller retry loops (`src/node/retry_on_compacted_version_conflict.h`, `src/node/rpc/frontend.h`), and opt-in trace emitters (`src/kv/trace.h`, `src/kv/trace.cpp`). diff --git a/lean/consensus/coverage_mask.json b/lean/consensus/coverage_mask.json new file mode 100644 index 000000000000..003ccf3c9dce --- /dev/null +++ b/lean/consensus/coverage_mask.json @@ -0,0 +1,155 @@ +{ + "spec": "consensus", + "description": "Line-range masks selecting the C++ implementation sections modeled by lean/consensus. Mapped files default to fully included; listed ranges exclude mechanisms explicitly outside lean/consensus (periodic task registration, uncommitted-transaction and ledger-backlog backpressure, batch-size byte heuristics, periodic signature disposition, KV local-write role-lock permit accessors, recovery-only force_become_primary/remove_deleted_nodes/enable_all_domains, external RPC/snapshot view-history queries, diagnostic status queries, commit_observer callbacks, trace-capture helpers, the KV Store/Adaptor bridge, and std::formatter logging boilerplate). Aft::periodic (CheckQuorum and election dispatch), recv_message error arms, and ConfigurationChangeHook remain included.", + "files": { + "src/consensus/aft/cft.h": { + "exclude": [ + { + "start": 245, + "end": 253, + "start_anchor": "void register_periodic_tasks(", + "end_anchor": "}", + "reason": "JobBoard periodic task registration is unmodeled (lean/consensus models no wall clock)" + }, + { + "start": 291, + "end": 303, + "start_anchor": "bool should_apply_backpressure() override", + "end_anchor": "}", + "reason": "Ledger-backlog and uncommitted-transaction backpressure are unmodeled" + }, + { + "start": 305, + "end": 317, + "start_anchor": "Consensus::SignatureDisposition get_signature_disposition() override", + "end_anchor": "}", + "reason": "Periodic signature scheduling (should_sign / SignatureDisposition) is unmodeled" + }, + { + "start": 341, + "end": 349, + "start_anchor": "void trace_retired_committed_tx(", + "end_anchor": "}", + "reason": "Trace-capture-only helper emitting ccf.cft retired_committed_tx events is unmodeled" + }, + { + "start": 351, + "end": 365, + "start_anchor": "ccf::kv::LocalWritePermit acquire_local_write_permit() override", + "end_anchor": "}", + "reason": "KV local-write role-lock permit accessors (acquire_local_write_permit, local_writes_enabled) are unmodeled concurrency plumbing" + }, + { + "start": 402, + "end": 436, + "start_anchor": "void remove_deleted_nodes(", + "end_anchor": "}", + "reason": "Disaster-recovery node deletion without retirement and node-identity reuse are out of scope of lean/consensus" + }, + { + "start": 472, + "end": 478, + "start_anchor": "void enable_all_domains() override", + "end_anchor": "}", + "reason": "Recovery-only public/private security-domain deserialisation toggle is unmodeled" + }, + { + "start": 495, + "end": 517, + "start_anchor": "void force_become_primary(", + "end_anchor": "}", + "reason": "Disaster-recovery four-argument force_become_primary overload is unmodeled (bootstrap zero-argument overload remains included)" + }, + { + "start": 571, + "end": 581, + "start_anchor": "std::vector get_view_history(Index idx) override", + "end_anchor": "}", + "reason": "External RPC/snapshot view-history query accessors are unused by consensus transitions" + }, + { + "start": 676, + "end": 700, + "start_anchor": "ccf::kv::ConsensusDetails get_details() override", + "end_anchor": "}", + "reason": "Read-only diagnostic/telemetry status snapshot is unmodeled" + }, + { + "start": 830, + "end": 841, + "start_anchor": "if (ledger->is_backlogged())", + "end_anchor": "}", + "reason": "Ledger I/O backlog message dropping is unmodeled (message loss is modeled non-deterministically by the network queue)" + }, + { + "start": 1038, + "end": 1052, + "start_anchor": "void update_batch_size()", + "end_anchor": "}", + "reason": "Byte-size moving-window AppendEntries batching heuristic is unmodeled" + }, + { + "start": 1071, + "end": 1076, + "start_anchor": "bool can_sign_unsafe()", + "end_anchor": "}", + "reason": "Helper used only by unmodeled get_signature_disposition" + }, + { + "start": 2715, + "end": 2719, + "start_anchor": "if (commit_observer != nullptr)", + "end_anchor": "}", + "reason": "External CommitObserver callback notification is unmodeled" + }, + { + "start": 2889, + "end": 2892, + "start_anchor": "const State& get_state_for_trace() const", + "end_anchor": "}", + "reason": "Trace-capture state accessor is unmodeled" + } + ] + }, + "src/consensus/aft/impl/state.h": { + "exclude": [ + { + "start": 110, + "end": 125, + "start_anchor": "[[nodiscard]] std::vector get_history_until(", + "end_anchor": "}", + "reason": "External RPC/snapshot view-history slice queries (get_history_until, get_history_since) are unused by consensus transitions" + } + ] + }, + "src/consensus/aft/cft_types.h": { + "exclude": [ + { + "start": 24, + "end": 86, + "start_anchor": "class Store", + "end_anchor": "};", + "reason": "KV Store interface and weak-pointer Adaptor bridge are abstracted away by NodeState.log in lean/consensus" + }, + { + "start": 267, + "end": 321, + "start_anchor": "template <>\nstruct std::formatter", + "end_anchor": "};", + "reason": "std::formatter logging formatter is unmodeled" + } + ] + }, + "src/node/hooks.h": { + "exclude": [ + { + "start": 99, + "end": 102, + "start_anchor": "if (!retired_committed.empty())", + "end_anchor": "}", + "reason": "Trace-capture-only retired_committed_tx emission is unmodeled" + } + ] + } + } +} diff --git a/lean/consistency/coverage_mask.json b/lean/consistency/coverage_mask.json new file mode 100644 index 000000000000..d76671cd277a --- /dev/null +++ b/lean/consistency/coverage_mask.json @@ -0,0 +1,120 @@ +{ + "spec": "consistency", + "description": "Positive whole-function include masks selecting the C++ implementation sections modeled by lean/consistency inside multi-purpose RPC and endpoint files (include/ccf/tx_status.h is included whole without a mask). Selects transaction status evaluation (/tx and get_status_for_txid_v1), initial x-ms-ccf-transaction-id header emission and default forwarding policies (endpoint_registry.cpp), and the RpcFrontend execution, forwarding, session-consistency, and commit/retry loop (frontend.h, including exception handlers).", + "files": { + "src/endpoints/base_endpoint_registry.cpp": { + "include": [ + { + "start": 67, + "end": 89, + "start_anchor": "ApiResult BaseEndpointRegistry::get_status_for_txid_v1(", + "end_anchor": "}", + "reason": "Delegates transaction status evaluation to consensus (implements Event.status reporting)" + } + ] + }, + "src/endpoints/common_endpoint_registry.cpp": { + "include": [ + { + "start": 36, + "end": 43, + "start_anchor": "struct GetTxStatus", + "end_anchor": "};", + "reason": "Response payload type for /tx status observations" + }, + { + "start": 54, + "end": 57, + "start_anchor": "DECLARE_JSON_TYPE(GetTxStatus::Out);", + "end_anchor": "static constexpr auto tx_id_param_key = \"transaction_id\";", + "reason": "JSON serialisation and query-parameter key for /tx status observations" + }, + { + "start": 234, + "end": 284, + "start_anchor": "auto get_tx_status = [this](auto& ctx, nlohmann::json&&) {", + "end_anchor": ".install();", + "reason": "/tx client endpoint handler and registration reporting Committed/Invalid/Pending/Unknown status" + } + ] + }, + "src/endpoints/endpoint_registry.cpp": { + "include": [ + { + "start": 204, + "end": 274, + "start_anchor": "void default_locally_committed_func(", + "end_anchor": "}", + "reason": "Populates x-ms-ccf-transaction-id on initial responses and sets default ForwardingRequired policies for write, read-only, and command endpoints" + }, + { + "start": 491, + "end": 531, + "start_anchor": "void EndpointRegistry::execute_command_endpoint(", + "end_anchor": "}", + "reason": "Executes endpoint handlers and locally committed TxID response callbacks" + }, + { + "start": 594, + "end": 597, + "start_anchor": "void EndpointRegistry::set_consensus(ccf::kv::Consensus* c)", + "end_anchor": "}", + "reason": "Binds consensus instance used by status evaluation" + } + ] + }, + "src/node/rpc/frontend.h": { + "include": [ + { + "start": 441, + "end": 476, + "start_anchor": "bool check_session_consistency(", + "end_anchor": "}", + "reason": "Pins session active view and aborts requests on view change to preserve session consistency" + }, + { + "start": 553, + "end": 621, + "start_anchor": "void forward(", + "end_anchor": "}", + "reason": "Forwards backup requests to the primary, prevents daisy-chain forwarding, and marks sessions as forwarding" + }, + { + "start": 759, + "end": 820, + "start_anchor": "bool redirect_or_forward(", + "end_anchor": "}", + "reason": "Dispatches backup forwarding according to endpoint ForwardingRequired policy and session forwarding state" + }, + { + "start": 822, + "end": 942, + "start_anchor": "enum class CommitAction : uint8_t", + "end_anchor": "}", + "reason": "Commits transactions, invokes locally_committed_func to emit TxIDs, and handles conflict retry and replication failure" + }, + { + "start": 944, + "end": 1161, + "start_anchor": "void process_command_inner(", + "end_anchor": "}", + "reason": "Main RPC execution, forwarding, session-consistency check, commit/retry loop, and error cleanup preventing false TxIDs" + }, + { + "start": 1233, + "end": 1238, + "start_anchor": "void process(std::shared_ptr ctx) override", + "end_anchor": "}", + "reason": "Client request entrypoint" + }, + { + "start": 1244, + "end": 1259, + "start_anchor": "void process_forwarded(std::shared_ptr ctx) override", + "end_anchor": "}", + "reason": "Forwarded request entrypoint enforcing single-hop forwarding invariants" + } + ] + } + } +} diff --git a/lean/disaster-recovery/coverage_mask.json b/lean/disaster-recovery/coverage_mask.json new file mode 100644 index 000000000000..58540dd76d30 --- /dev/null +++ b/lean/disaster-recovery/coverage_mask.json @@ -0,0 +1,123 @@ +{ + "spec": "disaster-recovery", + "description": "Line-range masks selecting the C++ implementation sections modeled by lean/disaster-recovery. Mapped files default to fully included (include/ccf/service/tables/self_healing_open.h is included whole without a mask); listed ranges exclude only RDP_TRACE instrumentation (and AdvanceTrace), wall-clock failover timer scheduling with cURL self-HTTP dispatch (start_failover_timers), and cURL HTTP/TLS message transport (dispatch_authenticated_message). All endpoint admission guards, quote/certificate pinning checks, /timeout primary-certificate authentication, retry phase dispatch, and message builders remain included.", + "files": { + "src/node/recovery_decision_protocol.cpp": { + "exclude": [ + { + "start": 28, + "end": 81, + "start_anchor": "namespace\n{\nconstexpr auto recovery_trace_marker", + "end_anchor": "}", + "reason": "RDP_TRACE environment check, thread-local batch/version state, and trace_safely helper are unmodeled trace instrumentation" + }, + { + "start": 88, + "end": 153, + "start_anchor": "void RecoveryDecisionProtocolSubsystem::emit_trace(nlohmann::json&& record)", + "end_anchor": "}", + "reason": "emit_trace, record_trace_send, prepare_trace_step, and trace_committed_step are unmodeled RDP_TRACE instrumentation" + }, + { + "start": 225, + "end": 235, + "start_anchor": "trace_safely([&]() {", + "end_anchor": "});", + "reason": "RDP_TRACE start-event emission inside try_start global hook is unmodeled trace instrumentation" + }, + { + "start": 514, + "end": 518, + "start_anchor": "trace_safely([&]() {", + "end_anchor": "});", + "reason": "RDP_TRACE retry batch/pre_version recording inside start_message_retry_timers is unmodeled trace instrumentation" + }, + { + "start": 600, + "end": 684, + "start_anchor": "void RecoveryDecisionProtocolSubsystem::start_failover_timers()", + "end_anchor": "}", + "reason": "Wall-clock periodic failover timer scheduling and cURL self-HTTP timeout delivery are abstracted as Input.timeout in DisasterRecovery/Model.lean" + }, + { + "start": 700, + "end": 767, + "start_anchor": "void RecoveryDecisionProtocolSubsystem::dispatch_authenticated_message(", + "end_anchor": "}", + "reason": "cURL HTTP/TLS client transport and record_trace_send are abstracted away by CCF.MultiNodeTransitionSystem" + } + ] + }, + "src/node/recovery_decision_protocol.h": { + "exclude": [ + { + "start": 46, + "end": 61, + "start_anchor": "// What one execution of advance() read, wrote and requested. Trace only.", + "end_anchor": "DECLARE_JSON_OPTIONAL_FIELDS(AdvanceTrace, chosen, open_kind, restart);", + "reason": "AdvanceTrace struct and JSON serialisation are trace-only instrumentation" + }, + { + "start": 83, + "end": 84, + "start_anchor": "std::atomic next_trace_sequence = 0;", + "end_anchor": "std::atomic next_trace_batch = 0;", + "reason": "Trace sequence and retry batch counters are trace-only instrumentation" + }, + { + "start": 98, + "end": 108, + "start_anchor": "// A handler execution is recorded here, and logged by trace_committed_step", + "end_anchor": "const ccf::TxID& txid) noexcept;", + "reason": "Declarations of unmodeled RDP_TRACE step helpers" + }, + { + "start": 113, + "end": 113, + "start_anchor": "void start_failover_timers();", + "end_anchor": "void start_failover_timers();", + "reason": "Declaration of unmodeled wall-clock failover timer scheduler" + }, + { + "start": 126, + "end": 132, + "start_anchor": "// Records the send in the trace, then dispatches it", + "end_anchor": "const crypto::Pem& privkey_pem);", + "reason": "Declaration of unmodeled cURL HTTP/TLS message dispatcher" + }, + { + "start": 138, + "end": 142, + "start_anchor": "void record_trace_send(", + "end_anchor": "void emit_trace(nlohmann::json&& record);", + "reason": "Declarations of unmodeled RDP_TRACE helpers" + } + ] + }, + "src/node/rpc/self_healing_open_handlers.h": { + "exclude": [ + { + "start": 149, + "end": 157, + "start_anchor": "std::optional trace_txid = std::nullopt;", + "end_anchor": "*args.rpc_ctx, trace_kind, in.info.location.name, trace_txid, trace);", + "reason": "RDP_TRACE prepare_trace_step hook is unmodeled trace instrumentation" + }, + { + "start": 166, + "end": 178, + "start_anchor": "// Logs each successful execution once its transaction commits, with the", + "end_anchor": "};", + "reason": "RDP_TRACE commit callback (trace_on_commit) is unmodeled trace instrumentation" + }, + { + "start": 407, + "end": 408, + "start_anchor": "node_operation->recovery_decision_protocol().prepare_trace_step(", + "end_anchor": "*args.rpc_ctx, \"timeout\", {}, std::nullopt, trace);", + "reason": "RDP_TRACE prepare_trace_step hook on /timeout is unmodeled trace instrumentation" + } + ] + } + } +} diff --git a/lean/kv/coverage_mask.json b/lean/kv/coverage_mask.json new file mode 100644 index 000000000000..7ea0c622a2b8 --- /dev/null +++ b/lean/kv/coverage_mask.json @@ -0,0 +1,588 @@ +{ + "spec": "kv", + "description": "Line-range masks selecting the C++ implementation sections modeled by lean/kv. Mapped files default to fully included; listed ranges exclude mechanisms explicitly outside lean/kv (snapshots, ledger serialisation/deserialisation, ReservedTx, MaterialisedReadOnly historical/replicated-state reads, signature-table access control, LocalWritePermit consensus-role fencing helpers, TxFlag, hooks, encryption/history/chunker plumbing, TxDiff/MapDiff, WriteSetObserver, StoreState::clear, Map::clear, swap_private_maps, and opt-in #ifdef CCF_KV_TRACING instrumentation blocks).", + "files": { + "src/kv/store.h": { + "exclude": [ + { + "start": 26, + "end": 32, + "start_anchor": "enum class StoreReadiness", + "end_anchor": "};", + "reason": "Node readiness state machine is unmodeled" + }, + { + "start": 77, + "end": 95, + "start_anchor": "void clear()", + "end_anchor": "}", + "reason": "StoreState::clear is unmodeled (trace::unsupported: store clear)" + }, + { + "start": 126, + "end": 202, + "start_anchor": "// Holds the lock of every map", + "end_anchor": "}", + "reason": "ScopedMapLocks (snapshot-only) and commit_deserialised are unmodeled (trace::unsupported: commit deserialised)" + }, + { + "start": 242, + "end": 255, + "start_anchor": "void set_readiness(", + "end_anchor": "}", + "reason": "Store readiness accessors are unmodeled" + }, + { + "start": 267, + "end": 331, + "start_anchor": "std::shared_ptr get_history()", + "end_anchor": "}", + "reason": "History, ledger chunker, encryptor, max_transaction_size, and snapshotter configuration are unmodeled" + }, + { + "start": 409, + "end": 422, + "start_anchor": "{\n// If we have any hooks for the given map name, set them on this new map", + "end_anchor": "}", + "reason": "Map and global hook attachment on dynamic map creation is unmodeled" + }, + { + "start": 425, + "end": 820, + "start_anchor": "std::unique_ptr snapshot_unsafe_maps(", + "end_anchor": "}", + "reason": "Snapshot creation, serialisation, SnapshotPublicMaps, and snapshot import/deserialisation are unmodeled (trace::unsupported: snapshot import)" + }, + { + "start": 825, + "end": 827, + "start_anchor": "#ifdef CCF_KV_TRACING\ntrace::Environment trace_environment;", + "end_anchor": "#endif", + "reason": "Opt-in CCF_KV_TRACING instrumentation is unmodeled" + }, + { + "start": 832, + "end": 842, + "start_anchor": "if (snapshotter)", + "end_anchor": "}", + "reason": "Snapshotter and ledger chunker compaction callbacks are unmodeled" + }, + { + "start": 848, + "end": 861, + "start_anchor": "#ifdef CCF_KV_TRACING\nif (trace::enabled())", + "end_anchor": "#endif", + "reason": "Opt-in CCF_KV_TRACING instrumentation is unmodeled" + }, + { + "start": 888, + "end": 892, + "start_anchor": "auto h = get_history();", + "end_anchor": "}", + "reason": "TxHistory compaction notification is unmodeled" + }, + { + "start": 895, + "end": 899, + "start_anchor": "for (auto& it : maps)", + "end_anchor": "}", + "reason": "Global post_compact hooks are unmodeled" + }, + { + "start": 904, + "end": 906, + "start_anchor": "#ifdef CCF_KV_TRACING\ntrace::Environment trace_environment;", + "end_anchor": "#endif", + "reason": "Opt-in CCF_KV_TRACING instrumentation is unmodeled" + }, + { + "start": 913, + "end": 915, + "start_anchor": "#ifdef CCF_KV_TRACING\ntrace::Rollback trace_rollback(this);", + "end_anchor": "#endif", + "reason": "Opt-in CCF_KV_TRACING instrumentation is unmodeled" + }, + { + "start": 932, + "end": 938, + "start_anchor": "// History must be informed", + "end_anchor": "}", + "reason": "TxHistory rollback notification is unmodeled" + }, + { + "start": 942, + "end": 952, + "start_anchor": "if (snapshotter)", + "end_anchor": "}", + "reason": "Snapshotter and chunker rollback notifications (no-op rollback branch) are unmodeled" + }, + { + "start": 968, + "end": 982, + "start_anchor": "if (snapshotter)", + "end_anchor": "}", + "reason": "Snapshotter, chunker, and encryptor rollback notifications are unmodeled" + }, + { + "start": 1020, + "end": 1036, + "start_anchor": "LocalWritePermit acquire_local_write_permit() override", + "end_anchor": "}", + "reason": "Consensus role-lock permit helpers (acquire_local_write_permit, local_writes_enabled) are unmodeled concurrency plumbing" + }, + { + "start": 1050, + "end": 1054, + "start_anchor": "auto h = get_history();", + "end_anchor": "}", + "reason": "TxHistory term notification is unmodeled" + }, + { + "start": 1057, + "end": 1156, + "start_anchor": "bool fill_maps(", + "end_anchor": "}", + "reason": "Ledger entry deserialisation (fill_maps, deserialize) is unmodeled (trace::unsupported: deserialisation)" + }, + { + "start": 1319, + "end": 1322, + "start_anchor": "auto leaf = h ?", + "end_anchor": "std::nullopt;", + "reason": "Merkle TxHistory leaf calculation inside Store::commit is unmodeled" + }, + { + "start": 1347, + "end": 1355, + "start_anchor": "if (leaf.has_value())", + "end_anchor": "}", + "reason": "Merkle TxHistory append_entry and ledger chunker size tracking inside Store::commit are unmodeled" + }, + { + "start": 1397, + "end": 1459, + "start_anchor": "bool should_schedule_snapshot()", + "end_anchor": "}", + "reason": "Snapshot scheduling and ledger chunking predicates are unmodeled" + }, + { + "start": 1471, + "end": 1474, + "start_anchor": "bool check_rollback_count(", + "end_anchor": "}", + "reason": "ReservedTx and MaterialisedReadOnly rollback-count check is unmodeled" + }, + { + "start": 1509, + "end": 1662, + "start_anchor": "std::optional next_txid() override", + "end_anchor": "}", + "reason": "Reserved next_txid, committable_gap, swap_private_maps, and map/global hook registration are unmodeled" + }, + { + "start": 1664, + "end": 1671, + "start_anchor": "std::pair materialised_read_state() override", + "end_anchor": "}", + "reason": "MaterialisedReadOnly replicated-state version lookup is unmodeled" + }, + { + "start": 1675, + "end": 1678, + "start_anchor": "if (is_historical)", + "end_anchor": "}", + "reason": "Historical MaterialisedReadOnly transaction creation branch is unmodeled" + }, + { + "start": 1684, + "end": 1688, + "start_anchor": "if (is_historical)", + "end_anchor": "}", + "reason": "Historical MaterialisedReadOnly transaction pointer creation branch is unmodeled" + }, + { + "start": 1692, + "end": 1704, + "start_anchor": "TxDiff create_tx_diff() override", + "end_anchor": "}", + "reason": "TxDiff and MaterialisedReadOnly replicated-state transaction creation are unmodeled" + }, + { + "start": 1716, + "end": 1777, + "start_anchor": "ReservedTx create_reserved_tx(", + "end_anchor": "}", + "reason": "ReservedTx creation, apply_tx_flags, and StoreFlag helpers are unmodeled" + } + ] + }, + "src/kv/untyped_map.h": { + "exclude": [ + { + "start": 92, + "end": 122, + "start_anchor": "static State deserialize_map_snapshot(", + "end_anchor": "}", + "reason": "Map snapshot deserialisation is unmodeled" + }, + { + "start": 236, + "end": 241, + "start_anchor": "else if (track_deletes_on_missing_keys)", + "end_anchor": "}", + "reason": "MapDiff delete-tracking branch in HandleCommitter::commit is unmodeled" + }, + { + "start": 252, + "end": 258, + "start_anchor": "ConsensusHookPtr post_commit()", + "end_anchor": "}", + "reason": "Map local commit hooks are unmodeled" + }, + { + "start": 261, + "end": 298, + "start_anchor": "class Snapshot : public AbstractMap::Snapshot", + "end_anchor": "};", + "reason": "Map::Snapshot serialisation is unmodeled" + }, + { + "start": 317, + "end": 519, + "start_anchor": "void serialise_changes(", + "end_anchor": "}", + "reason": "Entry serialisation, SnapshotHandleCommitter, snapshot import, and ledger deserialisation are unmodeled" + }, + { + "start": 530, + "end": 536, + "start_anchor": "auto* snapshot_change_set =", + "end_anchor": "}", + "reason": "SnapshotChangeSet committer branch is unmodeled" + }, + { + "start": 550, + "end": 604, + "start_anchor": "void set_map_hook(", + "end_anchor": "}", + "reason": "Hook setters, security domain accessor, and Map::snapshot are unmodeled" + }, + { + "start": 622, + "end": 626, + "start_anchor": "// We know that write set is not empty.", + "end_anchor": "}", + "reason": "Global hook commit_deltas collection during compact is unmodeled" + }, + { + "start": 630, + "end": 634, + "start_anchor": "// Discardable, so move to commit_deltas.", + "end_anchor": "}", + "reason": "Global hook commit_deltas collection during compact is unmodeled" + }, + { + "start": 650, + "end": 653, + "start_anchor": "if (global_hook && !r->writes.empty())", + "end_anchor": "}", + "reason": "Global hook commit_deltas collection during compact is unmodeled" + }, + { + "start": 656, + "end": 672, + "start_anchor": "void post_compact()", + "end_anchor": "}", + "reason": "Global hook execution (post_compact) is unmodeled (trace::unsupported: global hook)" + }, + { + "start": 705, + "end": 713, + "start_anchor": "void clear()", + "end_anchor": "}", + "reason": "Map::clear outside a transaction is unmodeled (trace::unsupported: map clear outside transaction)" + }, + { + "start": 727, + "end": 732, + "start_anchor": "// Exchanges the entire state", + "end_anchor": "}", + "reason": "Map::swap (used only by swap_private_maps) is unmodeled" + }, + { + "start": 750, + "end": 759, + "start_anchor": "if (track_deletes_on_missing_keys)", + "end_anchor": "}", + "reason": "MapDiff delete-tracking path in create_change_set is unmodeled" + }, + { + "start": 797, + "end": 809, + "start_anchor": "ConsensusHookPtr trigger_map_hook(", + "end_anchor": "}", + "reason": "Local map hooks are unmodeled (trace::unsupported: local hook)" + } + ] + }, + "src/kv/untyped_change_set.h": { + "exclude": [ + { + "start": 40, + "end": 42, + "start_anchor": "#ifdef CCF_KV_TRACING\ntrace::MapMetadata trace_metadata;", + "end_anchor": "#endif", + "reason": "Opt-in CCF_KV_TRACING metadata field is unmodeled" + }, + { + "start": 76, + "end": 95, + "start_anchor": "// This is a container for a snapshot.", + "end_anchor": "};", + "reason": "SnapshotChangeSet is unmodeled" + }, + { + "start": 98, + "end": 176, + "start_anchor": "namespace map", + "end_anchor": "}", + "reason": "Snapshot/map wire serialisation helpers are unmodeled" + } + ] + }, + "src/kv/untyped_map_handle.cpp": { + "exclude": [ + { + "start": 11, + "end": 59, + "start_anchor": "#ifdef CCF_KV_TRACING\nnamespace", + "end_anchor": "#endif", + "reason": "Opt-in CCF_KV_TRACING traced_foreach helper is unmodeled" + }, + { + "start": 269, + "end": 271, + "start_anchor": "#ifdef CCF_KV_TRACING\ntrace::Suppress trace_suppress(tx_changes.trace_metadata);", + "end_anchor": "#endif", + "reason": "Opt-in CCF_KV_TRACING suppression guard is unmodeled" + }, + { + "start": 295, + "end": 297, + "start_anchor": "#ifdef CCF_KV_TRACING\ntrace::Suppress trace_suppress(tx_changes.trace_metadata);", + "end_anchor": "#endif", + "reason": "Opt-in CCF_KV_TRACING suppression guard is unmodeled" + }, + { + "start": 314, + "end": 332, + "start_anchor": "#ifdef CCF_KV_TRACING\n// Records the bounds and the collected entries", + "end_anchor": "#endif", + "reason": "Opt-in CCF_KV_TRACING range-iteration logging is unmodeled" + } + ] + }, + "src/kv/apply_changes.h": { + "exclude": [ + { + "start": 54, + "end": 71, + "start_anchor": "if (expected_rollback_count.has_value()", + "end_anchor": "}", + "reason": "expected_rollback_count is only used by ReservedTx signature transactions (unmodeled)" + }, + { + "start": 145, + "end": 153, + "start_anchor": "// Collect ConsensusHooks", + "end_anchor": "}", + "reason": "ConsensusHook collection via post_commit is unmodeled" + } + ] + }, + "src/kv/tx.cpp": { + "exclude": [ + { + "start": 29, + "end": 75, + "start_anchor": "void BaseTx::check_map_access(", + "end_anchor": "}", + "reason": "Signature-table, ReservedTx, and MaterialisedReadOnly access-control enforcement is unmodeled" + }, + { + "start": 105, + "end": 107, + "start_anchor": "#ifdef CCF_KV_TRACING\ntrace::Context trace_context(pimpl->trace_attempt.id);", + "end_anchor": "#endif", + "reason": "Opt-in CCF_KV_TRACING context guard is unmodeled" + }, + { + "start": 153, + "end": 161, + "start_anchor": "if (\n pimpl->role == PrivateImpl::Role::MaterialisedReadOnly", + "end_anchor": "}", + "reason": "MaterialisedReadOnly rollback-invalidation guard is unmodeled" + }, + { + "start": 200, + "end": 208, + "start_anchor": "BaseTx::BaseTx(AbstractStore* store_, MaterialisedReadOnlyTag /*tag*/) :", + "end_anchor": "}", + "reason": "MaterialisedReadOnly transaction constructor is unmodeled" + } + ] + }, + "src/kv/tx_pimpl.h": { + "exclude": [ + { + "start": 12, + "end": 17, + "start_anchor": "enum class Role : std::uint8_t", + "end_anchor": "};", + "reason": "Reserved and MaterialisedReadOnly transaction roles are unmodeled" + }, + { + "start": 21, + "end": 23, + "start_anchor": "#ifdef CCF_KV_TRACING\ntrace::Attempt trace_attempt;", + "end_anchor": "#endif", + "reason": "Opt-in CCF_KV_TRACING attempt state is unmodeled" + } + ] + }, + "include/ccf/kv/tx.h": { + "exclude": [ + { + "start": 50, + "end": 56, + "start_anchor": "enum class AccessMode : std::uint8_t", + "end_anchor": "};", + "reason": "AccessMode for signature-table, ReservedTx, and MaterialisedReadOnly access control is unmodeled" + }, + { + "start": 128, + "end": 129, + "start_anchor": "struct MaterialisedReadOnlyTag", + "end_anchor": "{};", + "reason": "MaterialisedReadOnly constructor tag is unmodeled" + }, + { + "start": 143, + "end": 146, + "start_anchor": "std::optional get_root_at_read_version()", + "end_anchor": "}", + "reason": "Merkle root at read version is unmodeled" + }, + { + "start": 149, + "end": 172, + "start_anchor": "class TxDiff : public BaseTx", + "end_anchor": "};", + "reason": "TxDiff / MapDiff is unmodeled (trace::unsupported: map diff)" + } + ] + }, + "src/kv/committable_tx.h": { + "exclude": [ + { + "start": 21, + "end": 28, + "start_anchor": "using TxFlags = uint8_t;", + "end_anchor": "};", + "reason": "Transaction ledger/snapshot flags are unmodeled" + }, + { + "start": 68, + "end": 83, + "start_anchor": "void serialise_all_changes(", + "end_anchor": "}", + "reason": "Transaction serialisation is unmodeled" + }, + { + "start": 93, + "end": 175, + "start_anchor": "size_t projected_serialised_size(", + "end_anchor": "}", + "reason": "Transaction size limit projection and serialisation are unmodeled" + }, + { + "start": 201, + "end": 205, + "start_anchor": "if (pimpl->role == PrivateImpl::Role::Reserved)", + "end_anchor": "}", + "reason": "ReservedTx misuse guard inside CommittableTx::commit is unmodeled" + }, + { + "start": 212, + "end": 214, + "start_anchor": "#ifdef CCF_KV_TRACING\ntrace::Commit trace_commit(pimpl->trace_attempt.id);", + "end_anchor": "#endif", + "reason": "Opt-in CCF_KV_TRACING commit guard is unmodeled" + }, + { + "start": 252, + "end": 268, + "start_anchor": "#ifdef CCF_KV_TRACING\ntrace::Json trace_writes;", + "end_anchor": "#endif", + "reason": "Opt-in CCF_KV_TRACING write-set capture is unmodeled" + }, + { + "start": 269, + "end": 272, + "start_anchor": "const auto force_ledger_chunk =", + "end_anchor": "tx_flag_enabled(TxFlag::SNAPSHOT_AT_NEXT_SIGNATURE);", + "reason": "Transaction ledger/snapshot TxFlag reads are unmodeled" + }, + { + "start": 284, + "end": 294, + "start_anchor": "if (snapshot_at_next_signature && !permit.allows_writes())", + "end_anchor": "}", + "reason": "Snapshot TxFlag admission guard is unmodeled" + }, + { + "start": 298, + "end": 301, + "start_anchor": "#ifdef CCF_KV_TRACING\ntrace::Context trace_context(", + "end_anchor": "#endif", + "reason": "Opt-in CCF_KV_TRACING context guard is unmodeled" + }, + { + "start": 350, + "end": 355, + "start_anchor": "if (snapshot_at_next_signature)", + "end_anchor": "}", + "reason": "Snapshot flag handling on read-only commit is unmodeled" + }, + { + "start": 360, + "end": 380, + "start_anchor": "// These side effects outlive this transaction", + "end_anchor": "}", + "reason": "Ledger chunk / snapshot TxFlag application is unmodeled" + }, + { + "start": 405, + "end": 410, + "start_anchor": "if (write_set_observer != nullptr)", + "end_anchor": "}", + "reason": "WriteSetObserver callback is unmodeled (trace::unsupported: write set observer)" + }, + { + "start": 511, + "end": 542, + "start_anchor": "void set_read_txid(", + "end_anchor": "}", + "reason": "set_read_txid, set_root_at_read_version, and TxFlag methods are unmodeled" + }, + { + "start": 545, + "end": 696, + "start_anchor": "// Used by frontend for reserved transactions.", + "end_anchor": "};", + "reason": "ReservedTx (signature transactions) is unmodeled (trace::unsupported: reserved transaction)" + } + ] + } + } +} diff --git a/scripts/ci-checks.sh b/scripts/ci-checks.sh index 7aea3ea5f2ae..41687e4fedf7 100755 --- a/scripts/ci-checks.sh +++ b/scripts/ci-checks.sh @@ -46,6 +46,7 @@ CHECKS=( "TypeScript, JavaScript, Markdown, TypeSpec, YAML and JSON format:prettier-checks.sh" "Documentation newlines:doc-newline-checks.sh" "Built-in maps documentation:builtin-maps-checks.sh" + "Lean coverage masks:lean-coverage-masks-checks.sh" "OpenAPI:openapi-checks.sh" "Copyright notice headers:copyright-checks.sh" "CMake format:cmake-format-checks.sh" diff --git a/scripts/lean-coverage-masks-checks.sh b/scripts/lean-coverage-masks-checks.sh new file mode 100755 index 000000000000..0f476ee7cc69 --- /dev/null +++ b/scripts/lean-coverage-masks-checks.sh @@ -0,0 +1,17 @@ +#!/bin/bash +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the Apache 2.0 License. + +# Validates all lean//coverage_mask.json files against +# lean/COVERAGE_MAPPING.md and the current C++ sources, and runs the +# lean_coverage_report unit tests. +# Accepts -f for interface consistency, but no auto-fix is available. + +set -euo pipefail + +SCRIPT_DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" >/dev/null 2>&1 && pwd )" +ROOT_DIR=$( dirname "$SCRIPT_DIR" ) +cd "$ROOT_DIR" || exit 1 + +"$SCRIPT_DIR"/lean_coverage_report.py --check-masks +"$SCRIPT_DIR"/tests/lean_coverage_report_test.py diff --git a/scripts/lean_coverage_report.py b/scripts/lean_coverage_report.py new file mode 100755 index 000000000000..896f49add0e3 --- /dev/null +++ b/scripts/lean_coverage_report.py @@ -0,0 +1,2109 @@ +#!/usr/bin/env python3 +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the Apache 2.0 License. + +"""Compute CI line/branch coverage and code/spec LoC for each Lean specification. + +Reads the Lean-to-C++ file mapping in ``lean/COVERAGE_MAPPING.md``, fetches the +latest patched ``llvm-cov report`` from the GitHub Actions ``coverage-history`` +artifact (or reads a local report via ``--report``), and prints a summary table +with C++ code LoC, Lean spec LoC, total Lean LoC, line coverage, and branch +coverage per specification. +""" + +import argparse +import gzip +import json +import os +import re +import subprocess +import sys +import tempfile +from collections.abc import Sequence +from html.parser import HTMLParser +from pathlib import Path +from typing import Any, NamedTuple + +from coverage_summary import ( + DEFAULT_REPOSITORY, + FileCoverage, + extract_coverage, + extract_file_coverage, +) + +DEFAULT_MAPPING = "lean/COVERAGE_MAPPING.md" +DEFAULT_BRANCH = "main" +EXPORT_JSON_ARTIFACT = "coverage-export-json" +TRACE_VALIDATED_JSON_ARTIFACT = "coverage-trace-validated-json" +HTML_REPORT_ARTIFACT = "coverage-report-html" + +_SPEC_HEADING_RE = re.compile(r"^##\s+.+?\(`lean/([^/`]+)`\)\s*$") +_SUBSECTION_RE = re.compile(r"^###\s+(.+?)\s*$") +_MARKDOWN_LINK_PATH_RE = re.compile(r"\[`((?:src|include)/[^`]+)`\]\([^)]+\)") +_CODE_PATH_RE = re.compile(r"`((?:src|include)/[^`]+)`") +_HISTORY_FILENAME_RE = re.compile(r"^(\d+)-(\d+)\.txt$") + +# Bullet prefixes that introduce commentary or explicitly excluded files rather +# than files mapped to the specification. +_NON_MAPPING_BULLET_PREFIXES = ( + "- **Partial coverage", + "- **Unmodeled paths", + "- **Explicitly excluded", +) + +# Bare punctuation or context-free keywords that are too weak as standalone +# single-line start_anchor values. +_WEAK_START_ANCHORS = frozenset( + { + "{", + "}", + "namespace", + "public:", + "private:", + "protected:", + "if", + "if (", + "else", + "try", + "catch", + "template <>", + "struct", + "class", + "default:", + } +) + + +class SpecMapping(NamedTuple): + name: str + files: list[str] + + +class SpecMetrics(NamedTuple): + name: str + files: list[str] + missing_from_report: list[str] + code_loc: int + spec_loc: int + total_lean_loc: int + lines: int + missed_lines: int + branches: int + missed_branches: int + masked: bool = False + branches_available: bool = True + tv_lines: int = 0 + tv_missed_lines: int = 0 + tv_branches: int = 0 + tv_missed_branches: int = 0 + tv_available: bool = False + tv_branches_available: bool = False + + @property + def lines_hit(self) -> int: + return self.lines - self.missed_lines + + @property + def branches_hit(self) -> int: + return self.branches - self.missed_branches + + @property + def line_coverage(self) -> float | None: + return _percentage(self.lines, self.missed_lines) + + @property + def branch_coverage(self) -> float | None: + if not self.branches_available: + return None + return _percentage(self.branches, self.missed_branches) + + @property + def tv_line_coverage(self) -> float | None: + if not self.tv_available: + return None + return _percentage(self.tv_lines, self.tv_missed_lines) + + @property + def tv_branch_coverage(self) -> float | None: + if not (self.tv_available and self.tv_branches_available): + return None + return _percentage(self.tv_branches, self.tv_missed_branches) + + +class RemovedMetrics(NamedTuple): + name: str + masked_files: int + code_loc: int + lines: int + missed_lines: int + branches: int + missed_branches: int + branches_available: bool = True + tv_lines: int = 0 + tv_missed_lines: int = 0 + tv_branches: int = 0 + tv_missed_branches: int = 0 + tv_available: bool = False + tv_branches_available: bool = False + + @property + def lines_hit(self) -> int: + return self.lines - self.missed_lines + + @property + def branches_hit(self) -> int: + return self.branches - self.missed_branches + + @property + def line_coverage(self) -> float | None: + return _percentage(self.lines, self.missed_lines) + + @property + def branch_coverage(self) -> float | None: + if not self.branches_available: + return None + return _percentage(self.branches, self.missed_branches) + + @property + def tv_line_coverage(self) -> float | None: + if not self.tv_available: + return None + return _percentage(self.tv_lines, self.tv_missed_lines) + + @property + def tv_branch_coverage(self) -> float | None: + if not (self.tv_available and self.tv_branches_available): + return None + return _percentage(self.tv_branches, self.tv_missed_branches) + + +class BranchRecord(NamedTuple): + line: int + col: int + end_line: int + end_col: int + true_count: int + false_count: int + + +class DetailedFileCoverage(NamedTuple): + lines: dict[int, int] + branches: list[BranchRecord] | None = None + + +class ReportSource(NamedTuple): + text: str + description: str + run_id: int | None = None + run_number: str | None = None + detail_description: str | None = None + trace_validated_description: str | None = None + + +def _percentage(total: int, missed: int) -> float | None: + if total == 0: + return None + return 100.0 * (total - missed) / total + + +def _format_percentage(value: float | None) -> str: + return f"{value:.2f}%" if value is not None else "-" + + +def _extract_bullet_paths(line: str) -> list[str]: + """Extract repo-relative implementation paths from the subject of a bullet. + + Only inspects the portion of the bullet before the first ``:`` (when a + colon is present outside link targets) so files mentioned only in + explanatory prose are not captured. + """ + body = line[2:].strip() + # Find the first colon not inside (...) link syntax. + depth = 0 + subject = body + for idx, ch in enumerate(body): + if ch == "(": + depth += 1 + elif ch == ")" and depth > 0: + depth -= 1 + elif ch == ":" and depth == 0: + subject = body[:idx] + break + + paths: list[str] = [] + seen: set[str] = set() + for pattern in (_MARKDOWN_LINK_PATH_RE, _CODE_PATH_RE): + for match in pattern.finditer(subject): + path = match.group(1) + if path not in seen: + seen.add(path) + paths.append(path) + return paths + + +def parse_coverage_mapping(text: str) -> list[SpecMapping]: + """Parse ``lean/COVERAGE_MAPPING.md`` into per-specification file lists.""" + mappings: list[SpecMapping] = [] + current_name: str | None = None + current_files: list[str] = [] + in_scope_section = False + + def flush() -> None: + nonlocal current_name, current_files + if current_name is not None: + mappings.append(SpecMapping(name=current_name, files=current_files)) + current_name = None + current_files = [] + + for raw_line in text.splitlines(): + line = raw_line.rstrip() + spec_match = _SPEC_HEADING_RE.match(line) + if spec_match: + flush() + current_name = spec_match.group(1) + in_scope_section = False + continue + + if current_name is None: + continue + + sub_match = _SUBSECTION_RE.match(line) + if sub_match: + heading = sub_match.group(1).lower() + in_scope_section = heading.startswith( + ("in-scope implementation", "core implementation") + ) + continue + + if not in_scope_section or not line.startswith("- "): + continue + + if any(line.startswith(prefix) for prefix in _NON_MAPPING_BULLET_PREFIXES): + continue + + for path in _extract_bullet_paths(line): + if path not in current_files: + current_files.append(path) + + flush() + return mappings + + +def count_cpp_loc(text: str, included_lines: set[int] | None = None) -> int: + """Count non-blank, non-comment C/C++ lines of code (SLOC). + + When ``included_lines`` is given, every line is still lexed to keep block + comment and raw-string state accurate, but only 1-based line numbers in + ``included_lines`` are counted. + """ + loc = 0 + in_block_comment = False + raw_delim: str | None = None + + for line_no, line in enumerate(text.splitlines(), start=1): + i = 0 + n = len(line) + has_code = False + in_string = False + in_char = False + + while i < n: + if raw_delim is not None: + end_marker = ")" + raw_delim + '"' + pos = line.find(end_marker, i) + has_code = True + if pos == -1: + i = n + else: + i = pos + len(end_marker) + raw_delim = None + continue + + if in_block_comment: + end_pos = line.find("*/", i) + if end_pos == -1: + i = n + else: + i = end_pos + 2 + in_block_comment = False + continue + + ch = line[i] + if in_string: + has_code = True + if ch == "\\" and i + 1 < n: + i += 2 + elif ch == '"': + in_string = False + i += 1 + else: + i += 1 + continue + + if in_char: + has_code = True + if ch == "\\" and i + 1 < n: + i += 2 + elif ch == "'": + in_char = False + i += 1 + else: + i += 1 + continue + + if ch == "/" and i + 1 < n: + nxt = line[i + 1] + if nxt == "/": + break + if nxt == "*": + in_block_comment = True + i += 2 + continue + + if ch == "R" and i + 1 < n and line[i + 1] == '"': + paren = line.find("(", i + 2) + if paren != -1: + candidate = line[i + 2 : paren] + if all(c not in " \t()\\" for c in candidate): + has_code = True + raw_delim = candidate + i = paren + 1 + continue + + if ch == '"': + has_code = True + in_string = True + i += 1 + continue + + if ch == "'": + has_code = True + in_char = True + i += 1 + continue + + if not ch.isspace(): + has_code = True + i += 1 + + if has_code and (included_lines is None or line_no in included_lines): + loc += 1 + + return loc + + +def count_lean_loc(text: str) -> int: + """Count non-blank, non-comment Lean lines of code (SLOC). + + Handles Lean's nested ``/- ... -/`` block comments (including ``/--`` and + ``/-!`` doc comments) and ``--`` line comments. + """ + loc = 0 + block_depth = 0 + + for line in text.splitlines(): + i = 0 + n = len(line) + has_code = False + in_string = False + + while i < n: + if block_depth > 0: + if line[i : i + 2] == "/-": + block_depth += 1 + i += 2 + elif line[i : i + 2] == "-/": + block_depth -= 1 + i += 2 + else: + i += 1 + continue + + ch = line[i] + if in_string: + has_code = True + if ch == "\\" and i + 1 < n: + i += 2 + elif ch == '"': + in_string = False + i += 1 + else: + i += 1 + continue + + if line[i : i + 2] == "--": + break + if line[i : i + 2] == "/-": + block_depth += 1 + i += 2 + continue + # Lean char literals like '"' or '\n' (distinct from identifier primes like x'). + if ch == "'": + if i + 3 < n and line[i + 1] == "\\" and line[i + 3] == "'": + has_code = True + i += 4 + continue + if i + 2 < n and line[i + 1] != "\\" and line[i + 2] == "'": + has_code = True + i += 3 + continue + if ch == '"': + has_code = True + in_string = True + i += 1 + continue + + if not ch.isspace(): + has_code = True + i += 1 + + if has_code: + loc += 1 + + return loc + + +def _is_spec_lean_file(rel_path: Path) -> bool: + """Return True for Model and Properties files (the human-reviewed spec).""" + parts = rel_path.parts + if len(parts) == 2 and parts[1] in ("Model.lean", "Properties.lean"): + return True + return len(parts) >= 3 and parts[1] in ("Model", "Properties") + + +def count_lean_package_loc(package_dir: Path) -> tuple[int, int]: + """Return ``(spec_loc, total_lean_loc)`` for a Lean package directory.""" + spec_loc = 0 + total_loc = 0 + for root, dirs, filenames in os.walk(package_dir): + dirs[:] = [d for d in dirs if d not in (".lake", "scripts")] + for filename in sorted(filenames): + if not filename.endswith(".lean"): + continue + file_path = Path(root) / filename + rel = file_path.relative_to(package_dir) + loc = count_lean_loc(file_path.read_text(encoding="utf-8")) + total_loc += loc + if _is_spec_lean_file(rel): + spec_loc += loc + return spec_loc, total_loc + + +def _run_gh(args: Sequence[str]) -> str: + try: + proc = subprocess.run( + ["gh", *args], + check=True, + capture_output=True, + text=True, + ) + except FileNotFoundError as exc: + raise RuntimeError( + "GitHub CLI 'gh' is required to fetch CI coverage artifacts." + ) from exc + except subprocess.CalledProcessError as exc: + detail = (exc.stderr or exc.stdout or "").strip() + raise RuntimeError(f"'gh {' '.join(args)}' failed: {detail}") from exc + return proc.stdout + + +def _select_latest_report(directory: Path) -> tuple[int, str, str]: + """Select the newest complete ``-.txt`` report.""" + candidates: list[tuple[int, str, Path]] = [] + for entry in directory.iterdir(): + if not entry.is_file(): + continue + match = _HISTORY_FILENAME_RE.match(entry.name) + if match: + candidates.append((int(match.group(1)), match.group(2), entry)) + + for run_id, run_number, path in sorted(candidates, reverse=True): + text = path.read_text(encoding="utf-8", errors="replace") + if extract_coverage(text) is not None and extract_file_coverage(text): + return run_id, run_number, text + + raise RuntimeError("No complete llvm-cov report found in downloaded artifact") + + +def fetch_ci_coverage_report( + repo: str, + branch: str, + run_id: int | None = None, +) -> ReportSource: + """Download the latest coverage-history artifact from GitHub Actions.""" + slug = branch.replace("/", "-") + artifact_name = f"coverage-history-{slug}" + + if run_id is not None: + candidate_run_ids = [run_id] + else: + raw = _run_gh( + [ + "api", + f"repos/{repo}/actions/artifacts?name={artifact_name}&per_page=100", + ] + ) + payload = json.loads(raw) + artifacts = [ + a + for a in payload.get("artifacts", []) + if not a.get("expired", False) + and a.get("workflow_run", {}).get("head_branch") == branch + ] + artifacts.sort(key=lambda a: a.get("created_at", ""), reverse=True) + candidate_run_ids = [] + seen_ids: set[int] = set() + for artifact in artifacts: + wf_id = artifact.get("workflow_run", {}).get("id") + if isinstance(wf_id, int) and wf_id not in seen_ids: + seen_ids.add(wf_id) + candidate_run_ids.append(wf_id) + if not candidate_run_ids: + raise RuntimeError( + f"No non-expired '{artifact_name}' artifacts found for branch " + f"'{branch}' in {repo}." + ) + + last_error: str | None = None + for candidate_id in candidate_run_ids[:10]: + with tempfile.TemporaryDirectory() as tmpdir: + try: + _run_gh( + [ + "run", + "download", + str(candidate_id), + "--repo", + repo, + "--name", + artifact_name, + "--dir", + tmpdir, + ] + ) + report_run_id, report_run_number, text = _select_latest_report( + Path(tmpdir) + ) + return ReportSource( + text=text, + description=( + f"{repo} run #{report_run_number} (ID {report_run_id}, " + f"artifact `{artifact_name}` on `{branch}`)" + ), + run_id=report_run_id, + run_number=report_run_number, + ) + except RuntimeError as exc: + last_error = str(exc) + + raise RuntimeError( + f"Failed to download '{artifact_name}' from {repo}: {last_error}" + ) + + +def _validate_start_anchor( + mask_path: Path, + rel_path: str, + source_lines: Sequence[str], + start: int, + start_anchor: Any, +) -> None: + if not isinstance(start_anchor, str) or not start_anchor.strip(): + raise ValueError( + f"{mask_path}: {rel_path}:{start} start_anchor must be a non-empty string" + ) + anchor_lines = start_anchor.splitlines() + if len(anchor_lines) == 1: + stripped = anchor_lines[0].strip() + if stripped in _WEAK_START_ANCHORS or not re.search(r"[A-Za-z_]", stripped): + raise ValueError( + f"{mask_path}: {rel_path}:{start} start_anchor {start_anchor!r} " + "is too weak (use an identifier-bearing anchor or multi-line anchor)" + ) + else: + if not any( + line.strip() not in _WEAK_START_ANCHORS and re.search(r"[A-Za-z_]", line) + for line in anchor_lines + ): + raise ValueError( + f"{mask_path}: {rel_path}:{start} start_anchor {start_anchor!r} " + "contains no meaningful identifier context" + ) + if start - 1 + len(anchor_lines) > len(source_lines): + raise ValueError( + f"{mask_path}: {rel_path}:{start} multi-line start_anchor extends past EOF" + ) + for offset, expected in enumerate(anchor_lines): + actual = source_lines[start - 1 + offset] + if expected not in actual: + raise ValueError( + f"{mask_path}: {rel_path}:{start + offset} start_anchor " + f"{expected!r} not found in {actual!r}" + ) + + +def _check_cpp_brace_balance( + mask_path: Path, + rel_path: str, + source_lines: Sequence[str], + start: int, + end: int, + kind: str, +) -> None: + """Verify lexical '{' / '}' balance across lines ``[start, end]``.""" + in_block_comment = False + raw_delim: str | None = None + brace_depth = 0 + + for line_no in range(1, end + 1): + line = source_lines[line_no - 1] + in_range = line_no >= start + i = 0 + n = len(line) + in_string = False + in_char = False + + while i < n: + if raw_delim is not None: + end_marker = ")" + raw_delim + '"' + pos = line.find(end_marker, i) + if pos == -1: + i = n + else: + i = pos + len(end_marker) + raw_delim = None + continue + + if in_block_comment: + end_pos = line.find("*/", i) + if end_pos == -1: + i = n + else: + i = end_pos + 2 + in_block_comment = False + continue + + ch = line[i] + if in_string: + if ch == "\\" and i + 1 < n: + i += 2 + elif ch == '"': + in_string = False + i += 1 + else: + i += 1 + continue + + if in_char: + if ch == "\\" and i + 1 < n: + i += 2 + elif ch == "'": + in_char = False + i += 1 + else: + i += 1 + continue + + if ch == "/" and i + 1 < n: + nxt = line[i + 1] + if nxt == "/": + break + if nxt == "*": + in_block_comment = True + i += 2 + continue + + if ch == "R" and i + 1 < n and line[i + 1] == '"': + paren = line.find("(", i + 2) + if paren != -1: + candidate = line[i + 2 : paren] + if all(c not in " \t()\\" for c in candidate): + raw_delim = candidate + i = paren + 1 + continue + + if ch == '"': + in_string = True + i += 1 + continue + + if ch == "'": + in_char = True + i += 1 + continue + + if in_range: + if ch == "{": + brace_depth += 1 + elif ch == "}": + brace_depth -= 1 + if brace_depth < 0: + raise ValueError( + f"{mask_path}: {rel_path} {kind} range {start}-{end} " + f"has unbalanced '}}' at line {line_no}" + ) + i += 1 + + if brace_depth != 0: + raise ValueError( + f"{mask_path}: {rel_path} {kind} range {start}-{end} " + f"has unbalanced braces (net depth {brace_depth})" + ) + + +def _expand_mask_ranges( + mask_path: Path, + rel_path: str, + source_lines: Sequence[str], + entries: Sequence[dict[str, Any]], + kind: str, +) -> set[int]: + num_lines = len(source_lines) + selected: set[int] = set() + for entry in entries: + start = int(entry["start"]) + end = int(entry["end"]) + if not (1 <= start <= end <= num_lines): + raise ValueError( + f"{mask_path}: {rel_path} {kind} range {start}-{end} " + f"is out of bounds (file has {num_lines} lines)" + ) + _validate_start_anchor( + mask_path, rel_path, source_lines, start, entry.get("start_anchor") + ) + end_anchor = entry.get("end_anchor") + if end_anchor and end_anchor not in source_lines[end - 1]: + raise ValueError( + f"{mask_path}: {rel_path}:{end} end_anchor " + f"{end_anchor!r} not found in {source_lines[end - 1]!r}" + ) + _check_cpp_brace_balance(mask_path, rel_path, source_lines, start, end, kind) + line_range = set(range(start, end + 1)) + overlap = selected & line_range + if overlap: + raise ValueError( + f"{mask_path}: {rel_path} {kind} range {start}-{end} overlaps " + f"an earlier range at line {min(overlap)}" + ) + selected.update(line_range) + return selected + + +def validate_disjoint_specs( + repo_root: Path, + mappings: Sequence[SpecMapping], + spec_masks: dict[str, dict[str, set[int]]] | None = None, +) -> None: + """Verify that no source line is mapped to more than one specification.""" + claimed: dict[str, dict[int, str]] = {} + line_count_cache: dict[str, int] = {} + + for mapping in mappings: + mask = (spec_masks or {}).get(mapping.name, {}) + for rel_path in mapping.files: + if rel_path not in line_count_cache: + line_count_cache[rel_path] = len( + (repo_root / rel_path).read_text(encoding="utf-8").splitlines() + ) + included = mask.get(rel_path) + lines = ( + included + if included is not None + else set(range(1, line_count_cache[rel_path] + 1)) + ) + file_claims = claimed.setdefault(rel_path, {}) + for line_no in sorted(lines): + prev = file_claims.get(line_no) + if prev is not None and prev != mapping.name: + raise ValueError( + f"Disjointness violation: {rel_path}:{line_no} is mapped " + f"to both '{prev}' and '{mapping.name}'" + ) + file_claims[line_no] = mapping.name + + +def load_spec_mask( + repo_root: Path, + spec_name: str, + mapped_files: Sequence[str] | None = None, +) -> dict[str, set[int]]: + """Load and validate ``lean//coverage_mask.json`` if present. + + Returns a mapping from repo-relative file path to the 1-based set of + included line numbers. Files without an entry in the mask are omitted from + the returned dict (meaning the whole file is included). Raises + ``ValueError`` if any line range is out of bounds or an anchor fails to + match the current source file. + """ + mask_path = repo_root / "lean" / spec_name / "coverage_mask.json" + if not mask_path.is_file(): + return {} + + payload = json.loads(mask_path.read_text(encoding="utf-8")) + if payload.get("spec") not in (None, spec_name): + raise ValueError( + f"{mask_path}: 'spec' is {payload.get('spec')!r}, expected {spec_name!r}" + ) + + files_cfg = payload.get("files", {}) + if not isinstance(files_cfg, dict): + raise TypeError(f"{mask_path}: 'files' must be an object") + + mapped_set = set(mapped_files) if mapped_files is not None else None + result: dict[str, set[int]] = {} + + for rel_path, rule in files_cfg.items(): + if mapped_set is not None and rel_path not in mapped_set: + raise ValueError( + f"{mask_path}: masked file '{rel_path}' is not in the " + f"'{spec_name}' mapping" + ) + source_path = repo_root / rel_path + if not source_path.is_file(): + raise ValueError(f"{mask_path}: file '{rel_path}' does not exist") + source_lines = source_path.read_text(encoding="utf-8").splitlines() + num_lines = len(source_lines) + + include_entries = rule.get("include") + exclude_entries = rule.get("exclude", []) + if include_entries is not None: + included = _expand_mask_ranges( + mask_path, rel_path, source_lines, include_entries, "include" + ) + else: + included = set(range(1, num_lines + 1)) + if exclude_entries: + included -= _expand_mask_ranges( + mask_path, rel_path, source_lines, exclude_entries, "exclude" + ) + result[rel_path] = included + + return result + + +def _parse_html_count(raw: str) -> int: + """Parse an llvm-cov HTML execution count cell such as '0', '42', or '1.2k'.""" + text = raw.strip() + if not text: + return 0 + if text.isdigit(): + return int(text) + suffix_mult = {"k": 1_000, "M": 1_000_000, "G": 1_000_000_000} + if text[-1] in suffix_mult: + return max(1, int(float(text[:-1]) * suffix_mult[text[-1]])) + return 1 + + +class _HtmlTopLevelLineParser(HTMLParser): + """Extract per-line execution counts from the top-level llvm-cov HTML table.""" + + def __init__(self) -> None: + super().__init__() + self.table_depth = 0 + self.in_tr = False + self.td_idx = -1 + self.cur_td_class = "" + self.cur_text: list[str] = [] + self.line_no: int | None = None + self.cls: str | None = None + self.cnt: str | None = None + self.lines: dict[int, int] = {} + + def handle_starttag(self, tag: str, attrs: list[tuple[str, str | None]]) -> None: + attr_map = dict(attrs) + if tag == "table": + self.table_depth += 1 + elif self.table_depth == 1: + if tag == "tr": + self.in_tr = True + self.td_idx = -1 + self.line_no = self.cls = self.cnt = None + elif self.in_tr and tag == "td": + self.td_idx += 1 + self.cur_td_class = attr_map.get("class") or "" + self.cur_text = [] + + def handle_endtag(self, tag: str) -> None: + if tag == "table": + self.table_depth -= 1 + elif self.table_depth == 1: + if self.in_tr and tag == "td": + txt = "".join(self.cur_text).strip() + if self.td_idx == 0 and txt.isdigit(): + self.line_no = int(txt) + elif self.td_idx == 1: + self.cls = self.cur_td_class + self.cnt = txt + elif tag == "tr" and self.in_tr: + if ( + self.line_no is not None + and self.cls in ("covered-line", "uncovered-line") + and self.cnt + ): + self.lines[self.line_no] = _parse_html_count(self.cnt) + self.in_tr = False + + def handle_data(self, data: str) -> None: + if self.table_depth == 1 and self.in_tr and self.td_idx in (0, 1): + self.cur_text.append(data) + + +def parse_html_file_coverage(html_text: str) -> dict[int, int]: + """Return ``{line_no: hit_count}`` for instrumented lines in an llvm-cov HTML file.""" + parser = _HtmlTopLevelLineParser() + parser.feed(html_text) + return parser.lines + + +def load_html_coverage_dir( + html_dir: Path, + target_files: Sequence[str], +) -> dict[str, DetailedFileCoverage]: + """Load per-line coverage from an extracted ``coverage-report-html`` directory.""" + all_html = [ + p.as_posix() for p in html_dir.rglob("*.html") if p.name != "index.html" + ] + details: dict[str, DetailedFileCoverage] = {} + for rel_path in target_files: + suffix = "/" + rel_path + ".html" + matches = [p for p in all_html if p == rel_path + ".html" or p.endswith(suffix)] + if not matches: + continue + html_path = Path(min(matches, key=len)) + line_counts = parse_html_file_coverage( + html_path.read_text(encoding="utf-8", errors="replace") + ) + details[rel_path] = DetailedFileCoverage(lines=line_counts, branches=None) + return details + + +def _lines_from_llvm_segments(segments: Sequence[Sequence[Any]]) -> dict[int, int]: + """Decode ``llvm-cov export`` file segments into per-line hit counts. + + Follows LLVM's ``LineCoverageStats`` rules so each physical instrumented + line is counted once. + """ + if not segments: + return {} + + by_line: dict[int, list[tuple[int, int, bool, bool, bool]]] = {} + min_line = int(segments[0][0]) + max_line = min_line + for seg in segments: + line = int(seg[0]) + col = int(seg[1]) + count = int(seg[2]) + has_count = bool(seg[3]) + is_entry = bool(seg[4]) + is_gap = bool(seg[5]) if len(seg) > 5 else False + by_line.setdefault(line, []).append((col, count, has_count, is_entry, is_gap)) + min_line = min(min_line, line) + max_line = max(max_line, line) + + result: dict[int, int] = {} + wrapped: tuple[int, int, bool, bool, bool] | None = None + for line in range(min_line, max_line + 1): + line_segs = by_line.get(line, []) + wrapped_active = ( + wrapped is not None + and wrapped[2] + and not wrapped[4] + and not (line_segs and line_segs[0][0] == 1) + ) + entry_counts = [seg[1] for seg in line_segs if seg[2] and seg[3] and not seg[4]] + if wrapped_active or entry_counts: + candidates = list(entry_counts) + if wrapped_active and wrapped is not None: + candidates.append(wrapped[1]) + result[line] = max(candidates) + if line_segs: + wrapped = line_segs[-1] + return result + + +def parse_llvm_cov_export_json( + payload: dict[str, Any], +) -> dict[str, DetailedFileCoverage]: + """Parse ``llvm-cov export -format=text`` JSON into per-file line and branch data.""" + details: dict[str, DetailedFileCoverage] = {} + for export_entry in payload.get("data", []): + for file_entry in export_entry.get("files", []): + filename = str(file_entry.get("filename", "")) + if not filename: + continue + line_counts = _lines_from_llvm_segments(file_entry.get("segments", [])) + branch_map: dict[tuple[int, int, int, int], tuple[int, int]] = {} + for raw_branch in file_entry.get("branches", []): + if len(raw_branch) < 6: + continue + line_start = int(raw_branch[0]) + col_start = int(raw_branch[1]) + line_end = int(raw_branch[2]) + col_end = int(raw_branch[3]) + true_count = int(raw_branch[4]) + false_count = int(raw_branch[5]) + key = (line_start, col_start, line_end, col_end) + prev = branch_map.get(key) + if prev is None: + branch_map[key] = (true_count, false_count) + else: + branch_map[key] = ( + max(prev[0], true_count), + max(prev[1], false_count), + ) + branches = [ + BranchRecord(k[0], k[1], k[2], k[3], v[0], v[1]) + for k, v in sorted(branch_map.items()) + ] + details[filename] = DetailedFileCoverage( + lines=line_counts, + branches=branches, + ) + return details + + +def load_export_json(path: Path) -> dict[str, DetailedFileCoverage]: + """Load an ``llvm-cov export`` JSON file (plain ``.json`` or ``.json.gz``).""" + if path.suffix == ".gz": + with gzip.open(path, "rt", encoding="utf-8") as fh: + payload = json.load(fh) + else: + payload = json.loads(path.read_text(encoding="utf-8")) + return parse_llvm_cov_export_json(payload) + + +def fetch_ci_detailed_coverage( + repo: str, + run_id: int, + target_files: Sequence[str], +) -> tuple[dict[str, DetailedFileCoverage], str]: + """Fetch per-line (and when available, per-branch) coverage for a CI run. + + Prefers ``coverage-export-json`` (which includes branch regions) and falls + back to ``coverage-report-html`` (line counts only) on runs that do not + upload the JSON export artifact. + """ + with tempfile.TemporaryDirectory() as tmpdir: + tmp = Path(tmpdir) + try: + _run_gh( + [ + "run", + "download", + str(run_id), + "--repo", + repo, + "--name", + EXPORT_JSON_ARTIFACT, + "--dir", + tmpdir, + ] + ) + json_files = sorted([*tmp.rglob("*.json.gz"), *tmp.rglob("*.json")]) + if json_files: + return load_export_json(json_files[0]), EXPORT_JSON_ARTIFACT + except RuntimeError: + pass + + with tempfile.TemporaryDirectory() as tmpdir: + _run_gh( + [ + "run", + "download", + str(run_id), + "--repo", + repo, + "--name", + HTML_REPORT_ARTIFACT, + "--dir", + tmpdir, + ] + ) + return ( + load_html_coverage_dir(Path(tmpdir), target_files), + HTML_REPORT_ARTIFACT, + ) + + +def load_trace_validated_dir( + directory: Path, + spec_names: Sequence[str], +) -> dict[str, dict[str, DetailedFileCoverage]]: + """Load per-spec ``.json.gz`` (or ``.json``) trace-validated exports.""" + loaded: dict[str, dict[str, DetailedFileCoverage]] = {} + for name in spec_names: + for ext in (".json.gz", ".json"): + candidate = directory / f"{name}{ext}" + if candidate.is_file(): + loaded[name] = load_export_json(candidate) + break + return loaded + + +def fetch_ci_trace_validated_coverage( + repo: str, + run_id: int, + spec_names: Sequence[str], +) -> tuple[dict[str, dict[str, DetailedFileCoverage]], str | None]: + """Fetch per-spec trace-validated JSON exports from CI if uploaded on ``run_id``.""" + with tempfile.TemporaryDirectory() as tmpdir: + try: + _run_gh( + [ + "run", + "download", + str(run_id), + "--repo", + repo, + "--name", + TRACE_VALIDATED_JSON_ARTIFACT, + "--dir", + tmpdir, + ] + ) + except RuntimeError: + return {}, None + loaded = load_trace_validated_dir(Path(tmpdir), spec_names) + if not loaded: + return {}, None + return loaded, TRACE_VALIDATED_JSON_ARTIFACT + + +def _lookup_detailed_coverage( + path: str, + by_path: dict[str, DetailedFileCoverage], +) -> DetailedFileCoverage | None: + if path in by_path: + return by_path[path] + suffix = "/" + path + matches = [k for k in by_path if k.endswith(suffix)] + if matches: + return by_path[min(matches, key=len)] + return None + + +def _summarize_detailed( + detail: DetailedFileCoverage, + included_lines: set[int] | None, +) -> tuple[int, int, int, int, bool]: + """Return ``(lines, missed_lines, branches, missed_branches, branches_ok)``.""" + lines = missed_lines = 0 + for line_no, count in detail.lines.items(): + if included_lines is None or line_no in included_lines: + lines += 1 + if count == 0: + missed_lines += 1 + + if detail.branches is None: + return lines, missed_lines, 0, 0, False + + branches = missed_branches = 0 + for br in detail.branches: + if included_lines is None or br.line in included_lines: + branches += 2 + if br.true_count == 0: + missed_branches += 1 + if br.false_count == 0: + missed_branches += 1 + return lines, missed_lines, branches, missed_branches, True + + +def _lookup_coverage( + path: str, + by_path: dict[str, FileCoverage], +) -> FileCoverage | None: + if path in by_path: + return by_path[path] + suffix = "/" + path + matches = [entry for k, entry in by_path.items() if k.endswith(suffix)] + if len(matches) == 1: + return matches[0] + return None + + +def _file_metrics( + path: str, + included_lines: set[int] | None, + by_path: dict[str, FileCoverage], + detailed_by_path: dict[str, DetailedFileCoverage] | None, +) -> tuple[int, int, int, int, bool, bool]: + """Return ``(lines, missed_lines, branches, missed_branches, branches_ok, present)``. + + When detailed coverage with branch data (``llvm-cov export`` JSON) is + available, use it uniformly for both masked and unmasked files so masked, + whole-file, and removed-region comparisons share identical branch + deduplication semantics. + """ + detail = ( + _lookup_detailed_coverage(path, detailed_by_path) + if detailed_by_path is not None + else None + ) + + if included_lines is not None: + if detail is None: + if _lookup_coverage(path, by_path) is None: + return 0, 0, 0, 0, True, False + raise RuntimeError( + f"File '{path}' has a line mask, but per-line coverage data " + "is unavailable. Pass --html-dir, --export-json, or fetch from CI." + ) + lines, missed_lines, branches, missed_branches, branches_ok = ( + _summarize_detailed(detail, included_lines) + ) + return lines, missed_lines, branches, missed_branches, branches_ok, True + + if detail is not None and detail.branches is not None: + lines, missed_lines, branches, missed_branches, branches_ok = ( + _summarize_detailed(detail, None) + ) + return lines, missed_lines, branches, missed_branches, branches_ok, True + + cov = _lookup_coverage(path, by_path) + if cov is not None: + return ( + cov.lines, + cov.missed_lines, + cov.branches, + cov.missed_branches, + True, + True, + ) + + if detail is not None: + lines, missed_lines, branches, missed_branches, branches_ok = ( + _summarize_detailed(detail, None) + ) + return lines, missed_lines, branches, missed_branches, branches_ok, True + + return 0, 0, 0, 0, True, False + + +def compute_metrics( + repo_root: Path, + mappings: Sequence[SpecMapping], + coverage_files: Sequence[FileCoverage], + spec_masks: dict[str, dict[str, set[int]]] | None = None, + detailed_coverage: dict[str, DetailedFileCoverage] | None = None, + trace_validated_coverage: dict[str, dict[str, DetailedFileCoverage]] | None = None, +) -> tuple[list[SpecMetrics], SpecMetrics, int]: + """Aggregate LoC and coverage metrics per specification and overall.""" + by_path: dict[str, FileCoverage] = {entry.path: entry for entry in coverage_files} + text_cache: dict[str, str] = {} + + def file_text(rel_path: str) -> str: + if rel_path not in text_cache: + text_cache[rel_path] = (repo_root / rel_path).read_text(encoding="utf-8") + return text_cache[rel_path] + + def cpp_loc(rel_path: str, included_lines: set[int] | None) -> int: + return count_cpp_loc(file_text(rel_path), included_lines) + + per_spec: list[SpecMetrics] = [] + all_unique_files: list[str] = [] + # Maps each unique file to its merged included line set across specs + # (None means at least one spec includes the whole file). + merged_masks: dict[str, set[int] | None] = {} + + for mapping in mappings: + files = list(mapping.files) + + mask = (spec_masks or {}).get(mapping.name, {}) + spec_is_masked = any(path in mask for path in files) + tv_by_path = (trace_validated_coverage or {}).get(mapping.name) + + code_loc = 0 + lines = missed_lines = branches = missed_branches = 0 + branches_available = True + tv_lines = tv_missed_lines = tv_branches = tv_missed_branches = 0 + tv_available = tv_by_path is not None + tv_branches_available = tv_available + missing: list[str] = [] + + for path in files: + included = mask.get(path) + code_loc += cpp_loc(path, included) + f_lines, f_missed, f_br, f_br_missed, f_br_ok, present = _file_metrics( + path, included, by_path, detailed_coverage + ) + if not present: + missing.append(path) + else: + lines += f_lines + missed_lines += f_missed + if f_br_ok: + branches += f_br + missed_branches += f_br_missed + else: + branches_available = False + + if tv_by_path is not None: + tv_detail = _lookup_detailed_coverage(path, tv_by_path) + if tv_detail is not None: + tl, tml, tbr, tmbr, tbr_ok = _summarize_detailed( + tv_detail, included + ) + tv_lines += tl + tv_missed_lines += tml + if tbr_ok: + tv_branches += tbr + tv_missed_branches += tmbr + else: + tv_branches_available = False + elif present: + # File was instrumented in the full run but absent from the + # trace-validated export (e.g. its binary never ran): count + # all of its instrumented lines/branches as missed. + tv_lines += f_lines + tv_missed_lines += f_lines + if f_br_ok: + tv_branches += f_br + tv_missed_branches += f_br + else: + tv_branches_available = False + + if path not in merged_masks: + all_unique_files.append(path) + merged_masks[path] = None if included is None else set(included) + elif merged_masks[path] is not None: + if included is None: + merged_masks[path] = None + else: + merged_masks[path] |= included + + spec_loc, total_lean_loc = count_lean_package_loc( + repo_root / "lean" / mapping.name + ) + per_spec.append( + SpecMetrics( + name=mapping.name, + files=files, + missing_from_report=missing, + code_loc=code_loc, + spec_loc=spec_loc, + total_lean_loc=total_lean_loc, + lines=lines, + missed_lines=missed_lines, + branches=branches, + missed_branches=missed_branches, + masked=spec_is_masked, + branches_available=branches_available, + tv_lines=tv_lines, + tv_missed_lines=tv_missed_lines, + tv_branches=tv_branches, + tv_missed_branches=tv_missed_branches, + tv_available=tv_available, + tv_branches_available=tv_branches_available, + ) + ) + + total_code_loc = 0 + total_lines = total_missed_lines = total_branches = total_missed_branches = 0 + total_branches_available = True + total_missing: list[str] = [] + for path in all_unique_files: + included = merged_masks[path] + total_code_loc += cpp_loc(path, included) + f_lines, f_missed, f_br, f_br_missed, f_br_ok, present = _file_metrics( + path, included, by_path, detailed_coverage + ) + if not present: + total_missing.append(path) + else: + total_lines += f_lines + total_missed_lines += f_missed + if f_br_ok: + total_branches += f_br + total_missed_branches += f_br_missed + else: + total_branches_available = False + + # Because specs are disjoint, summing each spec's own trace-validated + # counts gives the exact aggregate trace-validated coverage. + total_tv_available = bool(per_spec) and all(m.tv_available for m in per_spec) + total_tv_branches_available = total_tv_available and all( + m.tv_branches_available for m in per_spec + ) + total_metrics = SpecMetrics( + name="Total (unique)", + files=all_unique_files, + missing_from_report=total_missing, + code_loc=total_code_loc, + spec_loc=sum(m.spec_loc for m in per_spec), + total_lean_loc=sum(m.total_lean_loc for m in per_spec), + lines=total_lines, + missed_lines=total_missed_lines, + branches=total_branches, + missed_branches=total_missed_branches, + masked=any(m.masked for m in per_spec), + branches_available=total_branches_available, + tv_lines=sum(m.tv_lines for m in per_spec) if total_tv_available else 0, + tv_missed_lines=( + sum(m.tv_missed_lines for m in per_spec) if total_tv_available else 0 + ), + tv_branches=( + sum(m.tv_branches for m in per_spec) if total_tv_branches_available else 0 + ), + tv_missed_branches=( + sum(m.tv_missed_branches for m in per_spec) + if total_tv_branches_available + else 0 + ), + tv_available=total_tv_available, + tv_branches_available=total_tv_branches_available, + ) + + common_dir = repo_root / "lean" / "common" + common_lean_loc = ( + count_lean_package_loc(common_dir)[1] if common_dir.is_dir() else 0 + ) + + return per_spec, total_metrics, common_lean_loc + + +def compute_removed_metrics( + repo_root: Path, + mappings: Sequence[SpecMapping], + coverage_files: Sequence[FileCoverage], + spec_masks: dict[str, dict[str, set[int]]], + detailed_coverage: dict[str, DetailedFileCoverage] | None, + trace_validated_coverage: dict[str, dict[str, DetailedFileCoverage]] | None = None, +) -> tuple[list[RemovedMetrics], RemovedMetrics]: + """Compute LoC and coverage over lines excluded by masks for each spec.""" + by_path: dict[str, FileCoverage] = {entry.path: entry for entry in coverage_files} + per_spec: list[RemovedMetrics] = [] + tot_files = 0 + tot_loc = tot_lines = tot_missed_lines = tot_br = tot_missed_br = 0 + tot_br_ok = True + + for mapping in mappings: + mask = spec_masks.get(mapping.name, {}) + tv_by_path = (trace_validated_coverage or {}).get(mapping.name) + masked_count = 0 + loc = lines = missed_lines = branches = missed_branches = 0 + branches_ok = True + tv_lines = tv_missed_lines = tv_branches = tv_missed_branches = 0 + tv_available = tv_by_path is not None + tv_branches_ok = tv_available + + for path in mapping.files: + included = mask.get(path) + if included is None: + continue + masked_count += 1 + text = (repo_root / path).read_text(encoding="utf-8") + num_lines = len(text.splitlines()) + excluded = set(range(1, num_lines + 1)) - included + loc += count_cpp_loc(text, excluded) + f_lines, f_missed, f_br, f_br_missed, f_br_ok, present = _file_metrics( + path, excluded, by_path, detailed_coverage + ) + if present: + lines += f_lines + missed_lines += f_missed + if f_br_ok: + branches += f_br + missed_branches += f_br_missed + else: + branches_ok = False + + if tv_by_path is not None: + tv_detail = _lookup_detailed_coverage(path, tv_by_path) + if tv_detail is not None: + tl, tml, tbr, tmbr, tbr_ok = _summarize_detailed( + tv_detail, excluded + ) + tv_lines += tl + tv_missed_lines += tml + if tbr_ok: + tv_branches += tbr + tv_missed_branches += tmbr + else: + tv_branches_ok = False + elif present: + tv_lines += f_lines + tv_missed_lines += f_lines + if f_br_ok: + tv_branches += f_br + tv_missed_branches += f_br + else: + tv_branches_ok = False + + per_spec.append( + RemovedMetrics( + name=mapping.name, + masked_files=masked_count, + code_loc=loc, + lines=lines, + missed_lines=missed_lines, + branches=branches, + missed_branches=missed_branches, + branches_available=branches_ok, + tv_lines=tv_lines, + tv_missed_lines=tv_missed_lines, + tv_branches=tv_branches, + tv_missed_branches=tv_missed_branches, + tv_available=tv_available, + tv_branches_available=tv_branches_ok, + ) + ) + tot_files += masked_count + tot_loc += loc + tot_lines += lines + tot_missed_lines += missed_lines + if branches_ok: + tot_br += branches + tot_missed_br += missed_branches + else: + tot_br_ok = False + + tot_tv_ok = bool(per_spec) and all(m.tv_available for m in per_spec) + tot_tv_br_ok = tot_tv_ok and all(m.tv_branches_available for m in per_spec) + total = RemovedMetrics( + name="Total", + masked_files=tot_files, + code_loc=tot_loc, + lines=tot_lines, + missed_lines=tot_missed_lines, + branches=tot_br, + missed_branches=tot_missed_br, + branches_available=tot_br_ok, + tv_lines=sum(m.tv_lines for m in per_spec) if tot_tv_ok else 0, + tv_missed_lines=sum(m.tv_missed_lines for m in per_spec) if tot_tv_ok else 0, + tv_branches=sum(m.tv_branches for m in per_spec) if tot_tv_br_ok else 0, + tv_missed_branches=( + sum(m.tv_missed_branches for m in per_spec) if tot_tv_br_ok else 0 + ), + tv_available=tot_tv_ok, + tv_branches_available=tot_tv_br_ok, + ) + return per_spec, total + + +def _format_two_level_table( + leading_headers: Sequence[str], + group_headers: Sequence[tuple[str, Sequence[str]]], + rows: Sequence[Sequence[str]], + right_align: Sequence[bool], + markdown: bool, + bold_last_row: bool = False, +) -> str: + """Render a table with a two-level column header. + + In Markdown mode, emits a GitHub-compatible HTML ```` using + ``rowspan="2"`` for ``leading_headers`` and ``colspan`` for each entry in + ``group_headers``. In text mode, emits an aligned two-row ASCII header. + """ + sub_headers = [ + *leading_headers, + *(col for _, cols in group_headers for col in cols), + ] + if markdown: + lines: list[str] = ["
", " ", " "] + for i, header in enumerate(leading_headers): + align = "right" if right_align[i] else "left" + lines.append(f' ') + for group_title, cols in group_headers: + lines.append( + f' ' + ) + lines.extend([" ", " "]) + col_idx = len(leading_headers) + for _, cols in group_headers: + for col in cols: + align = "right" if right_align[col_idx] else "left" + lines.append(f' ') + col_idx += 1 + lines.extend([" ", " ", " "]) + for r_idx, row in enumerate(rows): + is_bold = bold_last_row and r_idx == len(rows) - 1 + lines.append(" ") + for i, cell in enumerate(row): + align = "right" if right_align[i] else "left" + content = f"{cell}" if is_bold and i == 0 else cell + lines.append(f' ') + lines.append(" ") + lines.extend([" ", "
{header}{group_title}
{col}
{content}
"]) + return "\n".join(lines) + + widths = [len(h) for h in sub_headers] + for row in rows: + for i, cell in enumerate(row): + widths[i] = max(widths[i], len(cell)) + + # Ensure each grouped column span is wide enough for its top-level header. + col_idx = len(leading_headers) + for group_title, cols in group_headers: + span_width = sum(widths[col_idx : col_idx + len(cols)]) + 2 * (len(cols) - 1) + if len(group_title) > span_width: + widths[col_idx + len(cols) - 1] += len(group_title) - span_width + col_idx += len(cols) + + top_cells = [" " * widths[i] for i in range(len(leading_headers))] + col_idx = len(leading_headers) + for group_title, cols in group_headers: + span_width = sum(widths[col_idx : col_idx + len(cols)]) + 2 * (len(cols) - 1) + top_cells.append(group_title.center(span_width)) + col_idx += len(cols) + + def render_row(cells: Sequence[str]) -> str: + return " ".join( + cell.rjust(widths[i]) if right_align[i] else cell.ljust(widths[i]) + for i, cell in enumerate(cells) + ) + + out_lines = [ + " ".join(top_cells).rstrip(), + render_row(sub_headers), + " ".join("-" * w for w in widths), + ] + out_lines.extend(render_row(row) for row in rows) + return "\n".join(out_lines) + + +def render_report( + per_spec: Sequence[SpecMetrics], + total: SpecMetrics, + common_lean_loc: int, + source: ReportSource, + per_file: bool, + coverage_files: Sequence[FileCoverage], + repo_root: Path, + markdown: bool = True, + spec_masks: dict[str, dict[str, set[int]]] | None = None, + detailed_coverage: dict[str, DetailedFileCoverage] | None = None, + removed_per_spec: Sequence[RemovedMetrics] | None = None, + removed_total: RemovedMetrics | None = None, + trace_validated_coverage: dict[str, dict[str, DetailedFileCoverage]] | None = None, +) -> str: + leading_headers = [ + "Item", + "Files", + "Code LoC", + "Spec LoC", + "Total Lean LoC", + ] + group_headers = [ + ("Total", ["Line Cov", "Branch Cov"]), + ("Trace-validated", ["Line Cov", "Branch Cov"]), + ] + right_align = [False, True, True, True, True, True, True, True, True] + + rows: list[list[str]] = [] + for item in [*per_spec, total]: + name = item.name + if item.masked and item is not total: + name = f"{name} (masked)" + rows.append( + [ + name, + str(len(item.files)), + f"{item.code_loc:,}", + f"{item.spec_loc:,}", + f"{item.total_lean_loc:,}", + _format_percentage(item.line_coverage), + _format_percentage(item.branch_coverage), + _format_percentage(item.tv_line_coverage), + _format_percentage(item.tv_branch_coverage), + ] + ) + + out: list[str] = [ + _format_two_level_table( + leading_headers, + group_headers, + rows, + right_align, + markdown, + bold_last_row=True, + ) + ] + + detail_note = ( + f"; per-line/branch source: {source.detail_description}" + if source.detail_description + else "" + ) + tv_note = ( + f"; trace-validated source: {source.trace_validated_description}" + if source.trace_validated_description + else "" + ) + notes = [ + f"Coverage source: {source.description} (in-scope files{detail_note}{tv_note}).", + ( + "Code LoC counts non-blank, non-comment C/C++ lines; " + "Spec LoC counts non-blank, non-comment Lean lines in Model and Properties; " + "Total Lean LoC includes Proofs, TraceValidation/Replay, and Tests " + f"(shared lean/common adds {common_lean_loc:,} LoC)." + ), + ] + masked_specs = [m.name for m in per_spec if m.masked] + if masked_specs: + mask_files = ", ".join( + ( + f"`lean/{name}/coverage_mask.json`" + if markdown + else f"lean/{name}/coverage_mask.json" + ) + for name in masked_specs + ) + notes.append(f"Line-range masks applied: {mask_files}.") + if any(not m.branches_available for m in [*per_spec, total]): + notes.append( + "Masked branch coverage requires an llvm-cov JSON export " + f"(artifact `{EXPORT_JSON_ARTIFACT}` or --export-json); " + "rows with masked files show '-' for branches when only HTML line coverage is available." + ) + if any(not m.tv_available for m in per_spec): + notes.append( + "Trace-validated coverage requires per-spec llvm-cov JSON exports " + f"(artifact `{TRACE_VALIDATED_JSON_ARTIFACT}` or --trace-validated-dir); " + "rows without a trace-validated export show '-'." + ) + if total.missing_from_report: + missing_list = ", ".join( + f"`{p}`" if markdown else p for p in total.missing_from_report + ) + notes.append( + f"Mapped files absent from llvm-cov report (0 instrumented lines; counted in Code LoC): {missing_list}." + ) + + out.append("") + out.extend(notes) + + if removed_per_spec is not None and removed_total is not None: + rem_leading = ["Removed regions", "Masked Files", "Excluded LoC"] + rem_align = [False, True, True, True, True, True, True] + rem_rows: list[list[str]] = [] + for rem in [*removed_per_spec, removed_total]: + rem_rows.append( + [ + rem.name, + str(rem.masked_files), + f"{rem.code_loc:,}", + _format_percentage(rem.line_coverage), + _format_percentage(rem.branch_coverage), + _format_percentage(rem.tv_line_coverage), + _format_percentage(rem.tv_branch_coverage), + ] + ) + out.append("") + out.append( + _format_two_level_table( + rem_leading, + group_headers, + rem_rows, + rem_align, + markdown, + bold_last_row=True, + ) + ) + + if per_file: + by_path = {entry.path: entry for entry in coverage_files} + file_leading = ["Item", "File", "Code LoC"] + file_align = [False, False, True, True, True, True, True] + file_rows: list[list[str]] = [] + for item in per_spec: + mask = (spec_masks or {}).get(item.name, {}) + tv_by_path = (trace_validated_coverage or {}).get(item.name) + for path in item.files: + included = mask.get(path) + loc = count_cpp_loc( + (repo_root / path).read_text(encoding="utf-8"), included + ) + f_lines, f_missed, f_br, f_br_missed, f_br_ok, present = _file_metrics( + path, included, by_path, detailed_coverage + ) + if not present: + line_cov = "-" + branch_cov = "-" + else: + line_cov = _format_percentage(_percentage(f_lines, f_missed)) + branch_cov = ( + _format_percentage(_percentage(f_br, f_br_missed)) + if f_br_ok + else "-" + ) + tv_line_cov = "-" + tv_branch_cov = "-" + if tv_by_path is not None and present: + tv_detail = _lookup_detailed_coverage(path, tv_by_path) + if tv_detail is not None: + tl, tml, tbr, tmbr, tbr_ok = _summarize_detailed( + tv_detail, included + ) + tv_line_cov = _format_percentage(_percentage(tl, tml)) + tv_branch_cov = ( + _format_percentage(_percentage(tbr, tmbr)) + if tbr_ok + else "-" + ) + else: + tv_line_cov = _format_percentage(_percentage(f_lines, f_lines)) + tv_branch_cov = ( + _format_percentage(_percentage(f_br, f_br)) + if f_br_ok + else "-" + ) + file_label = f"{path}" if markdown else path + if included is not None: + file_label += " (masked)" + file_rows.append( + [ + item.name, + file_label, + f"{loc:,}", + line_cov, + branch_cov, + tv_line_cov, + tv_branch_cov, + ] + ) + out.append("") + out.append( + _format_two_level_table( + file_leading, + group_headers, + file_rows, + file_align, + markdown, + bold_last_row=False, + ) + ) + + return "\n".join(out) + + +def main(argv: Sequence[str] | None = None) -> int: + parser = argparse.ArgumentParser( + description=( + "Report CI line/branch coverage and code/spec LoC per Lean " + "specification from lean/COVERAGE_MAPPING.md." + ) + ) + parser.add_argument( + "--mapping", + default=DEFAULT_MAPPING, + help=f"Path to coverage mapping Markdown file (default: {DEFAULT_MAPPING}).", + ) + parser.add_argument( + "--repo", + default=DEFAULT_REPOSITORY, + help=f"GitHub repository to fetch artifacts from (default: {DEFAULT_REPOSITORY}).", + ) + parser.add_argument( + "--branch", + default=DEFAULT_BRANCH, + help=f"Branch whose coverage-history artifact to fetch (default: {DEFAULT_BRANCH}).", + ) + parser.add_argument( + "--run-id", + type=int, + default=None, + help="Specific GitHub Actions Coverage workflow run ID to download.", + ) + parser.add_argument( + "--report", + default=None, + help="Path to a local llvm-cov report file (skips GitHub artifact download).", + ) + parser.add_argument( + "--export-json", + default=None, + help=( + "Path to a local llvm-cov export JSON (.json or .json.gz) for " + "uniform per-line and deduplicated per-branch coverage." + ), + ) + parser.add_argument( + "--trace-validated-dir", + default=None, + help=( + "Directory containing per-spec trace-validated llvm-cov JSON exports " + "(.json.gz or .json)." + ), + ) + parser.add_argument( + "--html-dir", + default=None, + help=( + "Path to an extracted coverage-report-html directory for masked " + "line coverage." + ), + ) + parser.add_argument( + "--check-masks", + action="store_true", + help=( + "Validate lean/COVERAGE_MAPPING.md, all lean//coverage_mask.json " + "anchors and brace balance, and cross-spec disjointness, then exit." + ), + ) + parser.add_argument( + "--no-masks", + action="store_true", + help="Ignore lean//coverage_mask.json files and report whole-file numbers.", + ) + parser.add_argument( + "--show-removed", + action="store_true", + help="Also print a summary table of LoC and coverage over mask-excluded regions.", + ) + parser.add_argument( + "--per-file", + action="store_true", + help="Also print a per-file breakdown table.", + ) + parser.add_argument( + "--format", + choices=("markdown", "text"), + default="markdown", + help="Output table format (default: markdown).", + ) + args = parser.parse_args(argv) + + repo_root = Path(__file__).resolve().parent.parent + mapping_path = Path(args.mapping) + if not mapping_path.is_absolute(): + mapping_path = repo_root / mapping_path + + mappings = parse_coverage_mapping(mapping_path.read_text(encoding="utf-8")) + if not mappings: + print(f"No specification mappings found in {mapping_path}.", file=sys.stderr) + return 1 + + spec_masks: dict[str, dict[str, set[int]]] = {} + if not args.no_masks: + for mapping in mappings: + mask = load_spec_mask(repo_root, mapping.name, mapping.files) + if mask: + spec_masks[mapping.name] = mask + + validate_disjoint_specs(repo_root, mappings, spec_masks) + + if args.check_masks: + for mapping in mappings: + for rel_path in mapping.files: + if not (repo_root / rel_path).is_file(): + raise ValueError( + f"{mapping_path}: mapped file '{rel_path}' for " + f"'{mapping.name}' does not exist" + ) + print( + f"Validated {len(mappings)} specifications and " + f"{sum(len(m) for m in spec_masks.values())} masked files." + ) + return 0 + + all_mapped_files: list[str] = [] + for mapping in mappings: + for path in mapping.files: + if path not in all_mapped_files: + all_mapped_files.append(path) + + detailed_coverage: dict[str, DetailedFileCoverage] | None = None + detail_description: str | None = None + + if args.report is not None: + report_path = Path(args.report) + source = ReportSource( + text=report_path.read_text(encoding="utf-8", errors="replace"), + description=str(report_path), + ) + coverage_files = extract_file_coverage(source.text) + elif args.export_json is not None and args.run_id is None: + export_path = Path(args.export_json) + detailed_coverage = load_export_json(export_path) + detail_description = str(export_path) + source = ReportSource( + text="", + description=str(export_path), + detail_description=detail_description, + ) + coverage_files = [] + else: + source = fetch_ci_coverage_report(args.repo, args.branch, args.run_id) + coverage_files = extract_file_coverage(source.text) + + if detailed_coverage is None: + if args.export_json is not None: + export_path = Path(args.export_json) + detailed_coverage = load_export_json(export_path) + detail_description = str(export_path) + elif args.html_dir is not None: + html_path = Path(args.html_dir) + detailed_coverage = load_html_coverage_dir(html_path, all_mapped_files) + detail_description = str(html_path) + elif source.run_id is not None: + detailed_coverage, artifact_used = fetch_ci_detailed_coverage( + args.repo, source.run_id, all_mapped_files + ) + detail_description = f"artifact `{artifact_used}`" + + spec_names = [mapping.name for mapping in mappings] + trace_validated_coverage: dict[str, dict[str, DetailedFileCoverage]] = {} + tv_description: str | None = None + if args.trace_validated_dir is not None: + tv_dir = Path(args.trace_validated_dir) + trace_validated_coverage = load_trace_validated_dir(tv_dir, spec_names) + tv_description = str(tv_dir) + elif source.run_id is not None: + trace_validated_coverage, tv_artifact = fetch_ci_trace_validated_coverage( + args.repo, source.run_id, spec_names + ) + if tv_artifact is not None: + tv_description = f"artifact `{tv_artifact}`" + + if detail_description is not None and source.detail_description is None: + source = source._replace(detail_description=detail_description) + if tv_description is not None: + source = source._replace(trace_validated_description=tv_description) + + if not coverage_files and detailed_coverage is None: + print("No per-file coverage rows found in report.", file=sys.stderr) + return 1 + + per_spec, total, common_lean_loc = compute_metrics( + repo_root=repo_root, + mappings=mappings, + coverage_files=coverage_files, + spec_masks=spec_masks, + detailed_coverage=detailed_coverage, + trace_validated_coverage=trace_validated_coverage or None, + ) + + removed_per_spec = removed_total = None + if args.show_removed and spec_masks: + removed_per_spec, removed_total = compute_removed_metrics( + repo_root=repo_root, + mappings=mappings, + coverage_files=coverage_files, + spec_masks=spec_masks, + detailed_coverage=detailed_coverage, + trace_validated_coverage=trace_validated_coverage or None, + ) + + print( + render_report( + per_spec=per_spec, + total=total, + common_lean_loc=common_lean_loc, + source=source, + per_file=args.per_file, + coverage_files=coverage_files, + repo_root=repo_root, + markdown=(args.format == "markdown"), + spec_masks=spec_masks, + detailed_coverage=detailed_coverage, + removed_per_spec=removed_per_spec, + removed_total=removed_total, + trace_validated_coverage=trace_validated_coverage or None, + ) + ) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/scripts/tests/lean_coverage_report_test.py b/scripts/tests/lean_coverage_report_test.py new file mode 100755 index 000000000000..c8362d4a9ed3 --- /dev/null +++ b/scripts/tests/lean_coverage_report_test.py @@ -0,0 +1,513 @@ +#!/usr/bin/env python3 +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the Apache 2.0 License. + +import gzip +import json +import sys +import tempfile +import unittest +from pathlib import Path + +sys.path.insert(0, str(Path(__file__).parents[1])) +import coverage_summary +import lean_coverage_report + + +class LeanCoverageReportTest(unittest.TestCase): + def test_parse_coverage_mapping(self) -> None: + doc = """ +# Title + +## Alpha (`lean/alpha`) + +### In-scope implementation files + +- [`src/a/one.h`](../src/a/one.h): core file mentioning `src/ignored/in_prose.h`. +- [`src/a/two.cpp`](../src/a/two.cpp) and [`include/ccf/a.h`](../include/ccf/a.h): paired files. + +### Out-of-scope subsystems and abstractions + +- [`src/a/excluded.h`](../src/a/excluded.h): explicitly out of scope. +""" + mappings = lean_coverage_report.parse_coverage_mapping(doc) + self.assertEqual(len(mappings), 1) + self.assertEqual(mappings[0].name, "alpha") + self.assertEqual( + mappings[0].files, + ["src/a/one.h", "src/a/two.cpp", "include/ccf/a.h"], + ) + + def test_count_cpp_loc(self) -> None: + code = """ +// line comment +/* single line block */ +int x = 1; // trailing comment +/* multi-line + comment */ int y = 2; +const char* s = "// not a comment"; +const char* r = R"raw( +// still inside raw string +)raw"; + +""" + # Lines: int x, int y, const char* s, const char* r, // still..., )raw"; + self.assertEqual(lean_coverage_report.count_cpp_loc(code), 6) + + def test_count_lean_loc_nested_comments_and_chars(self) -> None: + code = """ +-- line comment +/- outer + /- nested -/ + still comment -/ +def f (x' : Char) : Bool := + x' == '"' -- char literal quote does not open string +/-- doc comment -/ +def g : Nat := 1 +""" + self.assertEqual(lean_coverage_report.count_lean_loc(code), 3) + + def test_compute_metrics_deduplicates_totals_and_tracks_missing(self) -> None: + with tempfile.TemporaryDirectory() as tmp: + root = Path(tmp) + (root / "src/a").mkdir(parents=True) + (root / "src/a/core.h").write_text("int a();\nint b();\n", encoding="utf-8") + (root / "src/a/types.h").write_text("struct T {};\n", encoding="utf-8") + (root / "lean/alpha/Alpha/Model").mkdir(parents=True) + (root / "lean/alpha/Alpha/Proofs").mkdir(parents=True) + (root / "lean/alpha/Alpha/Model.lean").write_text( + "def s := 1\n", encoding="utf-8" + ) + (root / "lean/alpha/Alpha/Model/Sub.lean").write_text( + "def t := 2\n", encoding="utf-8" + ) + (root / "lean/alpha/Alpha/Proofs/P.lean").write_text( + "theorem p : True := trivial\n", encoding="utf-8" + ) + (root / "lean/beta/Beta").mkdir(parents=True) + (root / "lean/beta/Beta/Properties.lean").write_text( + "theorem q : True := trivial\n", encoding="utf-8" + ) + + mappings = [ + lean_coverage_report.SpecMapping( + name="alpha", + files=["src/a/core.h", "src/a/types.h"], + ), + lean_coverage_report.SpecMapping( + name="beta", + files=["src/a/core.h"], + ), + ] + cov_files = [ + coverage_summary.FileCoverage( + path="src/a/core.h", + lines=10, + missed_lines=2, + branches=4, + missed_branches=1, + ) + ] + + per_spec, total, _ = lean_coverage_report.compute_metrics( + root, mappings, cov_files + ) + self.assertEqual(per_spec[0].code_loc, 3) + self.assertEqual(per_spec[0].spec_loc, 2) + self.assertEqual(per_spec[0].total_lean_loc, 3) + self.assertEqual(per_spec[0].missing_from_report, ["src/a/types.h"]) + # Total deduplicates src/a/core.h across alpha and beta. + self.assertEqual(total.code_loc, 3) + self.assertEqual(total.lines, 10) + self.assertEqual(total.missed_lines, 2) + self.assertEqual(total.branches, 4) + self.assertEqual(total.missed_branches, 1) + self.assertEqual(total.spec_loc, 3) + self.assertEqual(total.total_lean_loc, 4) + + def test_count_cpp_loc_with_mask_preserves_block_comment_state(self) -> None: + code = ( + "int keep_1 = 1;\n" + "/* comment starts in excluded range\n" + " still commented inside included range */\n" + "int keep_2 = 2;\n" + "int drop_me = 3;\n" + ) + # Include lines 1, 3, 4; exclude lines 2 and 5. + # Line 3 is still inside the block comment opened on excluded line 2. + self.assertEqual(lean_coverage_report.count_cpp_loc(code, {1, 3, 4}), 2) + + def test_load_spec_mask_and_anchor_drift(self) -> None: + with tempfile.TemporaryDirectory() as tmp: + root = Path(tmp) + (root / "src/kv").mkdir(parents=True) + (root / "lean/kv").mkdir(parents=True) + (root / "src/kv/a.h").write_text( + "int keep();\nvoid skip_me()\n{\n}\nint also_keep();\n", + encoding="utf-8", + ) + mask = { + "spec": "kv", + "files": { + "src/kv/a.h": { + "exclude": [ + { + "start": 2, + "end": 4, + "start_anchor": "void skip_me()", + "end_anchor": "}", + "reason": "unmodeled", + } + ] + } + }, + } + mask_path = root / "lean/kv/coverage_mask.json" + mask_path.write_text(json.dumps(mask), encoding="utf-8") + + loaded = lean_coverage_report.load_spec_mask(root, "kv", ["src/kv/a.h"]) + self.assertEqual(loaded, {"src/kv/a.h": {1, 5}}) + + # Anchor drift must raise ValueError. + mask["files"]["src/kv/a.h"]["exclude"][0]["start_anchor"] = "wrong()" + mask_path.write_text(json.dumps(mask), encoding="utf-8") + with self.assertRaises(ValueError): + lean_coverage_report.load_spec_mask(root, "kv", ["src/kv/a.h"]) + + # Weak punctuation-only start_anchor must raise ValueError. + (root / "src/kv/a.h").write_text( + "int keep();\n{\n int x = 1;\n}\nint also_keep();\n", + encoding="utf-8", + ) + mask["files"]["src/kv/a.h"]["exclude"][0]["start_anchor"] = "{" + mask_path.write_text(json.dumps(mask), encoding="utf-8") + with self.assertRaises(ValueError): + lean_coverage_report.load_spec_mask(root, "kv", ["src/kv/a.h"]) + + # Multi-line start_anchor with identifier context passes. + mask["files"]["src/kv/a.h"]["exclude"][0]["start_anchor"] = "{\nint x = 1;" + mask_path.write_text(json.dumps(mask), encoding="utf-8") + loaded_multi = lean_coverage_report.load_spec_mask( + root, "kv", ["src/kv/a.h"] + ) + self.assertEqual(loaded_multi, {"src/kv/a.h": {1, 5}}) + + # Unbalanced braces in range must raise ValueError. + mask["files"]["src/kv/a.h"]["exclude"][0]["end"] = 3 + mask["files"]["src/kv/a.h"]["exclude"][0]["end_anchor"] = "int x = 1;" + mask_path.write_text(json.dumps(mask), encoding="utf-8") + with self.assertRaises(ValueError): + lean_coverage_report.load_spec_mask(root, "kv", ["src/kv/a.h"]) + + def test_validate_disjoint_specs(self) -> None: + with tempfile.TemporaryDirectory() as tmp: + root = Path(tmp) + (root / "src/a").mkdir(parents=True) + (root / "src/a/f.h").write_text("int a;\nint b;\n", encoding="utf-8") + mappings = [ + lean_coverage_report.SpecMapping(name="s1", files=["src/a/f.h"]), + lean_coverage_report.SpecMapping(name="s2", files=["src/a/f.h"]), + ] + # Disjoint masks pass. + lean_coverage_report.validate_disjoint_specs( + root, + mappings, + {"s1": {"src/a/f.h": {1}}, "s2": {"src/a/f.h": {2}}}, + ) + # Overlapping masks fail. + with self.assertRaises(ValueError): + lean_coverage_report.validate_disjoint_specs( + root, + mappings, + {"s1": {"src/a/f.h": {1, 2}}, "s2": {"src/a/f.h": {2}}}, + ) + + def test_parse_html_ignores_nested_expansion_tables(self) -> None: + html = ( + "" + "" + "" + "" + "" + "" + "" + "
1
1.2k
int x;
2
0
"
+            ""
+            ""
+            ""
+            "
1
0
nested
" + ) + parsed = lean_coverage_report.parse_html_file_coverage(html) + self.assertEqual(parsed, {1: 1200, 2: 0}) + + def test_load_export_json_gz_and_masked_branches(self) -> None: + payload = { + "data": [ + { + "files": [ + { + "filename": "/__w/CCF/src/kv/a.h", + "segments": [ + [1, 1, 5, True, True, False], + [3, 1, 0, False, False, False], + [4, 1, 0, True, True, False], + [5, 1, 0, False, False, False], + ], + "branches": [ + [1, 5, 1, 10, 4, 1, 0, 0, 4], + # Duplicate instantiation of same branch location: + [1, 5, 1, 10, 0, 2, 0, 0, 4], + # Branch on excluded line 4: + [4, 5, 4, 10, 0, 0, 0, 0, 4], + ], + } + ] + } + ] + } + with tempfile.TemporaryDirectory() as tmp: + root = Path(tmp) + (root / "src/kv").mkdir(parents=True) + (root / "lean/kv/Kv").mkdir(parents=True) + (root / "src/kv/a.h").write_text( + "if (a) {}\nint b = 1;\n\nif (c) {}\n", encoding="utf-8" + ) + (root / "lean/kv/Kv/Model.lean").write_text( + "def x := 1\n", encoding="utf-8" + ) + + gz_path = root / "coverage.json.gz" + with gzip.open(gz_path, "wt", encoding="utf-8") as fh: + json.dump(payload, fh) + + details = lean_coverage_report.load_export_json(gz_path) + mappings = [ + lean_coverage_report.SpecMapping(name="kv", files=["src/kv/a.h"]) + ] + # Mask includes lines 1-3, excludes line 4. + per_spec, total, _ = lean_coverage_report.compute_metrics( + repo_root=root, + mappings=mappings, + coverage_files=[], + spec_masks={"kv": {"src/kv/a.h": {1, 2, 3}}}, + detailed_coverage=details, + ) + kv = per_spec[0] + self.assertTrue(kv.masked) + self.assertTrue(kv.branches_available) + self.assertEqual(kv.code_loc, 2) + # Lines 1 and 2 are covered (count 5); line 3 ends region at col 1; line 4 excluded. + self.assertEqual((kv.lines, kv.missed_lines), (2, 0)) + # Only the deduplicated branch on line 1 is included: both true (4) and false (2) hit. + self.assertEqual((kv.branches, kv.missed_branches), (2, 0)) + self.assertEqual((total.lines, total.branches), (2, 2)) + + rem_per_spec, rem_total = lean_coverage_report.compute_removed_metrics( + repo_root=root, + mappings=mappings, + coverage_files=[], + spec_masks={"kv": {"src/kv/a.h": {1, 2, 3}}}, + detailed_coverage=details, + ) + self.assertEqual(rem_per_spec[0].code_loc, 1) + self.assertEqual( + (rem_per_spec[0].lines, rem_per_spec[0].missed_lines), (1, 1) + ) + self.assertEqual( + (rem_per_spec[0].branches, rem_per_spec[0].missed_branches), (2, 2) + ) + self.assertEqual((rem_total.lines, rem_total.branches), (1, 2)) + + def test_trace_validated_coverage_and_two_level_table(self) -> None: + full_payload = { + "data": [ + { + "files": [ + { + "filename": "/__w/CCF/src/kv/a.h", + "segments": [ + [1, 1, 5, True, True, False], + [3, 1, 0, False, False, False], + ], + "branches": [[1, 5, 1, 10, 4, 1, 0, 0, 4]], + }, + { + "filename": "/__w/CCF/src/kv/b.h", + "segments": [ + [1, 1, 3, True, True, False], + [2, 1, 0, False, False, False], + ], + "branches": [[1, 5, 1, 10, 2, 1, 0, 0, 4]], + }, + ] + } + ] + } + # Trace-validated run covers only line 1 of a.h (one branch arm hit) + # and does not execute b.h at all. + tv_payload = { + "data": [ + { + "files": [ + { + "filename": "/__w/CCF/src/kv/a.h", + "segments": [ + [1, 1, 2, True, True, False], + [2, 1, 0, True, True, False], + [3, 1, 0, False, False, False], + ], + "branches": [[1, 5, 1, 10, 2, 0, 0, 0, 4]], + } + ] + } + ] + } + with tempfile.TemporaryDirectory() as tmp: + root = Path(tmp) + (root / "src/kv").mkdir(parents=True) + (root / "lean/kv/Kv").mkdir(parents=True) + (root / "tv").mkdir() + (root / "src/kv/a.h").write_text( + "if (a) {}\nint x = 1;\n", encoding="utf-8" + ) + (root / "src/kv/b.h").write_text("if (b) {}\n", encoding="utf-8") + (root / "lean/kv/Kv/Model.lean").write_text( + "def x := 1\n", encoding="utf-8" + ) + with gzip.open(root / "tv/kv.json.gz", "wt", encoding="utf-8") as fh: + json.dump(tv_payload, fh) + + full_details = lean_coverage_report.parse_llvm_cov_export_json(full_payload) + tv_by_spec = lean_coverage_report.load_trace_validated_dir( + root / "tv", ["kv"] + ) + mappings = [ + lean_coverage_report.SpecMapping( + name="kv", files=["src/kv/a.h", "src/kv/b.h"] + ) + ] + per_spec, total, common_loc = lean_coverage_report.compute_metrics( + repo_root=root, + mappings=mappings, + coverage_files=[], + detailed_coverage=full_details, + trace_validated_coverage=tv_by_spec, + ) + kv = per_spec[0] + self.assertTrue(kv.tv_available) + self.assertTrue(kv.tv_branches_available) + # Total: 3/3 lines (100%), 4/4 branches (100%). + self.assertEqual((kv.lines, kv.missed_lines), (3, 0)) + self.assertEqual((kv.branches, kv.missed_branches), (4, 0)) + # Trace-validated: 1/3 lines (a.h:1 hit, a.h:2 missed, b.h:1 absent->missed) + # and 1/4 branches (a.h true hit, false missed; b.h absent->2 missed). + self.assertEqual((kv.tv_lines, kv.tv_missed_lines), (3, 2)) + self.assertEqual((kv.tv_branches, kv.tv_missed_branches), (4, 3)) + self.assertEqual((total.tv_lines, total.tv_missed_lines), (3, 2)) + self.assertEqual((total.tv_branches, total.tv_missed_branches), (4, 3)) + + source = lean_coverage_report.ReportSource(text="", description="unit-test") + md_out = lean_coverage_report.render_report( + per_spec=per_spec, + total=total, + common_lean_loc=common_loc, + source=source, + per_file=False, + coverage_files=[], + repo_root=root, + markdown=True, + detailed_coverage=full_details, + trace_validated_coverage=tv_by_spec, + ) + self.assertIn('Total', md_out) + self.assertIn('Trace-validated', md_out) + self.assertNotIn("Lines (Hit/Total)", md_out) + self.assertNotIn("Branches (Hit/Total)", md_out) + self.assertIn("33.33%", md_out) + self.assertIn("25.00%", md_out) + + txt_out = lean_coverage_report.render_report( + per_spec=per_spec, + total=total, + common_lean_loc=common_loc, + source=source, + per_file=False, + coverage_files=[], + repo_root=root, + markdown=False, + detailed_coverage=full_details, + trace_validated_coverage=tv_by_spec, + ) + self.assertIn("Total", txt_out) + self.assertIn("Trace-validated", txt_out) + self.assertIn("33.33%", txt_out) + + def test_repo_coverage_masks_are_valid(self) -> None: + repo_root = Path(__file__).resolve().parents[2] + mappings = lean_coverage_report.parse_coverage_mapping( + (repo_root / "lean/COVERAGE_MAPPING.md").read_text(encoding="utf-8") + ) + expected_masked_files = { + "consensus": { + "src/consensus/aft/cft.h", + "src/consensus/aft/impl/state.h", + "src/consensus/aft/cft_types.h", + "src/node/hooks.h", + }, + "consistency": { + "src/endpoints/base_endpoint_registry.cpp", + "src/endpoints/common_endpoint_registry.cpp", + "src/endpoints/endpoint_registry.cpp", + "src/node/rpc/frontend.h", + }, + "disaster-recovery": { + "src/node/recovery_decision_protocol.cpp", + "src/node/recovery_decision_protocol.h", + "src/node/rpc/self_healing_open_handlers.h", + }, + "kv": { + "src/kv/store.h", + "src/kv/untyped_map.h", + "src/kv/untyped_change_set.h", + "src/kv/untyped_map_handle.cpp", + "src/kv/apply_changes.h", + "src/kv/tx.cpp", + "src/kv/tx_pimpl.h", + "include/ccf/kv/tx.h", + "src/kv/committable_tx.h", + }, + } + self.assertEqual({m.name for m in mappings}, set(expected_masked_files.keys())) + all_masks: dict[str, dict[str, set[int]]] = {} + for mapping in mappings: + loaded = lean_coverage_report.load_spec_mask( + repo_root, mapping.name, mapping.files + ) + self.assertEqual( + set(loaded.keys()), + expected_masked_files[mapping.name], + msg=f"Unexpected masked files for {mapping.name}", + ) + all_masks[mapping.name] = loaded + lean_coverage_report.validate_disjoint_specs(repo_root, mappings, all_masks) + + def test_check_masks_cli_succeeds(self) -> None: + self.assertEqual(lean_coverage_report.main(["--check-masks"]), 0) + + def test_check_masks_cli_rejects_missing_mapped_file(self) -> None: + with tempfile.TemporaryDirectory() as tmp: + mapping_path = Path(tmp) / "COVERAGE_MAPPING.md" + mapping_path.write_text( + "## Alpha (`lean/alpha`)\n\n" + "### In-scope implementation files\n\n" + "- [`src/does/not/exist.h`](../src/does/not/exist.h): missing.\n", + encoding="utf-8", + ) + with self.assertRaises(FileNotFoundError): + lean_coverage_report.main( + ["--check-masks", "--mapping", str(mapping_path)] + ) + + +if __name__ == "__main__": + unittest.main()