diff --git a/changelog.d/1585-gate-battery-shared-adoption-apis.added.md b/changelog.d/1585-gate-battery-shared-adoption-apis.added.md new file mode 100644 index 0000000000..f596fa9f2c --- /dev/null +++ b/changelog.d/1585-gate-battery-shared-adoption-apis.added.md @@ -0,0 +1 @@ +The gate battery gains the shared pieces a country needs to adopt it tool by tool: stage-level evaluation (`evaluate_entries`, `blocking_outcomes` and `assemble_phase_report`), the UK's scoping and re-minting binding lifted into shared code (`scoped_gate_manifest` and `EvaluatorBinding`), and a narrow `load_gates_manifest` with a per-country `country_resource` (microcosm#1585 item 11). diff --git a/changelog.d/1585-uk-exact-k-checker-synthetic-smoke.fixed.md b/changelog.d/1585-uk-exact-k-checker-synthetic-smoke.fixed.md new file mode 100644 index 0000000000..4f9038ba24 --- /dev/null +++ b/changelog.d/1585-uk-exact-k-checker-synthetic-smoke.fixed.md @@ -0,0 +1 @@ +The exact-k UK schema-4 gate-report checker now accepts the `synthetic_smoke` field the executor writes into every report's body and attestation, which made it refuse every report the executor writes, and requires that field to be false (microcosm#1585 item 11). diff --git a/docs/gate-battery-contract.md b/docs/gate-battery-contract.md index b8ffb08f7d..26a055f8bd 100644 --- a/docs/gate-battery-contract.md +++ b/docs/gate-battery-contract.md @@ -17,13 +17,15 @@ split: - **Batched within a phase, fail-closed at the phase boundary.** Every gate bound to a phase evaluates — a raising evaluator becomes a failed result, never a crash that masks the remaining gates — and the build - decides at the boundary, not per gate. + decides at the boundary, not per gate. A build that gates stage by stage + decides at the stage, by the same rule (see + [outcomes and blocking](#outcomes-and-blocking)). - **Write-then-block.** The full report, including the block itself, is on disk before `enforce` raises. A blocked build always leaves evidence. - **Every declared gate has exactly one outcome.** Nothing is omitted: evidence that does not exist is a named gap (`evidence_absent`), a - reviewed non-selection is a receipt (`not_applicable`), and entries - after a blocked phase are `unreached`. Silence is not in the vocabulary. + reviewed non-selection is a receipt (`not_applicable`), and entries a + block left behind are `unreached`. Silence is not in the vocabulary. ## Declaring gates: `gates.json` @@ -31,7 +33,10 @@ A country's gate policy is one JSON resource, `/gates.json`, inside its spec-only country package. It must be listed in `/country_package.json` `resources` — `load_country_spec` refuses undeclared files on disk and missing declared ones — and it is parsed and -validated by canonical filename into `CountrySpec.gates`. +validated by canonical filename into `CountrySpec.gates`. A tool that needs +only its gate policy reads it with `load_gates_manifest("")`, which +parses and validates `gates.json` alone, with no bundle load or file-closure +check, and returns the manifest `load_country_spec("").gates` returns. The header: @@ -52,6 +57,8 @@ Each entry in `gates`: | `criticality` | `release_blocking` or `diagnostic`. At least one entry must be release-blocking — a country whose every gate is diagnostic has no release contract. | | `parameters` | Declarative gate inputs: tolerances, surfaces, exclusion registers, reference pins. Pure data, recursively frozen at load (mappings become read-only proxies, lists become tuples). Thresholds live *here*, covered by the policy hash — never in runner code. | | `not_applicable` | Reviewed reason this gate deliberately does not run for this country. Mutually exclusive with a non-empty `parameters`; the entry appears in every report as `not_applicable` and never evaluates. | +| `evidence_absent_blocks` | `true` makes an `evidence_absent` outcome block every posture, not only release candidates (see [outcomes and blocking](#outcomes-and-blocking)). Mutually exclusive with `not_applicable`. | +| `population_fact_check` | `true` marks a gate that checks the frame against published population statistics. A synthetic smoke build records its failure without blocking on it; every other posture blocks. | | `notes` | Free-text rationale and provenance. | Entry validation is closed-world: an unknown key is refused, not ignored, @@ -82,8 +89,9 @@ shaped like a dotted entry point. Name parameters accordingly. Three digests pin the declaration, all carried in every report: - `policy_sha256` — over each entry's `id`/`gate`/`phase`/`criticality`/ - `parameters`/`not_applicable`, sorted by id. **Excludes `notes`**: - editing rationale does not move gate policy. + `parameters`/`not_applicable`, and `evidence_absent_blocks` when it is + true, sorted by id. **Excludes `notes`**: editing rationale does not move + gate policy. - `gates_manifest_sha256` — over the full manifest including `notes` and the phase order. - `spec_fingerprint` — the composition fingerprint of `gates.json` only. @@ -91,6 +99,9 @@ Three digests pin the declaration, all carried in every report: resources do not. Anything pinning it must be regenerated in the same change. +`population_fact_check` is in neither digest. It changes only the synthetic +smoke posture, which can never be a release candidate. + ## Supplying evidence: `EvidenceContext` and bindings Gates read evidence through an `EvidenceContext`, built by the country's @@ -116,6 +127,17 @@ add or override bindings. A declared gate with no binding in the active registry is a named `evidence_absent` gap — an incomplete registry cannot manufacture a pass. +Two binding classes are shared. `FunctionBinding` routes declared parameters +into a pure gate function's keyword arguments. `EvaluatorBinding` hands a +country evaluator the whole `(context, parameters)` pair, may choose its +artifacts and its need for a frame from the parameters, and re-mints a gate +written before the battery: the executor fails any result whose name differs +from the declared gate, so `legacy_name` names the one other name the +evaluator may return, and that result is re-minted under the declared name. +The UK's `UKGateBinding` is an alias of it. A binding reads the packaged +registers its declared `*_resource` parameters name with +`country_resource("", name)`. + Canonical artifact keys: | key | supplied by | consumed by | @@ -145,9 +167,9 @@ UK-flavored result names of the legacy evaluators onto the shared vocabulary. Every verdict is computed by the existing UK gate functions — a binding adapts evidence; it never re-implements a comparison. The differential test -(`tests/test_uk_battery_bindings.py`) holds the battery's verdicts equal -to the incumbent UK battery's, failure line for failure line, over -identical evidence. +(`packages/microcosm-build/tests/engine_free/uk/test_uk_battery_bindings.py`) +holds the battery's verdicts equal to the incumbent UK battery's, failure +line for failure line, over identical evidence. ## Outcomes and blocking @@ -159,7 +181,7 @@ Five statuses, one per declared entry per report: | `failed` | Evaluated and failed — including evaluator crashes, wrong-name results, and unattestable evidence, all failed closed. | | `evidence_absent` | Declared, but a required artifact, frame, or binding was missing; the gap is named. | | `not_applicable` | Declared with a reviewed reason not to run. Reported even if its phase never ran. | -| `unreached` | Its phase never ran because an earlier phase blocked. | +| `unreached` | Its phase never ran because an earlier phase blocked, or, in a phase evaluated stage by stage, an earlier stage of the same phase blocked before this entry's stage ran. Its reason then names the entry that blocked, and `blocked_at_phase` is that phase. An entry the run itself evaluated at its stage is never `unreached`. | `passed` and `not_applicable` are the only shippable statuses. @@ -176,6 +198,10 @@ Blocking is a two-axis decision at each phase boundary: `input_mass_parity` entry deliberately does not: missing licensed reference totals record `evidence_absent`, and that gap blocks release candidates through the normal posture rule. +- A synthetic smoke build (`synthetic_smoke=True`) runs on a fixture, not + the population. It can never be a release candidate, its report and + attestation say so, and a failed entry declaring `population_fact_check` + does not block it. The battery run (`GateBatteryRun`) executes phases in declared order: `run_phase` evaluates the batch and persists the full report atomically @@ -185,7 +211,55 @@ written downstream of a block) or returns the verdict while the artifact is written and marked (`MARKS_ARTIFACT` — intermediates: an artifact with a failed gate can be worth keeping; it just is not ready). Once a phase blocks, later phases refuse to run and their entries stay `unreached` — -which is the truth. +which is the truth — except an entry the run had already evaluated at its +stage, which keeps that outcome (below). + +A phase evaluated somewhere else is recorded, not re-run. +`gate_phase_report_payload` turns a phase report into plain data bound to the +manifest digest, `gate_phase_report_from_payload` checks it against the +current manifest, and `record_phase` persists it through the same +write-then-block boundary as `run_phase` without running an evaluator. The UK +graph replays its stored phase reports this way, and the transport graph's +`gates.battery@1` kernel (`microcosm.build.transport.gate_kernels`) runs one +phase of any country's `gates.json` as a graph gate node, whose report +artifact carries that payload. + +A build may also evaluate a phase's gates where each one's evidence appears +instead of in one batch at the boundary, which keeps it failing fast and gives +each gate its own stage's evidence. The run's `evaluate_entries` resolves +named entries exactly as the batch would, once each and with the run's +registry (the module-level `evaluate_entries` takes the registry explicitly +and has no default), `blocking_outcomes` says whether they stop the build +under its posture, and `assemble_phase_report` gathers the phase's outcomes +into its report in manifest order, refusing a missing or duplicate entry. A +build that stopped at a blocking stage names that entry in `blocked_by`, with +the run's posture (`release_candidate`, `synthetic_smoke`), since the posture +decides which outcomes block; the named entry must be among +`blocking_outcomes` under it. It also names in `unreached` the entries whose +stages never ran. Those become `unreached`, with a reason naming the blocker, +and any other entry without an outcome is still refused. `record_phase` takes +such a phase only if the named entry blocks under the run's own posture, +recording `blocked_at_phase` in the same write. The run keeps the outcome of +each entry it evaluates at a stage, and refuses a second `evaluate_entries` +for that entry and a `run_phase` for its phase. Until that entry's phase is +recorded, the report carries the outcome in place of `unreached`, so a block +in an earlier phase cannot sign the gate as never reached; the outcome counts +toward `shippable` only once its phase is recorded. `record_phase` refuses a +phase that marks one of those entries `unreached` or carries another outcome +for it. Outcomes are compared by content, so the same outcomes carried +through a phase payload and back still record. These checks see only the +run's own stages: for an entry the run did not evaluate, such as one in a +phase carried in from another process, it has no outcome of its own to +compare. A signed run can then be assembled at the end, from phases carried +between stages or processes. Stage-assembled phases are for `GateBatteryRun` +only for now. The transport kernel evaluates each phase in one batch, so +there `unreached` still means only that an earlier phase blocked, and its +report check refuses a phase that stopped part way. + +A posture that must keep going past failed gates, such as an evidence build +or a dry run, runs every phase and never calls `enforce`. Every phase is +recorded, nothing is marked blocked, and the report stays unshippable while a +release-blocking entry has not passed. The report is signed (HMAC-SHA256) with a per-country key; the signature is valid over failed reports — a blocked build's evidence is still @@ -218,20 +292,20 @@ too. `enforce(..., BLOCKS_ARTIFACT)` raises only after the report — with and the schema-versioned body and attestation — is on disk. The other two statuses are exercised in -`tests/test_gate_battery.py::TestOutcomeTaxonomy`, which reaches all five -in one report. +`packages/microcosm-build/tests/engine_free/shared/test_gate_battery.py::TestOutcomeTaxonomy`, +which reaches all five in one report. ## Two postures, one executor -The two country specs in the tree show how far the same executor -stretches on declaration alone: +BE, AM and NZ declare only the `terminal` phase. Two of the country specs in +the tree show how far the same executor stretches on declaration alone: | | BE | UK | | --- | --- | --- | | phases | `terminal` | `preflight`, `assembled`, `transferred`, `terminal` | -| entries | 9 | 73 (64 national-build entries, 7 local-candidate entries and 2 local diagnostics) | +| entries | 9 | 94 (85 national-line entries, 7 local-candidate entries and 2 local diagnostics) | | incumbent posture | none — incumbent-comparison gates deliberately not selected; external oracles replace self-parity | full — export surface, input coverage and input mass against the current build of the cut's own line (microcosm#1095; until then the pinned enhanced-FRS incumbent) | -| criticality mix | 8 blocking + 1 diagnostic | 71 blocking + 2 local diagnostics | +| criticality mix | 8 blocking + 1 diagnostic | 92 blocking + 2 local diagnostics | The differences are entirely in the two country inputs — the spec file and the registry — which is the point. The UK national build is the @@ -241,13 +315,19 @@ frame loads, terminal immediately before the staging writer), while BE remains spec-only. UK evaluates the declaration through four producer scopes: spine, -calibration seam, national release cut, and local candidate. The first three -compose the national release certification. The seven local-candidate entries -are explicitly classified as excluded from that certification until the +calibration seam, national release cut, and local candidate. One +`GateBatteryRun` runs one manifest, each phase once and in order, so each +scope is a manifest of its own, built by the shared `scoped_gate_manifest` +(`uk_scoped_gate_manifest` supplies the UK spec), with its own pinned digests. +The first three compose the national release certification. The seven +local-candidate entries are explicitly classified as excluded from that +certification until the local publication work in #146; they are evaluated in their own signed `local_candidate` report rather than silently disappearing from union accounting. +US adoption is in progress (microcosm#1585 item 11). + ## The reference rule A parity gate is only as honest as its reference: comparing a calibrated @@ -278,19 +358,28 @@ enhanced FRS, through a closed registry of named identities with 1. **The spec**: `/gates.json` (header, phase order, entries per the anatomy above), listed in `/country_package.json` `resources`. - Loaded via `load_country_spec("").gates`; nothing else is needed - for the spec to reach the battery. + Loaded via `load_country_spec("").gates`, or alone via + `load_gates_manifest("")`; nothing else is needed for the spec to + reach the battery. A country whose build tools each gate part of the + spec gives each tool its own scope (`scoped_gate_manifest`), each pinned + separately. 2. **A registry**, if `DEFAULT_REGISTRY` does not already bind every - selected gate: bindings implementing the `GateBinding` protocol, - passed as `GateBatteryRun(..., registry=...)`. Unbound declared gates - are named gaps, so a country can land its spec before its bindings. + selected gate: bindings implementing the `GateBinding` protocol + (`FunctionBinding` over a pure gate function, `EvaluatorBinding` over a + country evaluator), passed as `GateBatteryRun(..., registry=...)`. A build + that gates stage by stage evaluates through the run + (`run.evaluate_entries`), so its stages use the same registry and the run + keeps the outcome each one produced. + Unbound declared gates are named gaps, so a country can land its spec + before its bindings. 3. **Runtime artifacts**, under the canonical keys each selected gate's binding declares (table above). Missing artifacts are named gaps that block release candidates only. 4. **A `Frame`** at every phase whose gates read one; preflight-style phases may run frameless. -5. **Run identity**: `release_id`, `release_candidate`, and a - `report_path` for the atomically-written report. +5. **Run identity**: `release_id`, `release_candidate` (and + `synthetic_smoke` for a build on a fixture), and a `report_path` for the + atomically-written report. 6. **The signing key**: `gate_signing_key_env("")` names the variable — `MICROCOSM__TERMINAL_GATE_SIGNING_KEY`, base64, exactly 32 decoded bytes. diff --git a/packages/microcosm-build/src/microcosm/build/country_spec.py b/packages/microcosm-build/src/microcosm/build/country_spec.py index 894f554c40..26cf98a6b0 100644 --- a/packages/microcosm-build/src/microcosm/build/country_spec.py +++ b/packages/microcosm-build/src/microcosm/build/country_spec.py @@ -41,6 +41,7 @@ from dataclasses import dataclass, field from functools import cache from importlib import resources as importlib_resources +from importlib.resources.abc import Traversable from pathlib import Path, PurePosixPath from types import MappingProxyType from typing import Any @@ -73,9 +74,11 @@ "GeographySpineSpec", "ReleaseContractManifest", "ResolvedCountrySpec", + "country_resource", "country_stage_plan", "load_country_take_up_contract_projection", "load_country_spec", + "load_gates_manifest", ] #: Resource kinds admitted by the binding ``resource_manifest.schema.json``. @@ -2157,6 +2160,99 @@ def load_normalized(row: CountryResourceRow) -> Mapping[str, Any]: return projection +def country_resource(country: str, name: str) -> Traversable: + """The packaged resource ``name`` of ``country``'s spec package. + + ``microcosm/build//``, read through + :mod:`importlib.resources` so it resolves the same from a wheel as from + the source tree. It reads no ``country_package.json``: the closed resource + inventory is :func:`load_country_spec`'s to enforce. Bindings read the + registers their declared ``*_resource`` parameters name through here. + + Raises: + ValueError: If ``country`` is not a lowercase ASCII country code. + """ + + if not (country.isascii() and country.isalpha() and country.islower()): + raise ValueError( + f"country must be a lowercase ASCII country code, got {country!r}." + ) + return importlib_resources.files(f"microcosm.build.{country}").joinpath(name) + + +def load_gates_manifest(country: str | Path) -> GatesManifest: + """Load and validate only the country's ``gates.json``. + + The narrow seam for a build tool that needs its gate policy and nothing + else, as the US tools will (microcosm#1585 item 11). Like + :func:`load_country_take_up_contract_projection`, it reads + ``country_package.json`` only to find the declared row, then parses that + one file with the validator :func:`load_country_spec` uses + (:meth:`GatesManifest.from_mapping`). It runs no bundle load, file-closure + check or validation of any other resource, so an edit elsewhere in the + package cannot break a tool's gates, and it returns the manifest + ``load_country_spec(country).gates`` returns. + + Args: + country: A country code (resolved inside ``microcosm.build``) or a + path to a country package directory. + + Raises: + FileNotFoundError: If the package or its declared ``gates.json`` is + missing. + ValueError: If the package declares no ``legacy_json`` ``gates.json`` + row, the file resolves outside the package or is not a file + holding a JSON mapping, or the manifest is malformed. + """ + + if isinstance(country, Path): + root = country + else: + root = Path(str(importlib_resources.files("microcosm.build").joinpath(country))) + package_path = root / "country_package.json" + if not package_path.exists(): + raise FileNotFoundError(f"No country package at {package_path}.") + package = _require_mapping( + json.loads(package_path.read_text(encoding="utf-8")), + context="country_package.json", + ) + declared_country = _require_non_empty_string( + package.get("country"), field_name="country", context="country_package.json" + ) + if declared_country != root.name: + raise ValueError( + f"country_package.json declares country {declared_country!r} but " + f"lives in directory {root.name!r}." + ) + rows = [ + row + for row in _resolve_country_resource_rows(package.get("resources", [])) + if row.path == "gates.json" + ] + if not rows or rows[0].kind != "legacy_json": + raise ValueError( + f"{root.name}: country_package.json declares no legacy_json " + "gates.json resource." + ) + # The same checks, in the same order, as the full loader's resource loop. + resource_path = _country_resource_path(root, "gates.json") + if not resource_path.exists(): + raise FileNotFoundError( + f"{root.name}: declared resource 'gates.json' is missing." + ) + if not resource_path.resolve().is_relative_to(root.resolve()): + raise ValueError( + f"{root.name}: declared resource 'gates.json' resolves outside the " + "country package." + ) + if not resource_path.is_file(): + raise ValueError(f"{root.name}: declared resource 'gates.json' is not a file.") + payload = _require_mapping( + json.loads(resource_path.read_text(encoding="utf-8")), context="gates.json" + ) + return GatesManifest.from_mapping(payload, country=declared_country) + + def load_country_spec(country: str | Path) -> ResolvedCountrySpec: """Load and validate the ``country`` package. diff --git a/packages/microcosm-build/src/microcosm/build/gate_battery.py b/packages/microcosm-build/src/microcosm/build/gate_battery.py index bddda6c93a..fd955d140c 100644 --- a/packages/microcosm-build/src/microcosm/build/gate_battery.py +++ b/packages/microcosm-build/src/microcosm/build/gate_battery.py @@ -26,10 +26,24 @@ - **Every declared gate has exactly one outcome.** ``passed`` / ``failed`` / ``not_applicable`` (a reviewed reason declared in the spec) / ``evidence_absent`` (no implementation or missing evidence — a named gap, - never a silent omission) / ``unreached`` (an earlier phase blocked first). - Conflating ``unreached`` with ``not_applicable`` is the failure mode the - battery exists to prevent, so the report carries ``phases_evaluated`` and - ``blocked_at_phase`` and the attestation covers both. + never a silent omission) / ``unreached`` (an earlier phase blocked first, + or, in a phase assembled from stage-level outcomes, an earlier stage of the + same phase blocked first; such an entry's reason names the entry that + blocked). Conflating ``unreached`` with ``not_applicable`` is the failure + mode the battery exists to prevent, so the report carries + ``phases_evaluated`` and ``blocked_at_phase`` and the attestation covers + both. + +A build may also evaluate a phase's gates at the stages where its evidence +appears, rather than in one batch at the boundary: +:meth:`GateBatteryRun.evaluate_entries` resolves named entries exactly as the +batch would, once each and with the run's registry, :func:`blocking_outcomes` +says whether they stop the build under its posture, and +:func:`assemble_phase_report` gathers them into the phase's +:class:`GatePhaseReport`, which :meth:`GateBatteryRun.record_phase` persists +through the same write-then-block boundary. That keeps fail-fast, gives each +gate its own stage's evidence, and lets the signed run be assembled at the end +(microcosm#1585 item 11). The gate *comparisons* stay in :mod:`microcosm.build.gates` — pure functions from evidence to :class:`~microcosm.build.gates.GateResult`, shared across @@ -48,8 +62,15 @@ import hmac import json import os -from collections.abc import Callable, Iterator, Mapping, Sequence -from dataclasses import dataclass, field +from collections.abc import ( + Callable, + Collection, + Iterable, + Iterator, + Mapping, + Sequence, +) +from dataclasses import dataclass, field, replace from pathlib import Path from typing import Any, Protocol @@ -68,6 +89,7 @@ __all__ = [ "BlockingMode", "DEFAULT_REGISTRY", + "EvaluatorBinding", "EvidenceContext", "FunctionBinding", "GATE_BATTERY_ATTESTATION_SCHEMA_VERSION", @@ -81,10 +103,14 @@ "GateOutcome", "GatePhaseReport", "GateStatus", + "assemble_phase_report", + "blocking_outcomes", + "evaluate_entries", "evaluate_phase", "gate_phase_report_from_payload", "gate_phase_report_payload", "gate_signing_key_env", + "scoped_gate_manifest", ] #: Continues the ``terminal_gates.json`` numbering: schema 3 is the UK-only @@ -349,6 +375,87 @@ def evidence_payload( return self.evidence(context, parameters) +@dataclass(frozen=True) +class EvaluatorBinding: + """A :class:`GateBinding` over a country runtime evaluator. + + Where :class:`FunctionBinding` routes declared parameters into a pure gate + function's keyword arguments, this binding hands its evaluator the whole + ``(context, parameters)`` pair, so a country runtime adapts its own + evidence and builds its own reviewed policy objects. It also re-mints + names. A gate written before the battery mints its own country-flavoured + result name, and the executor fails any result whose name differs from + the declared one, so ``legacy_name`` names the one other name the + evaluator may return, and that result is re-minted under ``name``. Any + other name passes through, so the executor's name check still fails it + closed. Lifted unchanged from the UK's ``UKGateBinding``, which is now an + alias of this class (microcosm#1585 item 11). + + Attributes: + name: The declared country-neutral gate name the battery expects + back. + evaluator: Runs the country gate over ``(context, parameters)``. + Declared parameters it does not consume pass through to the + gate call, so an unknown parameter raises and fails closed — + the same discipline as :class:`FunctionBinding`. + parameter_keys: The spec parameter keys the evaluator can route — + checked against every declared entry before any gate runs + (``validate_gate_parameters``), so a typo'd parameter is + refused at arm time instead of surfacing as a mid-battery + evaluator error. Fail-closed empty by default. + artifact_keys: Context artifact keys the gate needs; missing keys + resolve to ``evidence_absent`` before evaluation. + artifact_selector: Optional parameter-dependent override of + ``artifact_keys`` for bindings whose evidence artifact follows a + declared parameter. + needs_frame: Whether the gate reads the phase frame. + frame_predicate: Optional parameter-dependent override of + ``needs_frame`` for bindings that serve more than one declared + entry (the UK coverage gate runs frameless at preflight). + legacy_name: The country-flavoured name the evaluator mints, when + it differs from ``name``; the verdict is re-minted under the + declared name. Any other unexpected name passes through so the + executor's name check fails it closed. + evidence: Optional hook producing the entry's ``evidence_sha256`` + payload; ``None`` records no evidence hash. + """ + + name: str + evaluator: Callable[[EvidenceContext, Mapping[str, Any]], GateResult] + parameter_keys: frozenset[str] = frozenset() + artifact_keys: frozenset[str] = frozenset() + artifact_selector: Callable[[Mapping[str, Any]], frozenset[str]] | None = None + needs_frame: bool = True + frame_predicate: Callable[[Mapping[str, Any]], bool] | None = None + legacy_name: str | None = None + evidence: Callable[[EvidenceContext, Mapping[str, Any]], object] | None = None + + def required_artifacts(self, parameters: Mapping[str, Any]) -> frozenset[str]: + if self.artifact_selector is not None: + return self.artifact_selector(parameters) + return self.artifact_keys + + def requires_frame(self, parameters: Mapping[str, Any]) -> bool: + if self.frame_predicate is not None: + return self.frame_predicate(parameters) + return self.needs_frame + + def evaluate( + self, context: EvidenceContext, parameters: Mapping[str, Any] + ) -> GateResult: + result = self.evaluator(context, parameters) + if self.legacy_name is not None and result.name == self.legacy_name: + result = replace(result, name=self.name) + return result + + def evidence_payload( + self, context: EvidenceContext, parameters: Mapping[str, Any] + ) -> object | None: + if self.evidence is None: + return None + return self.evidence(context, parameters) + + def _input_mass_evidence( context: EvidenceContext, parameters: Mapping[str, Any] ) -> object: @@ -432,12 +539,22 @@ class GateStatus(enum.Enum): FAILED = "failed" NOT_APPLICABLE = "not_applicable" EVIDENCE_ABSENT = "evidence_absent" + #: An earlier phase blocked first, or, in a phase assembled from + #: stage-level outcomes (:func:`assemble_phase_report`), an earlier stage + #: of the same phase blocked first; the outcome's reason then names the + #: entry that blocked. UNREACHED = "unreached" #: Statuses a release-blocking entry may hold on a shippable report. _SHIPPABLE_STATUSES = frozenset({GateStatus.PASSED, GateStatus.NOT_APPLICABLE}) +#: Statuses of an entry whose stage ran. ``not_applicable`` is not among +#: them: a declared excuse holds whether or not its phase was reached. +_REACHED_STATUSES = frozenset( + {GateStatus.PASSED, GateStatus.FAILED, GateStatus.EVIDENCE_ABSENT} +) + @dataclass(frozen=True) class GateOutcome: @@ -509,6 +626,50 @@ def to_payload(self) -> dict[str, object]: } +def blocking_outcomes( + outcomes: Iterable[GateOutcome], + *, + release_candidate: bool, + synthetic_smoke: bool = False, +) -> tuple[GateOutcome, ...]: + """Outcomes that stop the build, under one run posture. + + The rule a phase boundary applies (:meth:`GatePhaseReport.blocking_outcomes`), + and the one a stage applies to the outcomes :func:`evaluate_entries` just + returned, so a build that gates stage by stage stops exactly where the + batch would have blocked. + + A failed release-blocking gate always blocks. A release-blocking + gate with absent evidence blocks release candidates only: a dev + build without, say, an incumbent parity snapshot gets an honest + non-shippable report instead of a crash, while a release build + cannot excuse missing evidence — a missing frozen reference is not + a passing gate. An entry declaring ``evidence_absent_blocks`` opts + out of that dev-posture leniency: its absence blocks every posture + (the legacy UK weights-audit strictness, ported during the #654 + schema-3 retirement — "an absent audit is not a passing audit"). + Diagnostic entries never block. A failed entry declaring + ``population_fact_check`` does not block a synthetic smoke build + (``synthetic_smoke``): the fixture is not the population its facts + describe, so the failure is recorded in the report and the build + continues; every other posture blocks on it as usual. + """ + + blocking = [] + for outcome in outcomes: + if outcome.entry.criticality != "release_blocking": + continue + if outcome.status is GateStatus.FAILED: + if synthetic_smoke and outcome.entry.population_fact_check: + continue + blocking.append(outcome) + elif outcome.status is GateStatus.EVIDENCE_ABSENT and ( + release_candidate or outcome.entry.evidence_absent_blocks + ): + blocking.append(outcome) + return tuple(blocking) + + @dataclass(frozen=True) class GatePhaseReport: """One phase's batched outcomes.""" @@ -521,35 +682,15 @@ def blocking_outcomes( ) -> tuple[GateOutcome, ...]: """Outcomes that stop the build at this phase boundary. - A failed release-blocking gate always blocks. A release-blocking - gate with absent evidence blocks release candidates only: a dev - build without, say, an incumbent parity snapshot gets an honest - non-shippable report instead of a crash, while a release build - cannot excuse missing evidence — a missing frozen reference is not - a passing gate. An entry declaring ``evidence_absent_blocks`` opts - out of that dev-posture leniency: its absence blocks every posture - (the legacy UK weights-audit strictness, ported during the #654 - schema-3 retirement — "an absent audit is not a passing audit"). - Diagnostic entries never block. A failed entry declaring - ``population_fact_check`` does not block a synthetic smoke build - (``synthetic_smoke``): the fixture is not the population its facts - describe, so the failure is recorded in the report and the build - continues; every other posture blocks on it as usual. + :func:`blocking_outcomes` over this phase's outcomes; its docstring + states the rule. """ - blocking = [] - for outcome in self.outcomes: - if outcome.entry.criticality != "release_blocking": - continue - if outcome.status is GateStatus.FAILED: - if synthetic_smoke and outcome.entry.population_fact_check: - continue - blocking.append(outcome) - elif outcome.status is GateStatus.EVIDENCE_ABSENT and ( - release_candidate or outcome.entry.evidence_absent_blocks - ): - blocking.append(outcome) - return tuple(blocking) + return blocking_outcomes( + self.outcomes, + release_candidate=release_candidate, + synthetic_smoke=synthetic_smoke, + ) @property def failures(self) -> tuple[str, ...]: @@ -586,20 +727,39 @@ def gate_phase_report_payload( "schema_version": 1, "gates_manifest_sha256": _canonical_sha256(_gates_manifest_payload(gates)), "phase": report.phase, - "outcomes": [ - { - "id": outcome.entry.id, - **outcome.to_payload(), - "result_name": outcome.result.name - if outcome.result is not None - else None, - "evidence_sha256": outcome.evidence_sha256, - } - for outcome in report.outcomes - ], + "outcomes": [_outcome_record(outcome) for outcome in report.outcomes], + } + + +def _outcome_record(outcome: GateOutcome) -> dict[str, object]: + """One outcome as a phase payload carries it. + + :func:`gate_phase_report_payload` writes it, and + :meth:`GateBatteryRun.record_phase` compares a stage's outcome by it + (:func:`_same_outcome`), so the comparison covers every field a phase + payload carries. + """ + + return { + "id": outcome.entry.id, + **outcome.to_payload(), + "result_name": outcome.result.name if outcome.result is not None else None, + "evidence_sha256": outcome.evidence_sha256, } +def _same_outcome(left: GateOutcome, right: GateOutcome) -> bool: + """Whether two outcomes carry the same verdict, as a phase payload holds it. + + A comparison of content, not identity, so an outcome carried through + :func:`gate_phase_report_payload` and back is still the same outcome. + """ + + return _canonical_json_bytes(_outcome_record(left)) == _canonical_json_bytes( + _outcome_record(right) + ) + + def gate_phase_report_from_payload( payload: Mapping[str, object], *, gates: GatesManifest ) -> GatePhaseReport: @@ -826,6 +986,296 @@ def evaluate_phase( return GatePhaseReport(phase=phase, outcomes=outcomes) +def evaluate_entries( + gates: GatesManifest, + entry_ids: Sequence[str], + context: EvidenceContext, + *, + registry: Mapping[str, GateBinding], +) -> tuple[GateOutcome, ...]: + """Evaluate the named entries at the stage where their gates run. + + The stage-level counterpart of :func:`evaluate_phase`, for a build that + gates a stage as soon as it finishes instead of batching a whole phase at + its boundary: the build keeps failing fast, and each gate sees its own + stage's evidence. Each entry resolves exactly as it would in the batch — + its binding, its named evidence gaps, fail-closed evaluation and its + evidence digest — and the whole manifest's parameters are validated + first, so a typo in any entry surfaces before the first gate runs. + + Prefer :meth:`GateBatteryRun.evaluate_entries`, which uses the run's + registry. ``registry`` has no default here: a stage that fell back to + :data:`DEFAULT_REGISTRY` would record a named gap for every gate only its + country binds, and a dev build would continue where the batch blocks. + + Never raises on a gate failure. Whether the build stops is the caller's + call (:func:`blocking_outcomes`), and :func:`assemble_phase_report` + gathers the outcomes into the phase's report. + + Returns: + One outcome per requested id, in the requested order. + + Raises: + TypeError: If ``entry_ids`` is one string rather than a sequence. + ValueError: If no id is given, an id repeats or is not declared, an + entry's phase is not in the declared order, or an entry declares + parameters outside its binding's vocabulary. + """ + + if isinstance(entry_ids, str): + raise TypeError("entry_ids must be a sequence of entry ids, not one string.") + requested = tuple(entry_ids) + if not requested: + raise ValueError("evaluate_entries needs at least one entry id.") + repeated = sorted( + {entry_id for entry_id in requested if requested.count(entry_id) > 1} + ) + if repeated: + raise ValueError(f"entry id(s) {repeated} are requested more than once.") + declared = {entry.id: entry for entry in gates.gates} + unknown = sorted(set(requested) - set(declared)) + if unknown: + raise ValueError( + f"entry id(s) {unknown} are not declared in the " + f"{gates.country!r} gate manifest." + ) + for entry_id in requested: + if declared[entry_id].phase not in gates.phases: + raise ValueError( + f"entry {entry_id!r} binds to phase {declared[entry_id].phase!r}, " + f"which is not in the declared order {list(gates.phases)}." + ) + validate_gate_parameters(gates, registry) + return tuple( + _resolve_entry(declared[entry_id], context, registry) for entry_id in requested + ) + + +def _unreached_reason(blocked_by: str, phase: str) -> str: + """The reason an entry left behind by an early block carries. + + :func:`assemble_phase_report` writes it and + :meth:`GateBatteryRun.record_phase` regenerates it to check the named + blocker, so the two cannot drift apart. + """ + + return ( + f"not reached: {blocked_by!r} blocked phase {phase!r} before this " + "entry's stage ran" + ) + + +def assemble_phase_report( + gates: GatesManifest, + phase: str, + outcomes: Iterable[GateOutcome], + *, + blocked_by: str | None = None, + unreached: Collection[str] = (), + release_candidate: bool | None = None, + synthetic_smoke: bool = False, +) -> GatePhaseReport: + """Assemble one phase's report from outcomes evaluated at their stages. + + Gathers the outcomes :func:`evaluate_entries` returned across a phase's + stages into the :class:`GatePhaseReport` :func:`evaluate_phase` would have + returned: one outcome per declared entry, in manifest order. An entry + declared ``not_applicable`` never runs, so when it has no outcome it gets + its reviewed one here. The report goes through + :meth:`GateBatteryRun.record_phase` and :func:`gate_phase_report_payload` + like any phase, so it can also be carried to another process. + + A phase whose build stopped at a blocking stage names that entry in + ``blocked_by``, and names in ``unreached`` the entries whose stages never + ran. Those become ``unreached``, with a reason naming ``blocked_by``; any + other entry without an outcome is refused, so a stage's dropped outcomes + cannot read as never reached. This extends what ``unreached`` means: an + earlier phase blocked, or an earlier stage of the same phase did. + Recording such a phase sets ``blocked_at_phase``. + + Whether an outcome blocks depends on the run's posture, so an early block + needs it: ``release_candidate`` and ``synthetic_smoke`` must be the ones + the recording :class:`GateBatteryRun` is constructed with, and + ``blocked_by`` must be among :func:`blocking_outcomes` under them. + :meth:`GateBatteryRun.record_phase` checks the named entry again against + the run's own posture. + + Raises: + TypeError: If ``unreached`` is one string rather than a collection. + ValueError: If ``phase`` is not declared; an outcome resolves an entry + this manifest does not declare in ``phase``, as it stands; an + entry has two outcomes; an outcome is already ``unreached``; + ``unreached`` repeats an id, names an entry that is not declared + in ``phase``, is declared ``not_applicable`` or has an outcome, or + is given without ``blocked_by``; an entry that runs has neither an + outcome nor a place in ``unreached``; or ``blocked_by`` is given + without ``release_candidate``, names an entry with no outcome + here, or names one that does not block under the given posture. + """ + + if phase not in gates.phases: + raise ValueError( + f"phase {phase!r} is not in the declared order {list(gates.phases)}." + ) + declared = tuple(entry for entry in gates.gates if entry.phase == phase) + declared_by_id = {entry.id: entry for entry in declared} + resolved: dict[str, GateOutcome] = {} + for outcome in outcomes: + entry_id = outcome.entry.id + if declared_by_id.get(entry_id) != outcome.entry: + raise ValueError( + f"the outcome for {entry_id!r} does not resolve an entry the " + f"manifest declares in phase {phase!r}." + ) + if entry_id in resolved: + raise ValueError(f"entry {entry_id!r} has more than one outcome.") + if outcome.status is GateStatus.UNREACHED: + raise ValueError( + f"entry {entry_id!r} is already unreached; only the assembly " + "marks the entries a block left behind." + ) + resolved[entry_id] = outcome + if isinstance(unreached, str): + raise TypeError("unreached must be a collection of entry ids, not one string.") + never_ran = tuple(unreached) + repeated = sorted( + {entry_id for entry_id in never_ran if never_ran.count(entry_id) > 1} + ) + if repeated: + raise ValueError(f"unreached names {repeated} more than once.") + for entry_id in never_ran: + entry = declared_by_id.get(entry_id) + if entry is None: + raise ValueError( + f"unreached names {entry_id!r}, which is not declared in phase " + f"{phase!r}." + ) + if entry.not_applicable is not None: + raise ValueError( + f"unreached names {entry_id!r}, which is declared " + "not_applicable and keeps its reviewed reason." + ) + if entry_id in resolved: + raise ValueError(f"unreached names {entry_id!r}, which has an outcome.") + if blocked_by is None: + if never_ran: + raise ValueError( + f"unreached names {sorted(never_ran)} without blocked_by; only an " + "early block leaves entries unreached." + ) + else: + if release_candidate is None: + raise ValueError( + "an early block needs the run's posture: pass release_candidate " + "(and synthetic_smoke) with blocked_by." + ) + blocker = resolved.get(blocked_by) + if blocker is None: + raise ValueError( + f"blocked_by names {blocked_by!r}, which has no outcome in " + f"phase {phase!r}." + ) + if not blocking_outcomes( + (blocker,), + release_candidate=release_candidate, + synthetic_smoke=synthetic_smoke, + ): + posture = ( + "synthetic smoke build" + if synthetic_smoke + else "release candidate" + if release_candidate + else "dev build" + ) + raise ValueError( + f"entry {blocked_by!r} cannot have blocked phase {phase!r}: it " + f"is {blocker.entry.criticality} with status " + f"{blocker.status.value!r}, which does not block a {posture}." + ) + missing = [ + entry.id + for entry in declared + if entry.id not in resolved + and entry.not_applicable is None + and entry.id not in never_ran + ] + if missing: + raise ValueError( + f"phase {phase!r} has no outcome for {missing}. A phase that " + "stopped early names the entry that blocked it (blocked_by) and " + "the entries that never ran (unreached)." + ) + # Every entry that runs has an outcome or is named in unreached by now, + # and unreached is empty without blocked_by. + unreached_reason = ( + _unreached_reason(blocked_by, phase) if blocked_by is not None else None + ) + assembled = [] + for entry in declared: + if entry.id in resolved: + assembled.append(resolved[entry.id]) + elif entry.not_applicable is not None: + assembled.append( + GateOutcome( + entry=entry, + status=GateStatus.NOT_APPLICABLE, + reason=entry.not_applicable, + ) + ) + else: + assembled.append( + GateOutcome( + entry=entry, status=GateStatus.UNREACHED, reason=unreached_reason + ) + ) + return GatePhaseReport(phase=phase, outcomes=tuple(assembled)) + + +# --------------------------------------------------------------------------- +# Scopes +# --------------------------------------------------------------------------- + + +def scoped_gate_manifest( + gates: GatesManifest, + scope: Collection[str], + *, + phases: Sequence[str], + policy_suffix: str, +) -> GatesManifest: + """Filter a gate manifest to one battery's scope. + + A :class:`GateBatteryRun` runs one manifest, each phase once and in + order, so a country whose build tools each gate part of its spec gives + each tool its own scope: the entries it evaluates, the phases it runs + them in, and a policy suffix naming the scope. Entries keep the + manifest's order, and the suffix lands in ``policy``, so each scope has + its own ``gates_manifest_sha256``, ``policy_sha256`` and + ``spec_fingerprint`` to pin. Lifted unchanged from the UK's + ``uk_scoped_gate_manifest`` (spine build, calibration seam, release cut, + local candidate), which now calls it (microcosm#1585 item 11). + + Raises: + RuntimeError: If the scope names an entry the manifest does not + declare. + """ + + entries = tuple(entry for entry in gates.gates if entry.id in scope) + missing = sorted(set(scope) - {entry.id for entry in entries}) + if missing: + raise RuntimeError( + f"{gates.country.upper()} gate scope names undeclared gate id(s): " + f"{missing}." + ) + return GatesManifest( + country=gates.country, + version=gates.version, + policy=f"{gates.policy}; {policy_suffix}", + phases=tuple(phases), + gates=entries, + ) + + # --------------------------------------------------------------------------- # The battery run # --------------------------------------------------------------------------- @@ -876,7 +1326,16 @@ class GateBatteryRun: :meth:`run_phase` (which persists the full report before returning) and then :meth:`enforce` (which blocks — or marks — strictly after persistence). Once a phase blocks, no later phase may run: the remaining - entries stay ``unreached`` in the report, which is the truth. + entries stay ``unreached`` in the report, which is the truth, except any + this run had already evaluated at its stage, which keeps the outcome that + stage produced. A phase evaluated elsewhere — at its stages + (:meth:`evaluate_entries`), or in another process — is persisted with + :meth:`record_phase` instead of :meth:`run_phase`. + + A posture that must keep going past failed gates (an evidence build, a + dry run) runs every phase and never calls :meth:`enforce`: nothing is + marked blocked, every phase is recorded, and the report stays + unshippable while a release-blocking entry has not passed. Args: gates: The country's gate manifest. @@ -933,6 +1392,12 @@ def __init__( ) self._phase_reports: dict[str, GatePhaseReport] = {} self._blocked_at_phase: str | None = None + # The outcome of each entry this run evaluated at its stage, by id. + # Each entry is evaluated once, and record_phase refuses a phase that + # marks one of them unreached or carries another outcome for it. + # Until its phase is recorded, the report carries it in place of + # unreached. + self._stage_outcomes: dict[str, GateOutcome] = {} @property def report_path(self) -> Path: @@ -986,7 +1451,9 @@ def run_phase(self, phase: str, context: EvidenceContext) -> GatePhaseReport: Raises: ValueError: If a phase runs out of declared order, re-runs, or runs after a block — each would make the persisted - ``unreached`` placeholders a lie. + ``unreached`` placeholders a lie — or if this run has already + evaluated one of its entries at a stage, which the batch + would evaluate again. """ if self._blocked_at_phase is not None: @@ -1002,15 +1469,113 @@ def run_phase(self, phase: str, context: EvidenceContext) -> GatePhaseReport: f"phase {phase!r} is out of order; expected {expected!r} " f"(declared order {list(self._gates.phases)})." ) + staged = sorted( + entry_id + for entry_id, outcome in self._stage_outcomes.items() + if outcome.entry.phase == phase + ) + if staged: + raise ValueError( + f"this run has already evaluated {staged} at their stages; " + f"assemble phase {phase!r} from their outcomes " + "(assemble_phase_report) and record it with record_phase." + ) report = evaluate_phase(self._gates, phase, context, registry=self._registry) self.record_phase(report) return report + def evaluate_entries( + self, entry_ids: Sequence[str], context: EvidenceContext + ) -> tuple[GateOutcome, ...]: + """Evaluate named entries at their stages, with this run's registry. + + The stage-level counterpart of :meth:`run_phase`: the module-level + :func:`evaluate_entries` over this run's manifest and registry, so a + stage cannot evaluate against another registry than the one the run + was armed with. It writes no report itself, but the run keeps each + outcome and evaluates each entry once, so a stage cannot evaluate a + gate again and keep the outcome it prefers. Until the entry's phase is + recorded, the report the run writes carries that outcome in place of + ``unreached``, so a block in an earlier phase cannot sign the gate as + never reached; it counts toward ``shippable`` only once its phase is + recorded. :meth:`record_phase` refuses a phase that marks one of + these entries ``unreached`` or carries another outcome for it. The + phase's report is assembled with :func:`assemble_phase_report`, under + this run's posture, and recorded with :meth:`record_phase`. + + Raises: + ValueError: If the battery has blocked, an entry belongs to a + phase already recorded, this run has already evaluated an + entry, or as :func:`evaluate_entries` raises. A refused call + evaluates none of its entries. + """ + + if self._blocked_at_phase is not None: + raise ValueError( + f"battery blocked at phase {self._blocked_at_phase!r}; no " + "later stage may run." + ) + if not isinstance(entry_ids, str): + phases = {entry.id: entry.phase for entry in self._gates.gates} + recorded = sorted( + { + phases[entry_id] + for entry_id in entry_ids + if phases.get(entry_id) in self._phase_reports + } + ) + if recorded: + raise ValueError( + f"phase(s) {recorded} have already been recorded; their " + "entries cannot be evaluated again." + ) + evaluated = sorted( + {entry_id for entry_id in entry_ids if entry_id in self._stage_outcomes} + ) + if evaluated: + raise ValueError( + f"this run has already evaluated {evaluated}; each entry is " + "evaluated once, and its phase records that outcome." + ) + outcomes = evaluate_entries( + self._gates, entry_ids, context, registry=self._registry + ) + self._stage_outcomes.update((outcome.entry.id, outcome) for outcome in outcomes) + return outcomes + def record_phase(self, report: GatePhaseReport) -> None: """Persist an evaluated or verified cached phase before enforcement. This is the same ordered write-then-block boundary as ``run_phase``; it never reruns evaluators and never accepts a different gate policy. + + A phase assembled after an early block + (:func:`assemble_phase_report` with ``blocked_by``) stopped part + way: some of its entries were reached and the rest are + ``unreached``. The entry its unreached entries name as the one that + stopped it must block under this run's posture, and the run records + ``blocked_at_phase`` in the same write, so the report on disk never + shows a phase that stopped part way without its block, or names a + blocker ``enforce`` would not block on. ``enforce`` then raises or + marks as usual. A phase whose entries are all unreached, the record a + graph keeps when an earlier phase blocked it, is recorded as before. + + Each entry this run evaluated at a stage (:meth:`evaluate_entries`) + must reach the phase with the outcome its stage produced: a phase + that marks one ``unreached``, or carries another outcome for it, is + refused, so a stage can neither drop a gate it evaluated nor keep a + second evaluation in its place. Outcomes are compared by content + (:func:`_same_outcome`), so the same outcome carried through a phase + payload and back is accepted. The check covers only the entries this + run evaluated; for any other entry, such as one in a phase carried in + from another process, the run has no outcome of its own to compare. + + Raises: + ValueError: If the battery has blocked, the phase is out of + order, its outcomes differ from the declared manifest, it + marks unreached or carries another outcome for an entry this + run evaluated, or it stopped part way but names a blocker + that does not block this run's posture, or nothing in it does. """ if self._blocked_at_phase is not None: raise ValueError(f"battery blocked at phase {self._blocked_at_phase!r}.") @@ -1019,7 +1584,66 @@ def record_phase(self, report: GatePhaseReport) -> None: f"phase {report.phase!r} is out of order; expected {self._next_phase()!r}." ) gate_phase_report_payload(report, gates=self._gates) + evaluated_unreached: list[str] = [] + replaced: list[str] = [] + for outcome in report.outcomes: + produced = self._stage_outcomes.get(outcome.entry.id) + if produced is None: + continue + if outcome.status is GateStatus.UNREACHED: + evaluated_unreached.append(outcome.entry.id) + elif not _same_outcome(outcome, produced): + replaced.append(outcome.entry.id) + if evaluated_unreached: + raise ValueError( + f"phase {report.phase!r} marks {sorted(evaluated_unreached)} " + "unreached, but this run evaluated them at their stages; record " + "the outcomes those stages produced." + ) + if replaced: + raise ValueError( + f"phase {report.phase!r} carries outcomes for {sorted(replaced)} " + "other than the ones this run's stages produced; record the " + "outcomes those stages produced." + ) + statuses = {outcome.status for outcome in report.outcomes} + stopped_early = GateStatus.UNREACHED in statuses and bool( + statuses & _REACHED_STATUSES + ) + if stopped_early: + blocking = report.blocking_outcomes( + release_candidate=self._release_candidate, + synthetic_smoke=self._synthetic_smoke, + ) + if not blocking: + raise ValueError( + f"phase {report.phase!r} stopped part way, but none of its " + "outcomes blocks this run's posture; a phase stops early " + "only on a block." + ) + # The assembly names the blocker only in this reason; regenerate + # it for each entry that does block, so a phase claiming another + # blocker is refused rather than signed. + reasons = { + _unreached_reason(outcome.entry.id, report.phase) + for outcome in blocking + } + misnamed = sorted( + outcome.entry.id + for outcome in report.outcomes + if outcome.status is GateStatus.UNREACHED + and outcome.reason not in reasons + ) + if misnamed: + raise ValueError( + f"phase {report.phase!r} stopped part way, but its " + f"unreached entries {misnamed} do not name an entry that " + f"blocks this run's posture; blocking here: " + f"{sorted(outcome.entry.id for outcome in blocking)}." + ) self._phase_reports[report.phase] = report + if stopped_early: + self._blocked_at_phase = report.phase self._write_report() def enforce(self, phase: str, *, mode: BlockingMode) -> bool: @@ -1075,6 +1699,11 @@ def _outcomes_by_entry(self) -> Iterator[GateOutcome]: } for entry in self._gates.gates: outcome = evaluated.get(entry.id) + if outcome is None: + # No recorded phase holds the entry. If this run's stage + # evaluated it, the report carries that outcome: its phase + # may still be recorded, or, after an earlier block, never. + outcome = self._stage_outcomes.get(entry.id) if outcome is not None: yield outcome elif entry.not_applicable is not None: @@ -1128,8 +1757,15 @@ def report_payload(self) -> dict[str, object]: except RuntimeError as exc: signing_key = None signing_error = exc + recorded = set(self._phase_reports) blocking_ok = all( outcome.status in _SHIPPABLE_STATUSES + # A stage's outcome counts only once its phase is recorded; a + # declared excuse holds whether or not its phase ran. + and ( + outcome.entry.phase in recorded + or outcome.entry.not_applicable is not None + ) for outcome in outcomes if outcome.entry.criticality == "release_blocking" ) diff --git a/packages/microcosm-build/src/microcosm/build/transport/gate_kernels.py b/packages/microcosm-build/src/microcosm/build/transport/gate_kernels.py index 212a027900..2b4b3d08a6 100644 --- a/packages/microcosm-build/src/microcosm/build/transport/gate_kernels.py +++ b/packages/microcosm-build/src/microcosm/build/transport/gate_kernels.py @@ -189,6 +189,12 @@ def phase_outcome(report: GatePhaseReport) -> str: 1. ``fail``: a release-blocking entry failed. 2. ``unreached``: an entry was not reached (an earlier phase blocked). + This kernel evaluates each phase in one batch, so here that is the + only way an entry is unreached. A phase assembled stage by stage + (:func:`~microcosm.build.gate_battery.assemble_phase_report`), where + ``unreached`` can also mean that an earlier stage of the same phase + blocked, is for ``GateBatteryRun`` only for now: this ranking does not + describe it, and :func:`decode_gate_report` refuses its rows. 3. ``evidence_absent``: a release-blocking entry lacked its evidence or implementation. 4. ``not_applicable``: the phase has no entries, or every entry carries a diff --git a/packages/microcosm-build/src/microcosm/build/uk_runtime/battery_bindings.py b/packages/microcosm-build/src/microcosm/build/uk_runtime/battery_bindings.py index 2f68553bf6..d17566c4d3 100644 --- a/packages/microcosm-build/src/microcosm/build/uk_runtime/battery_bindings.py +++ b/packages/microcosm-build/src/microcosm/build/uk_runtime/battery_bindings.py @@ -29,18 +29,19 @@ import hashlib import json -from collections.abc import Callable, Iterable, Mapping -from dataclasses import dataclass, replace +from collections.abc import Iterable, Mapping +from dataclasses import replace from datetime import date, datetime -from importlib.resources import files from types import MappingProxyType from typing import Any import numpy as np import pandas as pd +from microcosm.build.country_spec import country_resource from microcosm.build.gate_battery import ( DEFAULT_REGISTRY, + EvaluatorBinding, EvidenceContext, GateBinding, ) @@ -137,73 +138,10 @@ ] -@dataclass(frozen=True) -class UKGateBinding: - """A :class:`GateBinding` over a UK runtime evaluator. - - Attributes: - name: The declared country-neutral gate name the battery expects - back. - evaluator: Runs the legacy UK gate over ``(context, parameters)``. - Declared parameters it does not consume pass through to the - gate call, so an unknown parameter raises and fails closed — - the same discipline as the battery's ``FunctionBinding``. - parameter_keys: The spec parameter keys the evaluator can route — - checked against every declared entry before any gate runs - (``validate_gate_parameters``), so a typo'd parameter is - refused at arm time instead of surfacing as a mid-battery - evaluator error. Fail-closed empty by default. - artifact_keys: Context artifact keys the gate needs; missing keys - resolve to ``evidence_absent`` before evaluation. - artifact_selector: Optional parameter-dependent override of - ``artifact_keys`` for bindings whose evidence artifact follows a - declared parameter. - needs_frame: Whether the gate reads the phase frame. - frame_predicate: Optional parameter-dependent override of - ``needs_frame`` for bindings that serve more than one declared - entry (the coverage gate runs frameless at preflight). - legacy_name: The UK-flavored name the legacy evaluator mints, when - it differs from ``name``; the verdict is re-minted under the - declared name. Any other unexpected name passes through so the - executor's name check fails it closed. - evidence: Optional hook producing the entry's ``evidence_sha256`` - payload; ``None`` records no evidence hash. - """ - - name: str - evaluator: Callable[[EvidenceContext, Mapping[str, Any]], GateResult] - parameter_keys: frozenset[str] = frozenset() - artifact_keys: frozenset[str] = frozenset() - artifact_selector: Callable[[Mapping[str, Any]], frozenset[str]] | None = None - needs_frame: bool = True - frame_predicate: Callable[[Mapping[str, Any]], bool] | None = None - legacy_name: str | None = None - evidence: Callable[[EvidenceContext, Mapping[str, Any]], object] | None = None - - def required_artifacts(self, parameters: Mapping[str, Any]) -> frozenset[str]: - if self.artifact_selector is not None: - return self.artifact_selector(parameters) - return self.artifact_keys - - def requires_frame(self, parameters: Mapping[str, Any]) -> bool: - if self.frame_predicate is not None: - return self.frame_predicate(parameters) - return self.needs_frame - - def evaluate( - self, context: EvidenceContext, parameters: Mapping[str, Any] - ) -> GateResult: - result = self.evaluator(context, parameters) - if self.legacy_name is not None and result.name == self.legacy_name: - result = replace(result, name=self.name) - return result - - def evidence_payload( - self, context: EvidenceContext, parameters: Mapping[str, Any] - ) -> object | None: - if self.evidence is None: - return None - return self.evidence(context, parameters) +#: The shared re-minting binding under the UK name its callers and tests use. +#: It moved unchanged to the battery module, where the US bindings can share +#: it (microcosm#1585 item 11). +UKGateBinding = EvaluatorBinding # --------------------------------------------------------------------------- @@ -851,9 +789,7 @@ def _evaluate_support( ) donor_ranges: dict[str, tuple[float, float]] = {} for resource_name in resource_names: - resource = json.loads( - files("microcosm.build.uk").joinpath(str(resource_name)).read_text() - ) + resource = json.loads(country_resource("uk", str(resource_name)).read_text()) raw_bounds = resource.get("bounds") if not isinstance(raw_bounds, Mapping): raise ValueError(f"{resource_name} is missing bounds.") @@ -1320,7 +1256,7 @@ def _evaluate_geography_ladder( def _local_area_roster( resource: str, levels: tuple[str, ...] ) -> dict[str, tuple[str, ...]]: - payload = json.loads(files("microcosm.build.uk").joinpath(resource).read_text()) + payload = json.loads(country_resource("uk", resource).read_text()) declared = payload.get("levels") if not isinstance(declared, Mapping): raise ValueError(f"{resource} must expose a levels object.") @@ -1571,12 +1507,8 @@ def _target_surface_evidence( ) crosswalk_resource = str(parameters["crosswalk_resource"]) membership_resource = str(parameters["membership_resource"]) - crosswalk_text = ( - files("microcosm.build.uk").joinpath(crosswalk_resource).read_text() - ) - membership_text = ( - files("microcosm.build.uk").joinpath(membership_resource).read_text() - ) + crosswalk_text = country_resource("uk", crosswalk_resource).read_text() + membership_text = country_resource("uk", membership_resource).read_text() candidate_targets = sorted(_local_default_candidate_surface(registry)) reference_targets = sorted(_local_default_expected_surface(crosswalk_resource)) reviewed_exclusions = _local_default_reviewed_exclusions(membership_resource) @@ -1616,9 +1548,7 @@ def _local_default_candidate_surface(registry: object) -> frozenset[str]: def _local_default_expected_surface(crosswalk_resource: str) -> frozenset[str]: - crosswalk = json.loads( - files("microcosm.build.uk").joinpath(crosswalk_resource).read_text() - ) + crosswalk = json.loads(country_resource("uk", crosswalk_resource).read_text()) levels = crosswalk.get("levels") if not isinstance(levels, Mapping): raise ValueError(f"{crosswalk_resource} must expose levels.") @@ -1675,9 +1605,7 @@ def _metric_area_scope( def _local_default_reviewed_exclusions( membership_resource: str, ) -> dict[str, str]: - membership = json.loads( - files("microcosm.build.uk").joinpath(membership_resource).read_text() - ) + membership = json.loads(country_resource("uk", membership_resource).read_text()) metric_by_target_id = _local_metric_by_target_id() reviewed: dict[str, str] = {} for deferral in membership.get("signed_deferrals", ()): @@ -1870,7 +1798,7 @@ def _evaluate_ledger_compile_parity( signed_resource = parameters.get("signed_differences_resource") if signed_resource is not None: signed_differences = json.loads( - files("microcosm.build.uk").joinpath(str(signed_resource)).read_text() + country_resource("uk", str(signed_resource)).read_text() )["differences"] target_period = parameters["target_period"] registry_artifact = _ledger_compile_parity_registry_artifact(parameters) @@ -1892,9 +1820,7 @@ def _evaluate_ledger_compile_parity( def _load_ledger_compile_parity_fixture(fixture_resource: str) -> dict[str, Any]: - fixture = json.loads( - files("microcosm.build.uk").joinpath(fixture_resource).read_text() - ) + fixture = json.loads(country_resource("uk", fixture_resource).read_text()) if fixture_resource == LOCAL_REGISTRY_PARITY_FIXTURE_RESOURCE: return align_uk_local_registry_parity_fixture(fixture) # The national fixtures spell the incumbent's regional rows their own way; @@ -1913,7 +1839,7 @@ def _ledger_compile_parity_evidence( registry_artifact=registry_artifact, ) fixture_resource = str(parameters["fixture_resource"]) - fixture_text = files("microcosm.build.uk").joinpath(fixture_resource).read_text() + fixture_text = country_resource("uk", fixture_resource).read_text() return { "registry_artifact": registry_artifact, "registry_version": getattr(registry, "version", None), diff --git a/packages/microcosm-build/src/microcosm/build/uk_runtime/calibration_run.py b/packages/microcosm-build/src/microcosm/build/uk_runtime/calibration_run.py index 3d1406da30..e092ae0c5b 100644 --- a/packages/microcosm-build/src/microcosm/build/uk_runtime/calibration_run.py +++ b/packages/microcosm-build/src/microcosm/build/uk_runtime/calibration_run.py @@ -36,6 +36,7 @@ ) from microcosm.build.gate_battery import ( gate_signing_key_env, + scoped_gate_manifest, ) from microcosm.build.uk_runtime.cgt_projection import ( UKCGTProjection, @@ -627,24 +628,17 @@ def uk_scoped_gate_manifest( ) -> GatesManifest: """Filter the declared UK gate spec to one battery's scope. - The one scope-filtering implementation every scoped producer shares - (spine build, calibration seam, release cut). ``source`` lets a caller + The shared :func:`~microcosm.build.gate_battery.scoped_gate_manifest`, + which every scoped producer calls through here (spine build, calibration + seam, release cut). ``source`` lets a caller that already holds a loaded spec — or a hermetic test that stubs one — supply it; the default is the committed package spec. """ if source is None: source = load_country_spec("uk").gates - entries = tuple(entry for entry in source.gates if entry.id in scope) - missing = sorted(set(scope) - {entry.id for entry in entries}) - if missing: - raise RuntimeError(f"UK gate scope names undeclared gate id(s): {missing}.") - return GatesManifest( - country=source.country, - version=source.version, - policy=f"{source.policy}; {policy_suffix}", - phases=phases, - gates=entries, + return scoped_gate_manifest( + source, scope, phases=phases, policy_suffix=policy_suffix ) diff --git a/packages/microcosm-build/tests/engine_free/shared/test_country_gates_manifest.py b/packages/microcosm-build/tests/engine_free/shared/test_country_gates_manifest.py new file mode 100644 index 0000000000..cc61bd836a --- /dev/null +++ b/packages/microcosm-build/tests/engine_free/shared/test_country_gates_manifest.py @@ -0,0 +1,96 @@ +"""The narrow gates loader and the per-country resource helper (#1585 item 11). + +A build tool that needs only its gate policy reads ``/gates.json`` through +``load_gates_manifest``, without the full country-spec load; bindings read the +registers their declared parameters name through ``country_resource``. +""" + +from __future__ import annotations + +import json +import shutil +from importlib.resources import files +from pathlib import Path + +import pytest + +from microcosm.build.country_spec import ( + country_resource, + load_country_spec, + load_gates_manifest, +) + + +def _package_copy(tmp_path: Path, country: str) -> Path: + root = tmp_path / country + shutil.copytree(Path(str(files("microcosm.build").joinpath(country))), root) + return root + + +@pytest.mark.parametrize("country", ["uk", "be", "am", "nz"]) +def test_the_narrow_loader_returns_the_full_loaders_manifest(country) -> None: + assert load_gates_manifest(country) == load_country_spec(country).gates + + +def test_the_narrow_loader_reads_no_other_resource(tmp_path) -> None: + root = _package_copy(tmp_path, "be") + (root / "undeclared.json").write_text("{}", encoding="utf-8") + with pytest.raises(ValueError, match="not declared"): + load_country_spec(root) + assert load_gates_manifest(root) == load_country_spec("be").gates + + +def test_the_narrow_loader_refuses_what_the_full_loader_refuses(tmp_path) -> None: + # The US package declares no gates.json yet; the loader never falls back. + with pytest.raises(ValueError, match="no legacy_json gates.json"): + load_gates_manifest("us") + root = _package_copy(tmp_path, "be") + gates = json.loads((root / "gates.json").read_text(encoding="utf-8")) + gates["phases"] = ["exported"] + (root / "gates.json").write_text(json.dumps(gates), encoding="utf-8") + with pytest.raises(ValueError, match="unknown phase"): + load_gates_manifest(root) + (root / "gates.json").unlink() + with pytest.raises(FileNotFoundError, match="gates.json"): + load_gates_manifest(root) + + +def test_country_resource_is_the_packaged_file() -> None: + assert ( + country_resource("uk", "gates.json").read_text() + == files("microcosm.build.uk").joinpath("gates.json").read_text() + ) + for country in ("UK", "u.k", "", "uk/x"): + with pytest.raises(ValueError, match="country code"): + country_resource(country, "gates.json") + + +def test_the_narrow_loader_keeps_each_resource_check(tmp_path) -> None: + # Review of #1609: one case for each check the full loader also runs. + misplaced = tmp_path / "misplaced" / "xx" + shutil.copytree(Path(str(files("microcosm.build").joinpath("be"))), misplaced) + with pytest.raises( + ValueError, match="declares country 'be' but lives in directory 'xx'" + ): + load_gates_manifest(misplaced) + + retyped = _package_copy(tmp_path / "retyped", "be") + package = json.loads((retyped / "country_package.json").read_text(encoding="utf-8")) + (row,) = [row for row in package["resources"] if row["path"] == "gates.json"] + row.update(kind="battery", schema_id="battery.schema.json") + (retyped / "country_package.json").write_text(json.dumps(package), encoding="utf-8") + with pytest.raises(ValueError, match="no legacy_json gates.json"): + load_gates_manifest(retyped) + + outside = _package_copy(tmp_path / "outside", "be") + elsewhere = tmp_path / "gates_elsewhere.json" + shutil.move(outside / "gates.json", elsewhere) + (outside / "gates.json").symlink_to(elsewhere) + with pytest.raises(ValueError, match="resolves outside the country package"): + load_gates_manifest(outside) + + directory = _package_copy(tmp_path / "directory", "be") + (directory / "gates.json").unlink() + (directory / "gates.json").mkdir() + with pytest.raises(ValueError, match="is not a file"): + load_gates_manifest(directory) diff --git a/packages/microcosm-build/tests/engine_free/shared/test_gate_battery.py b/packages/microcosm-build/tests/engine_free/shared/test_gate_battery.py index 468d5e95c2..44028280bc 100644 --- a/packages/microcosm-build/tests/engine_free/shared/test_gate_battery.py +++ b/packages/microcosm-build/tests/engine_free/shared/test_gate_battery.py @@ -20,13 +20,22 @@ from microcosm.build.gate_battery import ( DEFAULT_REGISTRY, BlockingMode, + EvaluatorBinding, EvidenceContext, FunctionBinding, GateBatteryBlockedError, GateBatteryRun, + GateOutcome, + GatePhaseReport, GateStatus, + assemble_phase_report, + blocking_outcomes, + evaluate_entries, evaluate_phase, + gate_phase_report_from_payload, + gate_phase_report_payload, gate_signing_key_env, + scoped_gate_manifest, validate_gate_parameters, ) from microcosm.build.trace import compute_composition_fingerprint @@ -917,3 +926,805 @@ def test_evidence_absent_blocks_a_synthetic_smoke_even_on_a_population_fact_chec lenient.run_phase("terminal", EvidenceContext()) assert lenient.enforce("terminal", mode=BlockingMode.BLOCKS_ARTIFACT) is False assert lenient.report_payload()["gates"]["fact"]["status"] == "evidence_absent" + + +class TestStageLevelEvaluation: + """Gates evaluated where they run, assembled into one phase (#1585 item 11). + + A build that gates each stage as it finishes keeps failing fast and gives + each gate its own stage's evidence. The phase report is assembled from + those outcomes and recorded through the same write-then-block boundary. + """ + + @staticmethod + def _registry(): + return { + "support": _binding("support"), + "exported_nonzero": _binding("exported_nonzero", passes=False), + "nonconstant_columns": _binding("nonconstant_columns"), + } + + @staticmethod + def _run(manifest, tmp_path, name, *, release_candidate=True): + return GateBatteryRun( + manifest, + release_id="xx-test-build", + report_path=tmp_path / name, + release_candidate=release_candidate, + registry=TestStageLevelEvaluation._registry(), + ) + + def test_assembled_stages_equal_the_batched_phase(self, tmp_path, signing_env): + manifest = _manifest( + [ + _entry("t_first", gate="support"), + _entry("t_second", gate="exported_nonzero"), + _entry("t_third", gate="nonconstant_columns"), + _entry("t_na", gate="parity", not_applicable="no incumbent dataset"), + ] + ) + registry = self._registry() + context = EvidenceContext() + # Stages finish in their own order; the report keeps manifest order. + later = evaluate_entries(manifest, ["t_third"], context, registry=registry) + earlier = evaluate_entries( + manifest, ["t_first", "t_second"], context, registry=registry + ) + assembled = assemble_phase_report(manifest, "terminal", [*later, *earlier]) + assert assembled == evaluate_phase( + manifest, "terminal", context, registry=registry + ) + + staged = self._run(manifest, tmp_path, "staged.json") + batched = self._run(manifest, tmp_path, "batched.json") + for run in (staged, batched): + run.run_phase("preflight", context) + staged.record_phase(assembled) + batched.run_phase("terminal", context) + assert staged.report_payload() == batched.report_payload() + assert staged.blocked_at_phase is None + + def test_an_early_block_leaves_the_rest_of_its_phase_unreached( + self, tmp_path, signing_env + ): + manifest = _manifest( + [ + _entry("a_first", gate="support", phase="assembled"), + _entry("a_block", gate="exported_nonzero", phase="assembled"), + _entry("a_later", gate="nonconstant_columns", phase="assembled"), + _entry( + "a_na", + gate="parity", + phase="assembled", + not_applicable="no incumbent dataset", + ), + _entry("t_gate", gate="support"), + ], + ["assembled", "terminal"], + ) + registry = self._registry() + context = EvidenceContext() + first = evaluate_entries(manifest, ["a_first"], context, registry=registry) + assert blocking_outcomes(first, release_candidate=True) == () + stopping = evaluate_entries(manifest, ["a_block"], context, registry=registry) + assert blocking_outcomes(stopping, release_candidate=True) == stopping + + report = assemble_phase_report( + manifest, + "assembled", + [*first, *stopping], + blocked_by="a_block", + unreached=["a_later"], + release_candidate=True, + ) + statuses = {outcome.entry.id: outcome.status for outcome in report.outcomes} + assert statuses == { + "a_first": GateStatus.PASSED, + "a_block": GateStatus.FAILED, + "a_later": GateStatus.UNREACHED, + "a_na": GateStatus.NOT_APPLICABLE, + } + # The assembled phase crosses processes like any other. + payload = gate_phase_report_payload(report, gates=manifest) + restored = gate_phase_report_from_payload(payload, gates=manifest) + assert restored == report + + run = self._run(manifest, tmp_path, "terminal_gates.json") + run.record_phase(restored) + # The block is on disk before enforce runs. + written = json.loads(run.report_path.read_text()) + assert written["blocked_at_phase"] == "assembled" + assert written["attestation"]["blocked_at_phase"] == "assembled" + assert written["phases_evaluated"] == ["assembled"] + assert written["gates"]["a_later"]["status"] == "unreached" + assert ( + "'a_block' blocked phase 'assembled'" + in (written["gates"]["a_later"]["reason"]) + ) + # An entry of a phase that never ran keeps the reasonless form. + assert written["gates"]["t_gate"]["status"] == "unreached" + assert written["gates"]["t_gate"]["reason"] is None + assert written["shippable"] is False + with pytest.raises(GateBatteryBlockedError) as blocked: + run.enforce("assembled", mode=BlockingMode.BLOCKS_ARTIFACT) + assert blocked.value.blocking_gate_ids == ("a_block",) + with pytest.raises(ValueError, match="blocked at phase 'assembled'"): + run.run_phase("terminal", context) + + def test_the_assembly_refuses_a_missing_or_duplicate_entry(self): + manifest = _manifest( + [ + _entry("t_pass", gate="support"), + _entry("t_fail", gate="exported_nonzero"), + _entry("t_diag", gate="exported_nonzero", criticality="diagnostic"), + _entry("pf_gate", gate="support", phase="preflight"), + ] + ) + registry = self._registry() + context = EvidenceContext() + passed, failed, diagnostic = evaluate_entries( + manifest, ["t_pass", "t_fail", "t_diag"], context, registry=registry + ) + (preflight,) = evaluate_entries( + manifest, ["pf_gate"], context, registry=registry + ) + with pytest.raises(ValueError, match=r"no outcome for \['t_diag'\]"): + assemble_phase_report(manifest, "terminal", [passed, failed]) + with pytest.raises(ValueError, match="more than one outcome"): + assemble_phase_report( + manifest, "terminal", [passed, failed, diagnostic, passed] + ) + with pytest.raises(ValueError, match="does not resolve an entry"): + assemble_phase_report(manifest, "terminal", [preflight]) + with pytest.raises(ValueError, match="does not resolve an entry"): + # The same id, evaluated against a different declaration. + assemble_phase_report( + _manifest([_entry("t_pass", gate="support", notes="edited")]), + "terminal", + [passed], + ) + with pytest.raises(ValueError, match="already unreached"): + assemble_phase_report( + manifest, + "terminal", + [GateOutcome(entry=passed.entry, status=GateStatus.UNREACHED)], + blocked_by="t_fail", + release_candidate=True, + ) + with pytest.raises(ValueError, match="needs the run's posture"): + assemble_phase_report(manifest, "terminal", [failed], blocked_by="t_fail") + with pytest.raises(ValueError, match="no outcome in phase"): + assemble_phase_report( + manifest, + "terminal", + [passed], + blocked_by="t_fail", + release_candidate=True, + ) + for blocker, outcome in (("t_pass", passed), ("t_diag", diagnostic)): + with pytest.raises(ValueError, match="cannot have blocked"): + assemble_phase_report( + manifest, + "terminal", + [outcome], + blocked_by=blocker, + release_candidate=True, + ) + with pytest.raises(ValueError, match="not in the declared order"): + assemble_phase_report(manifest, "simulated", []) + + with pytest.raises(TypeError, match="not one string"): + evaluate_entries(manifest, "t_pass", context, registry=registry) + for ids, message in ( + ([], "at least one"), + (["t_pass", "t_pass"], "more than once"), + (["t_missing"], "not declared"), + ): + with pytest.raises(ValueError, match=message): + evaluate_entries(manifest, ids, context, registry=registry) + + def test_a_phase_stopped_early_must_block_the_runs_posture( + self, tmp_path, signing_env + ): + # Absent evidence blocks release candidates only, so a dev run cannot + # record a phase that claims to have stopped on it. + manifest = _manifest( + [ + _entry("t_absent", gate="weights_audit"), + _entry("t_later", gate="support"), + ], + ["terminal"], + ) + (absent,) = evaluate_entries( + manifest, ["t_absent"], EvidenceContext(), registry=DEFAULT_REGISTRY + ) + assert absent.status is GateStatus.EVIDENCE_ABSENT + report = assemble_phase_report( + manifest, + "terminal", + [absent], + blocked_by="t_absent", + unreached=["t_later"], + release_candidate=True, + ) + dev = self._run(manifest, tmp_path, "dev.json", release_candidate=False) + with pytest.raises(ValueError, match="stops early only on a block"): + dev.record_phase(report) + assert dev.phases_evaluated == () + candidate = self._run(manifest, tmp_path, "candidate.json") + candidate.record_phase(report) + assert candidate.blocked_at_phase == "terminal" + # A phase with every entry unreached, as the UK spine graph stores a + # phase an earlier one blocked, did not stop part way: it records as + # it did before stage-level assembly, with no block of its own. + never_reached = GatePhaseReport( + phase="terminal", + outcomes=tuple( + GateOutcome( + entry=entry, + status=GateStatus.UNREACHED, + reason="An earlier phase blocked this phase.", + ) + for entry in manifest.gates + ), + ) + replay = self._run(manifest, tmp_path, "replay.json", release_candidate=False) + replay.record_phase(never_reached) + assert replay.phases_evaluated == ("terminal",) + assert replay.blocked_at_phase is None + + def test_the_named_blocker_must_block_the_runs_posture(self, tmp_path, signing_env): + # Review of #1609: the posture decides which outcome stops a phase, so + # the named blocker is checked against it, at assembly and at record. + manifest = _manifest( + [ + _entry("a_absent", gate="weights_audit", phase="assembled"), + _entry("a_fail", gate="exported_nonzero", phase="assembled"), + _entry("a_later", gate="support", phase="assembled"), + ], + ["assembled"], + ) + registry = { + **self._registry(), + "weights_audit": DEFAULT_REGISTRY["weights_audit"], + } + reached = evaluate_entries( + manifest, ["a_absent", "a_fail"], EvidenceContext(), registry=registry + ) + # A dev build does not stop on absent evidence, only on the failure. + with pytest.raises(ValueError, match="does not block a dev build"): + assemble_phase_report( + manifest, + "assembled", + reached, + blocked_by="a_absent", + unreached=["a_later"], + release_candidate=False, + ) + # A phase assembled under a release candidate's posture does name it; + # a dev run refuses to record that claim even though a_fail blocks. + candidate_claim = assemble_phase_report( + manifest, + "assembled", + reached, + blocked_by="a_absent", + unreached=["a_later"], + release_candidate=True, + ) + dev = self._run(manifest, tmp_path, "dev.json", release_candidate=False) + with pytest.raises( + ValueError, match=r"do not name an entry that blocks.*\['a_fail'\]" + ): + dev.record_phase(candidate_claim) + assert dev.phases_evaluated == () + + report = assemble_phase_report( + manifest, + "assembled", + reached, + blocked_by="a_fail", + unreached=["a_later"], + release_candidate=False, + ) + dev.record_phase(report) + assert ( + "'a_fail' blocked phase 'assembled'" + in (dev.report_payload()["gates"]["a_later"]["reason"]) + ) + with pytest.raises(GateBatteryBlockedError) as blocked: + dev.enforce("assembled", mode=BlockingMode.BLOCKS_ARTIFACT) + assert blocked.value.blocking_gate_ids == ("a_fail",) + + # A synthetic smoke build does not stop on a failed population fact. + facts = _manifest( + [ + _entry( + "a_fact", + gate="exported_nonzero", + phase="assembled", + population_fact_check=True, + ), + _entry("a_later", gate="support", phase="assembled"), + ], + ["assembled"], + ) + fact = evaluate_entries( + facts, ["a_fact"], EvidenceContext(), registry=self._registry() + ) + with pytest.raises(ValueError, match="does not block a synthetic smoke"): + assemble_phase_report( + facts, + "assembled", + fact, + blocked_by="a_fact", + unreached=["a_later"], + release_candidate=False, + synthetic_smoke=True, + ) + + def test_the_run_evaluates_entries_with_its_own_registry( + self, tmp_path, signing_env + ): + # Review of #1609: a stage that fell back to the default registry + # would record a named gap for a gate only its country binds, and a + # dev build would continue where the batch blocks. + manifest = _manifest( + [ + _entry("pf_gate", gate="exported_nonzero", phase="preflight"), + _entry("t_gate", gate="exported_nonzero"), + _entry("t_later", gate="exported_nonzero"), + ] + ) + run = self._run(manifest, tmp_path, "terminal_gates.json") + (stage,) = run.evaluate_entries(["t_gate"], EvidenceContext()) + assert stage.status is GateStatus.FAILED # the run's binding ran + with pytest.raises(TypeError, match="registry"): + evaluate_entries(manifest, ["t_gate"], EvidenceContext()) + run.run_phase("preflight", EvidenceContext()) + with pytest.raises(ValueError, match="already been recorded"): + run.evaluate_entries(["pf_gate"], EvidenceContext()) + with pytest.raises(GateBatteryBlockedError): + run.enforce("preflight", mode=BlockingMode.BLOCKS_ARTIFACT) + # An entry of a later phase that this run has not evaluated and no + # recorded phase holds: only the block refuses it. + with pytest.raises(ValueError, match="no later stage may run"): + run.evaluate_entries(["t_later"], EvidenceContext()) + + def test_evaluate_entries_refuses_an_undeclared_phase_and_a_stray_key(self): + # Review of #1609: one case for each refusal before any gate runs. + manifest = _manifest( + [ + _entry("pf_gate", gate="support", phase="preflight"), + _entry("t_gate", gate="support"), + ] + ) + terminal_only = scoped_gate_manifest( + manifest, + ("pf_gate", "t_gate"), + phases=("terminal",), + policy_suffix="terminal_only", + ) + with pytest.raises(ValueError, match=r"'pf_gate' binds to phase 'preflight'"): + evaluate_entries( + terminal_only, + ["pf_gate"], + EvidenceContext(), + registry=self._registry(), + ) + calls = [] + + def counting(**kwargs) -> GateResult: + calls.append(kwargs) + return GateResult(name="support", passed=True) + + stray = _manifest( + [ + _entry("t_gate", gate="support"), + _entry( + "t_typo", + gate="input_mass_parity", + parameters={"relative_tolerence": 0.5}, + ), + ], + ["terminal"], + ) + with pytest.raises(ValueError, match=r"'t_typo'.*relative_tolerence"): + evaluate_entries( + stray, + ["t_gate"], + EvidenceContext(), + registry={ + **DEFAULT_REGISTRY, + "support": FunctionBinding(name="support", gate=counting), + }, + ) + assert calls == [] + + def test_an_early_block_names_the_entries_that_never_ran(self): + # Review of #1609: an entry with no outcome is unreached only when the + # caller names it, so a stage's dropped outcomes are refused, not + # signed as never reached. + manifest = _manifest( + [ + _entry("t_pass", gate="support"), + _entry("t_diag", gate="exported_nonzero", criticality="diagnostic"), + _entry("t_block", gate="exported_nonzero"), + _entry("t_later", gate="nonconstant_columns"), + _entry("t_na", gate="parity", not_applicable="no incumbent dataset"), + ], + ["terminal"], + ) + reached = evaluate_entries( + manifest, + ["t_pass", "t_diag", "t_block"], + EvidenceContext(), + registry=self._registry(), + ) + block = {"blocked_by": "t_block", "release_candidate": True} + with pytest.raises(ValueError, match=r"no outcome for \['t_pass', 't_diag'\]"): + assemble_phase_report( + manifest, "terminal", reached[2:], unreached=["t_later"], **block + ) + for unreached, message in ( + (["t_later", "t_pass"], "which has an outcome"), + (["t_later", "t_na"], "declared not_applicable"), + (["t_later", "t_elsewhere"], "not declared in phase"), + (["t_later", "t_later"], "more than once"), + ): + with pytest.raises(ValueError, match=message): + assemble_phase_report( + manifest, "terminal", reached, unreached=unreached, **block + ) + with pytest.raises(TypeError, match="not one string"): + assemble_phase_report( + manifest, "terminal", reached, unreached="t_later", **block + ) + with pytest.raises(ValueError, match="without blocked_by"): + assemble_phase_report(manifest, "terminal", reached, unreached=["t_later"]) + report = assemble_phase_report( + manifest, "terminal", reached, unreached=["t_later"], **block + ) + assert [outcome.status for outcome in report.outcomes] == [ + GateStatus.PASSED, + GateStatus.FAILED, + GateStatus.FAILED, + GateStatus.UNREACHED, + GateStatus.NOT_APPLICABLE, + ] + + def test_the_run_refuses_an_unreached_entry_it_evaluated( + self, tmp_path, signing_env + ): + # Review of #1609: a caller that fills ``unreached`` from the entries + # it lacks outcomes for would sign a gate the run evaluated as never + # reached, so the run keeps the ids it evaluates. + manifest = _manifest( + [ + _entry("a_first", gate="support", phase="assembled"), + _entry("a_block", gate="exported_nonzero", phase="assembled"), + _entry("a_later", gate="nonconstant_columns", phase="assembled"), + ], + ["assembled"], + ) + run = self._run(manifest, tmp_path, "terminal_gates.json") + first = run.evaluate_entries(["a_first"], EvidenceContext()) + stopping = run.evaluate_entries(["a_block"], EvidenceContext()) + block = {"blocked_by": "a_block", "release_candidate": True} + dropped = assemble_phase_report( + manifest, "assembled", stopping, unreached=["a_first", "a_later"], **block + ) + with pytest.raises( + ValueError, match=r"marks \['a_first'\] unreached, but this run evaluated" + ): + run.record_phase(dropped) + # A phase with every entry unreached is refused on the same ground. + never_reached = GatePhaseReport( + phase="assembled", + outcomes=tuple( + GateOutcome( + entry=entry, + status=GateStatus.UNREACHED, + reason="An earlier phase blocked this phase.", + ) + for entry in manifest.gates + ), + ) + with pytest.raises(ValueError, match=r"marks \['a_block', 'a_first'\]"): + run.record_phase(never_reached) + assert run.phases_evaluated == () + assert run.blocked_at_phase is None + # The phase that carries what its stages produced records and blocks. + run.record_phase( + assemble_phase_report( + manifest, + "assembled", + [*first, *stopping], + unreached=["a_later"], + **block, + ) + ) + assert run.blocked_at_phase == "assembled" + assert run.report_payload()["gates"]["a_first"]["status"] == "passed" + + def test_the_run_evaluates_each_entry_once(self, tmp_path, signing_env): + # Review of #1609: a stage that could evaluate a gate again, with + # other evidence, could keep whichever outcome it preferred. + manifest = _manifest( + [ + _entry("a_first", gate="support", phase="assembled"), + _entry("a_block", gate="exported_nonzero", phase="assembled"), + ], + ["assembled"], + ) + run = self._run(manifest, tmp_path, "terminal_gates.json") + (failed,) = run.evaluate_entries(["a_block"], EvidenceContext()) + assert failed.status is GateStatus.FAILED + other = EvidenceContext(artifacts={"exported": "other evidence"}) + with pytest.raises(ValueError, match=r"already evaluated \['a_block'\];"): + run.evaluate_entries(["a_first", "a_block"], other) + # Nor may the batch evaluate the phase's entries again. + with pytest.raises( + ValueError, match=r"already evaluated \['a_block'\] at their stages" + ): + run.run_phase("assembled", other) + assert run.phases_evaluated == () + # A refused call evaluates none of its entries, so a_first still runs. + (passed,) = run.evaluate_entries(["a_first"], EvidenceContext()) + run.record_phase(assemble_phase_report(manifest, "assembled", [passed, failed])) + with pytest.raises(GateBatteryBlockedError): + run.enforce("assembled", mode=BlockingMode.BLOCKS_ARTIFACT) + + def test_the_run_refuses_an_outcome_its_stage_did_not_produce( + self, tmp_path, signing_env + ): + # Review of #1609: a phase must carry the outcome the run's stage + # produced, not another evaluation, such as one under another registry. + manifest = _manifest( + [ + _entry("a_first", gate="support", phase="assembled"), + _entry("a_block", gate="exported_nonzero", phase="assembled"), + ], + ["assembled"], + ) + run = self._run(manifest, tmp_path, "terminal_gates.json") + produced = run.evaluate_entries(["a_first", "a_block"], EvidenceContext()) + lenient = {**self._registry(), "exported_nonzero": _binding("exported_nonzero")} + (passing,) = evaluate_entries( + manifest, ["a_block"], EvidenceContext(), registry=lenient + ) + assert passing.status is GateStatus.PASSED + swapped = assemble_phase_report(manifest, "assembled", [produced[0], passing]) + with pytest.raises( + ValueError, match=r"carries outcomes for \['a_block'\] other than" + ): + run.record_phase(swapped) + assert run.phases_evaluated == () + # The stages' own outcomes, carried through a phase payload and back, + # are compared by content and record. + carried = gate_phase_report_from_payload( + gate_phase_report_payload( + assemble_phase_report(manifest, "assembled", produced), gates=manifest + ), + gates=manifest, + ) + assert carried.outcomes[1] is not produced[1] + run.record_phase(carried) + assert run.report_payload()["gates"]["a_block"]["status"] == "failed" + + def test_the_report_carries_a_stage_outcome_its_phase_never_recorded( + self, tmp_path, signing_env + ): + # Review of #1609: a terminal stage that ran before preflight blocked + # was signed unreached, since the blocked run never records its phase. + manifest = _manifest( + [ + _entry("pf_gate", gate="exported_nonzero", phase="preflight"), + _entry("t_gate", gate="exported_nonzero"), + _entry("t_later", gate="support"), + ] + ) + run = self._run(manifest, tmp_path, "terminal_gates.json") + (stage,) = run.evaluate_entries(["t_gate"], EvidenceContext()) + assert stage.status is GateStatus.FAILED + run.run_phase("preflight", EvidenceContext()) + with pytest.raises(GateBatteryBlockedError): + run.enforce("preflight", mode=BlockingMode.BLOCKS_ARTIFACT) + written = json.loads(run.report_path.read_text()) + assert written == run.report_payload() + assert written["blocked_at_phase"] == "preflight" + assert written["phases_evaluated"] == ["preflight"] + assert written["gates"]["t_gate"] == stage.to_payload() + # An entry the run never evaluated is still unreached. + assert written["gates"]["t_later"]["status"] == "unreached" + assert written["shippable"] is False + + def test_a_stage_outcome_ships_only_once_its_phase_is_recorded( + self, tmp_path, signing_env + ): + # The report shows a stage's outcome before its phase is recorded, + # but a run whose last phase has passed only at its stages has not + # finished, so it cannot ship until that phase is recorded. + manifest = _manifest( + [ + _entry("pf_gate", gate="support", phase="preflight"), + _entry("t_gate", gate="support"), + ] + ) + run = self._run(manifest, tmp_path, "terminal_gates.json") + run.run_phase("preflight", EvidenceContext()) + assert run.enforce("preflight", mode=BlockingMode.BLOCKS_ARTIFACT) is False + (passed,) = run.evaluate_entries(["t_gate"], EvidenceContext()) + assert passed.status is GateStatus.PASSED + assert run.report_payload()["shippable"] is False + run.record_phase(assemble_phase_report(manifest, "terminal", [passed])) + assert run.report_payload()["shippable"] is True + + +class TestRecordWithoutEnforce: + """The keep-going posture: run every phase, never enforce (#1585 item 11). + + An evidence build and a dry run continue past failed gates. Running every + phase without ``enforce`` records them all, marks nothing blocked, and + leaves the report unshippable while a release-blocking entry has not + passed. + """ + + @pytest.mark.parametrize("release_candidate", [True, False]) + def test_every_phase_records_and_the_report_stays_unshippable( + self, tmp_path, signing_env, release_candidate + ): + manifest = _manifest( + [ + _entry("pf_fail", gate="support", phase="preflight"), + _entry("t_pass", gate="exported_nonzero"), + _entry("t_absent", gate="weights_audit"), + ] + ) + run = GateBatteryRun( + manifest, + release_id="xx-test-build", + report_path=tmp_path / "terminal_gates.json", + release_candidate=release_candidate, + registry={ + "support": _binding("support", passes=False), + "exported_nonzero": _binding("exported_nonzero"), + "weights_audit": DEFAULT_REGISTRY["weights_audit"], + }, + ) + run.run_phase("preflight", EvidenceContext()) + # Under enforce the failure would have blocked here. + assert run.phase_report("preflight").blocking_outcomes( + release_candidate=release_candidate + ) + assert json.loads(run.report_path.read_text())["phases_evaluated"] == [ + "preflight" + ] + run.run_phase("terminal", EvidenceContext()) + + report = json.loads(run.report_path.read_text()) + assert report == run.report_payload() + assert report["phases_evaluated"] == ["preflight", "terminal"] + assert report["blocked_at_phase"] is None + assert {entry: gate["status"] for entry, gate in report["gates"].items()} == { + "pf_fail": "failed", + "t_pass": "passed", + "t_absent": "evidence_absent", + } + assert report["shippable"] is False + assert report["attestation"]["signature"] is not None + + +class TestSharedScopesAndBindings: + """The UK's scoping and re-minting binding, lifted for every country. + + One battery run takes one manifest, so each build tool runs its own + scope; and gates written before the battery mint their own result names, + which the shared binding re-mints (#1585 item 11). + """ + + def test_a_scope_keeps_declared_order_and_has_its_own_digests(self, tmp_path): + manifest = _manifest( + [ + _entry("pf", gate="support", phase="preflight"), + _entry("t_a", gate="exported_nonzero"), + _entry("t_b", gate="nonconstant_columns"), + ] + ) + scoped = scoped_gate_manifest( + manifest, + frozenset({"t_b", "t_a"}), + phases=("terminal",), + policy_suffix="terminal_scope", + ) + assert [entry.id for entry in scoped.gates] == ["t_a", "t_b"] + assert scoped.phases == ("terminal",) + assert scoped.policy == "test battery; terminal_scope" + assert (scoped.country, scoped.version) == (manifest.country, manifest.version) + runs = [ + GateBatteryRun( + gates, + release_id="xx-test-build", + report_path=tmp_path / f"{index}.json", + release_candidate=False, + registry={}, + ) + for index, gates in enumerate((manifest, scoped)) + ] + for digest in ("gates_manifest_sha256", "policy_sha256", "spec_fingerprint"): + assert getattr(runs[0], digest) != getattr(runs[1], digest), digest + with pytest.raises( + RuntimeError, + match=r"XX gate scope names undeclared gate id\(s\): \['t_missing'\]", + ): + scoped_gate_manifest( + manifest, + ("t_a", "t_missing"), + phases=("terminal",), + policy_suffix="terminal_scope", + ) + + def test_the_binding_re_mints_only_its_declared_legacy_name(self): + manifest = _manifest([_entry("t", gate="support")], ["terminal"]) + + def minting(name): + return lambda context, parameters: GateResult(name=name, passed=True) + + def binding(minted): + # Frameless here; like UKGateBinding, the binding needs a frame + # unless it says otherwise. + return EvaluatorBinding( + name="support", + evaluator=minting(minted), + legacy_name="xx_support", + needs_frame=False, + ) + + reminted, impostor = binding("xx_support"), binding("parity") + (passed,) = evaluate_phase( + manifest, "terminal", EvidenceContext(), registry={"support": reminted} + ).outcomes + assert passed.status is GateStatus.PASSED + assert passed.result.name == "support" + (failed,) = evaluate_phase( + manifest, "terminal", EvidenceContext(), registry={"support": impostor} + ).outcomes + assert failed.status is GateStatus.FAILED + assert failed.result.details["returned_gate"] == "parity" + + def test_the_binding_selects_its_evidence_from_declared_parameters(self): + binding = EvaluatorBinding( + name="support", + evaluator=lambda context, parameters: GateResult( + name="support", passed=True + ), + parameter_keys=frozenset({"source"}), + artifact_selector=lambda parameters: frozenset({parameters["source"]}), + frame_predicate=lambda parameters: parameters["source"] == "stage_frame", + ) + manifest = _manifest( + [ + _entry("t_frame", gate="support", parameters={"source": "stage_frame"}), + _entry("t_counts", gate="support", parameters={"source": "counts"}), + ], + ["terminal"], + ) + report = evaluate_phase( + manifest, + "terminal", + EvidenceContext(artifacts={"counts": 3}), + registry={"support": binding}, + ) + by_id = {outcome.entry.id: outcome for outcome in report.outcomes} + assert by_id["t_counts"].status is GateStatus.PASSED + assert by_id["t_frame"].status is GateStatus.EVIDENCE_ABSENT + assert by_id["t_frame"].reason == "missing evidence: frame, stage_frame" + with pytest.raises(ValueError, match=r"'t'.*sorce"): + evaluate_phase( + _manifest( + [_entry("t", gate="support", parameters={"sorce": "counts"})], + ["terminal"], + ), + "terminal", + EvidenceContext(), + registry={"support": binding}, + ) diff --git a/packages/microcosm-build/tests/engine_free/shared/test_gate_battery_contract_pins.py b/packages/microcosm-build/tests/engine_free/shared/test_gate_battery_contract_pins.py index 358bf8b0c4..0b326bf3f4 100644 --- a/packages/microcosm-build/tests/engine_free/shared/test_gate_battery_contract_pins.py +++ b/packages/microcosm-build/tests/engine_free/shared/test_gate_battery_contract_pins.py @@ -13,14 +13,18 @@ import hashlib import hmac import json +from collections.abc import Mapping +from dataclasses import dataclass import pytest from microcosm.build import load_country_spec +from microcosm.build.country_spec import GatesManifest from microcosm.build.gate_battery import ( GATE_BATTERY_ATTESTATION_SCHEMA_VERSION, GATE_BATTERY_PRODUCER, GATE_BATTERY_SCHEMA_VERSION, + BlockingMode, EvidenceContext, GateBatteryRun, GateOutcome, @@ -41,6 +45,182 @@ KEY = base64.b64encode(b"\x07" * 32).decode("ascii") +def _green_uk_details() -> dict[str, dict[str, object]]: + """Synthetic details, keyed by entry id, shaped as the exact-k checker + reads them; the values the checker pins come from its own mirrors.""" + + evaluated_on = "2026-11-13" + weights = dict.fromkeys(data_contract._UK_WEIGHT_SUMMARY_FIELDS, 1.0) + reference_build = "uk-frs-calibration-attempt-fixture" + reference_release = sorted(data_contract._UK_CUT_REFERENCE_RELEASES)[0] + exclusions = { + "reviewed_exclusions": {}, + "stale_exclusions": [], + "dormant_exclusions": [], + } + dated_exclusions = { + **exclusions, + "expired_exclusions": [], + "premature_exclusions": [], + "exclusions_evaluated_on": evaluated_on, + } + return { + "uk_release_input_coverage_manifest_current": {"check": "manifest_current"}, + "uk_release_family_build_stages": {"stage_names": ["fixture_stage"]}, + "uk_release_input_coverage": { + "required_columns": 3, + "present_columns": 3, + "missing": [], + "degenerate_required": [], + **exclusions, + }, + "uk_degenerate_release_surface": { + "columns_checked": 3, + "findings": {}, + "all_null_columns": [], + "all_zero_columns": [], + "constant_columns": [], + **dated_exclusions, + }, + "uk_zero_weight_strata": { + "household_rows": 3, + "zero_weight_rows": 0, + "declared_strata": [], + "unmatched_zero_weight_rows": 0, + "unmatched_household_examples": [], + "ambiguous_zero_weight_rows": 0, + "ambiguous_household_examples": [], + }, + "uk_weight_ess": { + **weights, + "minimum_ess_fraction": data_contract._UK_MIN_ESS_FRACTION, + }, + "uk_weight_ratio": { + **weights, + "maximum_max_to_median_ratio": data_contract._UK_MAX_TO_MEDIAN_WEIGHT_RATIO, + }, + "uk_weights_audit": { + "fits_checked": 1, + "resolved_weight_kinds": {"fixture_fit": "design"}, + "unweighted_fits": [], + "allowed_unweighted": [], + "unused_allowed_unweighted": [], + }, + "uk_export_surface": { + "candidate_columns": 3, + "reference_columns": 3, + "missing_reference_columns": [], + "unexpected_candidate_columns": [], + "forbidden_candidate_columns": [], + }, + "uk_target_surface": { + "candidate_targets": 3, + "reference_targets": 3, + "extra_candidate_targets": [], + "missing_reference_targets": [], + }, + "uk_target_fit": { + "targets_checked": 3, + "max_abs_relative_error": data_contract._UK_MAX_TARGET_ABS_RELATIVE_ERROR, + "failing_targets": {}, + **dated_exclusions, + }, + "uk_aggregate_admin": {"anchors_checked": 3}, + "uk_input_mass_parity": { + "candidate_name": "candidate", + "reference_name": "reference", + "relative_tolerance": data_contract._UK_INPUT_MASS_RELATIVE_TOLERANCE, + "minimum_reference_total": ( + data_contract._UK_INPUT_MASS_MINIMUM_REFERENCE_TOTAL + ), + "maximum_relative_drop": data_contract._UK_INPUT_MASS_MAXIMUM_RELATIVE_DROP, + "excess_drops": [], + "columns_checked": 3, + "columns_below_reference_floor": [], + "candidate_only_columns": [], + "worst_drifts": [], + "unused_reviewed_exclusions": [], + **dated_exclusions, + "reference": data_contract._UK_INPUT_MASS_ACTIVE_REFERENCE, + "reference_scope_note": "fixture reference", + "reference_label": f"{reference_release}@{reference_build}", + "reference_identity": { + "filename": "fixture.h5", + "revision": reference_build, + "sha256": "d" * 64, + "vintage": "fixture", + }, + }, + "uk_support": {"columns_checked": 3}, + } + + +@dataclass(frozen=True) +class _GreenBinding: + """Passes every entry of one gate, each with its own details and evidence. + + Rows are ``(parameters, details, evidence)``; an entry is found by its + declared parameters, and entries that declare equal ones share a row. + """ + + name: str + parameter_keys: frozenset[str] + rows: tuple[tuple[Mapping[str, object], Mapping[str, object], object], ...] + + def _row(self, parameters): + return next(row for row in self.rows if row[0] == parameters) + + def required_artifacts(self, parameters) -> frozenset[str]: + return frozenset() + + def requires_frame(self, parameters) -> bool: + return False + + def evaluate(self, context, parameters) -> GateResult: + return GateResult( + name=self.name, passed=True, details=dict(self._row(parameters)[1]) + ) + + def evidence_payload(self, context, parameters) -> object | None: + return self._row(parameters)[2] + + +def _green_uk_registry(gates: GatesManifest) -> dict[str, _GreenBinding]: + from microcosm.build.uk_runtime.terminal_gates import ( + uk_default_degenerate_reviewed_exclusions, + ) + + details = _green_uk_details() + # The checker pins the degenerate entry's evidence to the committed register. + committed_register = { + "exclusions_policy": "committed", + "reviewed_exclusions": { + name: record.policy_payload() + for name, record in sorted( + uk_default_degenerate_reviewed_exclusions().items() + ) + }, + } + rows: dict[str, list] = {} + for entry in gates.gates: + evidence = None + if entry.id == "uk_degenerate_release_surface": + evidence = committed_register + elif entry.id in data_contract._UK_GATE_BATTERY_EVIDENCE_IDS: + evidence = {"fixture_evidence": entry.id} + rows.setdefault(entry.gate, []).append( + (entry.parameters, details.get(entry.id, {}), evidence) + ) + return { + gate: _GreenBinding( + name=gate, + parameter_keys=frozenset(key for row in gate_rows for key in row[0]), + rows=tuple(gate_rows), + ) + for gate, gate_rows in rows.items() + } + + def _uk_run(tmp_path, **overrides) -> GateBatteryRun: arguments = { "release_id": "populace-uk-2023-frs-k535080", @@ -225,6 +405,8 @@ class TestProducerRoundTrip: "signing_key_sha256 does not identify", "gate_outcomes_sha256 does not match", "exactly the declared UK entry ids", + "(schema 4) must contain exactly", + "attestation must contain exactly", ) def test_signature_scheme_is_verifiable_across_the_shards( @@ -284,6 +466,43 @@ def test_a_real_report_survives_every_mirror_check( ] assert drifted == [], drifted + def test_a_green_report_from_the_executor_passes_the_checker( + self, tmp_path, monkeypatch + ) -> None: + """The checker accepts, with no failure at all, what the executor writes. + + Every UK entry passes with details shaped as the checker reads them, + so any failure is a drift between the report the executor writes and + the one the checker expects, such as the ``synthetic_smoke`` field the + test above missed. + """ + + monkeypatch.setenv(gate_signing_key_env("uk"), KEY) + gates = load_country_spec("uk").gates + run = _uk_run( + tmp_path, + release_candidate=True, + registry=_green_uk_registry(gates), + release_evidence={"calibration_diagnostics_sha256": "c" * 64}, + ) + for phase in gates.phases: + run.run_phase(phase, EvidenceContext()) + assert run.enforce(phase, mode=BlockingMode.BLOCKS_ARTIFACT) is False + report = json.loads((tmp_path / "terminal_gates.json").read_text()) + assert report["shippable"] is True + assert report["synthetic_smoke"] is False + + failures: list[str] = [] + data_contract._check_uk_gate_battery_report( + report, + release_id="populace-uk-2023-frs-k535080", + calibration_diagnostics_sha256="c" * 64, + build_manifest=None, + calibration_diagnostics={"targets": [{}, {}, {}]}, + failures=failures, + ) + assert failures == [] + class TestCertificationMirrors: """The data shard's certification mirrors track the build shard.""" diff --git a/packages/microcosm-data/src/microcosm/data/contract.py b/packages/microcosm-data/src/microcosm/data/contract.py index 1ab255142a..06d4eb9d70 100644 --- a/packages/microcosm-data/src/microcosm/data/contract.py +++ b/packages/microcosm-data/src/microcosm/data/contract.py @@ -3309,6 +3309,7 @@ def _check_uk_gate_battery_report( "country", "release_id", "release_candidate", + "synthetic_smoke", "spec_fingerprint", "gates_manifest_sha256", "phases", @@ -3348,6 +3349,11 @@ def _check_uk_gate_battery_report( "the candidate posture excused absent evidence and cannot be " "promoted into a release." ) + if report.get("synthetic_smoke") is not False: + failures.append( + f"{file} synthetic_smoke must be false: a synthetic smoke build " + "ran on a fixture, not the population, and is never a release." + ) if report.get("blocked_at_phase") is not None: failures.append(f"{file} blocked_at_phase must be null for a release.") if list(report.get("phases") or ()) != list(_UK_GATE_BATTERY_PHASES): @@ -3623,6 +3629,7 @@ def _check_uk_gate_battery_report( "country", "release_id", "release_candidate", + "synthetic_smoke", "spec_fingerprint", "gates_manifest_sha256", "policy_sha256", @@ -3661,6 +3668,7 @@ def _check_uk_gate_battery_report( "country", "release_id", "release_candidate", + "synthetic_smoke", "spec_fingerprint", "gates_manifest_sha256", "policy_sha256", diff --git a/packages/microcosm-data/tests/engine_free/shared/test_contract.py b/packages/microcosm-data/tests/engine_free/shared/test_contract.py index 07070a4904..84ec885418 100644 --- a/packages/microcosm-data/tests/engine_free/shared/test_contract.py +++ b/packages/microcosm-data/tests/engine_free/shared/test_contract.py @@ -1368,6 +1368,7 @@ def _resign_gate_battery( "country": payload["country"], "release_id": payload["release_id"], "release_candidate": payload["release_candidate"], + "synthetic_smoke": payload["synthetic_smoke"], "spec_fingerprint": payload["spec_fingerprint"], "gates_manifest_sha256": payload["gates_manifest_sha256"], "policy_sha256": payload["policy_sha256"], @@ -1603,6 +1604,7 @@ def _gate_battery_payload( "country": "uk", "release_id": release_id, "release_candidate": True, + "synthetic_smoke": False, "spec_fingerprint": UK_GATE_BATTERY_SPEC_FINGERPRINT, "gates_manifest_sha256": UK_GATE_BATTERY_GATES_MANIFEST_SHA256, "phases": ["preflight", "assembled", "transferred", "terminal"], @@ -5197,6 +5199,43 @@ def test_exact_k_uk_gate_battery_rejects_a_non_candidate_report( assert "release_candidate must be true" in _battery_failures(directory) +def test_exact_k_uk_gate_battery_rejects_a_synthetic_smoke_report( + tmp_path: Path, +) -> None: + # The executor writes synthetic_smoke into the body and the attestation of + # every schema-4 report; a smoke build ran on a fixture and never ships. + directory, payload = _write_battery_release(tmp_path) + payload["synthetic_smoke"] = True + _rewrite_battery_report(directory, payload) + + assert "synthetic_smoke must be false" in _battery_failures(directory) + + +def test_exact_k_uk_gate_battery_rejects_an_attestation_smoke_flag_off_the_body( + tmp_path: Path, +) -> None: + # Review of #1609: the attestation's own copy must restate the body's. + # Signed honestly over the divergent copy, so only that check refuses it. + directory, payload = _write_battery_release(tmp_path) + attestation = payload["attestation"] + attestation["synthetic_smoke"] = True + attestation["signature"] = None + attestation["signature"] = hmac.new( + TEST_UK_TERMINAL_GATE_SIGNING_KEY_BYTES, + _canonical_json_bytes(payload), + hashlib.sha256, + ).hexdigest() + _rewrite_battery_report(directory, payload, resign=False) + + failures = _battery_failures(directory) + assert ( + "attestation.synthetic_smoke must equal the report body's synthetic_smoke" + in failures + ) + assert "signature does not authenticate" not in failures + assert "synthetic_smoke must be false" not in failures + + def test_exact_k_uk_gate_battery_rejects_loosened_input_mass_tolerance( tmp_path: Path, ) -> None: