From ad8130e4642fb750d985be10c800805b0f631b59 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mar=C3=ADa=20Juaristi?= <127882282+juaristi22@users.noreply.github.com> Date: Sun, 15 Nov 2026 14:05:15 +0000 Subject: [PATCH 01/31] Test the narrow gates loader's refusal on a package copy, not the US PR 1's test (microcosm#1609) checked that load_gates_manifest refuses a package with no gates.json row by loading "us", which declared none. PR 2 of microcosm#1585 item 11 gives the US its gates.json, so the test now removes the row from a copy of the Belgian package instead. The refusal and its message are unchanged. This is a change to PR 1's shared test, kept as its own commit at the bottom of PR 2 so PR 1's branch stays as reviewed. Co-Authored-By: Claude Opus 5.5 --- .../shared/test_country_gates_manifest.py | 14 ++++++++++++-- 1 file changed, 12 insertions(+), 2 deletions(-) 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 index cc61bd836a..01e95d6942 100644 --- 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 @@ -41,9 +41,19 @@ def test_the_narrow_loader_reads_no_other_resource(tmp_path) -> None: 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. + # A package that declares no gates.json row; the loader never falls back. + undeclared = _package_copy(tmp_path / "undeclared", "be") + package = json.loads( + (undeclared / "country_package.json").read_text(encoding="utf-8") + ) + package["resources"] = [ + row for row in package["resources"] if row["path"] != "gates.json" + ] + (undeclared / "country_package.json").write_text( + json.dumps(package), encoding="utf-8" + ) with pytest.raises(ValueError, match="no legacy_json gates.json"): - load_gates_manifest("us") + load_gates_manifest(undeclared) root = _package_copy(tmp_path, "be") gates = json.loads((root / "gates.json").read_text(encoding="utf-8")) gates["phases"] = ["exported"] From b25f570863d63aa5fc6f55c079bf08e856338c63 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mar=C3=ADa=20Juaristi?= <127882282+juaristi22@users.noreply.github.com> Date: Sun, 15 Nov 2026 14:05:43 +0000 Subject: [PATCH 02/31] Add the shared US pieces for running the gate battery in shadow PR 2 of 4 for microcosm#1585 item 11 (microcosm#611). Today's US gates stay authoritative; each tool will evaluate its gates' declared entries beside them and compare the verdicts. - us_runtime/gate_shadow.py: GateBatteryShadow observes each gate where it runs, compares verdicts (the waiver proposal's rule: verdicts, not enforcement; a crash matches an evaluation_error; a gate today's code did not run matches evidence_absent; a runtime threshold override explains its difference), never raises while the tool runs, assembles the phases at the end, and writes the battery's report and the comparison beside the tool's outputs. A difference fails the finished run; today's own exception always propagates unchanged. Observations can be saved and loaded across processes for tools that run stages separately. - us_runtime/battery_bindings.py: USGateSpec and USCheckBinding re-mint a pre-battery gate under the declared name, route keyword thresholds from the spec, and pin module-constant thresholds equal to today's values. Bindings call the gate a site calls, through the tool's own globals. - us_runtime/gate_scopes.py: the four scopes (us_base, us_pool, us_national, us_local), one per build tool, owned by id prefix and checked closed-world, each with its own digests. Co-Authored-By: Claude Opus 5.5 --- .../build/us_runtime/battery_bindings.py | 464 +++++++ .../microcosm/build/us_runtime/gate_scopes.py | 200 +++ .../microcosm/build/us_runtime/gate_shadow.py | 1123 +++++++++++++++++ .../engine_free/us/test_us_gate_shadow.py | 821 ++++++++++++ .../microcosm_build/us_gate_shadow.py | 123 ++ 5 files changed, 2731 insertions(+) create mode 100644 packages/microcosm-build/src/microcosm/build/us_runtime/battery_bindings.py create mode 100644 packages/microcosm-build/src/microcosm/build/us_runtime/gate_scopes.py create mode 100644 packages/microcosm-build/src/microcosm/build/us_runtime/gate_shadow.py create mode 100644 packages/microcosm-build/tests/engine_free/us/test_us_gate_shadow.py create mode 100644 test_support/microcosm_build/us_gate_shadow.py diff --git a/packages/microcosm-build/src/microcosm/build/us_runtime/battery_bindings.py b/packages/microcosm-build/src/microcosm/build/us_runtime/battery_bindings.py new file mode 100644 index 0000000000..6af1243086 --- /dev/null +++ b/packages/microcosm-build/src/microcosm/build/us_runtime/battery_bindings.py @@ -0,0 +1,464 @@ +"""US gate bindings for the shared battery (microcosm#1585 item 11, PR 2 of 4). + +Every US gate was written before the battery. It takes its evidence as +ordinary arguments, keeps its thresholds as module constants or keyword +defaults, and mints its own result name. A binding here adapts one such gate +to the battery's ``(context, parameters)`` call: + +- the evidence comes from named context artifacts, and from the phase frame + where the gate reads one; +- a threshold the gate already takes as a keyword is routed from the entry + parameter of the same name, so the battery evaluates with the declared + value; +- a threshold the gate reads from a module constant is *pinned*: the entry + declares it, and the binding fails the entry closed unless the declared + value equals today's constant. The gate functions stay as they are in this + pull request, which adds code and removes nothing (about 25 of their modules + are attested by the US seed protocol, so editing them would move its pins). + The flip (PR 3) removes the constants and turns each pinned threshold into + a routed keyword; +- the gate's own result name is re-minted under the declared one, as + :class:`~microcosm.build.gate_battery.EvaluatorBinding` does. + +Most US gates are declared as ``stage_health`` entries whose ``check`` +parameter names the gate, the UK's pattern for stage-time checks, so that no +name enters the shared vocabulary (``country_spec.ALLOWED_GATE_FUNCTIONS``) +before Max's Step 0 answer. One :class:`USCheckBinding` serves every such +entry, dispatching on ``check``. + +A binding calls the gate function the gate's site calls, looked up where the +site looks it up and when it runs, so a test that patches a tool's global +reaches both verdicts. A reference is ``"tool:"`` for a name in the +build tool's own module (the package never imports ``tools/``: the tool +passes its live ``globals()`` when it builds its registry, which works however +the tool was loaded), or ``":"`` for a package module. Each registry call returns a new mapping and resolves every +reference once up front, so a misspelt name is refused before a gate runs and +no shared registry is mutated. +""" + +from __future__ import annotations + +import importlib +import json +from collections.abc import Callable, Mapping, Sequence +from dataclasses import dataclass, field, replace +from types import MappingProxyType, ModuleType +from typing import Any + +from microcosm.build.gate_battery import ( + DEFAULT_REGISTRY, + EvidenceContext, + GateBinding, +) +from microcosm.build.gates import GateResult + +__all__ = [ + "FRAME", + "ToolNamespace", + "USCheckBinding", + "USGateSpec", + "declared_value", + "resolve_reference", + "us_check_binding", +] + +#: The argument source that means "the phase's frame", not an artifact. +FRAME = "frame" + +_TOOL = "tool" + + +def declared_value(value: object) -> object: + """``value`` as a ``gates.json`` entry declares it (JSON's data model).""" + + if isinstance(value, Mapping): + return {str(key): declared_value(item) for key, item in value.items()} + if isinstance(value, (tuple, list)): + return [declared_value(item) for item in value] + if isinstance(value, (set, frozenset)): + return sorted(declared_value(item) for item in value) + item = getattr(value, "item", None) + if callable(item) and not isinstance(value, (bool, int, float, str)): + return declared_value(item()) + return value + + +def _routed(value: object) -> object: + """A declared value as the gate's keyword takes it: JSON lists as tuples. + + Gates format their bounds into failure lines, so a band must reach them + as the tuple today's default is, or the two verdicts' lines would differ. + """ + + if isinstance(value, list): + return tuple(_routed(item) for item in value) + if isinstance(value, Mapping): + return {key: _routed(item) for key, item in value.items()} + return value + + +def _same(left: object, right: object) -> bool: + return json.dumps(declared_value(left), sort_keys=True) == json.dumps( + declared_value(right), sort_keys=True + ) + + +def _split_reference(reference: str) -> tuple[str, str]: + module, separator, name = reference.partition(":") + if not separator or not module or not name: + raise ValueError( + f"reference {reference!r} must be 'tool:' or ':'." + ) + return module, name + + +#: A build tool's namespace: its module, or its live ``globals()``. +ToolNamespace = ModuleType | Mapping[str, Any] + + +def resolve_reference(reference: str, *, tool: ToolNamespace | None) -> object: + """The object ``reference`` names, looked up now.""" + + module, name = _split_reference(reference) + if module == _TOOL: + if tool is None: + raise ValueError( + f"{reference!r} names a tool global, but no tool was given." + ) + if isinstance(tool, Mapping): + try: + return tool[name] + except KeyError: + raise AttributeError(f"the tool has no global {name!r}") from None + return getattr(tool, name) + return getattr(importlib.import_module(module), name) + + +@dataclass(frozen=True) +class USGateSpec: + """How the battery calls one US gate. + + Attributes: + check: The value of the entry's ``check`` parameter. + legacy_name: The result name the gate mints today; re-minted under + the declared gate name. + gate: Reference to the gate function the site calls. + positional: Argument sources passed positionally, in order: artifact + keys, or :data:`FRAME`. + arguments: Keyword argument to its source (artifact key or + :data:`FRAME`). + parameters: Threshold keywords the gate takes, each routed from the + entry parameter of the same name. + pinned: Entry parameter to the reference of the module constant the + gate reads it from; the declared value must equal the constant. + returns_failures: The gate returns failure lines rather than a + :class:`~microcosm.build.gates.GateResult`; the binding wraps + them (an empty list passes). + adapt: Optional final step turning the gate's return value into its + :class:`~microcosm.build.gates.GateResult`. + """ + + check: str + legacy_name: str + gate: str + positional: tuple[str, ...] = () + arguments: Mapping[str, str] = field(default_factory=dict) + parameters: frozenset[str] = frozenset() + pinned: Mapping[str, str] = field(default_factory=dict) + returns_failures: bool = False + adapt: Callable[[Any], GateResult] | None = None + + def __post_init__(self) -> None: + if not self.check or not self.legacy_name: + raise ValueError("a US gate spec needs its check and its legacy name.") + _split_reference(self.gate) + for reference in self.pinned.values(): + _split_reference(reference) + keys = set(self.parameters) | set(self.pinned) + if "check" in keys: + raise ValueError( + f"{self.check}: 'check' is the dispatch key, not a threshold." + ) + if set(self.parameters) & set(self.pinned): + raise ValueError( + f"{self.check}: {sorted(set(self.parameters) & set(self.pinned))} " + "are both routed and pinned." + ) + overlap = keys & set(self.arguments) + if overlap: + raise ValueError( + f"{self.check}: {sorted(overlap)} are both evidence and thresholds." + ) + if self.returns_failures and self.adapt is not None: + raise ValueError(f"{self.check}: returns_failures and adapt both wrap.") + object.__setattr__(self, "arguments", MappingProxyType(dict(self.arguments))) + object.__setattr__(self, "pinned", MappingProxyType(dict(self.pinned))) + + @property + def parameter_keys(self) -> frozenset[str]: + return frozenset(self.parameters) | frozenset(self.pinned) + + @property + def sources(self) -> tuple[str, ...]: + return (*self.positional, *self.arguments.values()) + + @property + def artifact_keys(self) -> frozenset[str]: + return frozenset(source for source in self.sources if source != FRAME) + + @property + def needs_frame(self) -> bool: + return FRAME in self.sources + + @property + def references(self) -> tuple[str, ...]: + return (self.gate, *self.pinned.values()) + + +def _as_gate_result(value: object, legacy_name: str) -> object: + """A verdict object that is not a GateResult, read as today's code reads it. + + Today's sites read only ``passed``, ``failures`` and ``details``, and the + builders' tests stand such objects in for gates; anything else is + returned as is, and the executor fails it closed. + """ + + passed = getattr(value, "passed", None) + failures = getattr(value, "failures", None) + if not isinstance(passed, bool) or failures is None or isinstance(failures, str): + return value + return GateResult( + name=str(getattr(value, "name", legacy_name)), + passed=passed, + failures=tuple(str(line) for line in failures), + details=dict(getattr(value, "details", None) or {}), + ) + + +def _source(context: EvidenceContext, source: str) -> object: + return context.frame if source == FRAME else context.artifacts[source] + + +class USCheckBinding: + """One declared gate name serving many US gates, chosen by ``check``. + + Implements :class:`~microcosm.build.gate_battery.GateBinding`. Its + ``parameter_keys`` is ``check`` plus every threshold any of its gates + takes or pins, so ``validate_gate_parameters`` refuses an unknown key + before a gate runs. An entry that declares fewer keys than its gate pins, + or a key its own gate does not take, fails closed when it evaluates. + + Args: + name: The declared gate name. + specs: One per check. + tool: The build tool's module, for ``"tool:"`` references. + """ + + def __init__( + self, + name: str, + specs: Sequence[USGateSpec], + *, + tool: ToolNamespace | None = None, + ) -> None: + by_check: dict[str, USGateSpec] = {} + for spec in specs: + if spec.check in by_check: + raise ValueError(f"{name}: check {spec.check!r} is declared twice.") + by_check[spec.check] = spec + unresolved = [] + for spec in by_check.values(): + for reference in spec.references: + try: + target = resolve_reference(reference, tool=tool) + except (AttributeError, ImportError, ValueError) as exc: + unresolved.append(f"{spec.check}: {reference} ({exc})") + continue + if reference == spec.gate and not callable(target): + unresolved.append(f"{spec.check}: {reference} is not callable") + if unresolved: + raise ValueError(f"{name}: unresolved references: {unresolved}.") + self.name = name + self._tool = tool + self._specs: Mapping[str, USGateSpec] = MappingProxyType(by_check) + self.parameter_keys = frozenset( + {"check"}.union(*(spec.parameter_keys for spec in specs)) + ) + + @property + def checks(self) -> Mapping[str, USGateSpec]: + return self._specs + + @property + def tool(self) -> ToolNamespace | None: + return self._tool + + def _lookup(self, parameters: Mapping[str, Any]) -> USGateSpec | None: + check = parameters.get("check") + return self._specs.get(check) if isinstance(check, str) else None + + def _spec(self, parameters: Mapping[str, Any]) -> USGateSpec: + spec = self._lookup(parameters) + if spec is None: + raise ValueError( + f"{self.name}: no US gate is bound to check " + f"{parameters.get('check')!r}; bound: {sorted(self._specs)}." + ) + return spec + + def required_artifacts(self, parameters: Mapping[str, Any]) -> frozenset[str]: + spec = self._lookup(parameters) + return spec.artifact_keys if spec is not None else frozenset() + + def requires_frame(self, parameters: Mapping[str, Any]) -> bool: + spec = self._lookup(parameters) + return spec.needs_frame if spec is not None else False + + def pinned_values(self, check: str) -> dict[str, object]: + """Today's value of each threshold ``check`` pins, as JSON data.""" + + spec = self._specs[check] + return { + key: declared_value(resolve_reference(reference, tool=self._tool)) + for key, reference in spec.pinned.items() + } + + def evaluate( + self, context: EvidenceContext, parameters: Mapping[str, Any] + ) -> GateResult: + spec = self._spec(parameters) + declared = {key: value for key, value in parameters.items() if key != "check"} + unknown = sorted(set(declared) - spec.parameter_keys) + if unknown: + raise ValueError( + f"check {spec.check!r} does not take parameter(s) {unknown}; it " + f"takes {sorted(spec.parameter_keys)}." + ) + undeclared = sorted(set(spec.pinned) - set(declared)) + if undeclared: + raise ValueError( + f"check {spec.check!r} pins {undeclared}, which the entry does " + "not declare." + ) + for key, reference in spec.pinned.items(): + today = resolve_reference(reference, tool=self._tool) + if not _same(declared[key], today): + raise ValueError( + f"check {spec.check!r}: declared {key}={declared_value(declared[key])!r} " + f"differs from today's {reference} = {declared_value(today)!r}; " + "until the flip the spec must equal today's constant." + ) + gate = resolve_reference(spec.gate, tool=self._tool) + value = gate( + *(_source(context, source) for source in spec.positional), + **{ + argument: _source(context, source) + for argument, source in spec.arguments.items() + }, + **{ + key: _routed(declared[key]) + for key in spec.parameters + if key in declared + }, + ) + if spec.returns_failures: + if isinstance(value, str): + raise TypeError(f"check {spec.check!r} returned one string, not lines.") + lines = tuple(str(line) for line in value) + value = GateResult(name=spec.legacy_name, passed=not lines, failures=lines) + elif spec.adapt is not None: + value = spec.adapt(value) + elif not isinstance(value, GateResult): + value = _as_gate_result(value, spec.legacy_name) + if isinstance(value, GateResult) and value.name == spec.legacy_name: + value = replace(value, name=self.name) + return value + + def evidence_payload( + self, context: EvidenceContext, parameters: Mapping[str, Any] + ) -> object | None: + return None + + +def us_check_binding( + name: str, + specs: Sequence[USGateSpec], + *, + tool: ToolNamespace | None = None, + extra: Mapping[str, GateBinding] | None = None, +) -> dict[str, GateBinding]: + """A fresh registry: the shared bindings, ``extra``, and ``name`` over ``specs``.""" + + return { + **DEFAULT_REGISTRY, + **dict(extra or {}), + name: USCheckBinding(name, specs, tool=tool), + } + + +# --------------------------------------------------------------------------- +# The four scopes' gates +# --------------------------------------------------------------------------- + +_US = "microcosm.build.us_runtime" + + +def _pins(module: str, *constants: str) -> dict[str, str]: + """Pinned parameters named after today's constants. + + ``_RENT_SHARE_BAND`` in ``us_runtime.housing_inputs`` is declared as + ``rent_share_band``. + """ + + return { + constant.lstrip("_").lower(): f"{_US}.{module}:{constant}" + for constant in constants + } + + +def _frame_check( + check: str, + legacy_name: str, + gate: str, + module: str, + *constants: str, +) -> USGateSpec: + """A signal gate over the stage frame, called as the tool calls it.""" + + return USGateSpec( + check=check, + legacy_name=legacy_name, + gate=f"tool:{gate}", + positional=(FRAME,), + pinned=_pins(module, *constants), + ) + + +#: The frame signal gates both the base builder and the national release +#: run, keyed by check: (legacy name, gate function, module, pinned +#: constants). Each tool calls its own global of the same name. +_SCOPE_SPECS: Mapping[str, Callable[[], tuple[USGateSpec, ...]]] = MappingProxyType({}) + + +def us_gate_specs(scope: str) -> tuple[USGateSpec, ...]: + """The gates a scope's ``stage_health`` entries name by ``check``.""" + + try: + build = _SCOPE_SPECS[scope] + except KeyError: + raise ValueError( + f"no US gate specs for scope {scope!r}; declared: {sorted(_SCOPE_SPECS)}." + ) from None + return build() + + +def us_gate_registry(scope: str, *, tool: ToolNamespace) -> dict[str, GateBinding]: + """A fresh registry for one tool's scope. + + ``tool`` is the build tool's live ``globals()``, whose names the bindings + call, so the gate a site calls is the gate the battery calls. Resolves + every reference now: a name the tool does not have is refused before a + gate runs. + """ + + return us_check_binding("stage_health", us_gate_specs(scope), tool=tool) diff --git a/packages/microcosm-build/src/microcosm/build/us_runtime/gate_scopes.py b/packages/microcosm-build/src/microcosm/build/us_runtime/gate_scopes.py new file mode 100644 index 0000000000..2f3696c8a5 --- /dev/null +++ b/packages/microcosm-build/src/microcosm/build/us_runtime/gate_scopes.py @@ -0,0 +1,200 @@ +"""The four US gate scopes: one battery per build tool (microcosm#1585 item 11). + +A :class:`~microcosm.build.gate_battery.GateBatteryRun` runs one manifest, +each phase once and in order, so the US gives each build tool its own scope +of ``us/gates.json``, as the UK does for its spine build, calibration seam, +release cut and local candidate: the entries the tool evaluates, the phases +it evaluates them in, and a policy suffix, so each scope has its own +``gates_manifest_sha256``, ``policy_sha256`` and ``spec_fingerprint`` to pin. + +- ``us_base``: ``tools/build_us_puf_support_base.py``, Route A's base. +- ``us_pool``: ``tools/build_us_multispine_pool.py``. +- ``us_national``: ``tools/build_us_fiscal_refresh_release.py``. +- ``us_local``: ``tools/build_us_acs_local_release.py``. + +A scope owns the entries whose id starts with its name and an underscore +(``us_base_weights_audit`` belongs to ``us_base``). The partition is checked +closed-world in both directions, as the UK's is: an entry no scope owns, or +one bound to a phase its scope does not evaluate, is refused when the +manifest is scoped. +""" + +from __future__ import annotations + +import os +from collections.abc import Mapping +from dataclasses import dataclass +from functools import cache +from pathlib import Path +from types import MappingProxyType + +from microcosm.build.country_spec import GatesManifest, load_gates_manifest +from microcosm.build.gate_battery import ( + GateBatteryRun, + GateBinding, + scoped_gate_manifest, +) + +__all__ = [ + "US_GATE_SCOPES", + "USGateScope", + "check_us_gate_scopes", + "us_gate_scope_digests", + "us_gates_manifest", + "us_scope_entry_ids", + "us_scoped_gate_manifest", +] + + +@dataclass(frozen=True) +class USGateScope: + """One US build tool's share of ``us/gates.json``. + + Attributes: + name: The scope's name; its entries' id prefix and policy suffix stem. + tool: The repository path of the tool that evaluates it. + phases: The phases it evaluates, in order. + """ + + name: str + tool: str + phases: tuple[str, ...] + + @property + def prefix(self) -> str: + return f"{self.name}_" + + @property + def policy_suffix(self) -> str: + return f"{self.name}_scope" + + +US_GATE_SCOPES: Mapping[str, USGateScope] = MappingProxyType( + { + scope.name: scope + for scope in ( + USGateScope( + name="us_base", + tool="tools/build_us_puf_support_base.py", + phases=("assembled", "transferred", "terminal"), + ), + USGateScope( + name="us_pool", + tool="tools/build_us_multispine_pool.py", + phases=("assembled", "transferred", "terminal"), + ), + USGateScope( + name="us_national", + tool="tools/build_us_fiscal_refresh_release.py", + phases=("preflight", "assembled", "terminal"), + ), + USGateScope( + name="us_local", + tool="tools/build_us_acs_local_release.py", + phases=("assembled", "terminal"), + ), + ) + } +) + + +@cache +def us_gates_manifest() -> GatesManifest: + """The committed ``us/gates.json``, read once per process.""" + + return load_gates_manifest("us") + + +def _owner(entry_id: str) -> list[str]: + return [ + scope.name + for scope in US_GATE_SCOPES.values() + if entry_id.startswith(scope.prefix) + ] + + +def check_us_gate_scopes(gates: GatesManifest) -> None: + """Refuse a manifest the four scopes do not partition exactly. + + Raises: + RuntimeError: An entry no scope owns, one two scopes' prefixes both + match, or an entry bound to a phase its scope does not evaluate. + """ + + unowned: list[str] = [] + ambiguous: list[str] = [] + stray: list[str] = [] + for entry in gates.gates: + owners = _owner(entry.id) + if not owners: + unowned.append(entry.id) + elif len(owners) > 1: + ambiguous.append(entry.id) + elif entry.phase not in US_GATE_SCOPES[owners[0]].phases: + stray.append(f"{entry.id} ({entry.phase})") + if unowned or ambiguous or stray: + raise RuntimeError( + "US gate scopes must partition us/gates.json: owned by no scope " + f"{sorted(unowned)}, by two {sorted(ambiguous)}, bound to a phase " + f"their scope does not evaluate {sorted(stray)}." + ) + + +def us_scope_entry_ids( + scope: str, gates: GatesManifest | None = None +) -> tuple[str, ...]: + """The ids ``scope`` owns, in manifest order.""" + + declared = _scope(scope) + source = us_gates_manifest() if gates is None else gates + return tuple( + entry.id for entry in source.gates if entry.id.startswith(declared.prefix) + ) + + +def _scope(scope: str) -> USGateScope: + try: + return US_GATE_SCOPES[scope] + except KeyError: + raise ValueError( + f"unknown US gate scope {scope!r}; declared: {sorted(US_GATE_SCOPES)}." + ) from None + + +def us_scoped_gate_manifest( + scope: str, *, source: GatesManifest | None = None +) -> GatesManifest: + """One tool's scope of ``us/gates.json``. + + ``source`` lets a caller that already holds a manifest, or a hermetic + test, supply it; the default is the committed package spec. + """ + + declared = _scope(scope) + gates = us_gates_manifest() if source is None else source + check_us_gate_scopes(gates) + return scoped_gate_manifest( + gates, + us_scope_entry_ids(scope, gates), + phases=declared.phases, + policy_suffix=declared.policy_suffix, + ) + + +def us_gate_scope_digests( + scope: str, registry: Mapping[str, GateBinding] +) -> dict[str, str]: + """The scope's three pinned digests, as its run would attest them.""" + + run = GateBatteryRun( + us_scoped_gate_manifest(scope), + release_id="us-gate-scope-digest-derivation", + report_path=Path(os.devnull), + release_candidate=False, + registry=registry, + ) + return { + "gates_manifest_sha256": run.gates_manifest_sha256, + "policy_sha256": run.policy_sha256, + "spec_fingerprint": run.spec_fingerprint, + } diff --git a/packages/microcosm-build/src/microcosm/build/us_runtime/gate_shadow.py b/packages/microcosm-build/src/microcosm/build/us_runtime/gate_shadow.py new file mode 100644 index 0000000000..fb4dfd20e8 --- /dev/null +++ b/packages/microcosm-build/src/microcosm/build/us_runtime/gate_shadow.py @@ -0,0 +1,1123 @@ +"""The shared gate battery in shadow beside today's US gates. + +microcosm#1585 item 11 moves every US gate onto the country-agnostic battery +(:mod:`microcosm.build.gate_battery`, microcosm#611) in four pull requests. +This module is the second one's runtime. Each US build tool keeps gating +exactly as it does today, and beside each gate it evaluates the gate's +declared ``us/gates.json`` entry through one +:class:`~microcosm.build.gate_battery.GateBatteryRun` per tool scope, on the +same evidence, then compares the two verdicts. + +Today's code stays authoritative. Its raises, written files and manifest keys +do not change, and nothing here raises while the tool is still running: a +difference, or a fault in the shadow itself, is recorded and decided at the +end. When the tool finishes, the scope's battery report and the comparison +are written beside its outputs as shadow files. A verdict difference then +fails the run, so a build proves parity on its own inputs. When today's code +raises, the files are written with what the battery saw up to that point, and +today's exception propagates unchanged. + +The comparison follows the waiver proposal posted on microcosm#1609, which is +still for Max and MarĂ­a to settle: + +- waivers stay the tools' ``--allow-*`` flags, and the battery evaluates every + entry as if unwaived; +- verdicts are compared, not enforcement: passed or failed, with the same + failure lines, so a waived gate that fails in both is a match; +- the shadow file records, by entry id, which waiver flags the build used; +- an exception in today's evaluation and a battery outcome carrying + ``evaluation_error`` count as the same verdict. + +Two cases have no verdict to compare. A gate today's code did not evaluate on +this build (a stage that did not run, a gate a flag skips) matches a battery +outcome of ``evidence_absent``. A gate whose threshold the build overrode +with a command-line flag is evaluated by the battery at the declared value, +so a difference there is recorded as explained by the override and does not +fail the run: the spec cannot hold a per-run threshold, and that decision +belongs to the flip (PR 3), not to the shadow. +""" + +from __future__ import annotations + +import enum +import hashlib +import json +import os +import sys +import threading +from collections.abc import Callable, Iterable, Iterator, Mapping, Sequence +from contextlib import contextmanager +from dataclasses import dataclass +from pathlib import Path +from types import TracebackType +from typing import Any + +from microcosm.build.country_spec import GatesManifest +from microcosm.build.gate_battery import ( + EvidenceContext, + GateBatteryRun, + GateBinding, + GateOutcome, + GateStatus, + assemble_phase_report, + blocking_outcomes, +) +from microcosm.build.gates import GateResult + +__all__ = [ + "GATE_BATTERY_SHADOW_COMPARISON_SUFFIX", + "GATE_BATTERY_SHADOW_DIRECTORY", + "GATE_BATTERY_SHADOW_PRODUCER", + "GATE_BATTERY_SHADOW_REPORT_SUFFIX", + "GATE_BATTERY_SHADOW_SCHEMA_VERSION", + "GateBatteryShadow", + "GateBatteryShadowMismatchError", + "LegacyStatus", + "LegacyVerdict", + "active_gate_shadow", + "compare_verdicts", + "current_gate_shadow", + "legacy_parameter_overrides", + "shadow_check", + "shadow_failures", + "shadow_file_paths", + "shadow_gate", + "shadow_not_run", +] + +GATE_BATTERY_SHADOW_SCHEMA_VERSION = 1 +GATE_BATTERY_SHADOW_PRODUCER = "microcosm.build.us_runtime.gate_shadow" +#: The directory a tool writes its shadow files into, beside its outputs and +#: never inside a release directory, whose files the release manifests and +#: checksum ledgers may pick up. +GATE_BATTERY_SHADOW_DIRECTORY = "gate_battery_shadow" +_OBSERVATIONS_KIND = "us_gate_battery_shadow_observations" +#: ````: the battery's own schema-4 report for the scope. +GATE_BATTERY_SHADOW_REPORT_SUFFIX = ".gate_battery_shadow_report.json" +#: ````: the comparison with today's verdicts. +GATE_BATTERY_SHADOW_COMPARISON_SUFFIX = ".gate_battery_shadow_comparison.json" + + +def shadow_file_paths(directory: Path | str, scope: str) -> tuple[Path, Path]: + """The scope's shadow report and comparison paths inside ``directory``.""" + + if not scope or not scope.replace("_", "").isalnum(): + raise ValueError(f"scope must be a plain identifier, got {scope!r}.") + root = Path(directory) + return ( + root / f"{scope}{GATE_BATTERY_SHADOW_REPORT_SUFFIX}", + root / f"{scope}{GATE_BATTERY_SHADOW_COMPARISON_SUFFIX}", + ) + + +class LegacyStatus(enum.Enum): + """What today's code concluded about one gate on this build.""" + + PASSED = "passed" + FAILED = "failed" + #: Today's evaluation raised (a crash, not a measured failure). + ERROR = "error" + #: Today's code did not evaluate the gate on this build. + NOT_RUN = "not_run" + + +@dataclass(frozen=True) +class LegacyVerdict: + """Today's verdict for one gate, in the comparator's terms. + + Attributes: + status: The :class:`LegacyStatus`. + failures: Today's failure lines, in today's order; empty unless + ``status`` is ``failed``. + error: ``": "`` when today's evaluation + raised. + reason: Why today's code did not evaluate the gate. + """ + + status: LegacyStatus + failures: tuple[str, ...] = () + error: str | None = None + reason: str | None = None + + def __post_init__(self) -> None: + if not isinstance(self.status, LegacyStatus): + raise TypeError("status must be a LegacyStatus.") + if (self.status is LegacyStatus.FAILED) != bool(self.failures): + raise ValueError("a failed verdict, and only one, names its failures.") + if (self.status is LegacyStatus.ERROR) != bool(self.error): + raise ValueError("an error verdict, and only one, names its error.") + if (self.status is LegacyStatus.NOT_RUN) != bool(self.reason): + raise ValueError("a gate that did not run, and only one, says why.") + + @classmethod + def from_result(cls, result: object) -> LegacyVerdict: + """Today's verdict object: a :class:`~microcosm.build.gates.GateResult`, + or anything else with ``passed`` and ``failures``, as today's code + reads it (tests stand in such objects for gates).""" + + passed = getattr(result, "passed", None) + failures = getattr(result, "failures", None) + if ( + not isinstance(passed, bool) + or failures is None + or isinstance(failures, str) + ): + raise TypeError( + f"expected a gate verdict with passed and failures, got " + f"{type(result).__name__}; wrap a failure list with " + "LegacyVerdict.from_failures." + ) + if passed: + return cls(status=LegacyStatus.PASSED) + return cls( + status=LegacyStatus.FAILED, + failures=tuple(str(line) for line in failures), + ) + + @classmethod + def from_failures(cls, failures: Iterable[str]) -> LegacyVerdict: + """Today's verdict from a gate that returns only failure lines.""" + + if isinstance(failures, str): + raise TypeError("failures must be a sequence of lines, not one string.") + lines = tuple(str(line) for line in failures) + if not lines: + return cls(status=LegacyStatus.PASSED) + return cls(status=LegacyStatus.FAILED, failures=lines) + + @classmethod + def from_exception(cls, error: BaseException) -> LegacyVerdict: + """Today's evaluation raised ``error``.""" + + return cls( + status=LegacyStatus.ERROR, + error=f"{type(error).__name__}: {error}", + ) + + @classmethod + def not_run(cls, reason: str) -> LegacyVerdict: + """Today's code did not evaluate the gate, for ``reason``.""" + + return cls(status=LegacyStatus.NOT_RUN, reason=str(reason)) + + def to_payload(self) -> dict[str, object]: + return { + "status": self.status.value, + "failures": list(self.failures), + "error": self.error, + "reason": self.reason, + } + + @classmethod + def from_payload(cls, payload: Mapping[str, object]) -> LegacyVerdict: + """The inverse of :meth:`to_payload`.""" + + failures = payload.get("failures") or () + if isinstance(failures, str) or not isinstance(failures, (list, tuple)): + raise ValueError("a stored legacy verdict's failures must be a list.") + return cls( + status=LegacyStatus(payload["status"]), + failures=tuple(str(line) for line in failures), + error=payload.get("error"), # type: ignore[arg-type] + reason=payload.get("reason"), # type: ignore[arg-type] + ) + + +def _evaluation_error(outcome: GateOutcome) -> Mapping[str, object] | None: + if outcome.result is None or outcome.result.passed: + return None + error = outcome.result.details.get("evaluation_error") + return error if isinstance(error, Mapping) else None + + +def compare_verdicts(legacy: LegacyVerdict, outcome: GateOutcome) -> str | None: + """Whether the battery reached today's verdict; ``None`` when it did. + + The rule is the waiver proposal's (module docstring): verdicts, not + enforcement. Otherwise the returned sentence says how they differ. + """ + + status = outcome.status + if legacy.status is LegacyStatus.NOT_RUN: + if status is GateStatus.EVIDENCE_ABSENT: + return None + return ( + f"today's code did not evaluate it ({legacy.reason}), but the battery " + f"recorded {status.value}." + ) + if outcome.result is None: + return ( + f"today's code reached {legacy.status.value}, but the battery " + f"recorded {status.value}: {outcome.reason}" + ) + crashed = _evaluation_error(outcome) + if legacy.status is LegacyStatus.ERROR: + if crashed is not None: + return None + return ( + f"today's evaluation raised {legacy.error}, but the battery's " + f"evaluation {status.value}." + ) + if crashed is not None: + return ( + f"the battery's evaluation raised {crashed.get('type')}: " + f"{crashed.get('message')}, but today's code {legacy.status.value}." + ) + if legacy.status is LegacyStatus.PASSED: + if status is GateStatus.PASSED: + return None + first = outcome.result.failures[0] if outcome.result.failures else "" + return f"today's code passed, but the battery failed: {first}" + if status is GateStatus.PASSED: + return f"today's code failed ({legacy.failures[0]}), but the battery passed." + battery_failures = tuple(str(line) for line in outcome.result.failures) + if battery_failures != legacy.failures: + return ( + "both failed, with different failure lines: today " + f"{list(legacy.failures)}, the battery {list(battery_failures)}." + ) + return None + + +def _outcome_payload(outcome: GateOutcome) -> dict[str, object]: + crashed = _evaluation_error(outcome) + return { + "status": outcome.status.value, + "failures": ( + [str(line) for line in outcome.result.failures] + if outcome.result is not None + else [] + ), + "evaluation_error": dict(crashed) if crashed is not None else None, + "reason": outcome.reason, + } + + +def _outcome_to_wire(outcome: GateOutcome) -> dict[str, object]: + return { + **outcome.to_payload(), + "result_name": outcome.result.name if outcome.result is not None else None, + "evidence_sha256": outcome.evidence_sha256, + } + + +def _outcome_from_wire( + gates: GatesManifest, entry_id: str, row: Mapping +) -> GateOutcome: + """Rebuild a stored outcome against the current entry, as replay does.""" + + declared = {entry.id: entry for entry in gates.gates} + entry = declared.get(entry_id) + if entry is None: + raise ValueError(f"stored outcome names undeclared entry {entry_id!r}.") + if any( + row.get(key) != getattr(entry, key) for key in ("gate", "phase", "criticality") + ): + raise ValueError(f"stored outcome for {entry_id!r} differs from its entry.") + status = GateStatus(row["status"]) + result = None + if status in (GateStatus.PASSED, GateStatus.FAILED): + result = GateResult( + name=str(row["result_name"]), + passed=status is GateStatus.PASSED, + failures=tuple(str(line) for line in row.get("failures") or ()), + details=dict(row.get("details") or {}), + ) + return GateOutcome( + entry=entry, + status=status, + result=result, + reason=row.get("reason"), + evidence_sha256=row.get("evidence_sha256"), + ) + + +@dataclass(frozen=True) +class _Observation: + entry_id: str + site: str | None + legacy: LegacyVerdict + outcome: GateOutcome | None + difference: str | None + explained_by: tuple[str, ...] + + +class GateBatteryShadowMismatchError(RuntimeError): + """The battery's verdicts differ from today's on a finished run. + + Raised by :meth:`GateBatteryShadow.finish` only after both shadow files + are on disk, and only when today's code completed: when today's code + raised, its own exception is the one that propagates. + """ + + def __init__(self, scope: str, differences: Sequence[str], path: Path) -> None: + self.scope = scope + self.differences = tuple(differences) + self.comparison_path = path + lines = "\n".join(f" - {line}" for line in self.differences) + super().__init__( + f"US gate battery shadow for scope {scope!r} disagrees with today's " + f"gates (comparison: {path}):\n{lines}" + ) + + +def _sha256_file(path: Path) -> str | None: + try: + return hashlib.sha256(path.read_bytes()).hexdigest() + except OSError: + return None + + +def _atomic_write_json(path: Path, payload: Mapping[str, object]) -> None: + path.parent.mkdir(parents=True, exist_ok=True) + tmp = path.with_name(path.name + ".tmp") + tmp.write_text( + json.dumps(payload, indent=2, sort_keys=True, allow_nan=False) + "\n", + encoding="utf-8", + ) + os.replace(tmp, path) + + +class GateBatteryShadow: + """One tool scope's battery, evaluated beside today's gates. + + Construct it before the tool's first gate, observe each gate where it + runs today (:meth:`gate`, :meth:`failures`, :meth:`check`, + :meth:`not_run`), and :meth:`finish` once at the end, or use the instance + as a context manager around the tool's body, which does both ends. + + No observation raises: an unknown entry, a context that cannot be built, + or any other fault in the shadow is recorded as a shadow error, which + fails the run at :meth:`finish` like a verdict difference. The battery is + run with the record-without-enforce posture (``release_candidate`` false, + never ``enforce``), so every phase the tool reaches is recorded and the + shadow report is never shippable: it is evidence, not an authority. + + Args: + gates: The scope's manifest (``us_scoped_gate_manifest``). + scope: The scope's name, written into both files. + release_id: The build the report describes. + report_path: Where the battery writes its schema-4 report. + comparison_path: Where the comparison is written. + registry: The scope's bindings. + waivers: Entry id to the ``--allow-*`` flags this build used that + waive it today. + overrides: Entry id to the declared parameters this build's flags + overrode, each ``{"declared": ..., "runtime": ...}``. + """ + + def __init__( + self, + gates: GatesManifest, + *, + scope: str, + release_id: str, + report_path: Path | str, + comparison_path: Path | str, + registry: Mapping[str, GateBinding], + waivers: Mapping[str, Sequence[str]] | None = None, + overrides: Mapping[str, Mapping[str, Mapping[str, object]]] | None = None, + ) -> None: + declared = {entry.id for entry in gates.gates} + self._scope = str(scope) + self._release_id = release_id + self._gates = gates + self._comparison_path = Path(comparison_path) + self._run = GateBatteryRun( + gates, + release_id=release_id, + report_path=report_path, + release_candidate=False, + registry=registry, + ) + self._waivers = { + str(entry_id): tuple(str(flag) for flag in flags) + for entry_id, flags in sorted((waivers or {}).items()) + if flags + } + self._overrides = { + str(entry_id): { + str(name): dict(values) for name, values in sorted(params.items()) + } + for entry_id, params in sorted((overrides or {}).items()) + if params + } + unknown = sorted((set(self._waivers) | set(self._overrides)) - declared) + if unknown: + raise ValueError( + f"waivers or overrides name entries outside scope {scope!r}: {unknown}." + ) + # A rerun into the same output directory must not leave an earlier + # attempt's shadow files looking like this run's when it stops before + # writing its own. + for stale in (self._run.report_path, self._comparison_path): + stale.unlink(missing_ok=True) + self._declared = frozenset(declared) + self._lock = threading.RLock() + self._observations: dict[str, _Observation] = {} + self._shadow_errors: list[str] = [] + self._finished = False + + # -- properties --------------------------------------------------------- + + @property + def scope(self) -> str: + return self._scope + + @property + def gates(self) -> GatesManifest: + return self._gates + + @property + def run(self) -> GateBatteryRun: + return self._run + + @property + def report_path(self) -> Path: + return self._run.report_path + + @property + def comparison_path(self) -> Path: + return self._comparison_path + + def declares(self, entry_id: str) -> bool: + """Whether ``entry_id`` belongs to this scope.""" + + return entry_id in self._declared + + def outcome(self, entry_id: str) -> GateOutcome | None: + """The battery's outcome for an observed entry, if it has one.""" + + observation = self._observations.get(entry_id) + return observation.outcome if observation is not None else None + + def differences(self) -> tuple[str, ...]: + """Unexplained verdict differences and shadow errors, so far.""" + + lines = [ + f"[{observation.entry_id}] {observation.difference}" + for observation in self._observations.values() + if observation.difference is not None and not observation.explained_by + ] + lines.extend(self._shadow_errors) + return tuple(lines) + + # -- observation -------------------------------------------------------- + + def check( + self, + entry_id: str, + context: EvidenceContext | Callable[[], EvidenceContext], + legacy: LegacyVerdict, + *, + site: str | None = None, + ) -> GateOutcome | None: + """Evaluate ``entry_id`` beside today's ``legacy`` verdict. + + ``context`` may be a callable, so building the evidence runs inside + the shadow's own guard. Returns the battery's outcome, or ``None`` + when the shadow could not evaluate the entry (recorded as a shadow + error). Never raises. + """ + + with self._lock: + return self._check(entry_id, context, legacy, site=site) + + def _check( + self, + entry_id: str, + context: EvidenceContext | Callable[[], EvidenceContext], + legacy: LegacyVerdict, + *, + site: str | None, + ) -> GateOutcome | None: + try: + if self._finished: + raise RuntimeError("the shadow has already finished.") + if entry_id in self._observations: + raise RuntimeError("entry observed more than once.") + if not isinstance(legacy, LegacyVerdict): + raise TypeError("legacy must be a LegacyVerdict.") + evidence = context() if callable(context) else context + if not isinstance(evidence, EvidenceContext): + raise TypeError("context must be an EvidenceContext.") + (outcome,) = self._run.evaluate_entries((entry_id,), evidence) + except Exception as exc: # noqa: BLE001 - the shadow never stops the tool + self._shadow_errors.append( + f"[{entry_id}] shadow could not evaluate the entry: " + f"{type(exc).__name__}: {exc}" + ) + return None + difference = compare_verdicts(legacy, outcome) + explained_by: tuple[str, ...] = () + if difference is not None and entry_id in self._overrides: + explained_by = tuple( + f"runtime override of {name}" for name in self._overrides[entry_id] + ) + self._observations[entry_id] = _Observation( + entry_id=entry_id, + site=site, + legacy=legacy, + outcome=outcome, + difference=difference, + explained_by=explained_by, + ) + return outcome + + def gate( + self, + entry_id: str, + evaluate: Callable[[], GateResult], + context: EvidenceContext | Callable[[], EvidenceContext], + *, + site: str | None = None, + ) -> GateResult: + """Run today's ``evaluate`` and observe it; return its result as is. + + Today's exception, if it raises, is re-raised unchanged after the + observation, so the call site behaves exactly as before. + """ + + try: + result = evaluate() + except Exception as exc: + self.check(entry_id, context, LegacyVerdict.from_exception(exc), site=site) + raise + try: + legacy = LegacyVerdict.from_result(result) + except Exception as exc: # noqa: BLE001 - recorded, never raised + self.record_error( + entry_id, + f"today's verdict is not comparable: {type(exc).__name__}: {exc}", + ) + return result + self.check(entry_id, context, legacy, site=site) + return result + + def failures( + self, + entry_id: str, + evaluate: Callable[[], Sequence[str]], + context: EvidenceContext | Callable[[], EvidenceContext], + *, + site: str | None = None, + ) -> Sequence[str]: + """:meth:`gate` for a gate that returns only failure lines.""" + + try: + lines = evaluate() + except Exception as exc: + self.check(entry_id, context, LegacyVerdict.from_exception(exc), site=site) + raise + try: + legacy = LegacyVerdict.from_failures(lines) + except Exception as exc: # noqa: BLE001 - recorded, never raised + self.record_error( + entry_id, + f"today's verdict is not comparable: {type(exc).__name__}: {exc}", + ) + return lines + self.check(entry_id, context, legacy, site=site) + return lines + + def record_error(self, entry_id: str, message: str) -> None: + """Record a fault in the shadow's own wiring for ``entry_id``. + + It fails a finished run like a verdict difference; it never raises. + """ + + with self._lock: + self._shadow_errors.append(f"[{entry_id}] {message}") + + def not_run(self, entry_id: str, reason: str, *, site: str | None = None) -> None: + """Record that today's code did not evaluate ``entry_id`` on this build. + + The battery evaluates it on no evidence, which must leave it + ``evidence_absent``. + """ + + self.check( + entry_id, + EvidenceContext(), + LegacyVerdict.not_run(reason), + site=site, + ) + + # -- carrying observations between processes ----------------------------- + + def save_observations(self, path: Path | str) -> None: + """Write this process's observations for a later process to load. + + A tool whose stages run as separate processes (the base builder's + checkpointed stages, ACS local's ``--stage`` runs) observes each + stage's gates in its own process and leaves them here; the process + that finishes the scope loads every stage's file. The file is bound + to the scope's manifest digest, so a later process with another + policy refuses it instead of mixing two. + """ + + with self._lock: + payload = { + "kind": _OBSERVATIONS_KIND, + "schema_version": GATE_BATTERY_SHADOW_SCHEMA_VERSION, + "producer": GATE_BATTERY_SHADOW_PRODUCER, + "scope": self._scope, + "gates_manifest_sha256": self._run.gates_manifest_sha256, + "observations": [ + { + "id": observation.entry_id, + "site": observation.site, + "legacy": observation.legacy.to_payload(), + "outcome": ( + _outcome_to_wire(observation.outcome) + if observation.outcome is not None + else None + ), + } + for observation in self._observations.values() + ], + "shadow_errors": list(self._shadow_errors), + } + _atomic_write_json(Path(path), payload) + + def load_observations(self, path: Path | str) -> None: + """Add the observations another process saved. Never raises. + + Each stored observation is compared again under this shadow's own + rule and overrides. A file for another scope or manifest, an entry + already observed, or an unreadable file is a shadow error. + """ + + source = Path(path) + with self._lock: + try: + payload = json.loads(source.read_text(encoding="utf-8")) + if ( + payload.get("kind") != _OBSERVATIONS_KIND + or payload.get("schema_version") + != GATE_BATTERY_SHADOW_SCHEMA_VERSION + ): + raise ValueError("not a shadow observations file.") + if payload.get("scope") != self._scope: + raise ValueError(f"observations of scope {payload.get('scope')!r}.") + if ( + payload.get("gates_manifest_sha256") + != self._run.gates_manifest_sha256 + ): + raise ValueError("observations made under another gate manifest.") + rows = payload.get("observations") + if not isinstance(rows, list): + raise ValueError("observations must be a list.") + for row in rows: + self._load_row(row, source) + for line in payload.get("shadow_errors") or (): + self._shadow_errors.append(f"{source.name}: {line}") + except Exception as exc: # noqa: BLE001 - recorded, never raised + self._shadow_errors.append( + f"could not load shadow observations {source}: " + f"{type(exc).__name__}: {exc}" + ) + + def _load_row(self, row: Mapping, source: Path) -> None: + entry_id = str(row["id"]) + if entry_id in self._observations: + self._shadow_errors.append( + f"[{entry_id}] observed again in {source.name}; kept the first." + ) + return + legacy = LegacyVerdict.from_payload(row["legacy"]) + stored = row.get("outcome") + outcome = ( + _outcome_from_wire(self._gates, entry_id, stored) + if stored is not None + else None + ) + if outcome is None: + # The process that made it could not evaluate it; its own shadow + # error travels with the file. + return + difference = compare_verdicts(legacy, outcome) + explained_by: tuple[str, ...] = () + if difference is not None and entry_id in self._overrides: + explained_by = tuple( + f"runtime override of {name}" for name in self._overrides[entry_id] + ) + self._observations[entry_id] = _Observation( + entry_id=entry_id, + site=row.get("site"), + legacy=legacy, + outcome=outcome, + difference=difference, + explained_by=explained_by, + ) + + # -- the end -------------------------------------------------------------- + + def __enter__(self) -> GateBatteryShadow: + return self + + def __exit__( + self, + exc_type: type[BaseException] | None, + exc: BaseException | None, + traceback: TracebackType | None, + ) -> None: + if self._finished: + # The tool finished the shadow itself (a dry run's deliberate + # stop), so its own exit stands. + return + if exc is None: + self.finish() + return + self.stop(exc) + + def stop(self, error: BaseException) -> None: + """Finish a run today's code stopped with ``error``; never raises. + + Today's exception is the one that must propagate, so a fault while + writing the shadow files only warns. + """ + + try: + self.finish(stopped_by=error) + except Exception as fault: # noqa: BLE001 - never replace today's error + print( + f"warning: US gate battery shadow for scope {self._scope!r} " + f"could not finish: {type(fault).__name__}: {fault}", + file=sys.stderr, + ) + + def finish( + self, + *, + stopped_by: BaseException | None = None, + stopped_at: str | None = None, + ) -> dict[str, object]: + """Record the phases, write both shadow files, then decide. + + A finished run (``stopped_by`` and ``stopped_at`` both ``None``) must + have observed every entry of its scope; it raises + :class:`GateBatteryShadowMismatchError` on any unexplained difference, + unobserved entry or shadow error, after the files are written. A run + today's code stopped early (``stopped_by``: its exception) or that + stops on purpose before its last phase (``stopped_at``: why, as the + release's dry run does) records the phases it completed, plus the + phase it stopped in when a battery outcome there blocks, and never + raises: the tool's own exit stands. + + Returns: + The comparison payload written to disk. + """ + + with self._lock: + return self._finish(stopped_by=stopped_by, stopped_at=stopped_at) + + def _finish( + self, + *, + stopped_by: BaseException | None, + stopped_at: str | None, + ) -> dict[str, object]: + if self._finished: + raise RuntimeError("the shadow has already finished.") + self._finished = True + completed = stopped_by is None and stopped_at is None + recorded: list[str] = [] + not_observed: list[str] = [] + try: + recorded, not_observed = self._record_phases(completed=completed) + except Exception as exc: # noqa: BLE001 - written down, decided below + self._shadow_errors.append( + f"shadow could not record its phases: {type(exc).__name__}: {exc}" + ) + if completed: + for entry_id in not_observed: + self._shadow_errors.append( + f"[{entry_id}] today's run finished without observing this " + "entry; its site is not wired." + ) + payload = self._comparison_payload( + recorded=recorded, + not_observed=not_observed, + completed=completed, + stopped_by=stopped_by, + stopped_at=stopped_at, + ) + try: + _atomic_write_json(self._comparison_path, payload) + except Exception as exc: + if completed: + raise + # Today's own exception (or deliberate stop) is the one that + # propagates; a shadow file that cannot be written must not + # replace it. + print( + f"warning: US gate battery shadow for scope {self._scope!r} " + f"could not write {self._comparison_path}: " + f"{type(exc).__name__}: {exc}", + file=sys.stderr, + ) + return payload + differences = self.differences() + if completed and differences: + raise GateBatteryShadowMismatchError( + self._scope, differences, self._comparison_path + ) + return payload + + def _record_phases(self, *, completed: bool) -> tuple[list[str], list[str]]: + """Assemble and record each phase the tool reached, in order.""" + + recorded: list[str] = [] + not_observed: list[str] = [] + stop = False + for phase in self._gates.phases: + entries = [entry for entry in self._gates.gates if entry.phase == phase] + ran = [ + entry + for entry in entries + if entry.not_applicable is None and self.outcome(entry.id) is not None + ] + missing = [ + entry.id + for entry in entries + if entry.not_applicable is None and self.outcome(entry.id) is None + ] + not_observed.extend(missing) + if stop: + continue + outcomes = [self.outcome(entry.id) for entry in ran] + if not missing: + self._run.record_phase( + assemble_phase_report(self._gates, phase, outcomes) + ) + recorded.append(phase) + continue + stop = True + if completed or not ran: + continue + # The tool stopped inside this phase. Name the last observed entry + # that blocks as the blocker, as the battery would have stopped + # there; without one the phase stays unrecorded. + observed_order = [ + observation.entry_id + for observation in self._observations.values() + if observation.outcome is not None + and observation.outcome.entry.phase == phase + ] + blocking = { + outcome.entry.id + for outcome in blocking_outcomes(outcomes, release_candidate=False) + } + blockers = [entry_id for entry_id in observed_order if entry_id in blocking] + if not blockers: + continue + self._run.record_phase( + assemble_phase_report( + self._gates, + phase, + outcomes, + blocked_by=blockers[-1], + unreached=missing, + release_candidate=False, + ) + ) + recorded.append(phase) + return recorded, not_observed + + def _comparison_payload( + self, + *, + recorded: list[str], + not_observed: list[str], + completed: bool, + stopped_by: BaseException | None, + stopped_at: str | None, + ) -> dict[str, object]: + report_path = self._run.report_path + report_written = bool(recorded) and report_path.is_file() + entries = [] + for observation in self._observations.values(): + outcome = observation.outcome + entry = outcome.entry if outcome is not None else None + entries.append( + { + "id": observation.entry_id, + "gate": entry.gate if entry is not None else None, + "phase": entry.phase if entry is not None else None, + "criticality": entry.criticality if entry is not None else None, + "site": observation.site, + "legacy": observation.legacy.to_payload(), + "battery": ( + _outcome_payload(outcome) if outcome is not None else None + ), + "waived_by": list(self._waivers.get(observation.entry_id, ())), + "match": observation.difference is None, + "difference": observation.difference, + "explained_by": list(observation.explained_by), + } + ) + unexplained = [ + {"id": observation.entry_id, "difference": observation.difference} + for observation in self._observations.values() + if observation.difference is not None and not observation.explained_by + ] + explained = [ + { + "id": observation.entry_id, + "difference": observation.difference, + "explained_by": list(observation.explained_by), + } + for observation in self._observations.values() + if observation.difference is not None and observation.explained_by + ] + return { + "schema_version": GATE_BATTERY_SHADOW_SCHEMA_VERSION, + "producer": GATE_BATTERY_SHADOW_PRODUCER, + "country": self._gates.country, + "scope": self._scope, + "authority": "legacy", + "release_id": self._release_id, + "gates_manifest_sha256": self._run.gates_manifest_sha256, + "policy_sha256": self._run.policy_sha256, + "spec_fingerprint": self._run.spec_fingerprint, + "report_file": report_path.name if report_written else None, + "report_sha256": _sha256_file(report_path) if report_written else None, + "phases_recorded": recorded, + "blocked_at_phase": self._run.blocked_at_phase, + "run_completed": completed, + "stopped_by": ( + {"type": type(stopped_by).__name__, "message": str(stopped_by)} + if stopped_by is not None + else None + ), + "stopped_at": stopped_at, + "waivers": {key: list(value) for key, value in self._waivers.items()}, + "overrides": self._overrides, + "entries": entries, + "not_observed": not_observed, + "differences": unexplained, + "explained_differences": explained, + "shadow_errors": list(self._shadow_errors), + "verdict_difference": bool(unexplained or self._shadow_errors), + } + + +# --------------------------------------------------------------------------- +# The shadow a tool has armed, for the gate sites to find +# --------------------------------------------------------------------------- + +_ACTIVE_LOCK = threading.Lock() +_ACTIVE: list[GateBatteryShadow] = [] + + +@contextmanager +def active_gate_shadow(shadow: GateBatteryShadow) -> Iterator[GateBatteryShadow]: + """Arm ``shadow`` for the gate sites while the block runs. + + The sites call :func:`shadow_gate` and its siblings, which observe through + the innermost armed shadow that declares the entry. Nothing is armed for + a tool that imports another tool's gate functions to re-run them (the + release's scorers, probe and dry-run grading), so those calls run exactly + as before. + """ + + with _ACTIVE_LOCK: + _ACTIVE.append(shadow) + try: + yield shadow + finally: + with _ACTIVE_LOCK: + _ACTIVE.remove(shadow) + + +def current_gate_shadow(entry_id: str | None = None) -> GateBatteryShadow | None: + """The innermost armed shadow, or the innermost declaring ``entry_id``.""" + + with _ACTIVE_LOCK: + armed = list(_ACTIVE) + for shadow in reversed(armed): + if entry_id is None or shadow.declares(entry_id): + return shadow + return None + + +def shadow_gate( + entry_id: str, + evaluate: Callable[[], GateResult], + context: EvidenceContext | Callable[[], EvidenceContext], + *, + site: str | None = None, +) -> GateResult: + """Run today's gate, observing it when a shadow declaring it is armed. + + Returns today's result unchanged, and re-raises today's exception + unchanged; with no shadow armed this is ``evaluate()``. + """ + + shadow = current_gate_shadow(entry_id) + if shadow is None: + return evaluate() + return shadow.gate(entry_id, evaluate, context, site=site) + + +def shadow_failures( + entry_id: str, + evaluate: Callable[[], Sequence[str]], + context: EvidenceContext | Callable[[], EvidenceContext], + *, + site: str | None = None, +) -> Sequence[str]: + """:func:`shadow_gate` for a gate that returns failure lines.""" + + shadow = current_gate_shadow(entry_id) + if shadow is None: + return evaluate() + return shadow.failures(entry_id, evaluate, context, site=site) + + +def shadow_check( + entry_id: str, + context: EvidenceContext | Callable[[], EvidenceContext], + legacy: LegacyVerdict, + *, + site: str | None = None, +) -> None: + """Observe a verdict today's code reached by itself, when armed.""" + + shadow = current_gate_shadow(entry_id) + if shadow is not None: + shadow.check(entry_id, context, legacy, site=site) + + +def shadow_not_run(entry_id: str, reason: str, *, site: str | None = None) -> None: + """Record, when armed, that today's code did not evaluate ``entry_id``.""" + + shadow = current_gate_shadow(entry_id) + if shadow is not None: + shadow.not_run(entry_id, reason, site=site) + + +def legacy_parameter_overrides( + declared: Mapping[str, Mapping[str, Any]], + runtime: Mapping[str, Mapping[str, Any]], +) -> dict[str, dict[str, dict[str, object]]]: + """The declared parameters a build's flags overrode, by entry id. + + ``declared`` and ``runtime`` map entry ids to parameter values; a + parameter whose runtime value differs from the declared one is an + override. Values compare as JSON would see them. + """ + + overrides: dict[str, dict[str, dict[str, object]]] = {} + for entry_id, values in runtime.items(): + for name, value in values.items(): + expected = declared.get(entry_id, {}).get(name) + if json.dumps(expected, sort_keys=True) != json.dumps( + value, sort_keys=True + ): + overrides.setdefault(entry_id, {})[name] = { + "declared": expected, + "runtime": value, + } + return overrides diff --git a/packages/microcosm-build/tests/engine_free/us/test_us_gate_shadow.py b/packages/microcosm-build/tests/engine_free/us/test_us_gate_shadow.py new file mode 100644 index 0000000000..994d9811fe --- /dev/null +++ b/packages/microcosm-build/tests/engine_free/us/test_us_gate_shadow.py @@ -0,0 +1,821 @@ +"""The US gate battery in shadow beside today's gates (microcosm#1585 item 11). + +PR 2 of 4. Today's gates stay authoritative; each tool evaluates the declared +entry beside each gate, compares verdicts, and writes the scope's report and +the comparison as shadow files. These tests hold the comparator's rule (the +waiver proposal on microcosm#1609), the shadow's never-raise-mid-run +discipline, and the assembly of phases from stage outcomes. +""" + +from __future__ import annotations + +import hashlib +import json + +import pytest + +from microcosm.build.country_spec import GatesManifest +from microcosm.build.gate_battery import ( + DEFAULT_REGISTRY, + EvidenceContext, + GateOutcome, + GateStatus, +) +from microcosm.build.gates import GateResult +from microcosm.build.us_runtime.battery_bindings import ( + FRAME, + USCheckBinding, + USGateSpec, + us_check_binding, +) +from microcosm.build.us_runtime.gate_shadow import ( + GateBatteryShadow, + GateBatteryShadowMismatchError, + LegacyStatus, + LegacyVerdict, + compare_verdicts, + legacy_parameter_overrides, + shadow_file_paths, +) + + +def _manifest(gates: list[dict], phases: list[str] | None = None) -> GatesManifest: + return GatesManifest.from_mapping( + { + "version": 1, + "country": "us", + "policy": "test shadow scope", + "phases": phases or ["assembled", "terminal"], + "gates": gates, + } + ) + + +def _entry(id_: str, check: str, phase: str = "assembled", **overrides) -> dict: + entry = { + "id": id_, + "gate": "stage_health", + "phase": phase, + "criticality": "release_blocking", + "parameters": {"check": check}, + } + entry.update(overrides) + return entry + + +def _gate(name: str): + """A legacy gate over an artifact: fails when the value exceeds ``cap``.""" + + def gate(value, *, cap=1.0): + if value > cap: + return GateResult( + name=name, + passed=False, + failures=(f"{name}: {value} exceeds {cap}.",), + details={"value": value}, + ) + return GateResult(name=name, passed=True, details={"value": value}) + + return gate + + +ALPHA = _gate("us_alpha_signal") +BETA = _gate("us_beta_signal") + + +#: The tool namespace the specs below resolve "tool:" references in, as a +#: build tool passes its ``globals()``. +TOOL = {"ALPHA": ALPHA, "BETA": BETA, "CRASH": None} + + +def _crashing_tool_gate(value, *, cap=1.0): + raise KeyError("missing column 'x'") + + +TOOL["CRASH"] = _crashing_tool_gate + + +def _registry(): + specs = ( + USGateSpec( + check="alpha", + legacy_name="us_alpha_signal", + gate="tool:ALPHA", + positional=("alpha_value",), + parameters=frozenset({"cap"}), + ), + USGateSpec( + check="beta", + legacy_name="us_beta_signal", + gate="tool:BETA", + arguments={"value": "beta_value"}, + parameters=frozenset({"cap"}), + ), + USGateSpec( + check="crash", + legacy_name="us_crash_signal", + gate="tool:CRASH", + positional=("alpha_value",), + parameters=frozenset({"cap"}), + ), + ) + return us_check_binding("stage_health", specs, tool=TOOL) + + +def _shadow(tmp_path, gates, **kwargs) -> GateBatteryShadow: + report, comparison = shadow_file_paths(tmp_path, "us_test") + return GateBatteryShadow( + gates, + scope="us_test", + release_id="us-test-build", + report_path=report, + comparison_path=comparison, + registry=kwargs.pop("registry", _registry()), + **kwargs, + ) + + +def _two_phase_gates() -> GatesManifest: + return _manifest( + [ + _entry("us_test_alpha", "alpha", parameters={"check": "alpha", "cap": 1.0}), + _entry("us_test_beta", "beta", parameters={"check": "beta", "cap": 1.0}), + _entry( + "us_test_final", + "alpha", + phase="terminal", + parameters={"check": "alpha", "cap": 1.0}, + ), + ] + ) + + +# --------------------------------------------------------------------------- +# The comparator +# --------------------------------------------------------------------------- + + +def _outcome(status: GateStatus, *, failures=(), details=None, reason=None): + entry = _two_phase_gates().gates[0] + result = None + if status in (GateStatus.PASSED, GateStatus.FAILED): + result = GateResult( + name="stage_health", + passed=status is GateStatus.PASSED, + failures=tuple(failures), + details=details or {}, + ) + return GateOutcome(entry=entry, status=status, result=result, reason=reason) + + +CRASH = {"evaluation_error": {"type": "KeyError", "message": "'x'"}} + + +@pytest.mark.parametrize( + ("legacy", "outcome", "match"), + [ + (LegacyVerdict.from_failures(()), _outcome(GateStatus.PASSED), True), + ( + LegacyVerdict.from_failures(("a", "b")), + _outcome(GateStatus.FAILED, failures=("a", "b")), + True, + ), + ( + LegacyVerdict.from_failures(("a", "b")), + _outcome(GateStatus.FAILED, failures=("b", "a")), + False, + ), + ( + LegacyVerdict.from_failures(()), + _outcome(GateStatus.FAILED, failures=("a",)), + False, + ), + ( + LegacyVerdict.from_failures(("a",)), + _outcome(GateStatus.PASSED), + False, + ), + # A crash in today's code and the battery's fail-closed crash are the + # same verdict. + ( + LegacyVerdict.from_exception(KeyError("x")), + _outcome(GateStatus.FAILED, failures=("crashed",), details=CRASH), + True, + ), + ( + LegacyVerdict.from_exception(KeyError("x")), + _outcome(GateStatus.FAILED, failures=("measured",)), + False, + ), + ( + LegacyVerdict.from_exception(KeyError("x")), + _outcome(GateStatus.PASSED), + False, + ), + ( + LegacyVerdict.from_failures(("crashed",)), + _outcome(GateStatus.FAILED, failures=("crashed",), details=CRASH), + False, + ), + ( + LegacyVerdict.not_run("the stage did not run"), + _outcome(GateStatus.EVIDENCE_ABSENT, reason="missing evidence: frame"), + True, + ), + ( + LegacyVerdict.not_run("the stage did not run"), + _outcome(GateStatus.PASSED), + False, + ), + ( + LegacyVerdict.from_failures(()), + _outcome(GateStatus.EVIDENCE_ABSENT, reason="missing evidence: frame"), + False, + ), + ], +) +def test_the_comparator_compares_verdicts(legacy, outcome, match) -> None: + difference = compare_verdicts(legacy, outcome) + assert (difference is None) is match + if not match: + assert isinstance(difference, str) and difference + + +def test_a_legacy_verdict_is_consistent() -> None: + with pytest.raises(ValueError): + LegacyVerdict(status=LegacyStatus.FAILED) + with pytest.raises(ValueError): + LegacyVerdict(status=LegacyStatus.PASSED, failures=("a",)) + with pytest.raises(ValueError): + LegacyVerdict(status=LegacyStatus.ERROR) + with pytest.raises(ValueError): + LegacyVerdict(status=LegacyStatus.NOT_RUN) + with pytest.raises(TypeError): + LegacyVerdict.from_failures("one line") + with pytest.raises(TypeError): + LegacyVerdict.from_result(["a"]) + assert LegacyVerdict.from_result( + GateResult(name="x", passed=False, failures=("a",)) + ) == LegacyVerdict.from_failures(["a"]) + + +# --------------------------------------------------------------------------- +# Observing gates +# --------------------------------------------------------------------------- + + +def test_a_matching_run_writes_both_files_and_passes(tmp_path) -> None: + gates = _two_phase_gates() + with _shadow(tmp_path, gates) as shadow: + result = shadow.gate( + "us_test_alpha", + lambda: ALPHA(0.5), + EvidenceContext(artifacts={"alpha_value": 0.5}), + site="after the alpha stage", + ) + assert result.name == "us_alpha_signal" + shadow.gate( + "us_test_beta", + lambda: BETA(2.0), + lambda: EvidenceContext(artifacts={"beta_value": 2.0}), + ) + shadow.gate( + "us_test_final", + lambda: ALPHA(0.1), + EvidenceContext(artifacts={"alpha_value": 0.1}), + ) + comparison = json.loads(shadow.comparison_path.read_text()) + assert comparison["run_completed"] is True + assert comparison["verdict_difference"] is False + assert comparison["phases_recorded"] == ["assembled", "terminal"] + assert [row["id"] for row in comparison["entries"]] == [ + "us_test_alpha", + "us_test_beta", + "us_test_final", + ] + beta = comparison["entries"][1] + assert beta["legacy"]["status"] == "failed" + assert beta["battery"]["status"] == "failed" + assert beta["battery"]["failures"] == beta["legacy"]["failures"] + report_bytes = shadow.report_path.read_bytes() + assert comparison["report_sha256"] == hashlib.sha256(report_bytes).hexdigest() + report = json.loads(report_bytes) + assert report["release_candidate"] is False + assert report["shippable"] is False + assert report["gates"]["us_test_beta"]["status"] == "failed" + assert report["blocked_at_phase"] is None + assert comparison["gates_manifest_sha256"] == report["gates_manifest_sha256"] + + +def test_a_waived_gate_that_fails_in_both_is_a_match(tmp_path) -> None: + gates = _two_phase_gates() + shadow = _shadow(tmp_path, gates, waivers={"us_test_beta": ["--allow-beta"]}) + shadow.gate( + "us_test_alpha", + lambda: ALPHA(0.5), + EvidenceContext(artifacts={"alpha_value": 0.5}), + ) + # Today's code records the failure and goes on: the flag waives it. + shadow.gate( + "us_test_beta", + lambda: BETA(3.0), + EvidenceContext(artifacts={"beta_value": 3.0}), + ) + shadow.gate( + "us_test_final", + lambda: ALPHA(0.5), + EvidenceContext(artifacts={"alpha_value": 0.5}), + ) + payload = shadow.finish() + assert payload["verdict_difference"] is False + assert payload["waivers"] == {"us_test_beta": ["--allow-beta"]} + (beta,) = [row for row in payload["entries"] if row["id"] == "us_test_beta"] + assert beta["waived_by"] == ["--allow-beta"] and beta["match"] is True + + +def test_a_crash_in_both_is_a_match_and_todays_exception_propagates(tmp_path) -> None: + gates = _manifest( + [_entry("us_test_crash", "crash"), _entry("us_test_alpha", "alpha")] + ) + shadow = _shadow(tmp_path, gates) + error = KeyError("missing column 'x'") + + def todays_gate(): + raise error + + with pytest.raises(KeyError) as raised: + with shadow: + shadow.gate( + "us_test_crash", + todays_gate, + EvidenceContext(artifacts={"alpha_value": 0.5}), + ) + assert raised.value is error + payload = json.loads(shadow.comparison_path.read_text()) + (crash,) = payload["entries"] + assert crash["legacy"]["status"] == "error" + assert crash["battery"]["evaluation_error"]["type"] == "KeyError" + assert crash["match"] is True + assert payload["run_completed"] is False + assert payload["stopped_by"]["type"] == "KeyError" + # The crash blocks: its phase is recorded with the rest unreached. + report = json.loads(shadow.report_path.read_text()) + assert report["blocked_at_phase"] == "assembled" + assert report["gates"]["us_test_alpha"]["status"] == "unreached" + + +def test_a_difference_fails_the_finished_run_after_both_files(tmp_path) -> None: + gates = _two_phase_gates() + shadow = _shadow(tmp_path, gates) + # Today's code passes at a looser cap than the spec declares. + shadow.gate( + "us_test_alpha", + lambda: ALPHA(1.5, cap=2.0), + EvidenceContext(artifacts={"alpha_value": 1.5}), + ) + shadow.gate( + "us_test_beta", + lambda: BETA(0.5), + EvidenceContext(artifacts={"beta_value": 0.5}), + ) + shadow.gate( + "us_test_final", + lambda: ALPHA(0.5), + EvidenceContext(artifacts={"alpha_value": 0.5}), + ) + with pytest.raises(GateBatteryShadowMismatchError, match="us_test_alpha") as raised: + shadow.finish() + assert raised.value.comparison_path.is_file() + payload = json.loads(raised.value.comparison_path.read_text()) + assert payload["verdict_difference"] is True + assert [row["id"] for row in payload["differences"]] == ["us_test_alpha"] + assert shadow.report_path.is_file() + + +def test_a_runtime_override_explains_its_difference(tmp_path) -> None: + gates = _two_phase_gates() + overrides = legacy_parameter_overrides( + {"us_test_alpha": {"cap": 1.0}}, {"us_test_alpha": {"cap": 2.0}} + ) + assert overrides == {"us_test_alpha": {"cap": {"declared": 1.0, "runtime": 2.0}}} + shadow = _shadow(tmp_path, gates, overrides=overrides) + shadow.gate( + "us_test_alpha", + lambda: ALPHA(1.5, cap=2.0), + EvidenceContext(artifacts={"alpha_value": 1.5}), + ) + shadow.gate( + "us_test_beta", + lambda: BETA(0.5), + EvidenceContext(artifacts={"beta_value": 0.5}), + ) + shadow.gate( + "us_test_final", + lambda: ALPHA(0.5), + EvidenceContext(artifacts={"alpha_value": 0.5}), + ) + payload = shadow.finish() + assert payload["verdict_difference"] is False + assert [row["id"] for row in payload["explained_differences"]] == ["us_test_alpha"] + + +def test_an_unwired_entry_fails_a_finished_run(tmp_path) -> None: + gates = _two_phase_gates() + shadow = _shadow(tmp_path, gates) + shadow.gate( + "us_test_alpha", + lambda: ALPHA(0.5), + EvidenceContext(artifacts={"alpha_value": 0.5}), + ) + shadow.gate( + "us_test_beta", + lambda: BETA(0.5), + EvidenceContext(artifacts={"beta_value": 0.5}), + ) + with pytest.raises(GateBatteryShadowMismatchError, match="us_test_final"): + shadow.finish() + payload = json.loads(shadow.comparison_path.read_text()) + assert payload["not_observed"] == ["us_test_final"] + assert payload["phases_recorded"] == ["assembled"] + + +def test_a_deliberate_stop_records_what_ran_and_never_raises(tmp_path) -> None: + gates = _two_phase_gates() + shadow = _shadow(tmp_path, gates) + shadow.gate( + "us_test_alpha", + lambda: ALPHA(0.5), + EvidenceContext(artifacts={"alpha_value": 0.5}), + ) + shadow.gate( + "us_test_beta", + lambda: BETA(0.5), + EvidenceContext(artifacts={"beta_value": 0.5}), + ) + payload = shadow.finish(stopped_at="dry run: stopped before target materialization") + assert payload["run_completed"] is False + assert payload["stopped_at"].startswith("dry run") + assert payload["not_observed"] == ["us_test_final"] + assert payload["verdict_difference"] is False + # Leaving the context manager after a deliberate finish changes nothing. + shadow.__exit__(None, None, None) + + +def test_a_stop_inside_a_phase_names_the_last_blocking_entry(tmp_path) -> None: + gates = _manifest( + [ + _entry("us_test_first", "alpha"), + _entry("us_test_second", "beta"), + _entry("us_test_third", "alpha"), + _entry("us_test_final", "alpha", phase="terminal"), + ] + ) + shadow = _shadow(tmp_path, gates) + error = RuntimeError("Release gates failed: beta") + with pytest.raises(RuntimeError): + with shadow: + shadow.gate( + "us_test_first", + lambda: ALPHA(0.5), + EvidenceContext(artifacts={"alpha_value": 0.5}), + ) + result = shadow.gate( + "us_test_second", + lambda: BETA(4.0), + EvidenceContext(artifacts={"beta_value": 4.0}), + ) + if not result.passed: + raise error + report = json.loads(shadow.report_path.read_text()) + assert report["blocked_at_phase"] == "assembled" + assert report["gates"]["us_test_second"]["status"] == "failed" + assert report["gates"]["us_test_third"]["status"] == "unreached" + assert "us_test_second" in report["gates"]["us_test_third"]["reason"] + assert report["gates"]["us_test_final"]["status"] == "unreached" + payload = json.loads(shadow.comparison_path.read_text()) + assert payload["phases_recorded"] == ["assembled"] + assert payload["stopped_by"] == { + "type": "RuntimeError", + "message": "Release gates failed: beta", + } + + +def test_a_stop_that_no_gate_explains_leaves_its_phase_unrecorded(tmp_path) -> None: + gates = _two_phase_gates() + shadow = _shadow(tmp_path, gates) + with pytest.raises(OSError): + with shadow: + shadow.gate( + "us_test_alpha", + lambda: ALPHA(0.5), + EvidenceContext(artifacts={"alpha_value": 0.5}), + ) + raise OSError("disk full") + payload = json.loads(shadow.comparison_path.read_text()) + assert payload["phases_recorded"] == [] + assert payload["report_file"] is None + assert not shadow.report_path.exists() + + +def test_the_shadow_never_raises_while_the_tool_runs(tmp_path) -> None: + gates = _two_phase_gates() + shadow = _shadow(tmp_path, gates) + + def broken_context(): + raise ValueError("cannot build evidence") + + assert ( + shadow.check( + "us_undeclared", EvidenceContext(), LegacyVerdict.from_failures(()) + ) + is None + ) + assert ( + shadow.check("us_test_alpha", broken_context, LegacyVerdict.from_failures(())) + is None + ) + assert shadow.check("us_test_beta", EvidenceContext(), "passed") is None + # The same entry twice is a wiring fault, recorded once. + shadow.gate( + "us_test_final", + lambda: ALPHA(0.5), + EvidenceContext(artifacts={"alpha_value": 0.5}), + ) + shadow.gate( + "us_test_final", + lambda: ALPHA(0.5), + EvidenceContext(artifacts={"alpha_value": 0.5}), + ) + differences = shadow.differences() + assert len(differences) == 4 + assert any("us_undeclared" in line for line in differences) + assert any("cannot build evidence" in line for line in differences) + assert any("more than once" in line for line in differences) + with pytest.raises(GateBatteryShadowMismatchError): + shadow.finish() + + +def test_a_gate_today_did_not_run_must_be_evidence_absent(tmp_path) -> None: + gates = _two_phase_gates() + shadow = _shadow(tmp_path, gates) + shadow.not_run("us_test_alpha", "pool base: the alpha stage did not run") + shadow.gate( + "us_test_beta", + lambda: BETA(0.5), + EvidenceContext(artifacts={"beta_value": 0.5}), + ) + shadow.gate( + "us_test_final", + lambda: ALPHA(0.5), + EvidenceContext(artifacts={"alpha_value": 0.5}), + ) + payload = shadow.finish() + (alpha,) = [row for row in payload["entries"] if row["id"] == "us_test_alpha"] + assert alpha["legacy"] == { + "status": "not_run", + "failures": [], + "error": None, + "reason": "pool base: the alpha stage did not run", + } + assert alpha["battery"]["status"] == "evidence_absent" + assert payload["verdict_difference"] is False + + +def test_failure_line_gates_compare_their_lines(tmp_path) -> None: + def spm_lines(value, *, cap=1.0): + return [f"spm: {value} exceeds {cap}."] if value > cap else [] + + specs = ( + USGateSpec( + check="spm", + legacy_name="us_spm_composition", + gate="tool:spm_lines", + positional=("value",), + parameters=frozenset({"cap"}), + returns_failures=True, + ), + ) + gates = _manifest( + [_entry("us_test_spm", "spm", phase="terminal")], phases=["terminal"] + ) + registry = us_check_binding("stage_health", specs, tool={"spm_lines": spm_lines}) + shadow = _shadow(tmp_path, gates, registry=registry) + lines = shadow.failures( + "us_test_spm", lambda: spm_lines(2.0), EvidenceContext(artifacts={"value": 2.0}) + ) + assert lines == ["spm: 2.0 exceeds 1.0."] + payload = shadow.finish() + assert payload["verdict_difference"] is False + assert payload["entries"][0]["battery"]["failures"] == lines + + +def test_stale_shadow_files_are_removed_when_a_run_starts(tmp_path) -> None: + report, comparison = shadow_file_paths(tmp_path, "us_test") + report.write_text("{}") + comparison.write_text("{}") + _shadow(tmp_path, _two_phase_gates()) + assert not report.exists() and not comparison.exists() + + +def test_waivers_and_overrides_must_name_scope_entries(tmp_path) -> None: + with pytest.raises(ValueError, match="outside scope"): + _shadow(tmp_path, _two_phase_gates(), waivers={"us_elsewhere": ["--allow-x"]}) + with pytest.raises(ValueError, match="outside scope"): + _shadow( + tmp_path, + _two_phase_gates(), + overrides={"us_elsewhere": {"cap": {"declared": 1, "runtime": 2}}}, + ) + + +def test_shadow_file_names_follow_the_scope() -> None: + report, comparison = shadow_file_paths("/out/gate_battery_shadow", "us_national") + assert report.name == "us_national.gate_battery_shadow_report.json" + assert comparison.name == "us_national.gate_battery_shadow_comparison.json" + with pytest.raises(ValueError): + shadow_file_paths("/out", "../escape") + + +# --------------------------------------------------------------------------- +# The US check binding +# --------------------------------------------------------------------------- + + +def test_the_check_binding_routes_evidence_and_thresholds() -> None: + binding = _registry()["stage_health"] + assert binding.parameter_keys == frozenset({"check", "cap"}) + alpha = {"check": "alpha", "cap": 0.25} + assert binding.required_artifacts(alpha) == frozenset({"alpha_value"}) + assert binding.requires_frame(alpha) is False + result = binding.evaluate(EvidenceContext(artifacts={"alpha_value": 0.5}), alpha) + # The declared threshold, not the function's default, decides; the + # legacy name is re-minted under the declared gate. + assert result.name == "stage_health" + assert result.failures == ("us_alpha_signal: 0.5 exceeds 0.25.",) + beta = binding.evaluate( + EvidenceContext(artifacts={"beta_value": 0.5}), {"check": "beta"} + ) + assert beta.passed and beta.name == "stage_health" + + +def test_the_check_binding_fails_closed() -> None: + binding = _registry()["stage_health"] + with pytest.raises(ValueError, match="no US gate is bound"): + binding.evaluate(EvidenceContext(), {"check": "gamma"}) + assert binding.required_artifacts({"check": "gamma"}) == frozenset() + spec = USGateSpec( + check="alpha", + legacy_name="us_alpha_signal", + gate="tool:ALPHA", + positional=("alpha_value",), + ) + strict = USCheckBinding("stage_health", (spec,), tool=TOOL) + with pytest.raises(ValueError, match="does not take parameter"): + strict.evaluate( + EvidenceContext(artifacts={"alpha_value": 0.5}), + {"check": "alpha", "cap": 1.0}, + ) + # Another name passes through, so the executor's name check fails it. + other = USCheckBinding( + "stage_health", + ( + USGateSpec( + check="alpha", + legacy_name="us_something_else", + gate="tool:ALPHA", + positional=("alpha_value",), + ), + ), + tool=TOOL, + ) + result = other.evaluate( + EvidenceContext(artifacts={"alpha_value": 0.5}), {"check": "alpha"} + ) + assert result.name == "us_alpha_signal" + + +def test_pinned_thresholds_must_equal_todays_constants() -> None: + namespace = {"GATE": ALPHA, "_CAP": 1.0} + spec = USGateSpec( + check="alpha", + legacy_name="us_alpha_signal", + gate="tool:GATE", + positional=("alpha_value",), + pinned={"cap": "tool:_CAP"}, + ) + binding = USCheckBinding("stage_health", (spec,), tool=namespace) + assert binding.parameter_keys == frozenset({"check", "cap"}) + assert binding.pinned_values("alpha") == {"cap": 1.0} + evidence = EvidenceContext(artifacts={"alpha_value": 1.5}) + # The declared value equals today's constant: today's gate decides with it. + assert binding.evaluate(evidence, {"check": "alpha", "cap": 1.0}).failures == ( + "us_alpha_signal: 1.5 exceeds 1.0.", + ) + with pytest.raises(ValueError, match="differs from today's"): + binding.evaluate(evidence, {"check": "alpha", "cap": 2.0}) + with pytest.raises(ValueError, match="does not declare"): + binding.evaluate(evidence, {"check": "alpha"}) + # A later patch of the constant reaches the next evaluation. + namespace["_CAP"] = 2.0 + with pytest.raises(ValueError, match="differs from today's"): + binding.evaluate(evidence, {"check": "alpha", "cap": 1.0}) + + +def test_routed_bands_reach_the_gate_as_tuples() -> None: + seen = [] + + def gate(value, *, bounds=(0.0, 1.0)): + seen.append(bounds) + return GateResult(name="us_band_signal", passed=True) + + spec = USGateSpec( + check="band", + legacy_name="us_band_signal", + gate="tool:gate", + positional=("value",), + parameters=frozenset({"bounds"}), + ) + binding = USCheckBinding("stage_health", (spec,), tool={"gate": gate}) + binding.evaluate( + EvidenceContext(artifacts={"value": 0.5}), {"check": "band", "bounds": [0, 1]} + ) + assert seen == [(0, 1)] + + +def test_tool_references_are_resolved_up_front() -> None: + spec = USGateSpec( + check="tool", + legacy_name="us_tool_signal", + gate="tool:_tool_gate", + arguments={"frame": FRAME}, + ) + assert spec.needs_frame and spec.references == ("tool:_tool_gate",) + with pytest.raises(ValueError, match="no tool was given"): + USCheckBinding("stage_health", (spec,)) + with pytest.raises(ValueError, match="no global '_tool_gate'"): + USCheckBinding("stage_health", (spec,), tool={"_other": BETA}) + with pytest.raises(ValueError, match="is not callable"): + USCheckBinding("stage_health", (spec,), tool={"_tool_gate": 3}) + missing_module = USGateSpec( + check="tool", + legacy_name="us_tool_signal", + gate="microcosm.build.no_such_module:gate", + ) + with pytest.raises(ValueError, match="unresolved references"): + USCheckBinding("stage_health", (missing_module,), tool={}) + namespace = { + "_tool_gate": lambda frame: GateResult(name="us_tool_signal", passed=True) + } + binding = USCheckBinding("stage_health", (spec,), tool=namespace) + assert binding.requires_frame({"check": "tool"}) + assert binding.evaluate(EvidenceContext(frame=object()), {"check": "tool"}).passed + # The binding calls what the namespace holds when it runs. + namespace["_tool_gate"] = lambda frame: GateResult( + name="us_tool_signal", passed=False, failures=("patched",) + ) + assert binding.evaluate( + EvidenceContext(frame=object()), {"check": "tool"} + ).failures == ("patched",) + + +def test_a_gate_spec_refuses_ambiguous_declarations() -> None: + with pytest.raises(ValueError, match="dispatch key"): + USGateSpec( + check="a", legacy_name="x", gate="tool:A", parameters=frozenset({"check"}) + ) + with pytest.raises(ValueError, match="both evidence and thresholds"): + USGateSpec( + check="a", + legacy_name="x", + gate="tool:A", + arguments={"cap": "cap_value"}, + parameters=frozenset({"cap"}), + ) + with pytest.raises(ValueError, match="both routed and pinned"): + USGateSpec( + check="a", + legacy_name="x", + gate="tool:A", + parameters=frozenset({"cap"}), + pinned={"cap": "tool:_CAP"}, + ) + with pytest.raises(ValueError, match="must be 'tool:'"): + USGateSpec(check="a", legacy_name="x", gate="no_separator") + with pytest.raises(ValueError, match="declared twice"): + USCheckBinding( + "stage_health", + ( + USGateSpec(check="a", legacy_name="x", gate="tool:ALPHA"), + USGateSpec(check="a", legacy_name="y", gate="tool:BETA"), + ), + tool=TOOL, + ) + + +def test_the_registry_is_fresh_on_every_call() -> None: + first = _registry() + second = _registry() + assert first is not second + assert first["stage_health"] is not second["stage_health"] + # The shared registry is never mutated. + assert "stage_health" not in DEFAULT_REGISTRY diff --git a/test_support/microcosm_build/us_gate_shadow.py b/test_support/microcosm_build/us_gate_shadow.py new file mode 100644 index 0000000000..fd015b9799 --- /dev/null +++ b/test_support/microcosm_build/us_gate_shadow.py @@ -0,0 +1,123 @@ +"""Shared helpers for the US gate battery's shadow tests (microcosm#1585 item 11). + +Each US scope is evaluated by one build tool whose gate functions the +bindings call through the tool's own globals, so the tests load the tools +the way their own tests do: by path, without engines. +""" + +from __future__ import annotations + +import ast +import importlib.util +import sys +from functools import cache +from pathlib import Path +from types import ModuleType + +from test_support.paths import paths_for + +#: Scope to the build tool that evaluates it. +US_GATE_SCOPE_TOOLS = { + "us_base": "build_us_puf_support_base", + "us_pool": "build_us_multispine_pool", + "us_national": "build_us_fiscal_refresh_release", + "us_local": "build_us_acs_local_release", +} + + +def us_gate_tool_path(scope: str) -> Path: + return ( + paths_for("microcosm-build").repository + / "tools" + / f"{US_GATE_SCOPE_TOOLS[scope]}.py" + ) + + +@cache +def load_us_gate_tool(scope: str) -> ModuleType: + """The scope's build tool, loaded once per process.""" + + path = us_gate_tool_path(scope) + name = f"us_gate_shadow_{US_GATE_SCOPE_TOOLS[scope]}" + spec = importlib.util.spec_from_file_location(name, path) + module = importlib.util.module_from_spec(spec) + assert spec.loader is not None + sys.modules[name] = module + spec.loader.exec_module(module) + return module + + +def _literal_string(node: ast.AST) -> str | None: + return ( + node.value + if isinstance(node, ast.Constant) and isinstance(node.value, str) + else None + ) + + +def _lambda_call_name(node: ast.AST) -> str | None: + if isinstance(node, ast.Lambda) and isinstance(node.body, ast.Call): + func = node.body.func + if isinstance(func, ast.Name): + return func.id + return None + + +#: Package modules where a scope observes a gate inside a runtime function +#: rather than in its tool. +US_GATE_SCOPE_RUNTIME_SITES: dict[str, tuple[str, ...]] = {} + +_HELPERS = frozenset( + { + "shadow_gate", + "shadow_failures", + "shadow_check", + "shadow_not_run", + "_shadow_frame_gate", + "_observe_frame_gate", + } +) + + +def _module_path(module: str) -> Path: + relative = module.removeprefix("microcosm.build.").replace(".", "/") + return ( + paths_for("microcosm-build").repository + / "packages/microcosm-build/src/microcosm/build" + / f"{relative}.py" + ) + + +def _sites(path: Path, namespace: str) -> list[tuple[str, str | None, str]]: + tree = ast.parse(path.read_text()) + sites = [] + for node in ast.walk(tree): + if not isinstance(node, ast.Call) or not node.args: + continue + func = node.func + name = func.id if isinstance(func, ast.Name) else getattr(func, "attr", None) + if name not in _HELPERS: + continue + entry_id = _literal_string(node.args[0]) + if entry_id is None: + continue + gate = _lambda_call_name(node.args[1]) if len(node.args) > 1 else None + reference = None if gate is None else f"{namespace}:{gate}" + sites.append((entry_id, reference, f"{path.name}:{node.lineno}")) + return sites + + +def shadow_wiring(scope: str) -> list[tuple[str, str | None, str]]: + """Every shadow call site of a scope: (entry id, gate reference, where). + + Reads the scope's tool and the runtime modules it observes gates in: a + call to one of the shadow helpers whose first argument is an entry id + literal. The gate reference names the function today's lambda calls at + that site, as a binding names it (``tool:`` in the tool, + ``:`` in a runtime module), when the site has one. + """ + + sites = _sites(us_gate_tool_path(scope), "tool") + for module in US_GATE_SCOPE_RUNTIME_SITES.get(scope, ()): + sites.extend(_sites(_module_path(module), module)) + return sites From 00344ebd248068fc7df4bad5c02179c7e1ab4c79 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mar=C3=ADa=20Juaristi?= <127882282+juaristi22@users.noreply.github.com> Date: Sun, 15 Nov 2026 14:06:17 +0000 Subject: [PATCH 03/31] Declare Route A's base gates and run them in shadow (us_base) PR 2 of 4 for microcosm#1585 item 11. us/gates.json is new, registered as a legacy_json row through the generator's LEGACY_RESOURCE_PATHS, and its first scope is us_base: the 37 gates tools/build_us_puf_support_base.py evaluates (8 before support cloning, the QRF weights audit, 26 after cloning, and the two location gates), as stage_health entries keyed by check, at today's thresholds. The base tool arms the scope around its single-process run, and around each checkpointed stage, whose child process saves what it observed for the parent to load and finish. Shadow files go to /gate_battery_shadow (the stages' observations to /gate_battery_shadow). Every raise, written file and summary key is as before; a run with stand-in arguments and no --out runs without a shadow. The capital-gains tail stage's gates sit inside transfer_puf_capital_gains_tail, a seed-attested runtime function, and are not declared yet. country_package.json gains the row the generator would write. The F0 field and inventory pins move with it and are re-pinned separately. Co-Authored-By: Claude Opus 5.5 --- .../microcosm/build/us/country_package.json | 5 + .../src/microcosm/build/us/gates.json | 805 ++++++++++++++++++ .../build/us_runtime/battery_bindings.py | 282 +++++- .../us/test_us_battery_bindings.py | 344 ++++++++ .../test_us_puf_support_base_gate_shadow.py | 239 ++++++ tools/build_us_puf_support_base.py | 660 +++++++++++--- tools/generate_us_bundle_from_constants.py | 1 + 7 files changed, 2237 insertions(+), 99 deletions(-) create mode 100644 packages/microcosm-build/src/microcosm/build/us/gates.json create mode 100644 packages/microcosm-build/tests/engine_free/us/test_us_battery_bindings.py create mode 100644 packages/microcosm-build/tests/engine_free/us/test_us_puf_support_base_gate_shadow.py diff --git a/packages/microcosm-build/src/microcosm/build/us/country_package.json b/packages/microcosm-build/src/microcosm/build/us/country_package.json index 5e14125c81..b6a71b3ced 100644 --- a/packages/microcosm-build/src/microcosm/build/us/country_package.json +++ b/packages/microcosm-build/src/microcosm/build/us/country_package.json @@ -92,6 +92,11 @@ "kind": "legacy_json", "schema_id": "legacy_json" }, + { + "path": "gates.json", + "kind": "legacy_json", + "schema_id": "legacy_json" + }, { "path": "obbba_reforms.json", "kind": "legacy_json", diff --git a/packages/microcosm-build/src/microcosm/build/us/gates.json b/packages/microcosm-build/src/microcosm/build/us/gates.json new file mode 100644 index 0000000000..cb2fcb2178 --- /dev/null +++ b/packages/microcosm-build/src/microcosm/build/us/gates.json @@ -0,0 +1,805 @@ +{ + "version": 1, + "country": "us", + "policy": "US gates declared as data for the shared battery (microcosm#1585 item 11, microcosm#611), one scope per build tool. PR 2 of 4 runs them in shadow: each US tool still gates as it did, evaluates the declared entry beside each gate on the same evidence, and fails the run on a verdict difference. A threshold the gate reads from a module constant is declared at today's value and pinned equal to that constant until the flip makes this file the only source; one the gate takes as a keyword is routed from here. Waivers stay the tools' --allow-* flags, which the shadow records by entry id. Gate names and phases are the shared vocabulary's, pending Max's Step 0 answer.", + "phases": [ + "assembled", + "transferred", + "terminal" + ], + "gates": [ + { + "id": "us_base_relationship_inputs", + "gate": "stage_health", + "phase": "assembled", + "criticality": "release_blocking", + "parameters": { + "check": "relationship_inputs_signal", + "household_head_share_band": [ + 0.3, + 0.55 + ], + "separated_share_band": [ + 0.003, + 0.04 + ], + "surviving_spouse_share_band": [ + 0.02, + 0.08 + ] + }, + "notes": "Route A base (tools/build_us_puf_support_base.py): relationship inputs on the ASEC frame before support cloning. Raises at once today, in the single-process run and in the checkpointed stage alike." + }, + { + "id": "us_base_spm_independence_role", + "gate": "stage_health", + "phase": "assembled", + "criticality": "release_blocking", + "parameters": { + "check": "spm_independence_role_signal", + "role_share_band": [ + 0.4, + 0.75 + ], + "minor_role_share_band": [ + 0.003, + 0.06 + ] + }, + "notes": "Route A base (tools/build_us_puf_support_base.py): SPM independence role on the ASEC frame before support cloning. Raises at once today, in the single-process run and in the checkpointed stage alike." + }, + { + "id": "us_base_medicare_take_up_pre_clone", + "gate": "stage_health", + "phase": "assembled", + "criticality": "release_blocking", + "parameters": { + "check": "medicare_take_up_input_signal", + "weighted_enrolled_share_band": [ + 0.15, + 0.24 + ], + "channel_enrolled_share_band": [ + 0.15, + 0.24 + ] + }, + "notes": "Route A base (tools/build_us_puf_support_base.py): Medicare enrollment input on the ASEC frame before support cloning. Raises at once today, in the single-process run and in the checkpointed stage alike." + }, + { + "id": "us_base_housing_inputs_pre_clone", + "gate": "stage_health", + "phase": "assembled", + "criticality": "release_blocking", + "parameters": { + "check": "housing_inputs_signal", + "rent_share_band": [ + 0.05, + 0.25 + ], + "housing_assistance_share_band": [ + 0.005, + 0.08 + ] + }, + "notes": "Route A base (tools/build_us_puf_support_base.py): housing inputs before support cloning: the source frame's verdict, or the verdict after the pinned ACS restore when the source frame is not green. Raises at once today, in the single-process run and in the checkpointed stage alike." + }, + { + "id": "us_base_eligibility_inputs", + "gate": "stage_health", + "phase": "assembled", + "criticality": "release_blocking", + "parameters": { + "check": "eligibility_inputs_signal", + "disabled_share_band": [ + 0.05, + 0.2 + ], + "full_time_student_share_band": [ + 0.01, + 0.08 + ], + "parent_share_band": [ + 0.12, + 0.4 + ], + "veterans_benefits_share_band": [ + 0.002, + 0.04 + ] + }, + "notes": "Route A base (tools/build_us_puf_support_base.py): eligibility inputs on the ASEC frame before support cloning. Raises at once today, in the single-process run and in the checkpointed stage alike." + }, + { + "id": "us_base_pregnancy", + "gate": "stage_health", + "phase": "assembled", + "criticality": "release_blocking", + "parameters": { + "check": "pregnancy_signal", + "pregnant_share_band": [ + 0.002, + 0.02 + ] + }, + "notes": "Route A base (tools/build_us_puf_support_base.py): pregnancy input on the ASEC frame before support cloning. Raises at once today, in the single-process run and in the checkpointed stage alike." + }, + { + "id": "us_base_wic_claim_pre_clone", + "gate": "stage_health", + "phase": "assembled", + "criticality": "release_blocking", + "parameters": { + "check": "wic_claim_input_signal", + "weighted_claim_share_band": [ + 0.015, + 0.06 + ], + "category_weighted_claim_share_bands": { + "pregnant": [ + 0.25, + 0.67 + ], + "postpartum": [ + 0.45, + 0.9 + ], + "infant": [ + 0.55, + 0.96 + ], + "child": [ + 0.3, + 0.63 + ], + "none": [ + 0.0, + 0.0 + ] + } + }, + "notes": "Route A base (tools/build_us_puf_support_base.py): WIC claims on the ASEC frame before support cloning. Raises at once today, in the single-process run and in the checkpointed stage alike." + }, + { + "id": "us_base_esi_premiums_pre_clone", + "gate": "stage_health", + "phase": "assembled", + "criticality": "release_blocking", + "parameters": { + "check": "esi_premiums_signal", + "positive_share_band": [ + 0.15, + 0.32 + ], + "raw_mean_band": [ + 6000.0, + 20000.0 + ] + }, + "notes": "Route A base (tools/build_us_puf_support_base.py): ESI employer premiums on the ASEC frame before support cloning. Raises at once today, in the single-process run and in the checkpointed stage alike." + }, + { + "id": "us_base_weights_audit", + "gate": "weights_audit", + "phase": "transferred", + "criticality": "release_blocking", + "parameters": {}, + "notes": "Route A base (tools/build_us_puf_support_base.py): every fit the PUF-support QRF finalization ran resolved a weight. Raises at once today." + }, + { + "id": "us_base_wic_claim_post_clone", + "gate": "stage_health", + "phase": "transferred", + "criticality": "release_blocking", + "parameters": { + "check": "wic_claim_input_signal", + "weighted_claim_share_band": [ + 0.015, + 0.06 + ], + "category_weighted_claim_share_bands": { + "pregnant": [ + 0.25, + 0.67 + ], + "postpartum": [ + 0.45, + 0.9 + ], + "infant": [ + 0.55, + 0.96 + ], + "child": [ + 0.3, + 0.63 + ], + "none": [ + 0.0, + 0.0 + ] + } + }, + "notes": "Route A base (tools/build_us_puf_support_base.py): WIC claims after support cloning, with the channel checks live. Raises at once today, in the single-process run and in the checkpointed stage alike." + }, + { + "id": "us_base_medicare_take_up_post_clone", + "gate": "stage_health", + "phase": "transferred", + "criticality": "release_blocking", + "parameters": { + "check": "medicare_take_up_input_signal", + "weighted_enrolled_share_band": [ + 0.15, + 0.24 + ], + "channel_enrolled_share_band": [ + 0.15, + 0.24 + ] + }, + "notes": "Route A base (tools/build_us_puf_support_base.py): Medicare enrollment input after support cloning. Raises at once today, in the single-process run and in the checkpointed stage alike." + }, + { + "id": "us_base_prior_year_income", + "gate": "stage_health", + "phase": "transferred", + "criticality": "release_blocking", + "parameters": { + "check": "prior_year_income_signal", + "previous_year_available_share_band": [ + 0.05, + 0.5 + ], + "self_employment_nonzero_share_band": [ + 0.01, + 0.25 + ] + }, + "notes": "Route A base (tools/build_us_puf_support_base.py): prior-year income inputs after support cloning. Raises at once today, in the single-process run and in the checkpointed stage alike." + }, + { + "id": "us_base_prior_year_income_source_reconciliation", + "gate": "stage_health", + "phase": "transferred", + "criticality": "release_blocking", + "parameters": { + "check": "prior_year_income_source_reconciliation" + }, + "notes": "Route A base (tools/build_us_puf_support_base.py): exact recomputation of the ASEC prior-year carry after support cloning. Raises at once today, in the single-process run and in the checkpointed stage alike." + }, + { + "id": "us_base_housing_inputs_post_clone", + "gate": "stage_health", + "phase": "transferred", + "criticality": "release_blocking", + "parameters": { + "check": "housing_inputs_signal", + "rent_share_band": [ + 0.05, + 0.25 + ], + "housing_assistance_share_band": [ + 0.005, + 0.08 + ] + }, + "notes": "Route A base (tools/build_us_puf_support_base.py): housing inputs after PUF-support imputation. Raises at once today, in the single-process run and in the checkpointed stage alike." + }, + { + "id": "us_base_qbi_inputs", + "gate": "stage_health", + "phase": "transferred", + "criticality": "release_blocking", + "parameters": { + "check": "qbi_inputs_signal", + "boolean_share_bands": { + "business_is_sstb": [ + 0.001, + 0.25 + ], + "estate_income_would_be_qualified": [ + 0.01, + 0.9999 + ], + "farm_operations_income_would_be_qualified": [ + 0.01, + 0.9999 + ], + "farm_rent_income_would_be_qualified": [ + 0.01, + 0.9999 + ], + "partnership_s_corp_income_would_be_qualified": [ + 0.01, + 0.9999 + ], + "rental_income_would_be_qualified": [ + 0.01, + 0.9999 + ], + "self_employment_income_would_be_qualified": [ + 0.01, + 0.9999 + ], + "sstb_self_employment_income_would_be_qualified": [ + 0.0001, + 0.25 + ] + }, + "numeric_nonzero_share_bands": { + "qualified_bdc_income": [ + 0.0001, + 0.15 + ], + "qualified_reit_and_ptp_income": [ + 0.001, + 0.35 + ], + "sstb_self_employment_income_before_lsr": [ + 0.0001, + 0.25 + ], + "sstb_unadjusted_basis_qualified_property": [ + 0.0001, + 0.25 + ], + "sstb_w2_wages_from_qualified_business": [ + 0.0001, + 0.2 + ], + "unadjusted_basis_qualified_property": [ + 0.001, + 0.45 + ], + "w2_wages_from_qualified_business": [ + 0.001, + 0.35 + ] + }, + "invariant_atol": 1e-08 + }, + "notes": "Route A base (tools/build_us_puf_support_base.py): QBI inputs after support cloning. Raises at once today, in the single-process run and in the checkpointed stage alike." + }, + { + "id": "us_base_farm_business_income", + "gate": "stage_health", + "phase": "transferred", + "criticality": "release_blocking", + "parameters": { + "check": "farm_business_income_signal", + "nonzero_share_bands": { + "farm_operations_income": [ + 0.0001, + 0.2 + ], + "farm_rent_income": [ + 1e-05, + 0.2 + ] + } + }, + "notes": "Route A base (tools/build_us_puf_support_base.py): farm business income after support cloning. Raises at once today, in the single-process run and in the checkpointed stage alike." + }, + { + "id": "us_base_domestic_production_ald", + "gate": "stage_health", + "phase": "transferred", + "criticality": "release_blocking", + "parameters": { + "check": "domestic_production_ald_signal", + "domestic_production_ald_positive_share_band": [ + 0.0001, + 0.02 + ] + }, + "notes": "Route A base (tools/build_us_puf_support_base.py): domestic production deduction after support cloning. Raises at once today, in the single-process run and in the checkpointed stage alike." + }, + { + "id": "us_base_child_support", + "gate": "stage_health", + "phase": "transferred", + "criticality": "release_blocking", + "parameters": { + "check": "child_support_inputs_signal", + "nonzero_share_bands": { + "child_support_received": [ + 0.005, + 0.15 + ], + "child_support_expense": [ + 0.003, + 0.15 + ] + }, + "channel_nonzero_share_band": [ + 0.002, + 0.15 + ] + }, + "notes": "Route A base (tools/build_us_puf_support_base.py): child support inputs after support cloning. Raises at once today, in the single-process run and in the checkpointed stage alike." + }, + { + "id": "us_base_disability_benefits", + "gate": "stage_health", + "phase": "transferred", + "criticality": "release_blocking", + "parameters": { + "check": "disability_benefits_signal", + "nonzero_share_band": [ + 0.003, + 0.15 + ], + "channel_nonzero_share_bands": { + "asec": [ + 0.003, + 0.02 + ], + "puf_tax_detail": [ + 0.002, + 0.15 + ] + } + }, + "notes": "Route A base (tools/build_us_puf_support_base.py): disability benefits after support cloning. Raises at once today, in the single-process run and in the checkpointed stage alike." + }, + { + "id": "us_base_workers_compensation", + "gate": "stage_health", + "phase": "transferred", + "criticality": "release_blocking", + "parameters": { + "check": "workers_compensation_signal", + "nonzero_share_band": [ + 0.0005, + 0.05 + ], + "channel_nonzero_share_bands": { + "asec": [ + 0.001, + 0.01 + ], + "puf_tax_detail": [ + 0.0002, + 0.1 + ] + } + }, + "notes": "Route A base (tools/build_us_puf_support_base.py): workers' compensation after support cloning. Raises at once today, in the single-process run and in the checkpointed stage alike." + }, + { + "id": "us_base_weeks_unemployed", + "gate": "stage_health", + "phase": "transferred", + "criticality": "release_blocking", + "parameters": { + "check": "weeks_unemployed_signal", + "channel_positive_share_bands": { + "asec": [ + 0.015, + 0.1 + ], + "puf_tax_detail": [ + 0.001, + 0.03 + ] + }, + "channel_weighted_mean_weeks_bands": { + "asec": [ + 0.2, + 2.0 + ], + "puf_tax_detail": [ + 0.01, + 0.5 + ] + } + }, + "notes": "Route A base (tools/build_us_puf_support_base.py): weeks unemployed after support cloning. Raises at once today, in the single-process run and in the checkpointed stage alike." + }, + { + "id": "us_base_educator_expense", + "gate": "stage_health", + "phase": "transferred", + "criticality": "release_blocking", + "parameters": { + "check": "educator_expense_signal", + "overall_positive_share_band": [ + 0.002, + 0.04 + ], + "puf_positive_share_band": [ + 0.005, + 0.08 + ] + }, + "notes": "Route A base (tools/build_us_puf_support_base.py): educator expenses after support cloning. Raises at once today, in the single-process run and in the checkpointed stage alike." + }, + { + "id": "us_base_form_4952_election", + "gate": "stage_health", + "phase": "transferred", + "criticality": "release_blocking", + "parameters": { + "check": "form_4952_election_signal", + "overall_positive_share_band": [ + 5e-05, + 0.02 + ], + "puf_positive_share_band": [ + 0.0001, + 0.04 + ] + }, + "notes": "Route A base (tools/build_us_puf_support_base.py): Form 4952 election after support cloning. Raises at once today, in the single-process run and in the checkpointed stage alike." + }, + { + "id": "us_base_salt_refund_income", + "gate": "stage_health", + "phase": "transferred", + "criticality": "release_blocking", + "parameters": { + "check": "salt_refund_income_signal", + "overall_positive_share_band": [ + 0.005, + 0.2 + ], + "puf_positive_share_band": [ + 0.01, + 0.4 + ] + }, + "notes": "Route A base (tools/build_us_puf_support_base.py): SALT refund income after support cloning. Raises at once today, in the single-process run and in the checkpointed stage alike." + }, + { + "id": "us_base_capital_gain_details", + "gate": "stage_health", + "phase": "transferred", + "criticality": "release_blocking", + "parameters": { + "check": "capital_gain_details_signal", + "signal_bands": { + "long_term_capital_gains_on_collectibles": { + "overall": [ + 1e-05, + 0.005 + ], + "puf": [ + 2e-05, + 0.01 + ] + }, + "unrecaptured_section_1250_gain": { + "overall": [ + 0.0005, + 0.03 + ], + "puf": [ + 0.001, + 0.06 + ] + } + } + }, + "notes": "Route A base (tools/build_us_puf_support_base.py): capital gain details after support cloning. Raises at once today, in the single-process run and in the checkpointed stage alike." + }, + { + "id": "us_base_childcare", + "gate": "stage_health", + "phase": "transferred", + "criticality": "release_blocking", + "parameters": { + "check": "childcare_inputs_signal", + "nonzero_share_band": [ + 0.005, + 0.5 + ] + }, + "notes": "Route A base (tools/build_us_puf_support_base.py): childcare inputs after support cloning. Raises at once today, in the single-process run and in the checkpointed stage alike." + }, + { + "id": "us_base_adult_care", + "gate": "stage_health", + "phase": "transferred", + "criticality": "release_blocking", + "parameters": { + "check": "adult_care_inputs_signal", + "flag_share_band": [ + 0.002, + 0.12 + ], + "expense_plausibility_ceiling": 250000.0 + }, + "notes": "Route A base (tools/build_us_puf_support_base.py): adult care inputs after support cloning. Raises at once today, in the single-process run and in the checkpointed stage alike." + }, + { + "id": "us_base_energy_subsidy", + "gate": "stage_health", + "phase": "transferred", + "criticality": "release_blocking", + "parameters": { + "check": "energy_subsidy_signal", + "overall_positive_share_band": [ + 0.01, + 0.2 + ], + "channel_positive_share_bands": { + "asec": [ + 0.025, + 0.045 + ], + "puf_tax_detail": [ + 0.002, + 0.2 + ] + } + }, + "notes": "Route A base (tools/build_us_puf_support_base.py): energy subsidy after support cloning. Raises at once today, in the single-process run and in the checkpointed stage alike." + }, + { + "id": "us_base_alimony", + "gate": "stage_health", + "phase": "transferred", + "criticality": "release_blocking", + "parameters": { + "check": "alimony_inputs_signal", + "nonzero_share_band": [ + 1e-05, + 0.02 + ] + }, + "notes": "Route A base (tools/build_us_puf_support_base.py): alimony after support cloning. Raises at once today, in the single-process run and in the checkpointed stage alike." + }, + { + "id": "us_base_casualty_loss", + "gate": "stage_health", + "phase": "transferred", + "criticality": "release_blocking", + "parameters": { + "check": "casualty_loss_signal", + "casualty_loss_nonzero_share_band": [ + 0.0001, + 0.02 + ] + }, + "notes": "Route A base (tools/build_us_puf_support_base.py): casualty losses after support cloning. Raises at once today, in the single-process run and in the checkpointed stage alike." + }, + { + "id": "us_base_misc_itemized", + "gate": "stage_health", + "phase": "transferred", + "criticality": "release_blocking", + "parameters": { + "check": "misc_itemized_signal", + "misc_itemized_nonzero_share_band": [ + 0.05, + 0.55 + ] + }, + "notes": "Route A base (tools/build_us_puf_support_base.py): miscellaneous itemized deductions after support cloning. Raises at once today, in the single-process run and in the checkpointed stage alike." + }, + { + "id": "us_base_retirement_contributions", + "gate": "stage_health", + "phase": "transferred", + "criticality": "release_blocking", + "parameters": { + "check": "retirement_contributions_signal", + "nonzero_share_band": [ + 0.0001, + 0.75 + ] + }, + "notes": "Route A base (tools/build_us_puf_support_base.py): retirement contributions after support cloning. Raises at once today, in the single-process run and in the checkpointed stage alike." + }, + { + "id": "us_base_retirement_distributions", + "gate": "stage_health", + "phase": "transferred", + "criticality": "release_blocking", + "parameters": { + "check": "retirement_distributions_signal", + "nonzero_share_bands": { + "taxable_401k_distributions": [ + 0.001, + 0.2 + ], + "taxable_403b_distributions": [ + 5e-05, + 0.05 + ], + "tax_exempt_ira_distributions": [ + 0.0001, + 0.05 + ], + "taxable_ira_distributions": [ + 0.001, + 0.25 + ], + "keogh_distributions": [ + 1e-07, + 0.005 + ], + "taxable_sep_distributions": [ + 1e-05, + 0.05 + ] + } + }, + "notes": "Route A base (tools/build_us_puf_support_base.py): retirement distributions after support cloning. Raises at once today, in the single-process run and in the checkpointed stage alike." + }, + { + "id": "us_base_education_inputs", + "gate": "stage_health", + "phase": "transferred", + "criticality": "release_blocking", + "parameters": { + "check": "education_inputs_signal", + "tuition_share_band": [ + 0.001, + 0.05 + ], + "assistance_share_band": [ + 0.005, + 0.08 + ] + }, + "notes": "Route A base (tools/build_us_puf_support_base.py): education inputs after support cloning. Raises at once today, in the single-process run and in the checkpointed stage alike." + }, + { + "id": "us_base_esi_premiums_post_clone", + "gate": "stage_health", + "phase": "transferred", + "criticality": "release_blocking", + "parameters": { + "check": "esi_premiums_signal", + "positive_share_band": [ + 0.15, + 0.32 + ], + "raw_mean_band": [ + 6000.0, + 20000.0 + ] + }, + "notes": "Route A base (tools/build_us_puf_support_base.py): ESI employer premiums after support cloning. Raises at once today, in the single-process run and in the checkpointed stage alike." + }, + { + "id": "us_base_geography_ladder", + "gate": "stage_health", + "phase": "terminal", + "criticality": "release_blocking", + "parameters": { + "check": "geography_ladder", + "nyc_share_bounds": [ + 0.005, + 0.06 + ], + "nyc_share_of_new_york_bounds": [ + 0.2, + 0.65 + ], + "place_share_bounds": [ + 0.4, + 0.95 + ], + "cbsa_share_bounds": [ + 0.75, + 0.99 + ], + "sld_min_share": 0.95 + }, + "notes": "Route A base (tools/build_us_puf_support_base.py): the household geography ladder before the H5 write. Runs with --block-ladder-artifact on the legacy location rule and on every block_v1 run; --allow-geography-ladder-gate-failures waives its raise today. Its thresholds are the gate's keyword defaults." + }, + { + "id": "us_base_block_location", + "gate": "stage_health", + "phase": "terminal", + "criticality": "release_blocking", + "parameters": { + "check": "block_location" + }, + "notes": "Route A base (tools/build_us_puf_support_base.py): every written geography equals the block ladder's lookup of its block. Runs on block_v1 runs only, where its failures and the ladder's share one raise." + } + ] +} diff --git a/packages/microcosm-build/src/microcosm/build/us_runtime/battery_bindings.py b/packages/microcosm-build/src/microcosm/build/us_runtime/battery_bindings.py index 6af1243086..0a0e61303d 100644 --- a/packages/microcosm-build/src/microcosm/build/us_runtime/battery_bindings.py +++ b/packages/microcosm-build/src/microcosm/build/us_runtime/battery_bindings.py @@ -437,7 +437,287 @@ def _frame_check( #: The frame signal gates both the base builder and the national release #: run, keyed by check: (legacy name, gate function, module, pinned #: constants). Each tool calls its own global of the same name. -_SCOPE_SPECS: Mapping[str, Callable[[], tuple[USGateSpec, ...]]] = MappingProxyType({}) +_SHARED_FRAME_SIGNALS: Mapping[str, tuple[str, str, str, tuple[str, ...]]] = ( + MappingProxyType( + { + "relationship_inputs_signal": ( + "relationship_inputs_signal", + "us_relationship_inputs_signal_gate", + "relationship_inputs", + ( + "_HOUSEHOLD_HEAD_SHARE_BAND", + "_SEPARATED_SHARE_BAND", + "_SURVIVING_SPOUSE_SHARE_BAND", + ), + ), + "spm_independence_role_signal": ( + "spm_independence_role_signal", + "us_spm_independence_role_signal_gate", + "spm_independence_role", + ("_ROLE_SHARE_BAND", "_MINOR_ROLE_SHARE_BAND"), + ), + "medicare_take_up_input_signal": ( + "medicare_take_up_input_signal", + "us_medicare_take_up_signal_gate", + "medicare_take_up", + ("_WEIGHTED_ENROLLED_SHARE_BAND", "_CHANNEL_ENROLLED_SHARE_BAND"), + ), + "housing_inputs_signal": ( + "housing_inputs_signal", + "us_housing_inputs_signal_gate", + "housing_inputs", + ("_RENT_SHARE_BAND", "_HOUSING_ASSISTANCE_SHARE_BAND"), + ), + "eligibility_inputs_signal": ( + "eligibility_inputs_signal", + "us_eligibility_inputs_signal_gate", + "eligibility_inputs", + ( + "_DISABLED_SHARE_BAND", + "_FULL_TIME_STUDENT_SHARE_BAND", + "_PARENT_SHARE_BAND", + "_VETERANS_BENEFITS_SHARE_BAND", + ), + ), + "pregnancy_signal": ( + "pregnancy_signal", + "us_pregnancy_signal_gate", + "pregnancy", + ("_PREGNANT_SHARE_BAND",), + ), + "wic_claim_input_signal": ( + "wic_claim_input_signal", + "us_wic_claim_signal_gate", + "wic_claim", + ("_WEIGHTED_CLAIM_SHARE_BAND", "_CATEGORY_WEIGHTED_CLAIM_SHARE_BANDS"), + ), + "esi_premiums_signal": ( + "esi_premiums_signal", + "us_esi_premiums_signal_gate", + "esi_premiums", + ("_POSITIVE_SHARE_BAND", "_RAW_MEAN_BAND"), + ), + "prior_year_income_signal": ( + "prior_year_income_signal", + "us_prior_year_income_signal_gate", + "prior_year_income", + ( + "_PREVIOUS_YEAR_AVAILABLE_SHARE_BAND", + "_SELF_EMPLOYMENT_NONZERO_SHARE_BAND", + ), + ), + "prior_year_income_source_reconciliation": ( + "prior_year_income_source_reconciliation", + "us_prior_year_income_source_reconciliation_gate", + "prior_year_income", + (), + ), + "qbi_inputs_signal": ( + "qbi_inputs_signal", + "us_qbi_inputs_signal_gate", + "qbi_inputs", + ( + "_BOOLEAN_SHARE_BANDS", + "_NUMERIC_NONZERO_SHARE_BANDS", + "_INVARIANT_ATOL", + ), + ), + "farm_business_income_signal": ( + "farm_business_income_signal", + "us_farm_business_income_signal_gate", + "farm_business_income", + ("_NONZERO_SHARE_BANDS",), + ), + "domestic_production_ald_signal": ( + "domestic_production_ald_signal", + "us_domestic_production_ald_signal_gate", + "domestic_production", + ("_DOMESTIC_PRODUCTION_ALD_POSITIVE_SHARE_BAND",), + ), + "child_support_inputs_signal": ( + "child_support_inputs_signal", + "us_child_support_signal_gate", + "child_support", + ("_NONZERO_SHARE_BANDS", "_CHANNEL_NONZERO_SHARE_BAND"), + ), + "disability_benefits_signal": ( + "disability_benefits_signal", + "us_disability_benefits_signal_gate", + "disability_benefits", + ("_NONZERO_SHARE_BAND", "_CHANNEL_NONZERO_SHARE_BANDS"), + ), + "workers_compensation_signal": ( + "workers_compensation_signal", + "us_workers_compensation_signal_gate", + "workers_compensation", + ("_NONZERO_SHARE_BAND", "_CHANNEL_NONZERO_SHARE_BANDS"), + ), + "weeks_unemployed_signal": ( + "weeks_unemployed_signal", + "us_weeks_unemployed_signal_gate", + "weeks_unemployed", + ( + "_CHANNEL_POSITIVE_SHARE_BANDS", + "_CHANNEL_WEIGHTED_MEAN_WEEKS_BANDS", + ), + ), + "educator_expense_signal": ( + "educator_expense_signal", + "us_educator_expense_signal_gate", + "educator_expenses", + ("_OVERALL_POSITIVE_SHARE_BAND", "_PUF_POSITIVE_SHARE_BAND"), + ), + "form_4952_election_signal": ( + "form_4952_election_signal", + "us_form_4952_election_signal_gate", + "form_4952", + ("_OVERALL_POSITIVE_SHARE_BAND", "_PUF_POSITIVE_SHARE_BAND"), + ), + "salt_refund_income_signal": ( + "salt_refund_income_signal", + "us_salt_refund_income_signal_gate", + "salt_refund_income", + ("_OVERALL_POSITIVE_SHARE_BAND", "_PUF_POSITIVE_SHARE_BAND"), + ), + "capital_gain_details_signal": ( + "capital_gain_details_signal", + "us_capital_gain_details_signal_gate", + "capital_gain_details", + ("_SIGNAL_BANDS",), + ), + "childcare_inputs_signal": ( + "childcare_inputs_signal", + "us_childcare_signal_gate", + "childcare", + ("_NONZERO_SHARE_BAND",), + ), + "adult_care_inputs_signal": ( + "adult_care_inputs_signal", + "us_adult_care_signal_gate", + "adult_care", + ("_FLAG_SHARE_BAND", "_EXPENSE_PLAUSIBILITY_CEILING"), + ), + "energy_subsidy_signal": ( + "energy_subsidy_signal", + "us_energy_subsidy_signal_gate", + "energy_subsidy", + ("_OVERALL_POSITIVE_SHARE_BAND", "_CHANNEL_POSITIVE_SHARE_BANDS"), + ), + "alimony_inputs_signal": ( + "alimony_inputs_signal", + "us_alimony_signal_gate", + "alimony", + ("_NONZERO_SHARE_BAND",), + ), + "casualty_loss_signal": ( + "casualty_loss_signal", + "us_casualty_loss_signal_gate", + "casualty_losses", + ("_CASUALTY_LOSS_NONZERO_SHARE_BAND",), + ), + "misc_itemized_signal": ( + "misc_itemized_signal", + "us_misc_itemized_signal_gate", + "misc_itemized", + ("_MISC_ITEMIZED_NONZERO_SHARE_BAND",), + ), + "retirement_contributions_signal": ( + "retirement_contributions_signal", + "us_retirement_contributions_signal_gate", + "retirement_contributions", + ("_NONZERO_SHARE_BAND",), + ), + "retirement_distributions_signal": ( + "retirement_distributions_signal", + "us_retirement_distributions_signal_gate", + "retirement_distributions", + ("_NONZERO_SHARE_BANDS",), + ), + "education_inputs_signal": ( + "education_inputs_signal", + "us_education_inputs_signal_gate", + "education_inputs", + ("_TUITION_SHARE_BAND", "_ASSISTANCE_SHARE_BAND"), + ), + } + ) +) + + +def _shared_frame_checks(*checks: str) -> tuple[USGateSpec, ...]: + return tuple( + _frame_check(check, legacy, gate, module, *constants) + for check in checks + for legacy, gate, module, constants in (_SHARED_FRAME_SIGNALS[check],) + ) + + +#: Thresholds the geography ladder gate takes as keywords today. +_GEOGRAPHY_LADDER_THRESHOLDS = frozenset( + { + "nyc_share_bounds", + "nyc_share_of_new_york_bounds", + "place_share_bounds", + "cbsa_share_bounds", + "sld_min_share", + } +) + + +def _us_base_specs() -> tuple[USGateSpec, ...]: + return ( + *_shared_frame_checks( + "relationship_inputs_signal", + "spm_independence_role_signal", + "medicare_take_up_input_signal", + "housing_inputs_signal", + "eligibility_inputs_signal", + "pregnancy_signal", + "wic_claim_input_signal", + "esi_premiums_signal", + "prior_year_income_signal", + "prior_year_income_source_reconciliation", + "qbi_inputs_signal", + "farm_business_income_signal", + "domestic_production_ald_signal", + "child_support_inputs_signal", + "disability_benefits_signal", + "workers_compensation_signal", + "weeks_unemployed_signal", + "educator_expense_signal", + "form_4952_election_signal", + "salt_refund_income_signal", + "capital_gain_details_signal", + "childcare_inputs_signal", + "adult_care_inputs_signal", + "energy_subsidy_signal", + "alimony_inputs_signal", + "casualty_loss_signal", + "misc_itemized_signal", + "retirement_contributions_signal", + "retirement_distributions_signal", + "education_inputs_signal", + ), + USGateSpec( + check="geography_ladder", + legacy_name="us_geography_ladder", + gate="tool:us_geography_ladder_gate", + positional=("household", "household_weights"), + parameters=_GEOGRAPHY_LADDER_THRESHOLDS, + ), + USGateSpec( + check="block_location", + legacy_name="us_block_location", + gate="tool:us_block_location_gate", + positional=("household", "location_ladder"), + ), + ) + + +#: Configuration and thresholds the PUMA ladder gate takes as keywords today. +_SCOPE_SPECS: Mapping[str, Callable[[], tuple[USGateSpec, ...]]] = MappingProxyType( + {"us_base": _us_base_specs} +) def us_gate_specs(scope: str) -> tuple[USGateSpec, ...]: diff --git a/packages/microcosm-build/tests/engine_free/us/test_us_battery_bindings.py b/packages/microcosm-build/tests/engine_free/us/test_us_battery_bindings.py new file mode 100644 index 0000000000..fb5dcbf5b5 --- /dev/null +++ b/packages/microcosm-build/tests/engine_free/us/test_us_battery_bindings.py @@ -0,0 +1,344 @@ +"""US gate scopes and bindings over today's gates (microcosm#1585 item 11). + +PR 2 of 4. ``us/gates.json`` declares every US gate the four build tools +evaluate in shadow; these tests hold the spec to today's code. Each scope is +a closed-world share of the spec with pinned digests; every declared +threshold equals the constant or keyword default today's gate uses; every +declared entry is wired at a site in its tool, calling the gate its binding +calls; and a fault injected into any gate fails it identically in today's +code and in the battery, in the entry's own phase. +""" + +from __future__ import annotations + +import importlib +import inspect +import json +from dataclasses import replace + +import pytest + +from microcosm.build import FitWeightRecord +from microcosm.build.country_spec import load_gates_manifest +from microcosm.build.gate_battery import EvidenceContext, GateStatus +from microcosm.build.gates import UNWEIGHTED_KIND, GateResult +from microcosm.build.us_runtime.battery_bindings import ( + FRAME, + USCheckBinding, + declared_value, + resolve_reference, + us_gate_registry, + us_gate_specs, +) +from microcosm.build.us_runtime.gate_scopes import ( + US_GATE_SCOPES, + check_us_gate_scopes, + us_gate_scope_digests, + us_scope_entry_ids, + us_scoped_gate_manifest, +) +from microcosm.build.us_runtime.gate_shadow import ( + GateBatteryShadow, + active_gate_shadow, + shadow_file_paths, + shadow_gate, +) +from test_support.microcosm_build.us_gate_shadow import ( + load_us_gate_tool, + shadow_wiring, +) + +#: The scopes PR 2 has declared so far, each wired in its tool. +WIRED_SCOPES = ("us_base",) + +#: Each scope's pinned digests. They move only when the scope's entries, +#: parameters, phases or the manifest's policy line do. +SCOPE_PINS: dict[str, dict[str, str]] = { + "us_base": { + "gates_manifest_sha256": ( + "b919d3a37e9aeadd507568a30c274d325a84b32c8706e1407dc9ac1626fef5ce" + ), + "policy_sha256": ( + "1a86c63cc20a6259c3349cc9dd831f0571d8c7e82e1ba77f06e4c4a102274e22" + ), + "spec_fingerprint": ( + "4ce5ca7abaef48a6026be8d120862761cf8a457904690b0e59e4a501828f43da" + ), + }, +} + + +def _entries(scope: str): + return us_scoped_gate_manifest(scope).gates + + +def _registry(scope: str): + return us_gate_registry(scope, tool=vars(load_us_gate_tool(scope))) + + +def _check_binding(scope: str) -> USCheckBinding: + binding = _registry(scope)["stage_health"] + assert isinstance(binding, USCheckBinding) + return binding + + +def _check_entries(scope: str): + return [entry for entry in _entries(scope) if entry.gate == "stage_health"] + + +def _same(left: object, right: object) -> bool: + return json.dumps(declared_value(left), sort_keys=True) == json.dumps( + declared_value(right), sort_keys=True + ) + + +# --------------------------------------------------------------------------- +# Scopes +# --------------------------------------------------------------------------- + + +def test_the_scopes_partition_the_spec() -> None: + gates = load_gates_manifest("us") + check_us_gate_scopes(gates) + owned = [ + entry_id for scope in US_GATE_SCOPES for entry_id in us_scope_entry_ids(scope) + ] + assert sorted(owned) == sorted(entry.id for entry in gates.gates) + assert len(owned) == len(set(owned)) + + +def test_a_manifest_the_scopes_do_not_partition_is_refused() -> None: + gates = load_gates_manifest("us") + first = gates.gates[0] + + def with_entries(*entries): + return replace(gates, gates=(*entries, *gates.gates[1:])) + + with pytest.raises( + RuntimeError, match="owned by no scope \\['us_elsewhere_gate'\\]" + ): + check_us_gate_scopes(with_entries(replace(first, id="us_elsewhere_gate"))) + with pytest.raises(RuntimeError, match="does not evaluate"): + check_us_gate_scopes(with_entries(replace(first, phase="simulated"))) + with pytest.raises(ValueError, match="unknown US gate scope"): + us_scoped_gate_manifest("us_elsewhere") + + +@pytest.mark.parametrize("scope", WIRED_SCOPES) +def test_each_scope_has_its_own_pinned_digests(scope) -> None: + digests = us_gate_scope_digests(scope, _registry(scope)) + assert digests == SCOPE_PINS[scope] + others = { + other: us_gate_scope_digests(other, _registry(other)) + for other in WIRED_SCOPES + if other != scope + } + assert all( + pins["gates_manifest_sha256"] != digests["gates_manifest_sha256"] + for pins in others.values() + ) + + +# --------------------------------------------------------------------------- +# Thresholds: the spec carries today's values +# --------------------------------------------------------------------------- + + +@pytest.mark.parametrize("scope", WIRED_SCOPES) +def test_every_pinned_threshold_equals_todays_constant(scope) -> None: + binding = _check_binding(scope) + for entry in _check_entries(scope): + check = entry.parameters["check"] + today = binding.pinned_values(check) + declared = {key: entry.parameters[key] for key in today} + assert _same(declared, today), (entry.id, declared, today) + + +@pytest.mark.parametrize("scope", WIRED_SCOPES) +def test_every_routed_threshold_equals_todays_default(scope) -> None: + binding = _check_binding(scope) + for entry in _check_entries(scope): + spec = binding.checks[entry.parameters["check"]] + if not spec.parameters: + continue + gate = resolve_reference(spec.gate, tool=binding.tool) + defaults = inspect.signature(gate).parameters + for key in spec.parameters: + assert _same(entry.parameters[key], defaults[key].default), ( + entry.id, + key, + ) + + +@pytest.mark.parametrize("scope", WIRED_SCOPES) +def test_entries_declare_exactly_their_gates_thresholds(scope) -> None: + binding = _check_binding(scope) + used = set() + for entry in _check_entries(scope): + check = entry.parameters["check"] + assert check in binding.checks, entry.id + used.add(check) + declared = set(entry.parameters) - {"check"} + assert declared == binding.checks[check].parameter_keys, entry.id + # No spec is dead weight in its scope. + assert used == set(binding.checks) + + +# --------------------------------------------------------------------------- +# Wiring: every entry has a site, calling the gate its binding calls +# --------------------------------------------------------------------------- + + +@pytest.mark.parametrize("scope", WIRED_SCOPES) +def test_every_entry_is_wired_at_a_site_calling_its_gate(scope) -> None: + binding = _check_binding(scope) + declared = {entry.id: entry for entry in _entries(scope)} + sites = shadow_wiring(scope) + unknown = sorted({entry_id for entry_id, _, _ in sites} - set(declared)) + assert not unknown, unknown + assert {entry_id for entry_id, _, _ in sites} == set(declared) + for entry_id, reference, where in sites: + entry = declared[entry_id] + if reference is None or entry.gate != "stage_health": + continue + spec = binding.checks[entry.parameters["check"]] + assert spec.gate == reference, (entry_id, where, reference, spec.gate) + + +# --------------------------------------------------------------------------- +# Fault injection: one failure per gate, identical in both, in its phase +# --------------------------------------------------------------------------- + + +def _shadow(tmp_path, scope: str) -> GateBatteryShadow: + report, comparison = shadow_file_paths(tmp_path, scope) + return GateBatteryShadow( + us_scoped_gate_manifest(scope), + scope=scope, + release_id=f"{scope}-fault-injection", + report_path=report, + comparison_path=comparison, + registry=_registry(scope), + ) + + +def _evidence(spec) -> EvidenceContext: + """Evidence of the right shape; the injected gate ignores its values.""" + + return EvidenceContext( + frame=object() if spec.needs_frame else None, + artifacts={key: object() for key in spec.artifact_keys}, + ) + + +def _fault_cases(scope: str): + return [ + pytest.param(scope, entry.id, id=entry.id) for entry in _check_entries(scope) + ] + + +@pytest.mark.parametrize( + ("scope", "entry_id"), + [case for scope in WIRED_SCOPES for case in _fault_cases(scope)], +) +@pytest.mark.parametrize("fault", ["fails", "crashes"]) +def test_an_injected_fault_fails_both_verdicts_alike( + tmp_path, monkeypatch, scope, entry_id, fault +) -> None: + tool = vars(load_us_gate_tool(scope)) + shadow = _shadow(tmp_path, scope) + entry = next(entry for entry in shadow.gates.gates if entry.id == entry_id) + spec = {spec.check: spec for spec in us_gate_specs(scope)}[ + entry.parameters["check"] + ] + namespace, _, gate_name = spec.gate.partition(":") + target = tool if namespace == "tool" else vars(importlib.import_module(namespace)) + lines = (f"{entry_id}: injected failure.",) + + def injected(*args, **kwargs): + if fault == "crashes": + raise KeyError(f"{entry_id}: injected crash") + if spec.returns_failures: + return list(lines) + return GateResult(name=spec.legacy_name, passed=False, failures=lines) + + monkeypatch.setitem(target, gate_name, injected) + evidence = _evidence(spec) + + def today(): + return target[gate_name]( + *( + evidence.frame if source == FRAME else evidence.artifacts[source] + for source in spec.positional + ), + ) + + with active_gate_shadow(shadow): + if fault == "crashes": + with pytest.raises(KeyError): + shadow_gate(entry_id, today, evidence) + else: + result = shadow_gate(entry_id, today, evidence) + assert result.failures == lines + outcome = shadow.outcome(entry_id) + assert outcome is not None and outcome.status is GateStatus.FAILED + assert outcome.entry.phase == entry.phase + if fault == "fails": + assert outcome.result.failures == lines + else: + assert "evaluation_error" in outcome.result.details + assert shadow.differences() == () + + +@pytest.mark.parametrize("scope", WIRED_SCOPES) +def test_the_shared_weights_audit_fails_both_verdicts_alike(tmp_path, scope) -> None: + shadow = _shadow(tmp_path, scope) + tool = vars(load_us_gate_tool(scope)) + records = [FitWeightRecord("us_puf_tax_detail_support", UNWEIGHTED_KIND)] + with active_gate_shadow(shadow): + result = shadow_gate( + f"{scope}_weights_audit", + lambda: tool["weights_audit_gate"](records), + EvidenceContext(artifacts={"fit_weight_records": records}), + ) + assert not result.passed + outcome = shadow.outcome(f"{scope}_weights_audit") + assert outcome.status is GateStatus.FAILED + assert outcome.result.failures == result.failures + assert shadow.differences() == () + + +def test_a_declared_threshold_off_todays_constant_is_a_difference(tmp_path) -> None: + # The pin is live: a spec edit that today's constant does not follow is + # caught at the next evaluation, as a verdict difference. + scoped = us_scoped_gate_manifest("us_base") + altered = replace( + scoped, + gates=tuple( + replace( + entry, + parameters={**entry.parameters, "pregnant_share_band": [0.0, 1.0]}, + ) + if entry.id == "us_base_pregnancy" + else entry + for entry in scoped.gates + ), + ) + report, comparison = shadow_file_paths(tmp_path, "us_base") + shadow = GateBatteryShadow( + altered, + scope="us_base", + release_id="us-base-altered", + report_path=report, + comparison_path=comparison, + registry=_registry("us_base"), + ) + passing = GateResult(name="pregnancy_signal", passed=True) + with active_gate_shadow(shadow): + shadow_gate( + "us_base_pregnancy", + lambda: passing, + EvidenceContext(frame=object()), + ) + (difference,) = shadow.differences() + assert "differs from today's" in difference diff --git a/packages/microcosm-build/tests/engine_free/us/test_us_puf_support_base_gate_shadow.py b/packages/microcosm-build/tests/engine_free/us/test_us_puf_support_base_gate_shadow.py new file mode 100644 index 0000000000..d1b438fd13 --- /dev/null +++ b/packages/microcosm-build/tests/engine_free/us/test_us_puf_support_base_gate_shadow.py @@ -0,0 +1,239 @@ +"""Route A's base builder runs the gate battery in shadow (microcosm#1585 item 11). + +``tools/build_us_puf_support_base.py`` arms the ``us_base`` scope around its +single-process pipeline, and around each checkpointed stage, whose child +process saves what it observed for the parent to finish. These tests drive +those seams with stand-in gates; the stages themselves are not run. +""" + +from __future__ import annotations + +import json +from types import SimpleNamespace + +import pytest + +from microcosm.build import FitWeightRecord, GateResult +from microcosm.build.gate_battery import EvidenceContext +from microcosm.build.us_runtime.battery_bindings import us_gate_specs +from microcosm.build.us_runtime.gate_scopes import us_scoped_gate_manifest +from microcosm.build.us_runtime.gate_shadow import ( + GATE_BATTERY_SHADOW_DIRECTORY, + GateBatteryShadowMismatchError, + active_gate_shadow, + shadow_file_paths, + shadow_gate, +) +from test_support.microcosm_build.us_gate_shadow import load_us_gate_tool + + +@pytest.fixture +def base(): + return load_us_gate_tool("us_base") + + +def _args(tmp_path, **overrides): + values = { + "target_year": 2024, + "out": tmp_path / "out", + "checkpoint_dir": tmp_path / "checkpoints", + "stage": "all", + "allow_geography_ladder_gate_failures": False, + "block_ladder_artifact": None, + "equivalence_boundary_dir": None, + } + values.update(overrides) + return SimpleNamespace(**values) + + +def _stand_in_gates(monkeypatch, base, *, failing=()): + """Replace every base gate the bindings call with a stand-in verdict.""" + + for spec in us_gate_specs("us_base"): + name = spec.gate.removeprefix("tool:") + failed = spec.check in failing + + def gate(*args, _legacy=spec.legacy_name, _failed=failed, **kwargs): + if _failed: + return GateResult( + name=_legacy, passed=False, failures=(f"{_legacy}: stand-in.",) + ) + return GateResult(name=_legacy, passed=True) + + monkeypatch.setitem(vars(base), name, gate) + + +def _observe_every_entry(base, args): + """What a passing pipeline observes: every frame gate, the audit, location.""" + + tool = vars(base) + frame = object() + specs = {spec.check: spec for spec in us_gate_specs("us_base")} + for entry in us_scoped_gate_manifest("us_base").gates: + if entry.gate == "weights_audit": + records = [FitWeightRecord("us_puf_tax_detail_support", "design")] + shadow_gate( + entry.id, + lambda records=records: tool["weights_audit_gate"](records), + EvidenceContext(artifacts={"fit_weight_records": records}), + ) + elif entry.parameters["check"] in {"geography_ladder", "block_location"}: + continue + else: + gate = tool[specs[entry.parameters["check"]].gate.removeprefix("tool:")] + base._shadow_frame_gate(entry.id, lambda gate=gate: gate(frame), frame) + base._shadow_legacy_location_not_run(args) + + +def test_the_single_process_run_finishes_its_shadow(tmp_path, monkeypatch, base): + args = _args(tmp_path, checkpoint_dir=None) + _stand_in_gates(monkeypatch, base) + monkeypatch.setattr(base, "_verify_asec_source_digests", lambda args: None) + monkeypatch.setattr(base, "_run_all", lambda args: _observe_every_entry(base, args)) + base._dispatch(args, None) + _, comparison = shadow_file_paths( + args.out.resolve() / GATE_BATTERY_SHADOW_DIRECTORY, "us_base" + ) + payload = json.loads(comparison.read_text()) + assert payload["run_completed"] is True + assert payload["verdict_difference"] is False + assert payload["phases_recorded"] == ["assembled", "transferred", "terminal"] + location = { + row["id"]: row + for row in payload["entries"] + if row["id"] in {"us_base_geography_ladder", "us_base_block_location"} + } + assert {row["legacy"]["status"] for row in location.values()} == {"not_run"} + assert {row["battery"]["status"] for row in location.values()} == { + "evidence_absent" + } + + +def test_a_verdict_difference_fails_the_single_process_run(tmp_path, monkeypatch, base): + args = _args(tmp_path, checkpoint_dir=None) + # The battery's gate fails where today's verdict passed. + _stand_in_gates(monkeypatch, base, failing={"pregnancy_signal"}) + monkeypatch.setattr(base, "_verify_asec_source_digests", lambda args: None) + + def run_all(args): + _observe_every_entry(base, args) + + original = base._shadow_frame_gate + + def legacy_passes(entry_id, evaluate, frame): + if entry_id == "us_base_pregnancy": + return original( + entry_id, + lambda: GateResult(name="pregnancy_signal", passed=True), + frame, + ) + return original(entry_id, evaluate, frame) + + monkeypatch.setattr(base, "_shadow_frame_gate", legacy_passes) + monkeypatch.setattr(base, "_run_all", run_all) + with pytest.raises(GateBatteryShadowMismatchError, match="us_base_pregnancy"): + base._dispatch(args, None) + + +def test_todays_raise_propagates_and_the_shadow_says_where(tmp_path, monkeypatch, base): + args = _args(tmp_path, checkpoint_dir=None) + _stand_in_gates(monkeypatch, base, failing={"relationship_inputs_signal"}) + monkeypatch.setattr(base, "_verify_asec_source_digests", lambda args: None) + tool = vars(base) + + def run_all(args): + frame = object() + gate = base._shadow_frame_gate( + "us_base_relationship_inputs", + lambda: tool["us_relationship_inputs_signal_gate"](frame), + frame, + ) + if not gate.passed: + raise SystemExit("Relationship-input signal gate failed") + + monkeypatch.setattr(base, "_run_all", run_all) + with pytest.raises(SystemExit, match="Relationship-input signal gate failed"): + base._dispatch(args, None) + report, comparison = shadow_file_paths( + args.out.resolve() / GATE_BATTERY_SHADOW_DIRECTORY, "us_base" + ) + payload = json.loads(comparison.read_text()) + assert payload["run_completed"] is False + assert payload["stopped_by"]["type"] == "SystemExit" + assert payload["blocked_at_phase"] == "assembled" + gates = json.loads(report.read_text())["gates"] + assert gates["us_base_relationship_inputs"]["status"] == "failed" + assert gates["us_base_pregnancy"]["status"] == "unreached" + + +def test_checkpointed_stages_carry_their_observations_to_the_parent( + tmp_path, monkeypatch, base +): + _stand_in_gates(monkeypatch, base, failing={"medicare_take_up_input_signal"}) + tool = vars(base) + frame = object() + wic = _args(tmp_path, stage="wic_post_clone") + with base._armed_stage_gate_shadow(wic) as save: + base._shadow_frame_gate( + "us_base_wic_claim_post_clone", + lambda: tool["us_wic_claim_signal_gate"](frame), + frame, + ) + save() + assert base._stage_gate_shadow_observations(wic, "wic_post_clone").is_file() + + medicare = _args(tmp_path, stage="medicare_post_clone") + with pytest.raises(SystemExit): + with base._armed_stage_gate_shadow(medicare): + gate = base._shadow_frame_gate( + "us_base_medicare_take_up_post_clone", + lambda: tool["us_medicare_take_up_signal_gate"](frame), + frame, + ) + if not gate.passed: + raise SystemExit("Medicare take-up input signal gate failed") + # The stage that raised still saved what it saw. + assert base._stage_gate_shadow_observations( + medicare, "medicare_post_clone" + ).is_file() + + parent = _args(tmp_path) + shadow = base._base_gate_shadow(parent, base._final_gate_shadow_directory(parent)) + base._load_stage_gate_shadows( + shadow, parent, ("wic_post_clone", "medicare_post_clone", "never_ran") + ) + shadow.stop(SystemExit("Checkpointed stage 'medicare_post_clone' failed")) + payload = json.loads(shadow.comparison_path.read_text()) + observed = {row["id"]: row for row in payload["entries"]} + assert set(observed) == { + "us_base_wic_claim_post_clone", + "us_base_medicare_take_up_post_clone", + } + assert all(row["match"] for row in observed.values()) + assert observed["us_base_medicare_take_up_post_clone"]["battery"]["status"] == ( + "failed" + ) + assert payload["shadow_errors"] == [] + + +def test_the_geography_waiver_is_recorded_by_entry(tmp_path, base) -> None: + shadow = base._base_gate_shadow( + _args(tmp_path, allow_geography_ladder_gate_failures=True), tmp_path + ) + payload = shadow.finish(stopped_at="test") + assert payload["waivers"] == { + "us_base_block_location": ["--allow-geography-ladder-gate-failures"], + "us_base_geography_ladder": ["--allow-geography-ladder-gate-failures"], + } + + +def test_the_legacy_location_rule_records_what_it_never_evaluates( + tmp_path, base +) -> None: + with_ladder = _args(tmp_path, block_ladder_artifact=tmp_path / "ladder.parquet") + shadow = base._base_gate_shadow(with_ladder, tmp_path) + with active_gate_shadow(shadow): + base._shadow_legacy_location_not_run(with_ladder) + # With a ladder artifact the ladder gate runs; only the block draw is absent. + assert shadow.outcome("us_base_block_location") is not None + assert shadow.outcome("us_base_geography_ladder") is None diff --git a/tools/build_us_puf_support_base.py b/tools/build_us_puf_support_base.py index b244dd7e10..30950f9957 100644 --- a/tools/build_us_puf_support_base.py +++ b/tools/build_us_puf_support_base.py @@ -33,8 +33,9 @@ import numpy as np import pandas as pd -from microcosm.build import FitWeightRecord, weights_audit_gate +from microcosm.build import FitWeightRecord, GateResult, weights_audit_gate from microcosm.build.frame_checkpoint import write_frame_checkpoint +from microcosm.build.gate_battery import EvidenceContext from microcosm.build.ledger_artifact import load_ledger_consumer_artifact from microcosm.build.outer_stage_runtime import ( Stage, @@ -172,6 +173,7 @@ write_puf_capital_gains_tail_manifest, ) from microcosm.build.us_runtime.asec_sources import ASEC_SOURCE_ARTIFACTS +from microcosm.build.us_runtime.battery_bindings import us_gate_registry from microcosm.build.us_runtime.block_location import ( POPULACE_BLOCK_LADDER_SHA256_ATTR, POPULACE_BLOCK_LADDER_VINTAGES_ATTR, @@ -192,6 +194,17 @@ household_source_keys, load_cps_household_geography, ) +from microcosm.build.us_runtime.gate_scopes import us_scoped_gate_manifest +from microcosm.build.us_runtime.gate_shadow import ( + GATE_BATTERY_SHADOW_DIRECTORY, + GateBatteryShadow, + LegacyVerdict, + active_gate_shadow, + current_gate_shadow, + shadow_file_paths, + shadow_gate, + shadow_not_run, +) from microcosm.build.us_runtime.h5_io import ( assert_h5_unchanged, refuse_denied_frame, @@ -895,9 +908,10 @@ def _dispatch( return if checkpoint_dir is None: # This is intentionally a direct call with no profiler, checkpoint - # directory creation, or other side effect, except telemetry: the - # emitter started in main() and the one stage change below, which - # change no output byte. It is the pre-refactor pipeline and remains + # directory creation, or other side effect, except telemetry (the + # emitter started in main() and the one stage change below) and the + # gate battery's shadow files beside the outputs, none of which + # changes an output byte. It is the pre-refactor pipeline and remains # the byte-for-byte compatibility path. if telemetry is not None: telemetry.transition_stage("all") @@ -909,10 +923,12 @@ def _dispatch( boundary_dir, pipeline_steps=_pipeline_steps_for(args) ) ) - if observer is None: - _run_all(args) - else: - _run_all(args, boundary_observer=observer) + with _armed_base_gate_shadow(args): + if observer is None: + _run_all(args) + else: + _run_all(args, boundary_observer=observer) + if observer is not None: observer.assert_complete() return _run_staged_all(args, telemetry) @@ -940,23 +956,183 @@ def _run_staged_all( # Re-enter only the fresh final child so it can validate/repair the # export and stage_all alias after a crash in the post-context window. remaining = ("final_export",) - for stage in remaining: - if telemetry is not None: - telemetry.transition_stage(stage) - completed = subprocess.run( - [ - sys.executable, - str(Path(__file__).resolve()), - *_stage_cli_args(args, stage), - ], - check=False, - env=_staged_subprocess_environment(), - ) - if completed.returncode != 0: - raise SystemExit( - f"Checkpointed stage {stage!r} failed with exit code " - f"{completed.returncode}." + # Each child observes its own stage's gates; this parent finishes the + # shadow scope from what they saved, completed stages included. + directory = _final_gate_shadow_directory(args) + shadow = None if directory is None else _base_gate_shadow(args, directory) + try: + for stage in remaining: + if telemetry is not None: + telemetry.transition_stage(stage) + completed = subprocess.run( + [ + sys.executable, + str(Path(__file__).resolve()), + *_stage_cli_args(args, stage), + ], + check=False, + env=_staged_subprocess_environment(), ) + if completed.returncode != 0: + raise SystemExit( + f"Checkpointed stage {stage!r} failed with exit code " + f"{completed.returncode}." + ) + except BaseException as error: + if shadow is not None: + _load_stage_gate_shadows(shadow, args, pipeline_steps) + shadow.stop(error) + raise + if shadow is not None: + _load_stage_gate_shadows(shadow, args, pipeline_steps) + shadow.finish() + + +#: This tool's scope of us/gates.json, evaluated in shadow beside today's +#: gates (microcosm#1585 item 11, PR 2 of 4). +US_BASE_GATE_SCOPE = "us_base" +_GEOGRAPHY_LADDER_WAIVER = "--allow-geography-ladder-gate-failures" + + +def _final_gate_shadow_directory(args: argparse.Namespace) -> Path | None: + """Where the finished shadow files go: beside the outputs. + + ``None`` only for stand-in arguments without ``--out`` (a test driving + the dispatcher), which have nowhere to write and run without a shadow; + the parser requires ``--out`` of every real run. + """ + + out = getattr(args, "out", None) + return None if out is None else Path(out).resolve() / GATE_BATTERY_SHADOW_DIRECTORY + + +def _stage_gate_shadow_observations(args: argparse.Namespace, stage: str) -> Path: + return ( + args.checkpoint_dir + / GATE_BATTERY_SHADOW_DIRECTORY + / f"{stage}.observations.json" + ) + + +def _base_gate_shadow(args: argparse.Namespace, directory: Path) -> GateBatteryShadow: + """This build's gate battery in shadow, its files in ``directory``.""" + + report_path, comparison_path = shadow_file_paths(directory, US_BASE_GATE_SCOPE) + waived = ( + ("us_base_geography_ladder", "us_base_block_location") + if getattr(args, "allow_geography_ladder_gate_failures", False) + else () + ) + target_year = getattr(args, "target_year", PERIOD) + return GateBatteryShadow( + us_scoped_gate_manifest(US_BASE_GATE_SCOPE), + scope=US_BASE_GATE_SCOPE, + release_id=f"populace-us-{target_year}-puf-support-base", + report_path=report_path, + comparison_path=comparison_path, + registry=us_gate_registry(US_BASE_GATE_SCOPE, tool=globals()), + waivers={entry_id: (_GEOGRAPHY_LADDER_WAIVER,) for entry_id in waived}, + ) + + +@contextmanager +def _armed_base_gate_shadow( + args: argparse.Namespace, +) -> Iterator[GateBatteryShadow | None]: + """The single-process run's shadow, finished when the block exits.""" + + directory = _final_gate_shadow_directory(args) + if directory is None: + yield None + return + shadow = _base_gate_shadow(args, directory) + with shadow, active_gate_shadow(shadow): + yield shadow + + +@contextmanager +def _armed_stage_gate_shadow(args: argparse.Namespace) -> Iterator[Callable[[], None]]: + """Arm one checkpointed stage's shadow; yield the call that saves it. + + The stage saves before it marks itself complete, so a resumed build finds + the observations of every stage it does not run again. A stage that + raises saves what it saw on the way out, so the parent's report says + where the build stopped. A save that fails warns and is otherwise left to + the parent, which then reports the stage's entries as unobserved. + """ + + shadow = _base_gate_shadow( + args, args.checkpoint_dir / GATE_BATTERY_SHADOW_DIRECTORY / args.stage + ) + path = _stage_gate_shadow_observations(args, args.stage) + saved = False + + def save() -> None: + nonlocal saved + if saved: + return + saved = True + try: + shadow.save_observations(path) + except Exception as error: # noqa: BLE001 - the shadow never stops a stage + print( + f"warning: could not save gate battery shadow observations to " + f"{path}: {type(error).__name__}: {error}", + file=sys.stderr, + ) + + with active_gate_shadow(shadow): + try: + yield save + except BaseException: + save() + raise + save() + + +def _load_stage_gate_shadows( + shadow: GateBatteryShadow, + args: argparse.Namespace, + pipeline_steps: Sequence[str], +) -> None: + for stage in pipeline_steps: + path = _stage_gate_shadow_observations(args, stage) + if path.is_file(): + shadow.load_observations(path) + + +def _shadow_frame_gate( + entry_id: str, evaluate: Callable[[], GateResult], frame: Frame +) -> GateResult: + """Today's frame signal gate, with the battery's entry beside it.""" + + return shadow_gate(entry_id, evaluate, lambda: EvidenceContext(frame=frame)) + + +def _observe_frame_gate(entry_id: str, result: GateResult, frame: Frame) -> None: + """Observe a frame gate verdict today's code reached by itself.""" + + shadow = current_gate_shadow(entry_id) + if shadow is None: + return + try: + legacy = LegacyVerdict.from_result(result) + except TypeError as error: + shadow.record_error(entry_id, f"today's verdict is not comparable: {error}") + return + shadow.check(entry_id, lambda: EvidenceContext(frame=frame), legacy) + + +def _shadow_legacy_location_not_run(args: argparse.Namespace) -> None: + """The location entries the legacy location rule never evaluates.""" + + shadow_not_run("us_base_block_location", "the legacy location rule draws no block") + if getattr(args, "block_ladder_artifact", None) is None: + shadow_not_run( + "us_base_geography_ladder", + "the legacy location rule assigns no geography ladder without " + "--block-ladder-artifact", + ) def _stage_cli_args(args: argparse.Namespace, stage: str) -> list[str]: @@ -1390,11 +1566,23 @@ def _block_v1_household_location( ) household = located.table("household") household_weights = located.weights_for("household").values - location_gate = us_block_location_gate(household, ladder) + location_gate = shadow_gate( + "us_base_block_location", + lambda: us_block_location_gate(household, ladder), + lambda: EvidenceContext( + artifacts={"household": household, "location_ladder": ladder} + ), + ) # The L0/refit release export re-runs the legacy geography-ladder gate # (l0_refit_export.py:export_us_l0_refit_h5) on frames built from this # base, so the block draw must pass it here too. - ladder_gate = us_geography_ladder_gate(household, household_weights) + ladder_gate = shadow_gate( + "us_base_geography_ladder", + lambda: us_geography_ladder_gate(household, household_weights), + lambda: EvidenceContext( + artifacts={"household": household, "household_weights": household_weights} + ), + ) failures = [ *(f"us_block_location: {failure}" for failure in location_gate.failures), *(f"geography_ladder: {failure}" for failure in ladder_gate.failures), @@ -1527,7 +1715,11 @@ def _run_all( seed=args.seed, time_period=args.target_year, ) - relationship_inputs_gate = us_relationship_inputs_signal_gate(base) + relationship_inputs_gate = _shadow_frame_gate( + "us_base_relationship_inputs", + lambda: us_relationship_inputs_signal_gate(base), + base, + ) if not relationship_inputs_gate.passed: raise SystemExit( "Relationship-input signal gate failed:\n " @@ -1539,7 +1731,11 @@ def _run_all( time_period=args.target_year, asec_spm_role_source_paths=_asec_education_source_paths(args), ) - spm_independence_role_gate = us_spm_independence_role_signal_gate(base) + spm_independence_role_gate = _shadow_frame_gate( + "us_base_spm_independence_role", + lambda: us_spm_independence_role_signal_gate(base), + base, + ) if not spm_independence_role_gate.passed: raise SystemExit( "SPM independence role signal gate failed:\n " @@ -1550,7 +1746,11 @@ def _run_all( seed=args.seed, time_period=args.target_year, ) - medicare_take_up_gate = us_medicare_take_up_signal_gate(base) + medicare_take_up_gate = _shadow_frame_gate( + "us_base_medicare_take_up_pre_clone", + lambda: us_medicare_take_up_signal_gate(base), + base, + ) if not medicare_take_up_gate.passed: raise SystemExit( "Medicare take-up input signal gate failed before support cloning:\n " @@ -1560,6 +1760,9 @@ def _run_all( acs_rent_donor: pd.DataFrame | None = None if not housing_inputs_gate.passed: if args.acs_h5 is None: + _observe_frame_gate( + "us_base_housing_inputs_pre_clone", housing_inputs_gate, base + ) raise SystemExit( "Housing-input signal gate is not already green and --acs-h5 " "was not provided; exact pre_subsidy_rent restoration requires " @@ -1573,6 +1776,7 @@ def _run_all( acs_rent_donor=acs_rent_donor, ) housing_inputs_gate = us_housing_inputs_signal_gate(base) + _observe_frame_gate("us_base_housing_inputs_pre_clone", housing_inputs_gate, base) if not housing_inputs_gate.passed: raise SystemExit( "Housing-input signal gate failed before support cloning:\n " @@ -1583,7 +1787,11 @@ def _run_all( seed=args.seed, time_period=args.target_year, ) - eligibility_inputs_gate = us_eligibility_inputs_signal_gate(base) + eligibility_inputs_gate = _shadow_frame_gate( + "us_base_eligibility_inputs", + lambda: us_eligibility_inputs_signal_gate(base), + base, + ) if not eligibility_inputs_gate.passed: raise SystemExit( "Eligibility-input signal gate failed before support cloning:\n " @@ -1594,7 +1802,9 @@ def _run_all( seed=args.seed, time_period=args.target_year, ) - pregnancy_gate = us_pregnancy_signal_gate(base) + pregnancy_gate = _shadow_frame_gate( + "us_base_pregnancy", lambda: us_pregnancy_signal_gate(base), base + ) if not pregnancy_gate.passed: raise SystemExit( "Pregnancy signal gate failed before support cloning:\n " @@ -1605,7 +1815,9 @@ def _run_all( seed=args.seed, time_period=args.target_year, ) - wic_claim_gate = us_wic_claim_signal_gate(base) + wic_claim_gate = _shadow_frame_gate( + "us_base_wic_claim_pre_clone", lambda: us_wic_claim_signal_gate(base), base + ) if not wic_claim_gate.passed: raise SystemExit( "WIC-claim signal gate failed before support cloning:\n " @@ -1657,7 +1869,11 @@ def _run_all( seed=args.seed, time_period=args.target_year, ) - esi_premiums_gate = us_esi_premiums_signal_gate(base) + esi_premiums_gate = _shadow_frame_gate( + "us_base_esi_premiums_pre_clone", + lambda: us_esi_premiums_signal_gate(base), + base, + ) if not esi_premiums_gate.passed: raise SystemExit( "ESI premium signal gate failed before support cloning:\n " @@ -1726,13 +1942,21 @@ def _run_all( seed=args.seed, time_period=args.target_year, ) - wic_claim_gate = us_wic_claim_signal_gate(imputed) + wic_claim_gate = _shadow_frame_gate( + "us_base_wic_claim_post_clone", + lambda: us_wic_claim_signal_gate(imputed), + imputed, + ) if not wic_claim_gate.passed: raise SystemExit( "WIC-claim signal gate failed after support cloning:\n " + "\n ".join(wic_claim_gate.failures) ) - medicare_take_up_gate = us_medicare_take_up_signal_gate(imputed) + medicare_take_up_gate = _shadow_frame_gate( + "us_base_medicare_take_up_post_clone", + lambda: us_medicare_take_up_signal_gate(imputed), + imputed, + ) if not medicare_take_up_gate.passed: raise SystemExit( "Medicare take-up input signal gate failed after support cloning:\n " @@ -1749,38 +1973,58 @@ def _run_all( seed=args.seed, time_period=args.target_year, ) - prior_year_income_gate = us_prior_year_income_signal_gate(imputed) + prior_year_income_gate = _shadow_frame_gate( + "us_base_prior_year_income", + lambda: us_prior_year_income_signal_gate(imputed), + imputed, + ) if not prior_year_income_gate.passed: raise SystemExit( "Prior-year-income signal gate failed:\n " + "\n ".join(prior_year_income_gate.failures) ) - prior_year_income_reconciliation_gate = ( - us_prior_year_income_source_reconciliation_gate(imputed) + prior_year_income_reconciliation_gate = _shadow_frame_gate( + "us_base_prior_year_income_source_reconciliation", + lambda: us_prior_year_income_source_reconciliation_gate(imputed), + imputed, ) if not prior_year_income_reconciliation_gate.passed: raise SystemExit( "Prior-year-income source reconciliation failed:\n " + "\n ".join(prior_year_income_reconciliation_gate.failures) ) - housing_inputs_gate = us_housing_inputs_signal_gate(imputed) + housing_inputs_gate = _shadow_frame_gate( + "us_base_housing_inputs_post_clone", + lambda: us_housing_inputs_signal_gate(imputed), + imputed, + ) if not housing_inputs_gate.passed: raise SystemExit( "Housing-input signal gate failed after PUF-support imputation:\n " + "\n ".join(housing_inputs_gate.failures) ) - qbi_inputs_gate = us_qbi_inputs_signal_gate(imputed) + qbi_inputs_gate = _shadow_frame_gate( + "us_base_qbi_inputs", lambda: us_qbi_inputs_signal_gate(imputed), imputed + ) if not qbi_inputs_gate.passed: raise SystemExit( "QBI-input signal gate failed:\n " + "\n ".join(qbi_inputs_gate.failures) ) - farm_business_income_gate = us_farm_business_income_signal_gate(imputed) + farm_business_income_gate = _shadow_frame_gate( + "us_base_farm_business_income", + lambda: us_farm_business_income_signal_gate(imputed), + imputed, + ) if not farm_business_income_gate.passed: raise SystemExit( "Farm-business-income signal gate failed:\n " + "\n ".join(farm_business_income_gate.failures) ) - domestic_production_ald_gate = us_domestic_production_ald_signal_gate(imputed) + domestic_production_ald_gate = _shadow_frame_gate( + "us_base_domestic_production_ald", + lambda: us_domestic_production_ald_signal_gate(imputed), + imputed, + ) if not domestic_production_ald_gate.passed: raise SystemExit( "Domestic-production-ALD signal gate failed:\n " @@ -1792,7 +2036,9 @@ def _run_all( seed=args.seed, time_period=args.target_year, ) - child_support_gate = us_child_support_signal_gate(imputed) + child_support_gate = _shadow_frame_gate( + "us_base_child_support", lambda: us_child_support_signal_gate(imputed), imputed + ) if not child_support_gate.passed: raise SystemExit( "Child-support signal gate failed:\n " @@ -1804,7 +2050,11 @@ def _run_all( seed=args.seed, time_period=args.target_year, ) - disability_benefits_gate = us_disability_benefits_signal_gate(imputed) + disability_benefits_gate = _shadow_frame_gate( + "us_base_disability_benefits", + lambda: us_disability_benefits_signal_gate(imputed), + imputed, + ) if not disability_benefits_gate.passed: raise SystemExit( "Disability-benefits signal gate failed:\n " @@ -1818,7 +2068,11 @@ def _run_all( seed=args.seed, time_period=args.target_year, ) - workers_compensation_gate = us_workers_compensation_signal_gate(imputed) + workers_compensation_gate = _shadow_frame_gate( + "us_base_workers_compensation", + lambda: us_workers_compensation_signal_gate(imputed), + imputed, + ) if not workers_compensation_gate.passed: raise SystemExit( "Workers-compensation signal gate failed:\n " @@ -1833,31 +2087,51 @@ def _run_all( time_period=args.target_year, asec_2023_source=weeks_unemployed_source, ) - weeks_unemployed_gate = us_weeks_unemployed_signal_gate(imputed) + weeks_unemployed_gate = _shadow_frame_gate( + "us_base_weeks_unemployed", + lambda: us_weeks_unemployed_signal_gate(imputed), + imputed, + ) if not weeks_unemployed_gate.passed: raise SystemExit( "Weeks-unemployed signal gate failed:\n " + "\n ".join(weeks_unemployed_gate.failures) ) - educator_expense_gate = us_educator_expense_signal_gate(imputed) + educator_expense_gate = _shadow_frame_gate( + "us_base_educator_expense", + lambda: us_educator_expense_signal_gate(imputed), + imputed, + ) if not educator_expense_gate.passed: raise SystemExit( "Educator-expense signal gate failed:\n " + "\n ".join(educator_expense_gate.failures) ) - form_4952_election_gate = us_form_4952_election_signal_gate(imputed) + form_4952_election_gate = _shadow_frame_gate( + "us_base_form_4952_election", + lambda: us_form_4952_election_signal_gate(imputed), + imputed, + ) if not form_4952_election_gate.passed: raise SystemExit( "Form 4952 election signal gate failed:\n " + "\n ".join(form_4952_election_gate.failures) ) - salt_refund_income_gate = us_salt_refund_income_signal_gate(imputed) + salt_refund_income_gate = _shadow_frame_gate( + "us_base_salt_refund_income", + lambda: us_salt_refund_income_signal_gate(imputed), + imputed, + ) if not salt_refund_income_gate.passed: raise SystemExit( "SALT-refund-income signal gate failed:\n " + "\n ".join(salt_refund_income_gate.failures) ) - capital_gain_details_gate = us_capital_gain_details_signal_gate(imputed) + capital_gain_details_gate = _shadow_frame_gate( + "us_base_capital_gain_details", + lambda: us_capital_gain_details_signal_gate(imputed), + imputed, + ) if not capital_gain_details_gate.passed: raise SystemExit( "Capital-gain details signal gate failed:\n " @@ -1869,7 +2143,9 @@ def _run_all( seed=args.seed, time_period=args.target_year, ) - childcare_gate = us_childcare_signal_gate(imputed) + childcare_gate = _shadow_frame_gate( + "us_base_childcare", lambda: us_childcare_signal_gate(imputed), imputed + ) if not childcare_gate.passed: raise SystemExit( "Childcare-input signal gate failed:\n " @@ -1881,7 +2157,9 @@ def _run_all( seed=args.seed, time_period=args.target_year, ) - adult_care_gate = us_adult_care_signal_gate(imputed) + adult_care_gate = _shadow_frame_gate( + "us_base_adult_care", lambda: us_adult_care_signal_gate(imputed), imputed + ) if not adult_care_gate.passed: raise SystemExit( "Adult-care input signal gate failed:\n " @@ -1893,24 +2171,34 @@ def _run_all( seed=args.seed, time_period=args.target_year, ) - energy_subsidy_gate = us_energy_subsidy_signal_gate(imputed) + energy_subsidy_gate = _shadow_frame_gate( + "us_base_energy_subsidy", + lambda: us_energy_subsidy_signal_gate(imputed), + imputed, + ) if not energy_subsidy_gate.passed: raise SystemExit( "Energy-subsidy signal gate failed:\n " + "\n ".join(energy_subsidy_gate.failures) ) - alimony_gate = us_alimony_signal_gate(imputed) + alimony_gate = _shadow_frame_gate( + "us_base_alimony", lambda: us_alimony_signal_gate(imputed), imputed + ) if not alimony_gate.passed: raise SystemExit( "Alimony-input signal gate failed:\n " + "\n ".join(alimony_gate.failures) ) - casualty_loss_gate = us_casualty_loss_signal_gate(imputed) + casualty_loss_gate = _shadow_frame_gate( + "us_base_casualty_loss", lambda: us_casualty_loss_signal_gate(imputed), imputed + ) if not casualty_loss_gate.passed: raise SystemExit( "Casualty-loss signal gate failed:\n " + "\n ".join(casualty_loss_gate.failures) ) - misc_itemized_gate = us_misc_itemized_signal_gate(imputed) + misc_itemized_gate = _shadow_frame_gate( + "us_base_misc_itemized", lambda: us_misc_itemized_signal_gate(imputed), imputed + ) if not misc_itemized_gate.passed: raise SystemExit( "Miscellaneous-itemized signal gate failed:\n " @@ -1922,7 +2210,11 @@ def _run_all( seed=args.seed, time_period=args.target_year, ) - retirement_contributions_gate = us_retirement_contributions_signal_gate(imputed) + retirement_contributions_gate = _shadow_frame_gate( + "us_base_retirement_contributions", + lambda: us_retirement_contributions_signal_gate(imputed), + imputed, + ) if not retirement_contributions_gate.passed: raise SystemExit( "Retirement-contribution signal gate failed:\n " @@ -1940,7 +2232,11 @@ def _run_all( # preserve this completed draw even after selecting a narrower support. force_puf_imputation=True, ) - retirement_distributions_gate = us_retirement_distributions_signal_gate(imputed) + retirement_distributions_gate = _shadow_frame_gate( + "us_base_retirement_distributions", + lambda: us_retirement_distributions_signal_gate(imputed), + imputed, + ) if not retirement_distributions_gate.passed: raise SystemExit( "Retirement-distribution signal gate failed:\n " @@ -1955,7 +2251,11 @@ def _run_all( time_period=args.target_year, asec_education_source=education_assistance_source, ) - education_inputs_gate = us_education_inputs_signal_gate(imputed) + education_inputs_gate = _shadow_frame_gate( + "us_base_education_inputs", + lambda: us_education_inputs_signal_gate(imputed), + imputed, + ) if not education_inputs_gate.passed: raise SystemExit( "Education-input signal gate failed:\n " @@ -1963,7 +2263,11 @@ def _run_all( ) # The ESI premium inputs ride the support clone unchanged; re-prove clone # agreement and the cell multiples on the cloned frame. - esi_premiums_post_clone_gate = us_esi_premiums_signal_gate(imputed) + esi_premiums_post_clone_gate = _shadow_frame_gate( + "us_base_esi_premiums_post_clone", + lambda: us_esi_premiums_signal_gate(imputed), + imputed, + ) if not esi_premiums_post_clone_gate.passed: raise SystemExit( "ESI premium signal gate failed after support cloning:\n " @@ -2038,6 +2342,7 @@ def _run_all( "applied": False, "opted_out": bool(args.without_block_ladder), } + _shadow_legacy_location_not_run(args) if args.block_ladder_artifact is not None: ladder = load_us_block_ladder(args.block_ladder_artifact) imputed = with_household_us_geography_ladder( @@ -2050,7 +2355,16 @@ def _run_all( ) household = imputed.table("household") household_weights = imputed.weights_for("household").values - gate = us_geography_ladder_gate(household, household_weights) + gate = shadow_gate( + "us_base_geography_ladder", + lambda: us_geography_ladder_gate(household, household_weights), + lambda: EvidenceContext( + artifacts={ + "household": household, + "household_weights": household_weights, + } + ), + ) if not gate.passed and not args.allow_geography_ladder_gate_failures: raise SystemExit( "Geography-ladder gate failed:\n " + "\n ".join(gate.failures) @@ -2374,7 +2688,10 @@ def _run_outer_stage(args: argparse.Namespace) -> None: ) return - with profile_stage(args.stage, args.checkpoint_dir): + with ( + profile_stage(args.stage, args.checkpoint_dir), + _armed_stage_gate_shadow(args) as save_gate_shadow, + ): if args.stage == "source_construction": predecessor = runtime.load_predecessor(args.stage) if predecessor is not None: @@ -2448,6 +2765,7 @@ def _run_outer_stage(args: argparse.Namespace) -> None: stage_metadata, ) assert_unchanged_identity(before, after, stage=args.stage) + save_gate_shadow() completed = runtime.complete(args.stage, after, metadata=metadata) if args.stage == "final_export": _link_all_stage_checkpoint(args.checkpoint_dir, completed.path) @@ -2722,7 +3040,11 @@ def _pre_clone_enrichment_stage( ) signals: dict[str, object] = { "relationship_inputs_signal": _checked_gate_payload( - us_relationship_inputs_signal_gate(base), + _shadow_frame_gate( + "us_base_relationship_inputs", + lambda: us_relationship_inputs_signal_gate(base), + base, + ), "Relationship-input signal gate failed", ) } @@ -2733,7 +3055,11 @@ def _pre_clone_enrichment_stage( asec_spm_role_source_paths=_asec_education_source_paths(args), ) signals["spm_independence_role_signal"] = _checked_gate_payload( - us_spm_independence_role_signal_gate(base), + _shadow_frame_gate( + "us_base_spm_independence_role", + lambda: us_spm_independence_role_signal_gate(base), + base, + ), "SPM independence role signal gate failed before support cloning", ) base = with_us_medicare_take_up_input( @@ -2742,13 +3068,18 @@ def _pre_clone_enrichment_stage( time_period=args.target_year, ) signals["medicare_take_up_input_signal"] = _checked_gate_payload( - us_medicare_take_up_signal_gate(base), + _shadow_frame_gate( + "us_base_medicare_take_up_pre_clone", + lambda: us_medicare_take_up_signal_gate(base), + base, + ), "Medicare take-up input signal gate failed before support cloning", ) housing_gate = us_housing_inputs_signal_gate(base) acs_rent_donor: pd.DataFrame | None = None if not housing_gate.passed: if args.acs_h5 is None: + _observe_frame_gate("us_base_housing_inputs_pre_clone", housing_gate, base) raise SystemExit( "Housing-input signal gate is not already green and --acs-h5 " "was not provided; exact pre_subsidy_rent restoration requires " @@ -2762,6 +3093,7 @@ def _pre_clone_enrichment_stage( acs_rent_donor=acs_rent_donor, ) housing_gate = us_housing_inputs_signal_gate(base) + _observe_frame_gate("us_base_housing_inputs_pre_clone", housing_gate, base) signals["housing_inputs_signal"] = _checked_gate_payload( housing_gate, "Housing-input signal gate failed before support cloning", @@ -2772,7 +3104,11 @@ def _pre_clone_enrichment_stage( time_period=args.target_year, ) signals["eligibility_inputs_signal"] = _checked_gate_payload( - us_eligibility_inputs_signal_gate(base), + _shadow_frame_gate( + "us_base_eligibility_inputs", + lambda: us_eligibility_inputs_signal_gate(base), + base, + ), "Eligibility-input signal gate failed before support cloning", ) base = with_us_pregnancy_inputs( @@ -2781,7 +3117,9 @@ def _pre_clone_enrichment_stage( time_period=args.target_year, ) signals["pregnancy_signal"] = _checked_gate_payload( - us_pregnancy_signal_gate(base), + _shadow_frame_gate( + "us_base_pregnancy", lambda: us_pregnancy_signal_gate(base), base + ), "Pregnancy signal gate failed before support cloning", ) base = with_us_wic_claim_input( @@ -2790,7 +3128,9 @@ def _pre_clone_enrichment_stage( time_period=args.target_year, ) signals["wic_claim_signal"] = _checked_gate_payload( - us_wic_claim_signal_gate(base), + _shadow_frame_gate( + "us_base_wic_claim_pre_clone", lambda: us_wic_claim_signal_gate(base), base + ), "WIC-claim signal gate failed before support cloning", ) base = with_us_child_support_inputs( @@ -2840,7 +3180,11 @@ def _pre_clone_enrichment_stage( time_period=args.target_year, ) signals["esi_premiums_signal"] = _checked_gate_payload( - us_esi_premiums_signal_gate(base), + _shadow_frame_gate( + "us_base_esi_premiums_pre_clone", + lambda: us_esi_premiums_signal_gate(base), + base, + ), "ESI premium signal gate failed before support cloning", ) base = with_us_immigration_inputs( @@ -2929,7 +3273,12 @@ def _qrf_finalization_stage( args.checkpoint_dir / "primary_qrf", tail_bound_diagnostics=tail_bound_diagnostics, ) - report = weights_audit_gate([FitWeightRecord(US_PUF_SUPPORT_FIT_NAME, weight_kind)]) + fit_records = [FitWeightRecord(US_PUF_SUPPORT_FIT_NAME, weight_kind)] + report = shadow_gate( + "us_base_weights_audit", + lambda: weights_audit_gate(fit_records), + lambda: EvidenceContext(artifacts={"fit_weight_records": fit_records}), + ) if not report.passed: raise SystemExit("Weights audit failed:\n " + "\n ".join(report.failures)) return imputed, { @@ -3205,11 +3554,19 @@ def _post_qrf_frame_stage( time_period=args.target_year, ) signals["wic_claim_signal"] = _checked_gate_payload( - us_wic_claim_signal_gate(frame), + _shadow_frame_gate( + "us_base_wic_claim_post_clone", + lambda: us_wic_claim_signal_gate(frame), + frame, + ), "WIC-claim signal gate failed after support cloning", ) signals["medicare_take_up_input_signal"] = _checked_gate_payload( - us_medicare_take_up_signal_gate(frame), + _shadow_frame_gate( + "us_base_medicare_take_up_post_clone", + lambda: us_medicare_take_up_signal_gate(frame), + frame, + ), "Medicare take-up input signal gate failed after support cloning", ) elif stage == "housing_assistance": @@ -3221,27 +3578,49 @@ def _post_qrf_frame_stage( time_period=args.target_year, ) signals["prior_year_income_signal"] = _checked_gate_payload( - us_prior_year_income_signal_gate(frame), + _shadow_frame_gate( + "us_base_prior_year_income", + lambda: us_prior_year_income_signal_gate(frame), + frame, + ), "Prior-year-income signal gate failed", ) signals["prior_year_income_source_reconciliation"] = _checked_gate_payload( - us_prior_year_income_source_reconciliation_gate(frame), + _shadow_frame_gate( + "us_base_prior_year_income_source_reconciliation", + lambda: us_prior_year_income_source_reconciliation_gate(frame), + frame, + ), "Prior-year-income source reconciliation failed", ) signals["housing_inputs_signal"] = _checked_gate_payload( - us_housing_inputs_signal_gate(frame), + _shadow_frame_gate( + "us_base_housing_inputs_post_clone", + lambda: us_housing_inputs_signal_gate(frame), + frame, + ), "Housing-input signal gate failed after PUF-support imputation", ) signals["qbi_inputs_signal"] = _checked_gate_payload( - us_qbi_inputs_signal_gate(frame), + _shadow_frame_gate( + "us_base_qbi_inputs", lambda: us_qbi_inputs_signal_gate(frame), frame + ), "QBI-input signal gate failed", ) signals["farm_business_income_signal"] = _checked_gate_payload( - us_farm_business_income_signal_gate(frame), + _shadow_frame_gate( + "us_base_farm_business_income", + lambda: us_farm_business_income_signal_gate(frame), + frame, + ), "Farm-business-income signal gate failed", ) signals["domestic_production_ald_signal"] = _checked_gate_payload( - us_domestic_production_ald_signal_gate(frame), + _shadow_frame_gate( + "us_base_domestic_production_ald", + lambda: us_domestic_production_ald_signal_gate(frame), + frame, + ), "Domestic-production-ALD signal gate failed", ) elif stage == "child_support_post_clone": @@ -3251,7 +3630,12 @@ def _post_qrf_frame_stage( time_period=args.target_year, ) signals["child_support_signal"] = _checked_gate_payload( - us_child_support_signal_gate(frame), "Child-support signal gate failed" + _shadow_frame_gate( + "us_base_child_support", + lambda: us_child_support_signal_gate(frame), + frame, + ), + "Child-support signal gate failed", ) elif stage == "disability_benefits_post_clone": frame = with_us_disability_benefits( @@ -3260,7 +3644,11 @@ def _post_qrf_frame_stage( time_period=args.target_year, ) signals["disability_benefits_signal"] = _checked_gate_payload( - us_disability_benefits_signal_gate(frame), + _shadow_frame_gate( + "us_base_disability_benefits", + lambda: us_disability_benefits_signal_gate(frame), + frame, + ), "Disability-benefits signal gate failed", ) elif stage == "workers_compensation_post_clone": @@ -3270,7 +3658,11 @@ def _post_qrf_frame_stage( time_period=args.target_year, ) signals["workers_compensation_signal"] = _checked_gate_payload( - us_workers_compensation_signal_gate(frame), + _shadow_frame_gate( + "us_base_workers_compensation", + lambda: us_workers_compensation_signal_gate(frame), + frame, + ), "Workers-compensation signal gate failed", ) elif stage == "weeks_unemployed_post_clone": @@ -3294,23 +3686,43 @@ def _post_qrf_frame_stage( asec_2023_source=weeks_source, ) signals["weeks_unemployed_signal"] = _checked_gate_payload( - us_weeks_unemployed_signal_gate(frame), + _shadow_frame_gate( + "us_base_weeks_unemployed", + lambda: us_weeks_unemployed_signal_gate(frame), + frame, + ), "Weeks-unemployed signal gate failed", ) signals["educator_expense_signal"] = _checked_gate_payload( - us_educator_expense_signal_gate(frame), + _shadow_frame_gate( + "us_base_educator_expense", + lambda: us_educator_expense_signal_gate(frame), + frame, + ), "Educator-expense signal gate failed", ) signals["form_4952_election_signal"] = _checked_gate_payload( - us_form_4952_election_signal_gate(frame), + _shadow_frame_gate( + "us_base_form_4952_election", + lambda: us_form_4952_election_signal_gate(frame), + frame, + ), "Form 4952 election signal gate failed", ) signals["salt_refund_income_signal"] = _checked_gate_payload( - us_salt_refund_income_signal_gate(frame), + _shadow_frame_gate( + "us_base_salt_refund_income", + lambda: us_salt_refund_income_signal_gate(frame), + frame, + ), "SALT-refund-income signal gate failed", ) signals["capital_gain_details_signal"] = _checked_gate_payload( - us_capital_gain_details_signal_gate(frame), + _shadow_frame_gate( + "us_base_capital_gain_details", + lambda: us_capital_gain_details_signal_gate(frame), + frame, + ), "Capital-gain details signal gate failed", ) elif stage == "childcare_post_clone": @@ -3320,7 +3732,10 @@ def _post_qrf_frame_stage( time_period=args.target_year, ) signals["childcare_inputs_signal"] = _checked_gate_payload( - us_childcare_signal_gate(frame), "Childcare-input signal gate failed" + _shadow_frame_gate( + "us_base_childcare", lambda: us_childcare_signal_gate(frame), frame + ), + "Childcare-input signal gate failed", ) elif stage == "adult_care_post_clone": frame = with_us_adult_care_inputs( @@ -3329,7 +3744,10 @@ def _post_qrf_frame_stage( time_period=args.target_year, ) signals["adult_care_inputs_signal"] = _checked_gate_payload( - us_adult_care_signal_gate(frame), "Adult-care input signal gate failed" + _shadow_frame_gate( + "us_base_adult_care", lambda: us_adult_care_signal_gate(frame), frame + ), + "Adult-care input signal gate failed", ) elif stage == "energy_subsidy_post_clone": frame = with_us_energy_subsidy_input( @@ -3338,17 +3756,33 @@ def _post_qrf_frame_stage( time_period=args.target_year, ) signals["energy_subsidy_signal"] = _checked_gate_payload( - us_energy_subsidy_signal_gate(frame), + _shadow_frame_gate( + "us_base_energy_subsidy", + lambda: us_energy_subsidy_signal_gate(frame), + frame, + ), "Energy-subsidy signal gate failed", ) signals["alimony_inputs_signal"] = _checked_gate_payload( - us_alimony_signal_gate(frame), "Alimony-input signal gate failed" + _shadow_frame_gate( + "us_base_alimony", lambda: us_alimony_signal_gate(frame), frame + ), + "Alimony-input signal gate failed", ) signals["casualty_loss_signal"] = _checked_gate_payload( - us_casualty_loss_signal_gate(frame), "Casualty-loss signal gate failed" + _shadow_frame_gate( + "us_base_casualty_loss", + lambda: us_casualty_loss_signal_gate(frame), + frame, + ), + "Casualty-loss signal gate failed", ) signals["misc_itemized_signal"] = _checked_gate_payload( - us_misc_itemized_signal_gate(frame), + _shadow_frame_gate( + "us_base_misc_itemized", + lambda: us_misc_itemized_signal_gate(frame), + frame, + ), "Miscellaneous-itemized signal gate failed", ) elif stage == "retirement_contributions_post_clone": @@ -3358,7 +3792,11 @@ def _post_qrf_frame_stage( time_period=args.target_year, ) signals["retirement_contributions_signal"] = _checked_gate_payload( - us_retirement_contributions_signal_gate(frame), + _shadow_frame_gate( + "us_base_retirement_contributions", + lambda: us_retirement_contributions_signal_gate(frame), + frame, + ), "Retirement-contribution signal gate failed", ) elif stage == "retirement_distributions_post_clone": @@ -3371,7 +3809,11 @@ def _post_qrf_frame_stage( force_puf_imputation=True, ) signals["retirement_distributions_signal"] = _checked_gate_payload( - us_retirement_distributions_signal_gate(frame), + _shadow_frame_gate( + "us_base_retirement_distributions", + lambda: us_retirement_distributions_signal_gate(frame), + frame, + ), "Retirement-distribution signal gate failed", ) elif stage == "education_inputs_post_clone": @@ -3386,11 +3828,19 @@ def _post_qrf_frame_stage( asec_education_source=education_assistance_source, ) signals["education_inputs_signal"] = _checked_gate_payload( - us_education_inputs_signal_gate(frame), + _shadow_frame_gate( + "us_base_education_inputs", + lambda: us_education_inputs_signal_gate(frame), + frame, + ), "Education-input signal gate failed", ) signals["esi_premiums_post_clone_signal"] = _checked_gate_payload( - us_esi_premiums_signal_gate(frame), + _shadow_frame_gate( + "us_base_esi_premiums_post_clone", + lambda: us_esi_premiums_signal_gate(frame), + frame, + ), "ESI premium signal gate failed after support cloning", ) elif stage == "congressional_district_assignment": @@ -3440,6 +3890,7 @@ def _post_qrf_frame_stage( "applied": False, "opted_out": bool(args.without_block_ladder), } + _shadow_legacy_location_not_run(args) if args.block_ladder_artifact is not None: ladder = load_us_block_ladder(args.block_ladder_artifact) frame = with_household_us_geography_ladder( @@ -3452,7 +3903,16 @@ def _post_qrf_frame_stage( ) household = frame.table("household") household_weights = frame.weights_for("household").values - gate = us_geography_ladder_gate(household, household_weights) + gate = shadow_gate( + "us_base_geography_ladder", + lambda: us_geography_ladder_gate(household, household_weights), + lambda: EvidenceContext( + artifacts={ + "household": household, + "household_weights": household_weights, + } + ), + ) if not gate.passed and not args.allow_geography_ladder_gate_failures: raise SystemExit( "Geography-ladder gate failed:\n " + "\n ".join(gate.failures) @@ -3722,7 +4182,11 @@ def impute_and_audit_us_puf_support( raw_predictions_callback=raw_predictions_callback, tail_bound_diagnostics=tail_bound_diagnostics, ) - report = weights_audit_gate(fit_records) + report = shadow_gate( + "us_base_weights_audit", + lambda: weights_audit_gate(fit_records), + lambda: EvidenceContext(artifacts={"fit_weight_records": list(fit_records)}), + ) if not report.passed: raise SystemExit("Weights audit failed:\n " + "\n ".join(report.failures)) weights_audit = { diff --git a/tools/generate_us_bundle_from_constants.py b/tools/generate_us_bundle_from_constants.py index fe40fd51f6..3a64210d15 100644 --- a/tools/generate_us_bundle_from_constants.py +++ b/tools/generate_us_bundle_from_constants.py @@ -143,6 +143,7 @@ def _domain_builders() -> dict[str, Callable[[], object]]: "ecps_parity_reference.json", "federal_eitc_by_state.json", "fiscal_target_references.json", + "gates.json", "obbba_reforms.json", "puf_aggregate_record_disaggregation.json", "release_input_coverage_manifest.json", From 51a30f9fba059592b4310b1fb14722ea8c7a7cd8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mar=C3=ADa=20Juaristi?= <127882282+juaristi22@users.noreply.github.com> Date: Sun, 15 Nov 2026 14:06:33 +0000 Subject: [PATCH 04/31] Declare the stacked pool's gates and run them in shadow (us_pool) PR 2 of 4 for microcosm#1585 item 11. us_pool holds the six gates of the stacked path of tools/build_us_multispine_pool.py: the PUMA ladder and the block_v1 block-location gate after assembly, the hours-worked signal (observed inside the pool runtime's source preparation) and the weights audit, and the terminal pair. The early gates raise where they run, as before. The terminal pair still marks: a failed pool publishes as gate_failed and the tool returns 1, and its GateReport(...).to_manifest() seal and manifest shape are untouched, since the shadow returns today's sealed results unchanged and evaluates its own. A resumed build records the gates its checkpoint skips as not run. The shadow finishes after every file the build writes, its Logbook row included, into /.gate_battery_shadow. The legacy two-spine path runs without a shadow. The battery re-evaluates the terminal pair, which adds that pair's wall time to a pool build once more. Co-Authored-By: Claude Opus 5.5 --- .../src/microcosm/build/us/gates.json | 89 +++++++++++ .../build/us_runtime/battery_bindings.py | 58 +++++++- .../build/us_runtime/multispine_pool.py | 10 +- .../us/test_us_battery_bindings.py | 13 +- .../us/test_us_multispine_pool_gate_shadow.py | 139 ++++++++++++++++++ .../microcosm_build/us_gate_shadow.py | 4 +- tools/build_us_multispine_pool.py | 138 +++++++++++++++-- 7 files changed, 432 insertions(+), 19 deletions(-) create mode 100644 packages/microcosm-build/tests/engine_free/us/test_us_multispine_pool_gate_shadow.py diff --git a/packages/microcosm-build/src/microcosm/build/us/gates.json b/packages/microcosm-build/src/microcosm/build/us/gates.json index cb2fcb2178..ef136c49bc 100644 --- a/packages/microcosm-build/src/microcosm/build/us/gates.json +++ b/packages/microcosm-build/src/microcosm/build/us/gates.json @@ -800,6 +800,95 @@ "check": "block_location" }, "notes": "Route A base (tools/build_us_puf_support_base.py): every written geography equals the block ladder's lookup of its block. Runs on block_v1 runs only, where its failures and the ladder's share one raise." + }, + { + "id": "us_pool_puma_ladder", + "gate": "stage_health", + "phase": "assembled", + "criticality": "release_blocking", + "parameters": { + "check": "puma_ladder", + "assign_tract": false, + "nyc_share_bounds": [ + 0.005, + 0.06 + ], + "nyc_share_of_new_york_bounds": [ + 0.2, + 0.65 + ] + }, + "notes": "US multispine pool (tools/build_us_multispine_pool.py), stacked path: the household PUMA ladder right after assembly, on a cold run; with block_v1 it runs beside the block draw's gate and shares its raise. Raises at once today. A resumed run re-reads its checkpointed receipt instead." + }, + { + "id": "us_pool_block_location", + "gate": "stage_health", + "phase": "assembled", + "criticality": "release_blocking", + "parameters": { + "check": "block_location" + }, + "notes": "US multispine pool (tools/build_us_multispine_pool.py), stacked path: every written geography equals the block ladder's lookup of its block. Runs on block_v1 cold runs only, where it shares one raise with the PUMA ladder." + }, + { + "id": "us_pool_hours_worked", + "gate": "stage_health", + "phase": "transferred", + "criticality": "release_blocking", + "parameters": { + "check": "hours_worked_signal", + "worked_share_band": [ + 0.35, + 0.62 + ], + "mean_weekly_hours_band": [ + 30.0, + 45.0 + ] + }, + "notes": "US multispine pool (tools/build_us_multispine_pool.py), stacked path: hours worked on the CPS evidence projection, inside the pool runtime's source preparation. Raises at once today. Skipped on a resume from the transferred or simulated checkpoint, which carries its receipt." + }, + { + "id": "us_pool_weights_audit", + "gate": "weights_audit", + "phase": "transferred", + "criticality": "release_blocking", + "parameters": {}, + "notes": "US multispine pool (tools/build_us_multispine_pool.py), stacked path: every gap-fill, primary-QRF and late-DAG fit resolved a weight, before the transferred checkpoint. Raises at once today; skipped as the hours gate is on a resume." + }, + { + "id": "us_pool_stacked_completeness", + "gate": "stage_health", + "phase": "terminal", + "criticality": "release_blocking", + "parameters": { + "check": "stacked_completeness" + }, + "notes": "US multispine pool (tools/build_us_multispine_pool.py), stacked path: the terminal completeness gate over the declared surface. It marks today: a failure publishes a gate_failed pool and the tool returns 1. Its GateReport(...).to_manifest() seal and the manifest shape are today's and unchanged; the battery re-evaluates it on its own." + }, + { + "id": "us_pool_by_origin_battery", + "gate": "stage_health", + "phase": "terminal", + "criticality": "release_blocking", + "parameters": { + "check": "by_origin_battery", + "battery_incidence_ratio_bounds": [ + 0.8, + 1.25 + ], + "battery_quantiles": [ + 0.1, + 0.25, + 0.5, + 0.75, + 0.9 + ], + "battery_quantile_envelope_tolerance": 0.25, + "battery_categorical_tvd_tolerance": 0.25, + "mass_rtol": 1e-09 + }, + "notes": "US multispine pool (tools/build_us_multispine_pool.py), stacked path: the terminal by-origin battery. It marks today, as the completeness gate does. Its first four thresholds are the ones us/spec/battery.yaml mirrors." } ] } diff --git a/packages/microcosm-build/src/microcosm/build/us_runtime/battery_bindings.py b/packages/microcosm-build/src/microcosm/build/us_runtime/battery_bindings.py index 0a0e61303d..5929218729 100644 --- a/packages/microcosm-build/src/microcosm/build/us_runtime/battery_bindings.py +++ b/packages/microcosm-build/src/microcosm/build/us_runtime/battery_bindings.py @@ -715,8 +715,64 @@ def _us_base_specs() -> tuple[USGateSpec, ...]: #: Configuration and thresholds the PUMA ladder gate takes as keywords today. +_PUMA_LADDER_KEYWORDS = frozenset( + {"assign_tract", "nyc_share_bounds", "nyc_share_of_new_york_bounds"} +) + + +def _us_pool_specs() -> tuple[USGateSpec, ...]: + return ( + USGateSpec( + check="puma_ladder", + legacy_name="us_puma_ladder", + gate="tool:us_puma_ladder_gate", + positional=("household", "household_weights"), + parameters=_PUMA_LADDER_KEYWORDS, + ), + USGateSpec( + check="block_location", + legacy_name="us_block_location", + gate="tool:us_block_location_gate", + positional=("household", "location_ladder"), + ), + USGateSpec( + # Evaluated inside the pool runtime's source preparation, not in + # the tool, so the binding calls the runtime's own global. + check="hours_worked_signal", + legacy_name="hours_worked_signal", + gate=f"{_US}.multispine_pool:us_hours_worked_signal_gate", + positional=(FRAME,), + pinned=_pins( + "hours_worked", "_WORKED_SHARE_BAND", "_MEAN_WEEKLY_HOURS_BAND" + ), + ), + USGateSpec( + check="stacked_completeness", + legacy_name="us_stacked_completeness", + gate="tool:stacked_completeness_gate", + positional=(FRAME,), + arguments={"tail_manifest": "tail_manifest"}, + ), + USGateSpec( + check="by_origin_battery", + legacy_name="us_by_origin_battery", + gate="tool:by_origin_battery", + positional=(FRAME,), + arguments={"tail_manifest": "tail_manifest"}, + pinned=_pins( + "stacked_spine", + "_BATTERY_INCIDENCE_RATIO_BOUNDS", + "_BATTERY_QUANTILES", + "_BATTERY_QUANTILE_ENVELOPE_TOLERANCE", + "_BATTERY_CATEGORICAL_TVD_TOLERANCE", + "_MASS_RTOL", + ), + ), + ) + + _SCOPE_SPECS: Mapping[str, Callable[[], tuple[USGateSpec, ...]]] = MappingProxyType( - {"us_base": _us_base_specs} + {"us_base": _us_base_specs, "us_pool": _us_pool_specs} ) diff --git a/packages/microcosm-build/src/microcosm/build/us_runtime/multispine_pool.py b/packages/microcosm-build/src/microcosm/build/us_runtime/multispine_pool.py index 07e87eebf6..2bc9da80cd 100644 --- a/packages/microcosm-build/src/microcosm/build/us_runtime/multispine_pool.py +++ b/packages/microcosm-build/src/microcosm/build/us_runtime/multispine_pool.py @@ -24,6 +24,7 @@ import numpy as np import pandas as pd +from microcosm.build.gate_battery import EvidenceContext from microcosm.build.gates import GateResult from microcosm.build.serialization_dtypes import canonicalize_frame_string_dtypes from microcosm.build.us_runtime.acs_income_universe import ( @@ -50,6 +51,7 @@ from microcosm.build.us_runtime.energy_subsidy import ( with_us_energy_subsidy_input, ) +from microcosm.build.us_runtime.gate_shadow import shadow_gate from microcosm.build.us_runtime.hours_worked import ( US_HOURS_WORKED_POOL_EXCLUDED_COLUMNS, us_hours_worked_signal_gate, @@ -1829,7 +1831,13 @@ def _with_gated_us_hours_worked_inputs(frame: Frame) -> PoolStageOutput: seed=POOL_RANDOM_SEED, time_period=POOL_TIME_PERIOD, ) - gate = us_hours_worked_signal_gate(produced) + # The pool builder's stacked path observes this gate for its shadow + # battery (microcosm#1585 item 11); with no shadow armed it is the call. + gate = shadow_gate( + "us_pool_hours_worked", + lambda: us_hours_worked_signal_gate(produced), + lambda: EvidenceContext(frame=produced), + ) if not gate.passed: raise ValueError( "Pool pre-clone hours-worked signal gate failed:\n " diff --git a/packages/microcosm-build/tests/engine_free/us/test_us_battery_bindings.py b/packages/microcosm-build/tests/engine_free/us/test_us_battery_bindings.py index fb5dcbf5b5..a56a8c20af 100644 --- a/packages/microcosm-build/tests/engine_free/us/test_us_battery_bindings.py +++ b/packages/microcosm-build/tests/engine_free/us/test_us_battery_bindings.py @@ -49,7 +49,7 @@ ) #: The scopes PR 2 has declared so far, each wired in its tool. -WIRED_SCOPES = ("us_base",) +WIRED_SCOPES = ("us_base", "us_pool") #: Each scope's pinned digests. They move only when the scope's entries, #: parameters, phases or the manifest's policy line do. @@ -65,6 +65,17 @@ "4ce5ca7abaef48a6026be8d120862761cf8a457904690b0e59e4a501828f43da" ), }, + "us_pool": { + "gates_manifest_sha256": ( + "31dfdd5dc38129e08979e3a47822b3c61891b489b9140b40ec80dc6aba791355" + ), + "policy_sha256": ( + "98ff80d5bbe6f7a11f3ee3f63cae5f953fc6607559de22e2f552fe3e1f06d872" + ), + "spec_fingerprint": ( + "cc1eeadceb9ea05efe81b5594c23832dd05e9fedbdd25c3cb1cfc52355c12047" + ), + }, } diff --git a/packages/microcosm-build/tests/engine_free/us/test_us_multispine_pool_gate_shadow.py b/packages/microcosm-build/tests/engine_free/us/test_us_multispine_pool_gate_shadow.py new file mode 100644 index 0000000000..4ffe586531 --- /dev/null +++ b/packages/microcosm-build/tests/engine_free/us/test_us_multispine_pool_gate_shadow.py @@ -0,0 +1,139 @@ +"""The pool builder's stacked path runs the gate battery in shadow (#1585 item 11). + +``tools/build_us_multispine_pool.py`` arms the ``us_pool`` scope around the +stacked path and finishes it after every file the build writes, beside the +pool's own files. These tests drive that seam with stand-in gates; no pool is +built. +""" + +from __future__ import annotations + +import importlib +import json +from types import SimpleNamespace + +import pytest + +from microcosm.build import FitWeightRecord, GateResult +from microcosm.build.gate_battery import EvidenceContext +from microcosm.build.us_runtime.battery_bindings import us_gate_specs +from microcosm.build.us_runtime.gate_shadow import ( + GateBatteryShadowMismatchError, + shadow_file_paths, + shadow_gate, + shadow_not_run, +) +from test_support.microcosm_build.us_gate_shadow import load_us_gate_tool + + +@pytest.fixture +def pool(): + return load_us_gate_tool("us_pool") + + +def _namespace(pool, reference: str): + namespace, _, name = reference.partition(":") + target = ( + vars(pool) if namespace == "tool" else vars(importlib.import_module(namespace)) + ) + return target, name + + +def _stand_in_gates(monkeypatch, pool, *, failing=()): + for spec in us_gate_specs("us_pool"): + target, name = _namespace(pool, spec.gate) + + def gate(*args, _legacy=spec.legacy_name, _failed=spec.check in failing, **kw): + if _failed: + return GateResult( + name=_legacy, passed=False, failures=(f"{_legacy}: stand-in.",) + ) + return GateResult(name=_legacy, passed=True) + + monkeypatch.setitem(target, name, gate) + + +def _cold_legacy_rule_run(pool, *, legacy_terminal=None): + """What a cold stacked build on the legacy location rule observes.""" + + tool = vars(pool) + household, weights, frame = object(), object(), object() + shadow_gate( + "us_pool_puma_ladder", + lambda: tool["us_puma_ladder_gate"](household, weights, assign_tract=False), + EvidenceContext( + artifacts={"household": household, "household_weights": weights} + ), + ) + shadow_not_run("us_pool_block_location", "the legacy location rule draws no block") + runtime = vars( + importlib.import_module("microcosm.build.us_runtime.multispine_pool") + ) + shadow_gate( + "us_pool_hours_worked", + lambda: runtime["us_hours_worked_signal_gate"](frame), + EvidenceContext(frame=frame), + ) + records = [FitWeightRecord("us_puf_tax_detail_support", "design")] + shadow_gate( + "us_pool_weights_audit", + lambda: tool["weights_audit_gate"](records), + EvidenceContext(artifacts={"fit_weight_records": records}), + ) + terminal = EvidenceContext(frame=frame, artifacts={"tail_manifest": {}}) + shadow_gate( + "us_pool_stacked_completeness", + lambda: tool["stacked_completeness_gate"](frame, tail_manifest={}), + terminal, + ) + shadow_gate( + "us_pool_by_origin_battery", + legacy_terminal or (lambda: tool["by_origin_battery"](frame, tail_manifest={})), + terminal, + ) + return 0 + + +def test_the_stacked_path_finishes_its_shadow_beside_the_pool( + tmp_path, monkeypatch, pool +) -> None: + args = SimpleNamespace(out=tmp_path / "pools" / "stacked.h5") + _stand_in_gates(monkeypatch, pool) + with pool._armed_pool_gate_shadow(args): + assert _cold_legacy_rule_run(pool) == 0 + directory = tmp_path / "pools" / "stacked.gate_battery_shadow" + assert pool._pool_gate_shadow_directory(args) == directory.resolve() + report, comparison = shadow_file_paths(directory, "us_pool") + payload = json.loads(comparison.read_text()) + assert payload["run_completed"] is True + assert payload["verdict_difference"] is False + assert payload["phases_recorded"] == ["assembled", "transferred", "terminal"] + assert json.loads(report.read_text())["shippable"] is False + + +def test_a_terminal_difference_fails_the_build_after_its_files( + tmp_path, monkeypatch, pool +) -> None: + args = SimpleNamespace(out=tmp_path / "stacked.h5") + _stand_in_gates(monkeypatch, pool, failing={"by_origin_battery"}) + passing = GateResult(name="us_by_origin_battery", passed=True) + with pytest.raises(GateBatteryShadowMismatchError, match="us_pool_by_origin"): + with pool._armed_pool_gate_shadow(args): + _cold_legacy_rule_run(pool, legacy_terminal=lambda: passing) + + +def test_a_marked_terminal_failure_is_a_match(tmp_path, monkeypatch, pool) -> None: + # The terminal pair marks today: the build publishes a gate_failed pool and + # returns 1. The battery fails it too, which is the same verdict. + args = SimpleNamespace(out=tmp_path / "stacked.h5") + _stand_in_gates(monkeypatch, pool, failing={"stacked_completeness"}) + with pool._armed_pool_gate_shadow(args): + _cold_legacy_rule_run(pool) + _, comparison = shadow_file_paths(pool._pool_gate_shadow_directory(args), "us_pool") + payload = json.loads(comparison.read_text()) + assert payload["verdict_difference"] is False + (completeness,) = [ + row for row in payload["entries"] if row["id"] == "us_pool_stacked_completeness" + ] + assert completeness["legacy"]["status"] == "failed" + assert completeness["battery"]["status"] == "failed" diff --git a/test_support/microcosm_build/us_gate_shadow.py b/test_support/microcosm_build/us_gate_shadow.py index fd015b9799..5f22164501 100644 --- a/test_support/microcosm_build/us_gate_shadow.py +++ b/test_support/microcosm_build/us_gate_shadow.py @@ -65,7 +65,9 @@ def _lambda_call_name(node: ast.AST) -> str | None: #: Package modules where a scope observes a gate inside a runtime function #: rather than in its tool. -US_GATE_SCOPE_RUNTIME_SITES: dict[str, tuple[str, ...]] = {} +US_GATE_SCOPE_RUNTIME_SITES = { + "us_pool": ("microcosm.build.us_runtime.multispine_pool",), +} _HELPERS = frozenset( { diff --git a/tools/build_us_multispine_pool.py b/tools/build_us_multispine_pool.py index 6a53ad1e3b..ba20a8c9b9 100644 --- a/tools/build_us_multispine_pool.py +++ b/tools/build_us_multispine_pool.py @@ -51,7 +51,8 @@ import subprocess import time import uuid -from collections.abc import Callable, Mapping, Sequence +from collections.abc import Callable, Iterator, Mapping, Sequence +from contextlib import contextmanager from dataclasses import asdict, dataclass, fields, is_dataclass, replace from datetime import UTC, datetime from enum import Enum @@ -68,6 +69,7 @@ write_frame_checkpoint, ) from microcosm.build.frame_sampling import EXACT_COUNT_RULE +from microcosm.build.gate_battery import EvidenceContext from microcosm.build.gates import ( FitWeightRecord, GateReport, @@ -106,6 +108,7 @@ from microcosm.build.us_runtime.asec_checkpoint import ( load_asec_raw_stage_checkpoint, ) +from microcosm.build.us_runtime.battery_bindings import us_gate_registry from microcosm.build.us_runtime.block_location import ( US_BLOCK_LOCATION_RULE_ID, US_LOCATION_RULE_BLOCK_V1, @@ -136,6 +139,15 @@ US_ELIGIBILITY_INPUTS_OUTPUT_COLUMNS, US_ELIGIBILITY_INPUTS_PARENT_ID_COLUMNS, ) +from microcosm.build.us_runtime.gate_scopes import us_scoped_gate_manifest +from microcosm.build.us_runtime.gate_shadow import ( + GATE_BATTERY_SHADOW_DIRECTORY, + GateBatteryShadow, + active_gate_shadow, + shadow_file_paths, + shadow_gate, + shadow_not_run, +) from microcosm.build.us_runtime.h5_io import ( POPULACE_BLOCK_LADDER_SHA256_ATTR, POPULACE_BLOCK_LADDER_VINTAGES_ATTR, @@ -2485,10 +2497,19 @@ def _assign_stacked_household_geography( household, boundary="stacked post-assembly geography assignment", ) - gate = us_puma_ladder_gate( - household, - assigned.weights_for("household").values, - assign_tract=False, + gate = shadow_gate( + "us_pool_puma_ladder", + lambda: us_puma_ladder_gate( + household, + assigned.weights_for("household").values, + assign_tract=False, + ), + lambda: EvidenceContext( + artifacts={ + "household": household, + "household_weights": assigned.weights_for("household").values, + } + ), ) if not gate.passed: raise ValueError( @@ -2608,8 +2629,20 @@ def _block_location_gate_report( ) -> GateReport: return GateReport( ( - us_block_location_gate(household, ladder), - us_puma_ladder_gate(household, weights, assign_tract=False), + shadow_gate( + "us_pool_block_location", + lambda: us_block_location_gate(household, ladder), + lambda: EvidenceContext( + artifacts={"household": household, "location_ladder": ladder} + ), + ), + shadow_gate( + "us_pool_puma_ladder", + lambda: us_puma_ladder_gate(household, weights, assign_tract=False), + lambda: EvidenceContext( + artifacts={"household": household, "household_weights": weights} + ), + ), ) ) @@ -4894,6 +4927,13 @@ def mark_phase(name: str) -> None: resume.late_producer_transition_authority_sha256 ) resume_stage = resume.stage + if resume_stage in {"transferred", "simulated"}: + for entry_id in ("us_pool_hours_worked", "us_pool_weights_audit"): + shadow_not_run( + entry_id, + f"resumed from the {resume_stage} checkpoint, which carries " + "this gate's passing receipt", + ) if resume_stage in {"transferred", "simulated"}: _validate_stacked_post_puf_stage_receipt( current, @@ -5089,7 +5129,13 @@ def primary_puf_producer(primary_input: Frame): "Stacked late-producer DAG emitted no post-PUF transfer receipt." ) fit_records.extend(late_stage.transfer_result.fit_records) - weights_audit = weights_audit_gate(fit_records) + weights_audit = shadow_gate( + "us_pool_weights_audit", + lambda: weights_audit_gate(fit_records), + lambda: EvidenceContext( + artifacts={"fit_weight_records": list(fit_records)} + ), + ) if not weights_audit.passed: raise ValueError( "Stacked imputation weights audit failed:\n " @@ -5242,13 +5288,24 @@ def primary_puf_producer(primary_input: Frame): ) assert_stacked_tail_cells_preserved(simulation_frame, tail_manifest) - completeness = stacked_completeness_gate( - simulation_frame, - tail_manifest=tail_manifest, + terminal_evidence = EvidenceContext( + frame=simulation_frame, artifacts={"tail_manifest": tail_manifest} ) - battery = by_origin_battery( - simulation_frame, - tail_manifest=tail_manifest, + completeness = shadow_gate( + "us_pool_stacked_completeness", + lambda: stacked_completeness_gate( + simulation_frame, + tail_manifest=tail_manifest, + ), + terminal_evidence, + ) + battery = shadow_gate( + "us_pool_by_origin_battery", + lambda: by_origin_battery( + simulation_frame, + tail_manifest=tail_manifest, + ), + terminal_evidence, ) # Manifest conversion is itself the final canonical-authority check and # deliberately happens before publication or readiness is asserted. @@ -6695,6 +6752,12 @@ def _main_stacked(args: argparse.Namespace) -> int: timestamp=started_ts, ) _append_phase(state, "checkpoint_loaded") + for entry_id in ("us_pool_puma_ladder", "us_pool_block_location"): + shadow_not_run( + entry_id, + f"resumed from the {resume.stage} checkpoint, which " + "carries the geography assignment's receipt", + ) if resume.stage == "assembled": acs_rent_donor = load_acs_2022_rent_donor(args.acs_rent_h5) puf_donor, _puf_donor_build = _load_puf_donor(args) @@ -6723,6 +6786,10 @@ def _main_stacked(args: argparse.Namespace) -> int: sample_seed=args.sample_seed, ) if geography_contract is None: + shadow_not_run( + "us_pool_block_location", + "the legacy location rule draws no block", + ) puma_ladder = load_us_puma_ladder(args.puma_ladder) ( stack_frame, @@ -6929,7 +6996,48 @@ def main(argv: list[str] | None = None) -> int: "--legacy-two-spine." ) return _main_legacy(args) - return _main_stacked(args) + with _armed_pool_gate_shadow(args): + return _main_stacked(args) + + +#: This tool's scope of us/gates.json, evaluated in shadow beside the stacked +#: path's gates (microcosm#1585 item 11, PR 2 of 4). The legacy two-spine path +#: runs without it. +US_POOL_GATE_SCOPE = "us_pool" + + +def _pool_gate_shadow_directory(args: argparse.Namespace) -> Path: + """``/.gate_battery_shadow``, beside the pool's files.""" + + out = Path(args.out).resolve() + return out.parent / f"{out.stem}.{GATE_BATTERY_SHADOW_DIRECTORY}" + + +def _pool_gate_shadow(args: argparse.Namespace) -> GateBatteryShadow: + report_path, comparison_path = shadow_file_paths( + _pool_gate_shadow_directory(args), US_POOL_GATE_SCOPE + ) + return GateBatteryShadow( + us_scoped_gate_manifest(US_POOL_GATE_SCOPE), + scope=US_POOL_GATE_SCOPE, + release_id=f"us-multispine-pool:{Path(args.out).name}", + report_path=report_path, + comparison_path=comparison_path, + registry=us_gate_registry(US_POOL_GATE_SCOPE, tool=globals()), + ) + + +@contextmanager +def _armed_pool_gate_shadow(args: argparse.Namespace) -> Iterator[GateBatteryShadow]: + """Arm the stacked path's shadow; finish it when the build returns. + + It finishes after every file today's build writes, its Logbook row + included, so a verdict difference fails the run without changing them. + """ + + shadow = _pool_gate_shadow(args) + with shadow, active_gate_shadow(shadow): + yield shadow if __name__ == "__main__": From d5f6ec5b3d269c78ec152be69b72c74650325995 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mar=C3=ADa=20Juaristi?= <127882282+juaristi22@users.noreply.github.com> Date: Sun, 15 Nov 2026 14:27:10 +0000 Subject: [PATCH 05/31] Declare the national release's gates and run them in shadow (us_national) PR 2 of 4 for microcosm#1585 item 11. us_national holds 76 gates of tools/build_us_fiscal_refresh_release.py: 5 preflight registers and surfaces, 55 signal gates at their own stages (each raising right after it, as before), and 16 after the solve, from the terminal batch to the stored-input recheck on the written H5. The tool arms the scope once the release id is known and finishes it in main(): a finished build fails on a verdict difference, a dry run's deliberate stop never does, and today's exception propagates unchanged. Shadow files go to /gate_battery_shadow, or beside the dry run's report, never into the release directory. Hooks sit at _main's call sites (and inside four helpers only _main calls), so the dry run's own grading, the scorers, the probe and every other importer of the tool see no change. The six --allow-* waivers and --evidence-release are recorded by entry; the input-mass thresholds are flags, declared at their parser defaults, and a build that passes others records an explained override. Shared additions this needed: a refusal-style check (one that raises to fail), a declared return shape for gates that do not return a GateResult (failure lines, a pair with details, one line or None), flag-backed thresholds and their overrides, shadow_value, and arming that spans _main and main(). Not declared: the reform-coverage smoke and --audit-export-targets, whose re-evaluation would repeat their microsimulations; the base-frame SPM composition (advisory); the inline checks, the pool-load receipt checks and the post-export observational writers. Co-Authored-By: Claude Opus 5.5 --- .../src/microcosm/build/us/gates.json | 1335 +++++++++++++++++ .../build/us_runtime/battery_bindings.py | 584 ++++++- .../microcosm/build/us_runtime/gate_shadow.py | 79 + .../us/test_us_battery_bindings.py | 78 +- .../us/test_us_fiscal_refresh_gate_shadow.py | 243 +++ .../engine_free/us/test_us_gate_shadow.py | 2 +- .../microcosm_build/us_gate_shadow.py | 2 + tools/build_us_fiscal_refresh_release.py | 873 +++++++++-- 8 files changed, 3003 insertions(+), 193 deletions(-) create mode 100644 packages/microcosm-build/tests/engine_free/us/test_us_fiscal_refresh_gate_shadow.py diff --git a/packages/microcosm-build/src/microcosm/build/us/gates.json b/packages/microcosm-build/src/microcosm/build/us/gates.json index ef136c49bc..9383733dfa 100644 --- a/packages/microcosm-build/src/microcosm/build/us/gates.json +++ b/packages/microcosm-build/src/microcosm/build/us/gates.json @@ -3,6 +3,7 @@ "country": "us", "policy": "US gates declared as data for the shared battery (microcosm#1585 item 11, microcosm#611), one scope per build tool. PR 2 of 4 runs them in shadow: each US tool still gates as it did, evaluates the declared entry beside each gate on the same evidence, and fails the run on a verdict difference. A threshold the gate reads from a module constant is declared at today's value and pinned equal to that constant until the flip makes this file the only source; one the gate takes as a keyword is routed from here. Waivers stay the tools' --allow-* flags, which the shadow records by entry id. Gate names and phases are the shared vocabulary's, pending Max's Step 0 answer.", "phases": [ + "preflight", "assembled", "transferred", "terminal" @@ -889,6 +890,1340 @@ "mass_rtol": 1e-09 }, "notes": "US multispine pool (tools/build_us_multispine_pool.py), stacked path: the terminal by-origin battery. It marks today, as the completeness gate does. Its first four thresholds are the ones us/spec/battery.yaml mirrors." + }, + { + "id": "us_national_validation_input_coverage", + "gate": "stage_health", + "phase": "preflight", + "criticality": "release_blocking", + "parameters": { + "check": "validation_input_coverage" + }, + "notes": "US national release (tools/build_us_fiscal_refresh_release.py): every validation provision's input leaves are produced by a source stage. Raises at once today, before any stage." + }, + { + "id": "us_national_register_consistency", + "gate": "stage_health", + "phase": "preflight", + "criticality": "release_blocking", + "parameters": { + "check": "register_consistency" + }, + "notes": "US national release (tools/build_us_fiscal_refresh_release.py): the reviewed registers agree with each other. Raises at once today." + }, + { + "id": "us_national_esi_anchor_feed", + "gate": "stage_health", + "phase": "preflight", + "criticality": "release_blocking", + "parameters": { + "check": "esi_anchor_feed" + }, + "notes": "US national release (tools/build_us_fiscal_refresh_release.py): the ESI premium anchor equals the Chronicle feed's facts. Exits at once today unless --allow-unpinned-feed or --allow-esi-premium-gaps waives it." + }, + { + "id": "us_national_target_parity", + "gate": "stage_health", + "phase": "preflight", + "criticality": "release_blocking", + "parameters": { + "check": "target_parity" + }, + "notes": "US national release (tools/build_us_fiscal_refresh_release.py): the compiled target registry covers the parity manifest. Raises at once today." + }, + { + "id": "us_national_target_profile_coverage", + "gate": "stage_health", + "phase": "preflight", + "criticality": "release_blocking", + "parameters": { + "check": "target_profile_coverage" + }, + "notes": "US national release (tools/build_us_fiscal_refresh_release.py): the target surface meets its coverage requirements, before the --target-surface narrowing. Raises at once today." + }, + { + "id": "us_national_capital_gains_tail_presence", + "gate": "stage_health", + "phase": "assembled", + "criticality": "release_blocking", + "parameters": { + "check": "capital_gains_tail_survives_selection" + }, + "notes": "US national release (tools/build_us_fiscal_refresh_release.py): the PUF capital-gains own-tail is present in the base, before any selection. Its refusal raises at once today." + }, + { + "id": "us_national_weeks_unemployed", + "gate": "stage_health", + "phase": "assembled", + "criticality": "release_blocking", + "parameters": { + "check": "weeks_unemployed_signal", + "channel_positive_share_bands": { + "asec": [ + 0.015, + 0.1 + ], + "puf_tax_detail": [ + 0.001, + 0.03 + ] + }, + "channel_weighted_mean_weeks_bands": { + "asec": [ + 0.2, + 2.0 + ], + "puf_tax_detail": [ + 0.01, + 0.5 + ] + } + }, + "notes": "US national release (tools/build_us_fiscal_refresh_release.py): weeks unemployed after its stage (computed on a non-pool base). Raises at once today." + }, + { + "id": "us_national_capital_gains_tail_retention", + "gate": "stage_health", + "phase": "assembled", + "criticality": "release_blocking", + "parameters": { + "check": "capital_gains_tail_survives_selection" + }, + "notes": "US national release (tools/build_us_fiscal_refresh_release.py): frozen-support selection keeps the PUF capital-gains tail and its weights. Runs only with a selection source; its refusal raises at once." + }, + { + "id": "us_national_weeks_unemployed_post_selection", + "gate": "stage_health", + "phase": "assembled", + "criticality": "release_blocking", + "parameters": { + "check": "weeks_unemployed_signal", + "channel_positive_share_bands": { + "asec": [ + 0.015, + 0.1 + ], + "puf_tax_detail": [ + 0.001, + 0.03 + ] + }, + "channel_weighted_mean_weeks_bands": { + "asec": [ + 0.2, + 2.0 + ], + "puf_tax_detail": [ + 0.01, + 0.5 + ] + } + }, + "notes": "US national release (tools/build_us_fiscal_refresh_release.py): weeks unemployed again after frozen-support selection, when one runs. Raises at once today." + }, + { + "id": "us_national_base_population_scale", + "gate": "stage_health", + "phase": "assembled", + "criticality": "release_blocking", + "parameters": { + "check": "base_population_scale", + "us_base_person_population_max_abs_relative_error": 0.25 + }, + "notes": "US national release (tools/build_us_fiscal_refresh_release.py): the base's person population against the Census benchmark, after the mass repair. Raises at once today." + }, + { + "id": "us_national_qbi_inputs", + "gate": "stage_health", + "phase": "assembled", + "criticality": "release_blocking", + "parameters": { + "check": "qbi_inputs_signal", + "boolean_share_bands": { + "business_is_sstb": [ + 0.001, + 0.25 + ], + "estate_income_would_be_qualified": [ + 0.01, + 0.9999 + ], + "farm_operations_income_would_be_qualified": [ + 0.01, + 0.9999 + ], + "farm_rent_income_would_be_qualified": [ + 0.01, + 0.9999 + ], + "partnership_s_corp_income_would_be_qualified": [ + 0.01, + 0.9999 + ], + "rental_income_would_be_qualified": [ + 0.01, + 0.9999 + ], + "self_employment_income_would_be_qualified": [ + 0.01, + 0.9999 + ], + "sstb_self_employment_income_would_be_qualified": [ + 0.0001, + 0.25 + ] + }, + "numeric_nonzero_share_bands": { + "qualified_bdc_income": [ + 0.0001, + 0.15 + ], + "qualified_reit_and_ptp_income": [ + 0.001, + 0.35 + ], + "sstb_self_employment_income_before_lsr": [ + 0.0001, + 0.25 + ], + "sstb_unadjusted_basis_qualified_property": [ + 0.0001, + 0.25 + ], + "sstb_w2_wages_from_qualified_business": [ + 0.0001, + 0.2 + ], + "unadjusted_basis_qualified_property": [ + 0.001, + 0.45 + ], + "w2_wages_from_qualified_business": [ + 0.001, + 0.35 + ] + }, + "invariant_atol": 1e-08 + }, + "notes": "US national release (tools/build_us_fiscal_refresh_release.py): QBI inputs after their reconciliation. Raises at once today." + }, + { + "id": "us_national_farm_business_income", + "gate": "stage_health", + "phase": "assembled", + "criticality": "release_blocking", + "parameters": { + "check": "farm_business_income_signal", + "nonzero_share_bands": { + "farm_operations_income": [ + 0.0001, + 0.2 + ], + "farm_rent_income": [ + 1e-05, + 0.2 + ] + } + }, + "notes": "US national release (tools/build_us_fiscal_refresh_release.py): farm business income on the base. Raises at once today." + }, + { + "id": "us_national_domestic_production_ald", + "gate": "stage_health", + "phase": "assembled", + "criticality": "release_blocking", + "parameters": { + "check": "domestic_production_ald_signal", + "domestic_production_ald_positive_share_band": [ + 0.0001, + 0.02 + ] + }, + "notes": "US national release (tools/build_us_fiscal_refresh_release.py): domestic production deduction. Raises at once today." + }, + { + "id": "us_national_child_support", + "gate": "stage_health", + "phase": "assembled", + "criticality": "release_blocking", + "parameters": { + "check": "child_support_inputs_signal", + "nonzero_share_bands": { + "child_support_received": [ + 0.005, + 0.15 + ], + "child_support_expense": [ + 0.003, + 0.15 + ] + }, + "channel_nonzero_share_band": [ + 0.002, + 0.15 + ] + }, + "notes": "US national release (tools/build_us_fiscal_refresh_release.py): child support inputs. Raises at once today." + }, + { + "id": "us_national_disability_benefits", + "gate": "stage_health", + "phase": "assembled", + "criticality": "release_blocking", + "parameters": { + "check": "disability_benefits_signal", + "nonzero_share_band": [ + 0.003, + 0.15 + ], + "channel_nonzero_share_bands": { + "asec": [ + 0.003, + 0.02 + ], + "puf_tax_detail": [ + 0.002, + 0.15 + ] + } + }, + "notes": "US national release (tools/build_us_fiscal_refresh_release.py): disability benefits. Raises at once today." + }, + { + "id": "us_national_workers_compensation", + "gate": "stage_health", + "phase": "assembled", + "criticality": "release_blocking", + "parameters": { + "check": "workers_compensation_signal", + "nonzero_share_band": [ + 0.0005, + 0.05 + ], + "channel_nonzero_share_bands": { + "asec": [ + 0.001, + 0.01 + ], + "puf_tax_detail": [ + 0.0002, + 0.1 + ] + } + }, + "notes": "US national release (tools/build_us_fiscal_refresh_release.py): workers' compensation. Raises at once today." + }, + { + "id": "us_national_educator_expense", + "gate": "stage_health", + "phase": "assembled", + "criticality": "release_blocking", + "parameters": { + "check": "educator_expense_signal", + "overall_positive_share_band": [ + 0.002, + 0.04 + ], + "puf_positive_share_band": [ + 0.005, + 0.08 + ] + }, + "notes": "US national release (tools/build_us_fiscal_refresh_release.py): educator expenses. Raises at once today." + }, + { + "id": "us_national_form_4952_election", + "gate": "stage_health", + "phase": "assembled", + "criticality": "release_blocking", + "parameters": { + "check": "form_4952_election_signal", + "overall_positive_share_band": [ + 5e-05, + 0.02 + ], + "puf_positive_share_band": [ + 0.0001, + 0.04 + ] + }, + "notes": "US national release (tools/build_us_fiscal_refresh_release.py): Form 4952 election. Raises at once today." + }, + { + "id": "us_national_salt_refund_income", + "gate": "stage_health", + "phase": "assembled", + "criticality": "release_blocking", + "parameters": { + "check": "salt_refund_income_signal", + "overall_positive_share_band": [ + 0.005, + 0.2 + ], + "puf_positive_share_band": [ + 0.01, + 0.4 + ] + }, + "notes": "US national release (tools/build_us_fiscal_refresh_release.py): SALT refund income. Raises at once today." + }, + { + "id": "us_national_capital_gain_details", + "gate": "stage_health", + "phase": "assembled", + "criticality": "release_blocking", + "parameters": { + "check": "capital_gain_details_signal", + "signal_bands": { + "long_term_capital_gains_on_collectibles": { + "overall": [ + 1e-05, + 0.005 + ], + "puf": [ + 2e-05, + 0.01 + ] + }, + "unrecaptured_section_1250_gain": { + "overall": [ + 0.0005, + 0.03 + ], + "puf": [ + 0.001, + 0.06 + ] + } + } + }, + "notes": "US national release (tools/build_us_fiscal_refresh_release.py): capital gain details. Raises at once today." + }, + { + "id": "us_national_childcare", + "gate": "stage_health", + "phase": "assembled", + "criticality": "release_blocking", + "parameters": { + "check": "childcare_inputs_signal", + "nonzero_share_band": [ + 0.005, + 0.5 + ] + }, + "notes": "US national release (tools/build_us_fiscal_refresh_release.py): childcare inputs after their stage. Raises at once today." + }, + { + "id": "us_national_energy_subsidy", + "gate": "stage_health", + "phase": "assembled", + "criticality": "release_blocking", + "parameters": { + "check": "energy_subsidy_signal", + "overall_positive_share_band": [ + 0.01, + 0.2 + ], + "channel_positive_share_bands": { + "asec": [ + 0.025, + 0.045 + ], + "puf_tax_detail": [ + 0.002, + 0.2 + ] + } + }, + "notes": "US national release (tools/build_us_fiscal_refresh_release.py): energy subsidy after its stage. Raises at once today." + }, + { + "id": "us_national_alimony", + "gate": "stage_health", + "phase": "assembled", + "criticality": "release_blocking", + "parameters": { + "check": "alimony_inputs_signal", + "nonzero_share_band": [ + 1e-05, + 0.02 + ] + }, + "notes": "US national release (tools/build_us_fiscal_refresh_release.py): alimony. Raises at once today." + }, + { + "id": "us_national_casualty_loss", + "gate": "stage_health", + "phase": "assembled", + "criticality": "release_blocking", + "parameters": { + "check": "casualty_loss_signal", + "casualty_loss_nonzero_share_band": [ + 0.0001, + 0.02 + ] + }, + "notes": "US national release (tools/build_us_fiscal_refresh_release.py): casualty losses. Raises at once today." + }, + { + "id": "us_national_misc_itemized", + "gate": "stage_health", + "phase": "assembled", + "criticality": "release_blocking", + "parameters": { + "check": "misc_itemized_signal", + "misc_itemized_nonzero_share_band": [ + 0.05, + 0.55 + ] + }, + "notes": "US national release (tools/build_us_fiscal_refresh_release.py): miscellaneous itemized deductions. Raises at once today." + }, + { + "id": "us_national_retirement_contributions", + "gate": "stage_health", + "phase": "assembled", + "criticality": "release_blocking", + "parameters": { + "check": "retirement_contributions_signal", + "nonzero_share_band": [ + 0.0001, + 0.75 + ] + }, + "notes": "US national release (tools/build_us_fiscal_refresh_release.py): retirement contributions after their stage. Raises at once today." + }, + { + "id": "us_national_immigration_composition", + "gate": "stage_health", + "phase": "assembled", + "criticality": "release_blocking", + "parameters": { + "check": "immigration_composition", + "non_citizen_share_band": [ + 0.03, + 0.12 + ], + "undocumented_anchor_relative_band": [ + 0.5, + 1.6 + ] + }, + "notes": "US national release (tools/build_us_fiscal_refresh_release.py): immigration composition after its stage. Raises at once today." + }, + { + "id": "us_national_take_up", + "gate": "stage_health", + "phase": "assembled", + "criticality": "release_blocking", + "parameters": { + "check": "take_up_signal", + "us_take_up_share_band": { + "takes_up_tanf_if_eligible": [ + 0.1, + 0.4 + ], + "takes_up_eitc": [ + 0.6, + 0.92 + ] + } + }, + "notes": "US national release (tools/build_us_fiscal_refresh_release.py): seeded take-up after its stage. Raises at once today." + }, + { + "id": "us_national_hours_worked", + "gate": "stage_health", + "phase": "assembled", + "criticality": "release_blocking", + "parameters": { + "check": "hours_worked_signal", + "worked_share_band": [ + 0.35, + 0.62 + ], + "mean_weekly_hours_band": [ + 30.0, + 45.0 + ] + }, + "notes": "US national release (tools/build_us_fiscal_refresh_release.py): hours worked after its stage. Raises at once today." + }, + { + "id": "us_national_snap_take_up", + "gate": "stage_health", + "phase": "assembled", + "criticality": "release_blocking", + "parameters": { + "check": "snap_take_up_signal", + "take_up_share_band": [ + 0.7, + 0.95 + ] + }, + "notes": "US national release (tools/build_us_fiscal_refresh_release.py): SNAP take-up after its stage, in every arm. Raises at once today." + }, + { + "id": "us_national_relationship_inputs", + "gate": "stage_health", + "phase": "assembled", + "criticality": "release_blocking", + "parameters": { + "check": "relationship_inputs_signal", + "household_head_share_band": [ + 0.3, + 0.55 + ], + "separated_share_band": [ + 0.003, + 0.04 + ], + "surviving_spouse_share_band": [ + 0.02, + 0.08 + ] + }, + "notes": "US national release (tools/build_us_fiscal_refresh_release.py): relationship inputs after their stage. Raises at once today." + }, + { + "id": "us_national_spm_independence_role", + "gate": "stage_health", + "phase": "assembled", + "criticality": "release_blocking", + "parameters": { + "check": "spm_independence_role_signal", + "role_share_band": [ + 0.4, + 0.75 + ], + "minor_role_share_band": [ + 0.003, + 0.06 + ] + }, + "notes": "US national release (tools/build_us_fiscal_refresh_release.py): SPM independence role. Raises at once today." + }, + { + "id": "us_national_medicare_take_up", + "gate": "stage_health", + "phase": "assembled", + "criticality": "release_blocking", + "parameters": { + "check": "medicare_take_up_input_signal", + "weighted_enrolled_share_band": [ + 0.15, + 0.24 + ], + "channel_enrolled_share_band": [ + 0.15, + 0.24 + ] + }, + "notes": "US national release (tools/build_us_fiscal_refresh_release.py): Medicare enrollment input. Raises at once today." + }, + { + "id": "us_national_prior_year_income", + "gate": "stage_health", + "phase": "assembled", + "criticality": "release_blocking", + "parameters": { + "check": "prior_year_income_signal", + "previous_year_available_share_band": [ + 0.05, + 0.5 + ], + "self_employment_nonzero_share_band": [ + 0.01, + 0.25 + ] + }, + "notes": "US national release (tools/build_us_fiscal_refresh_release.py): prior-year income inputs. Raises at once today." + }, + { + "id": "us_national_housing_inputs", + "gate": "stage_health", + "phase": "assembled", + "criticality": "release_blocking", + "parameters": { + "check": "housing_inputs_signal", + "rent_share_band": [ + 0.05, + 0.25 + ], + "housing_assistance_share_band": [ + 0.005, + 0.08 + ] + }, + "notes": "US national release (tools/build_us_fiscal_refresh_release.py): housing and tenure inputs. Raises at once today." + }, + { + "id": "us_national_retirement_distributions", + "gate": "stage_health", + "phase": "assembled", + "criticality": "release_blocking", + "parameters": { + "check": "retirement_distributions_signal", + "nonzero_share_bands": { + "taxable_401k_distributions": [ + 0.001, + 0.2 + ], + "taxable_403b_distributions": [ + 5e-05, + 0.05 + ], + "tax_exempt_ira_distributions": [ + 0.0001, + 0.05 + ], + "taxable_ira_distributions": [ + 0.001, + 0.25 + ], + "keogh_distributions": [ + 1e-07, + 0.005 + ], + "taxable_sep_distributions": [ + 1e-05, + 0.05 + ] + } + }, + "notes": "US national release (tools/build_us_fiscal_refresh_release.py): retirement distributions after their stage. Its failures join the terminal batch rather than raising here." + }, + { + "id": "us_national_eligibility_inputs", + "gate": "stage_health", + "phase": "assembled", + "criticality": "release_blocking", + "parameters": { + "check": "eligibility_inputs_signal", + "disabled_share_band": [ + 0.05, + 0.2 + ], + "full_time_student_share_band": [ + 0.01, + 0.08 + ], + "parent_share_band": [ + 0.12, + 0.4 + ], + "veterans_benefits_share_band": [ + 0.002, + 0.04 + ] + }, + "notes": "US national release (tools/build_us_fiscal_refresh_release.py): eligibility inputs after their stage. Raises at once today." + }, + { + "id": "us_national_education_inputs", + "gate": "stage_health", + "phase": "assembled", + "criticality": "release_blocking", + "parameters": { + "check": "education_inputs_signal", + "tuition_share_band": [ + 0.001, + 0.05 + ], + "assistance_share_band": [ + 0.005, + 0.08 + ] + }, + "notes": "US national release (tools/build_us_fiscal_refresh_release.py): education inputs after their stage. Raises at once today." + }, + { + "id": "us_national_pregnancy", + "gate": "stage_health", + "phase": "assembled", + "criticality": "release_blocking", + "parameters": { + "check": "pregnancy_signal", + "pregnant_share_band": [ + 0.002, + 0.02 + ] + }, + "notes": "US national release (tools/build_us_fiscal_refresh_release.py): pregnancy input after its stage. Raises at once today." + }, + { + "id": "us_national_reported_coverage_vintage", + "gate": "stage_health", + "phase": "assembled", + "criticality": "release_blocking", + "parameters": { + "check": "reported_coverage_vintage_signal", + "us_reported_coverage_vintage_gate_min_rows": 5000 + }, + "notes": "US national release (tools/build_us_fiscal_refresh_release.py): reported coverage carries its source vintage. Writes its failure receipt, then raises at once today." + }, + { + "id": "us_national_wic_claim", + "gate": "stage_health", + "phase": "assembled", + "criticality": "release_blocking", + "parameters": { + "check": "wic_claim_input_signal", + "weighted_claim_share_band": [ + 0.015, + 0.06 + ], + "category_weighted_claim_share_bands": { + "pregnant": [ + 0.25, + 0.67 + ], + "postpartum": [ + 0.45, + 0.9 + ], + "infant": [ + 0.55, + 0.96 + ], + "child": [ + 0.3, + 0.63 + ], + "none": [ + 0.0, + 0.0 + ] + } + }, + "notes": "US national release (tools/build_us_fiscal_refresh_release.py): WIC claims after their stage. Raises at once today." + }, + { + "id": "us_national_snap_discretionary_exemption", + "gate": "stage_health", + "phase": "assembled", + "criticality": "release_blocking", + "parameters": { + "check": "snap_discretionary_exemption_signal", + "exempt_share_band": [ + 0.015, + 0.09 + ] + }, + "notes": "US national release (tools/build_us_fiscal_refresh_release.py): SNAP discretionary exemption, in every arm. Raises at once today." + }, + { + "id": "us_national_scf_wealth", + "gate": "stage_health", + "phase": "assembled", + "criticality": "release_blocking", + "parameters": { + "check": "scf_wealth_signal", + "bank_nonzero_share_band": [ + 0.25, + 0.85 + ], + "stock_nonzero_share_band": [ + 0.03, + 0.4 + ], + "bond_nonzero_share_band": [ + 0.001, + 0.12 + ], + "net_worth_nonzero_share_band": [ + 0.9, + 1.0 + ], + "net_worth_positive_share_band": [ + 0.75, + 1.0 + ], + "net_worth_negative_share_band": [ + 0.001, + 0.25 + ], + "scf_source_share_band": [ + 0.4, + 0.6 + ], + "bank_low_tail_threshold": 2000.0 + }, + "notes": "US national release (tools/build_us_fiscal_refresh_release.py): SCF wealth after its stage, with the SIPP blend required. Raises at once today." + }, + { + "id": "us_national_ssi_disability_criteria", + "gate": "stage_health", + "phase": "assembled", + "criticality": "release_blocking", + "parameters": { + "check": "ssi_disability_criteria_signal", + "true_share_band": [ + 0.001, + 0.25 + ] + }, + "notes": "US national release (tools/build_us_fiscal_refresh_release.py): SSI disability criteria. Raises at once today." + }, + { + "id": "us_national_sipp_head_start", + "gate": "stage_health", + "phase": "assembled", + "criticality": "release_blocking", + "parameters": { + "check": "sipp_head_start_signal", + "eligible_take_up_share_band": [ + 0.005, + 0.25 + ] + }, + "notes": "US national release (tools/build_us_fiscal_refresh_release.py): SIPP Head Start. Raises at once today." + }, + { + "id": "us_national_ssi_take_up", + "gate": "stage_health", + "phase": "assembled", + "criticality": "release_blocking", + "parameters": { + "check": "ssi_take_up" + }, + "notes": "US national release (tools/build_us_fiscal_refresh_release.py): the SSI take-up stage's diagnostics against the registry's band targets. Raises at once today." + }, + { + "id": "us_national_scf_auto_loans", + "gate": "stage_health", + "phase": "assembled", + "criticality": "release_blocking", + "parameters": { + "check": "scf_auto_loans_signal", + "auto_loan_nonzero_share_band": [ + 0.1, + 0.6 + ] + }, + "notes": "US national release (tools/build_us_fiscal_refresh_release.py): SCF auto loans. Raises at once today." + }, + { + "id": "us_national_scf_education_debt", + "gate": "stage_health", + "phase": "assembled", + "criticality": "release_blocking", + "parameters": { + "check": "scf_education_debt_signal", + "borrower_household_share_band": [ + 0.08, + 0.35 + ] + }, + "notes": "US national release (tools/build_us_fiscal_refresh_release.py): SCF education debt, with --scf-education-debt only. Raises at once today." + }, + { + "id": "us_national_sipp_vehicles", + "gate": "stage_health", + "phase": "assembled", + "criticality": "release_blocking", + "parameters": { + "check": "sipp_vehicles_signal", + "owned_nonzero_share_band": [ + 0.4, + 0.99 + ], + "value_nonzero_share_band": [ + 0.25, + 0.99 + ] + }, + "notes": "US national release (tools/build_us_fiscal_refresh_release.py): SIPP vehicles. Raises at once today." + }, + { + "id": "us_national_voluntary_filing", + "gate": "stage_health", + "phase": "assembled", + "criticality": "release_blocking", + "parameters": { + "check": "voluntary_filing_signal", + "true_share_band": [ + 0.45, + 0.95 + ] + }, + "notes": "US national release (tools/build_us_fiscal_refresh_release.py): voluntary filing. Raises at once today." + }, + { + "id": "us_national_sipp_tips", + "gate": "stage_health", + "phase": "assembled", + "criticality": "release_blocking", + "parameters": { + "check": "sipp_tips_signal", + "tipped_occupation_share_band": [ + 0.02, + 0.15 + ], + "tip_income_nonzero_share_band": [ + 0.001, + 0.03 + ] + }, + "notes": "US national release (tools/build_us_fiscal_refresh_release.py): SIPP tips. Raises at once today." + }, + { + "id": "us_national_org_wages", + "gate": "stage_health", + "phase": "assembled", + "criticality": "release_blocking", + "parameters": { + "check": "org_wages_signal", + "share_bands": { + "cps_race": [ + 0.95, + 1.0 + ], + "is_hispanic": [ + 0.05, + 0.3 + ], + "detailed_occupation_recode": [ + 0.65, + 0.95 + ], + "detailed_industry_recode": [ + 0.7, + 0.92 + ], + "major_industry_recode": [ + 0.7, + 0.92 + ], + "worked_last_year": [ + 0.4, + 0.62 + ], + "has_never_worked": [ + 0.15, + 0.35 + ], + "is_military": [ + 0.0005, + 0.01 + ], + "is_computer_scientist": [ + 0.005, + 0.05 + ], + "is_executive_administrative_professional": [ + 0.2, + 0.4 + ], + "is_farmer_fisher": [ + 0.001, + 0.015 + ], + "hourly_wage": [ + 0.4, + 0.7 + ], + "is_paid_hourly": [ + 0.15, + 0.4 + ], + "is_union_member_or_covered": [ + 0.02, + 0.12 + ], + "fsla_overtime_premium": [ + 0.01, + 0.15 + ] + } + }, + "notes": "US national release (tools/build_us_fiscal_refresh_release.py): CPS ORG and FLSA wages. Raises at once today." + }, + { + "id": "us_national_health_input", + "gate": "stage_health", + "phase": "assembled", + "criticality": "release_blocking", + "parameters": { + "check": "health_input_signal" + }, + "notes": "US national release (tools/build_us_fiscal_refresh_release.py): the health inputs are not constant, on the base. Raises at once today." + }, + { + "id": "us_national_medicaid_take_up", + "gate": "stage_health", + "phase": "assembled", + "criticality": "release_blocking", + "parameters": { + "check": "medicaid_take_up", + "tolerance": 0.02 + }, + "notes": "US national release (tools/build_us_fiscal_refresh_release.py): Medicaid take-up against the state enrollment targets. Raises at once today." + }, + { + "id": "us_national_snap_state_take_up", + "gate": "stage_health", + "phase": "assembled", + "criticality": "release_blocking", + "parameters": { + "check": "snap_state_take_up", + "tolerance": 0.02 + }, + "notes": "US national release (tools/build_us_fiscal_refresh_release.py): SNAP state take-up against the state caseloads. Raises at once today." + }, + { + "id": "us_national_other_health_insurance", + "gate": "stage_health", + "phase": "assembled", + "criticality": "release_blocking", + "parameters": { + "check": "other_health_insurance_premiums_signal", + "positive_share_band": [ + 0.15, + 0.65 + ] + }, + "notes": "US national release (tools/build_us_fiscal_refresh_release.py): other health insurance premiums. Raises at once today." + }, + { + "id": "us_national_esi_premiums", + "gate": "stage_health", + "phase": "assembled", + "criticality": "release_blocking", + "parameters": { + "check": "esi_premiums_signal", + "positive_share_band": [ + 0.15, + 0.32 + ], + "raw_mean_band": [ + 6000.0, + 20000.0 + ] + }, + "notes": "US national release (tools/build_us_fiscal_refresh_release.py): ESI premiums on the base. Raises at once today unless --allow-esi-premium-gaps waives it." + }, + { + "id": "us_national_input_mass_reference", + "gate": "stage_health", + "phase": "assembled", + "criticality": "release_blocking", + "parameters": { + "check": "input_mass_parity", + "relative_tolerance": 0.5, + "minimum_reference_total": 1000000000.0 + }, + "notes": "US national release (tools/build_us_fiscal_refresh_release.py): the base's input mass against --input-mass-reference-h5, when one is given. Raises unless --allow-input-mass-drift waives it, or joins the batch when earlier failures are on record. Its two thresholds are flags; the entry declares their defaults." + }, + { + "id": "us_national_degenerate_input", + "gate": "stage_health", + "phase": "assembled", + "criticality": "release_blocking", + "parameters": { + "check": "degenerate_input_signal" + }, + "notes": "US national release (tools/build_us_fiscal_refresh_release.py): no persisted input column sits at the engine default without a reviewed exclusion. Raises at once today, or joins the batch when earlier failures are on record." + }, + { + "id": "us_national_ecps_parity", + "gate": "stage_health", + "phase": "assembled", + "criticality": "release_blocking", + "parameters": { + "check": "ecps_parity" + }, + "notes": "US national release (tools/build_us_fiscal_refresh_release.py): the base populates every layer the incumbent eCPS does, or a reviewed gap names it. Raises unless --allow-ecps-parity-gaps waives it." + }, + { + "id": "us_national_exact_k_puf_capital_gains_tail", + "gate": "stage_health", + "phase": "terminal", + "criticality": "release_blocking", + "parameters": { + "check": "exact_k_puf_capital_gains_tail" + }, + "notes": "US national release (tools/build_us_fiscal_refresh_release.py): the exact-k selection keeps the PUF capital-gains tail. Exact-k arm only. Joins the terminal batch, which raises before the H5 write." + }, + { + "id": "us_national_ssi_take_up_final", + "gate": "stage_health", + "phase": "terminal", + "criticality": "release_blocking", + "parameters": { + "check": "ssi_take_up" + }, + "notes": "US national release (tools/build_us_fiscal_refresh_release.py): the SSI take-up law on the export frame. Joins the terminal batch, which raises before the H5 write." + }, + { + "id": "us_national_ssi_take_up_delivery", + "gate": "stage_health", + "phase": "terminal", + "criticality": "release_blocking", + "parameters": { + "check": "ssi_take_up_delivery", + "us_ssi_take_up_band_delivery_relative_tolerance": 0.05 + }, + "notes": "US national release (tools/build_us_fiscal_refresh_release.py): the enforced SSI bands are delivered on release weights (with the dense default's fences under --dense-default-dataset). Joins the terminal batch, which raises before the H5 write." + }, + { + "id": "us_national_health_input_export", + "gate": "stage_health", + "phase": "terminal", + "criticality": "release_blocking", + "parameters": { + "check": "health_input_signal" + }, + "notes": "US national release (tools/build_us_fiscal_refresh_release.py): the health inputs again, on the export frame. Joins the terminal batch, which raises before the H5 write." + }, + { + "id": "us_national_reported_coverage_vintage_export", + "gate": "stage_health", + "phase": "terminal", + "criticality": "release_blocking", + "parameters": { + "check": "reported_coverage_vintage_signal", + "us_reported_coverage_vintage_gate_min_rows": 5000 + }, + "notes": "US national release (tools/build_us_fiscal_refresh_release.py): reported coverage vintage again, on the export frame. Joins the terminal batch, which raises before the H5 write." + }, + { + "id": "us_national_other_health_insurance_export", + "gate": "stage_health", + "phase": "terminal", + "criticality": "release_blocking", + "parameters": { + "check": "other_health_insurance_premiums_signal", + "positive_share_band": [ + 0.15, + 0.65 + ] + }, + "notes": "US national release (tools/build_us_fiscal_refresh_release.py): other health insurance premiums on the export frame. Joins the terminal batch, which raises before the H5 write." + }, + { + "id": "us_national_esi_premiums_export", + "gate": "stage_health", + "phase": "terminal", + "criticality": "release_blocking", + "parameters": { + "check": "esi_premiums_signal", + "positive_share_band": [ + 0.15, + 0.32 + ], + "raw_mean_band": [ + 6000.0, + 20000.0 + ] + }, + "notes": "US national release (tools/build_us_fiscal_refresh_release.py): ESI premiums on the export frame. Joins the terminal batch, which raises before the H5 write. --allow-esi-premium-gaps waives it." + }, + { + "id": "us_national_exact_k_frozen_register_fit", + "gate": "stage_health", + "phase": "terminal", + "criticality": "release_blocking", + "parameters": { + "check": "exact_k_frozen_register_fit", + "us_fiscal_target_loss_cap": 1.0 + }, + "notes": "US national release (tools/build_us_fiscal_refresh_release.py): an exact-k candidate beats the incumbent on the frozen register. Exact-k arm only. Joins the terminal batch, which raises before the H5 write." + }, + { + "id": "us_national_release_gates", + "gate": "stage_health", + "phase": "terminal", + "criticality": "release_blocking", + "parameters": { + "check": "release_gate_failures" + }, + "notes": "US national release (tools/build_us_fiscal_refresh_release.py): the calibration's own gates (critical target fits, the SOI Table 1.4 fit, finite and falling loss) with the pre-solve gates they re-read; build_manifest gates.calibration records them. Joins the terminal batch, which raises before the H5 write." + }, + { + "id": "us_national_spm_composition", + "gate": "stage_health", + "phase": "terminal", + "criticality": "release_blocking", + "parameters": { + "check": "spm_composition" + }, + "notes": "US national release (tools/build_us_fiscal_refresh_release.py): every SPM unit on the export frame classifies. Joins the terminal batch, which raises before the H5 write." + }, + { + "id": "us_national_stored_inputs", + "gate": "stage_health", + "phase": "terminal", + "criticality": "release_blocking", + "parameters": { + "check": "stored_inputs" + }, + "notes": "US national release (tools/build_us_fiscal_refresh_release.py): every stored column is a model input the recorded engine defines. Joins the terminal batch, which raises before the H5 write." + }, + { + "id": "us_national_release_input_coverage", + "gate": "stage_health", + "phase": "terminal", + "criticality": "release_blocking", + "parameters": { + "check": "release_input_coverage" + }, + "notes": "US national release (tools/build_us_fiscal_refresh_release.py): the export frame covers the release input-coverage manifest. Joins the terminal batch, which raises before the H5 write. --allow-input-coverage-gaps waives it." + }, + { + "id": "us_national_esi_premiums_anchor", + "gate": "stage_health", + "phase": "terminal", + "criticality": "release_blocking", + "parameters": { + "check": "esi_premiums_anchor", + "anchor_relative_tolerance": 0.05, + "employed_share_band": [ + 0.8, + 0.95 + ], + "raw_mean_band": [ + 6000.0, + 20000.0 + ] + }, + "notes": "US national release (tools/build_us_fiscal_refresh_release.py): ESI premiums against the MEPS anchor on the export frame. Joins the terminal batch, which raises before the H5 write. --allow-esi-premium-gaps waives it." + }, + { + "id": "us_national_export_input_mass", + "gate": "stage_health", + "phase": "terminal", + "criticality": "release_blocking", + "parameters": { + "check": "export_input_mass_parity", + "relative_tolerance": 0.5, + "minimum_reference_total": 1000000000.0 + }, + "notes": "US national release (tools/build_us_fiscal_refresh_release.py): the export's input mass against the base or --export-input-mass-reference-h5. Joins the terminal batch, which raises before the H5 write. --allow-input-mass-drift waives it. Its thresholds are the same flags as the base-frame gate's." + }, + { + "id": "us_national_qrf_tail_concentration", + "gate": "stage_health", + "phase": "terminal", + "criticality": "release_blocking", + "parameters": { + "check": "qrf_tail_concentration", + "us_qrf_tail_concentration_top_k": 100, + "us_qrf_tail_concentration_max_top_share": 0.75, + "us_qrf_tail_concentration_min_nonzero_records": 500, + "us_qrf_sparse_nonzero_share_max": 0.05 + }, + "notes": "US national release (tools/build_us_fiscal_refresh_release.py): tail concentration over the sparse QRF-imputed export columns, with the run's reviewed exclusions. Joins the terminal batch, which raises before the H5 write. --allow-qrf-tail-concentration waives it." + }, + { + "id": "us_national_stored_inputs_written", + "gate": "stage_health", + "phase": "terminal", + "criticality": "release_blocking", + "parameters": { + "check": "stored_inputs_written" + }, + "notes": "US national release (tools/build_us_fiscal_refresh_release.py): the written H5's stored inputs are the ones the pre-export gate graded. Raises at once today, after the H5 write." } ] } diff --git a/packages/microcosm-build/src/microcosm/build/us_runtime/battery_bindings.py b/packages/microcosm-build/src/microcosm/build/us_runtime/battery_bindings.py index 5929218729..98bbc5da09 100644 --- a/packages/microcosm-build/src/microcosm/build/us_runtime/battery_bindings.py +++ b/packages/microcosm-build/src/microcosm/build/us_runtime/battery_bindings.py @@ -57,6 +57,8 @@ "ToolNamespace", "USCheckBinding", "USGateSpec", + "RETURNS", + "us_flag_overrides", "declared_value", "resolve_reference", "us_check_binding", @@ -151,11 +153,23 @@ class USGateSpec: entry parameter of the same name. pinned: Entry parameter to the reference of the module constant the gate reads it from; the declared value must equal the constant. - returns_failures: The gate returns failure lines rather than a - :class:`~microcosm.build.gates.GateResult`; the binding wraps - them (an empty list passes). - adapt: Optional final step turning the gate's return value into its - :class:`~microcosm.build.gates.GateResult`. + returns: How the gate hands back its verdict (:data:`RETURNS`): + ``result``, a :class:`~microcosm.build.gates.GateResult` (or an + object with ``passed`` and ``failures``); ``failures``, failure + lines (none is a pass); ``failures_and_details``, a pair of those + lines and a details mapping; ``result_and_details``, a pair whose + first item is the result; ``failure_or_none``, one failure line or + ``None``; ``mapping``, a dict carrying ``passed`` and + ``failures``; or ``receipt``, a refusal-style check whose + returning at all is a pass and whose ``refusals`` are its + failures. + refusals: Exception types a refusal-style check raises to fail; the + binding reads one as a failure whose line is its message, as + the shadow reads today's. + flags: Routed parameter to the tool's argparse destination that + sets it per run. The entry declares the parser's default; a + build that passes another value is a runtime override, which + the shadow records and explains. """ check: str @@ -165,8 +179,9 @@ class USGateSpec: arguments: Mapping[str, str] = field(default_factory=dict) parameters: frozenset[str] = frozenset() pinned: Mapping[str, str] = field(default_factory=dict) - returns_failures: bool = False - adapt: Callable[[Any], GateResult] | None = None + returns: str = "result" + refusals: tuple[type[BaseException], ...] = () + flags: Mapping[str, str] = field(default_factory=dict) def __post_init__(self) -> None: if not self.check or not self.legacy_name: @@ -189,10 +204,20 @@ def __post_init__(self) -> None: raise ValueError( f"{self.check}: {sorted(overlap)} are both evidence and thresholds." ) - if self.returns_failures and self.adapt is not None: - raise ValueError(f"{self.check}: returns_failures and adapt both wrap.") + if self.returns not in RETURNS: + raise ValueError( + f"{self.check}: returns {self.returns!r} is not one of {sorted(RETURNS)}." + ) + if self.returns == "receipt" and not self.refusals: + raise ValueError(f"{self.check}: a receipt check fails only by a refusal.") + stray_flags = sorted(set(self.flags) - set(self.parameters)) + if stray_flags: + raise ValueError( + f"{self.check}: flags {stray_flags} name parameters it does not route." + ) object.__setattr__(self, "arguments", MappingProxyType(dict(self.arguments))) object.__setattr__(self, "pinned", MappingProxyType(dict(self.pinned))) + object.__setattr__(self, "flags", MappingProxyType(dict(self.flags))) @property def parameter_keys(self) -> frozenset[str]: @@ -349,27 +374,22 @@ def evaluate( "until the flip the spec must equal today's constant." ) gate = resolve_reference(spec.gate, tool=self._tool) - value = gate( - *(_source(context, source) for source in spec.positional), - **{ - argument: _source(context, source) - for argument, source in spec.arguments.items() - }, - **{ - key: _routed(declared[key]) - for key in spec.parameters - if key in declared - }, - ) - if spec.returns_failures: - if isinstance(value, str): - raise TypeError(f"check {spec.check!r} returned one string, not lines.") - lines = tuple(str(line) for line in value) - value = GateResult(name=spec.legacy_name, passed=not lines, failures=lines) - elif spec.adapt is not None: - value = spec.adapt(value) - elif not isinstance(value, GateResult): - value = _as_gate_result(value, spec.legacy_name) + try: + value = gate( + *(_source(context, source) for source in spec.positional), + **{ + argument: _source(context, source) + for argument, source in spec.arguments.items() + }, + **{ + key: _routed(declared[key]) + for key in spec.parameters + if key in declared + }, + ) + except spec.refusals as refusal: + return GateResult(name=self.name, passed=False, failures=(str(refusal),)) + value = _verdict_of(spec, value) if isinstance(value, GateResult) and value.name == spec.legacy_name: value = replace(value, name=self.name) return value @@ -380,6 +400,90 @@ def evidence_payload( return None +#: How a gate hands back its verdict (:attr:`USGateSpec.returns`). +RETURNS = frozenset( + { + "result", + "failures", + "failures_and_details", + "result_and_details", + "failure_or_none", + "mapping", + "receipt", + } +) + + +def _lines(value: object, check: str) -> tuple[str, ...]: + if isinstance(value, str): + raise TypeError(f"check {check!r} returned one string, not lines.") + return tuple(str(line) for line in value) + + +def _verdict_of(spec: USGateSpec, value: Any) -> object: + """The gate's return value as its result, by :attr:`USGateSpec.returns`.""" + + name = spec.legacy_name + if spec.returns == "result": + return value if isinstance(value, GateResult) else _as_gate_result(value, name) + if spec.returns == "result_and_details": + first = value[0] + return first if isinstance(first, GateResult) else _as_gate_result(first, name) + if spec.returns == "receipt": + return GateResult(name=name, passed=True) + if spec.returns == "mapping": + failures = _lines(value.get("failures") or (), spec.check) + details = {key: item for key, item in value.items() if key != "failures"} + return GateResult( + name=name, + passed=bool(value.get("passed")), + failures=failures, + details=details, + ) + if spec.returns == "failure_or_none": + if value is None: + return GateResult(name=name, passed=True) + return GateResult(name=name, passed=False, failures=(str(value),)) + details: dict[str, object] = {} + if spec.returns == "failures_and_details": + value, raw_details = value + details = dict(raw_details or {}) + failures = _lines(value, spec.check) + return GateResult( + name=name, passed=not failures, failures=failures, details=details + ) + + +def us_flag_overrides( + gates: Any, specs: Sequence[USGateSpec], args: Any +) -> dict[str, dict[str, dict[str, object]]]: + """The declared thresholds this build's flags overrode, by entry id. + + For each ``stage_health`` entry whose gate routes a flag-set threshold, + a parsed value that differs from the declared one is an override. + """ + + by_check = {spec.check: spec for spec in specs} + overrides: dict[str, dict[str, dict[str, object]]] = {} + for entry in gates.gates: + if entry.gate != "stage_health": + continue + spec = by_check.get(entry.parameters.get("check")) + if spec is None: + continue + for key, destination in spec.flags.items(): + if not hasattr(args, destination): + continue + runtime = getattr(args, destination) + declared = entry.parameters.get(key) + if not _same(declared, runtime): + overrides.setdefault(entry.id, {})[key] = { + "declared": declared_value(declared), + "runtime": declared_value(runtime), + } + return overrides + + def us_check_binding( name: str, specs: Sequence[USGateSpec], @@ -771,8 +875,426 @@ def _us_pool_specs() -> tuple[USGateSpec, ...]: ) +def _tool_pins(*constants: str) -> dict[str, str]: + """Pinned parameters named after the tool's own module constants.""" + + return {constant.lstrip("_").lower(): f"tool:{constant}" for constant in constants} + + +#: Frame signal gates only the national release runs: (check, legacy name, +#: gate, module, pinned constants). +_NATIONAL_FRAME_SIGNALS: tuple[tuple[str, str, str, str, tuple[str, ...]], ...] = ( + ( + "immigration_composition", + "immigration_composition", + "us_immigration_composition_gate", + "immigration", + ("_NON_CITIZEN_SHARE_BAND", "_UNDOCUMENTED_ANCHOR_RELATIVE_BAND"), + ), + ( + "take_up_signal", + "take_up_signal", + "us_take_up_signal_gate", + "take_up", + ("US_TAKE_UP_SHARE_BAND",), + ), + ( + "hours_worked_signal", + "hours_worked_signal", + "us_hours_worked_signal_gate", + "hours_worked", + ("_WORKED_SHARE_BAND", "_MEAN_WEEKLY_HOURS_BAND"), + ), + ( + "snap_take_up_signal", + "snap_take_up_signal", + "us_snap_take_up_signal_gate", + "snap_take_up", + ("_TAKE_UP_SHARE_BAND",), + ), + ( + "snap_discretionary_exemption_signal", + "snap_discretionary_exemption_signal", + "us_snap_discretionary_exemption_signal_gate", + "snap_discretionary_exemption", + ("_EXEMPT_SHARE_BAND",), + ), + ( + "ssi_disability_criteria_signal", + "ssi_disability_criteria_signal", + "us_ssi_disability_criteria_signal_gate", + "ssi_disability_criteria", + ("_TRUE_SHARE_BAND",), + ), + ( + "sipp_head_start_signal", + "sipp_head_start_signal", + "us_sipp_head_start_signal_gate", + "sipp_head_start", + ("_ELIGIBLE_TAKE_UP_SHARE_BAND",), + ), + ( + "scf_auto_loans_signal", + "scf_auto_loans_signal", + "us_scf_auto_loans_signal_gate", + "scf_auto_loans", + ("_AUTO_LOAN_NONZERO_SHARE_BAND",), + ), + ( + "scf_education_debt_signal", + "scf_education_debt_signal", + "us_scf_education_debt_signal_gate", + "scf_education_debt", + ("_BORROWER_HOUSEHOLD_SHARE_BAND",), + ), + ( + "sipp_vehicles_signal", + "sipp_vehicles_signal", + "us_sipp_vehicles_signal_gate", + "sipp_vehicles", + ("_OWNED_NONZERO_SHARE_BAND", "_VALUE_NONZERO_SHARE_BAND"), + ), + ( + "voluntary_filing_signal", + "voluntary_filing_signal", + "us_voluntary_filing_signal_gate", + "voluntary_filing", + ("_TRUE_SHARE_BAND",), + ), + ( + "sipp_tips_signal", + "sipp_tips_signal", + "us_sipp_tips_signal_gate", + "sipp_tips", + ("_TIPPED_OCCUPATION_SHARE_BAND", "_TIP_INCOME_NONZERO_SHARE_BAND"), + ), + ( + "org_wages_signal", + "org_wages_signal", + "us_org_wages_signal_gate", + "org_wages", + ("_SHARE_BANDS",), + ), + ( + "other_health_insurance_premiums_signal", + "other_health_insurance_premiums_signal", + "us_other_health_insurance_signal_gate", + "other_health_insurance", + ("_POSITIVE_SHARE_BAND",), + ), +) + + +def _us_national_specs() -> tuple[USGateSpec, ...]: + return ( + # Preflight: the registers and the target surface, before any stage. + USGateSpec( + check="validation_input_coverage", + legacy_name="us_validation_input_coverage", + gate="tool:us_validation_input_coverage_gate", + ), + USGateSpec( + check="register_consistency", + legacy_name="us_register_consistency", + gate="tool:us_register_consistency_gate", + arguments={ + "degenerate_reviewed_exclusions": "degenerate_reviewed_exclusions", + "documented_absent_inputs": "documented_absent_inputs", + "nonconstant_required_columns": "nonconstant_required_columns", + }, + ), + USGateSpec( + check="esi_anchor_feed", + legacy_name="esi_anchor_feed", + gate="tool:us_esi_premiums_anchor_feed_mismatches", + positional=("ledger_facts",), + returns="failures", + ), + USGateSpec( + check="target_parity", + legacy_name="us_release_target_parity", + gate="tool:us_release_target_parity_gate", + positional=("target_parity_registry",), + ), + USGateSpec( + check="target_profile_coverage", + legacy_name="target_profile_coverage", + gate="tool:target_profile_coverage_gate", + positional=("target_specs", "target_coverage_requirements"), + ), + # The staged stages' signal gates. + USGateSpec( + check="capital_gains_tail_survives_selection", + legacy_name="capital_gains_tail_survives_selection", + gate="tool:assert_puf_capital_gains_tail_survives_selection", + positional=("tail_candidate_frame", FRAME), + arguments={"require_present": "tail_require_present"}, + refusals=(ValueError,), + returns="receipt", + ), + *_shared_frame_checks( + "weeks_unemployed_signal", + "qbi_inputs_signal", + "farm_business_income_signal", + "domestic_production_ald_signal", + "child_support_inputs_signal", + "disability_benefits_signal", + "workers_compensation_signal", + "educator_expense_signal", + "form_4952_election_signal", + "salt_refund_income_signal", + "capital_gain_details_signal", + "childcare_inputs_signal", + "energy_subsidy_signal", + "alimony_inputs_signal", + "casualty_loss_signal", + "misc_itemized_signal", + "retirement_contributions_signal", + "relationship_inputs_signal", + "spm_independence_role_signal", + "medicare_take_up_input_signal", + "prior_year_income_signal", + "housing_inputs_signal", + "retirement_distributions_signal", + "eligibility_inputs_signal", + "education_inputs_signal", + "pregnancy_signal", + "wic_claim_input_signal", + "esi_premiums_signal", + ), + *( + _frame_check(check, legacy, gate, module, *constants) + for check, legacy, gate, module, constants in _NATIONAL_FRAME_SIGNALS + ), + USGateSpec( + check="base_population_scale", + legacy_name="base_population_scale", + gate="tool:_base_population_scale_gate", + positional=(FRAME,), + arguments={"mass_repair": "base_population_mass_repair"}, + pinned=_tool_pins("US_BASE_PERSON_POPULATION_MAX_ABS_RELATIVE_ERROR"), + ), + USGateSpec( + check="reported_coverage_vintage_signal", + legacy_name="reported_coverage_vintage_signal", + gate="tool:us_reported_coverage_vintage_signal_gate", + positional=(FRAME,), + pinned=_pins("cps_carried", "US_REPORTED_COVERAGE_VINTAGE_GATE_MIN_ROWS"), + ), + USGateSpec( + check="scf_wealth_signal", + legacy_name="scf_wealth_signal", + gate="tool:us_scf_wealth_signal_gate", + positional=(FRAME,), + arguments={"require_sipp_blend": "scf_require_sipp_blend"}, + pinned=_pins( + "scf_wealth", + "_BANK_NONZERO_SHARE_BAND", + "_STOCK_NONZERO_SHARE_BAND", + "_BOND_NONZERO_SHARE_BAND", + "_NET_WORTH_NONZERO_SHARE_BAND", + "_NET_WORTH_POSITIVE_SHARE_BAND", + "_NET_WORTH_NEGATIVE_SHARE_BAND", + "_SCF_SOURCE_SHARE_BAND", + "_BANK_LOW_TAIL_THRESHOLD", + ), + ), + USGateSpec( + check="ssi_take_up", + legacy_name="ssi_take_up", + gate="tool:us_ssi_take_up_gate", + positional=("ssi_take_up_diagnostics",), + arguments={"targets": "ssi_band_targets"}, + ), + USGateSpec( + check="health_input_signal", + legacy_name="health_input_signal", + gate="tool:_health_input_signal_gate", + positional=(FRAME,), + ), + USGateSpec( + check="medicaid_take_up", + legacy_name="medicaid_take_up", + gate="tool:us_medicaid_take_up_gate", + positional=("medicaid_take_up_diagnostics",), + parameters=frozenset({"tolerance"}), + ), + USGateSpec( + check="snap_state_take_up", + legacy_name="snap_state_take_up", + gate="tool:us_snap_state_take_up_gate", + positional=("snap_state_take_up_diagnostics",), + parameters=frozenset({"tolerance"}), + ), + USGateSpec( + check="input_mass_parity", + legacy_name="input_mass_parity", + gate="tool:us_input_mass_parity_gate", + positional=("candidate_input_mass_totals", "reference_input_mass_totals"), + arguments={ + "carriers": "input_mass_carriers", + "candidate_name": "input_mass_candidate_name", + "reference_name": "input_mass_reference_name", + }, + parameters=frozenset({"relative_tolerance", "minimum_reference_total"}), + flags={ + "relative_tolerance": "input_mass_relative_tolerance", + "minimum_reference_total": "input_mass_minimum_reference_total", + }, + ), + USGateSpec( + check="degenerate_input_signal", + legacy_name="degenerate_input_signal", + gate="tool:_degenerate_input_signal_gate", + positional=(FRAME, "policyengine_engine"), + ), + USGateSpec( + check="ecps_parity", + legacy_name="parity", + gate="tool:_ecps_parity_gate", + positional=(FRAME,), + ), + # After the solve: the terminal batch and the export checks. + USGateSpec( + check="exact_k_puf_capital_gains_tail", + legacy_name="exact_k_puf_capital_gains_tail", + gate="tool:_exact_k_puf_tail_support_gate", + positional=(FRAME, "exact_k_support"), + ), + USGateSpec( + check="ssi_take_up_delivery", + legacy_name="ssi_take_up_delivery", + gate="tool:us_ssi_take_up_delivery_gate", + positional=("ssi_take_up_diagnostics",), + arguments={ + "targets": "ssi_band_targets", + "enforcement_fences": "ssi_enforcement_fences", + }, + pinned=_pins( + "ssi_take_up", "US_SSI_TAKE_UP_BAND_DELIVERY_RELATIVE_TOLERANCE" + ), + ), + USGateSpec( + check="exact_k_frozen_register_fit", + legacy_name="exact_k_frozen_register_fit", + gate="tool:_exact_k_frozen_register_fit_gate", + positional=("calibration_result", "incumbent_diagnostics"), + arguments={ + "target_registry": "target_registry", + "target_loss_weights": "target_loss_weights", + "configured_loss_basis": "configured_loss_basis", + "incumbent_loss_basis": "incumbent_loss_basis", + }, + pinned=_tool_pins("US_FISCAL_TARGET_LOSS_CAP"), + ), + USGateSpec( + check="release_gate_failures", + legacy_name="release_gate_failures", + gate="tool:_release_gate_failures", + positional=("calibration_result", "target_compilation"), + arguments={ + name: f"release_gates_{name}" + for name in ( + "target_profile_gate", + "health_input_gate", + "base_population_gate", + "incumbent_diagnostics", + "immigration_gate", + "input_mass_reference_gate", + "degenerate_input_gate", + "ecps_parity_gate", + "hours_worked_gate", + "snap_take_up_gate", + "eligibility_inputs_gate", + "pregnancy_gate", + "reported_coverage_vintage_gate", + "snap_discretionary_exemption_gate", + "target_registry", + ) + }, + returns="failures", + ), + USGateSpec( + check="spm_composition", + legacy_name="spm_composition", + gate="tool:_spm_composition_gate_failures", + positional=(FRAME,), + arguments={"stage": "spm_composition_stage"}, + returns="failures_and_details", + ), + USGateSpec( + check="stored_inputs", + legacy_name="stored_inputs", + gate="tool:_stored_input_gate_failures", + positional=(FRAME,), + arguments={"stage": "stored_inputs_stage"}, + returns="failures_and_details", + ), + USGateSpec( + check="release_input_coverage", + legacy_name="us_release_input_coverage", + gate="tool:us_release_input_coverage_gate", + positional=(FRAME, "release_engine"), + ), + USGateSpec( + check="esi_premiums_anchor", + legacy_name="esi_premiums_anchor", + gate="tool:us_esi_premiums_anchor_gate", + positional=(FRAME,), + arguments={"time_period": "time_period"}, + pinned=_pins( + "esi_premiums", + "ANCHOR_RELATIVE_TOLERANCE", + "_EMPLOYED_SHARE_BAND", + "_RAW_MEAN_BAND", + ), + ), + USGateSpec( + check="export_input_mass_parity", + legacy_name="input_mass_parity", + gate="tool:_export_input_mass_gate", + positional=(FRAME, "base_frame"), + arguments={ + "reference_frame": "export_input_mass_reference_frame", + "reference_name": "export_input_mass_reference_name", + "reviewed_exclusions": "export_input_mass_reviewed_exclusions", + }, + parameters=frozenset({"relative_tolerance", "minimum_reference_total"}), + flags={ + "relative_tolerance": "input_mass_relative_tolerance", + "minimum_reference_total": "input_mass_minimum_reference_total", + }, + ), + USGateSpec( + check="qrf_tail_concentration", + legacy_name="tail_concentration", + gate="tool:_qrf_tail_concentration_gate", + positional=(FRAME,), + arguments={"reviewed_exclusions": "qrf_tail_reviewed_exclusions"}, + returns="result_and_details", + pinned=_tool_pins( + "US_QRF_TAIL_CONCENTRATION_TOP_K", + "US_QRF_TAIL_CONCENTRATION_MAX_TOP_SHARE", + "US_QRF_TAIL_CONCENTRATION_MIN_NONZERO_RECORDS", + "US_QRF_SPARSE_NONZERO_SHARE_MAX", + ), + ), + USGateSpec( + check="stored_inputs_written", + legacy_name="stored_inputs_written", + gate="tool:_written_stored_input_verdict_mismatch", + positional=("dataset_path", "pre_export_stored_inputs"), + returns="failure_or_none", + ), + ) + + _SCOPE_SPECS: Mapping[str, Callable[[], tuple[USGateSpec, ...]]] = MappingProxyType( - {"us_base": _us_base_specs, "us_pool": _us_pool_specs} + { + "us_base": _us_base_specs, + "us_pool": _us_pool_specs, + "us_national": _us_national_specs, + } ) diff --git a/packages/microcosm-build/src/microcosm/build/us_runtime/gate_shadow.py b/packages/microcosm-build/src/microcosm/build/us_runtime/gate_shadow.py index fb4dfd20e8..b0b384e3aa 100644 --- a/packages/microcosm-build/src/microcosm/build/us_runtime/gate_shadow.py +++ b/packages/microcosm-build/src/microcosm/build/us_runtime/gate_shadow.py @@ -75,14 +75,17 @@ "LegacyStatus", "LegacyVerdict", "active_gate_shadow", + "arm_gate_shadow", "compare_verdicts", "current_gate_shadow", + "disarm_gate_shadow", "legacy_parameter_overrides", "shadow_check", "shadow_failures", "shadow_file_paths", "shadow_gate", "shadow_not_run", + "shadow_value", ] GATE_BATTERY_SHADOW_SCHEMA_VERSION = 1 @@ -629,6 +632,47 @@ def record_error(self, entry_id: str, message: str) -> None: with self._lock: self._shadow_errors.append(f"[{entry_id}] {message}") + def value( + self, + entry_id: str, + evaluate: Callable[[], Any], + context: EvidenceContext | Callable[[], EvidenceContext], + *, + verdict: Callable[[Any], LegacyVerdict], + refusals: tuple[type[BaseException], ...] = (), + site: str | None = None, + ) -> Any: + """:meth:`gate` for a check that returns something else. + + ``verdict`` reads today's verdict from the value; an exception of a + ``refusals`` type is the check's own failure, its message the line. + Either way today's value, or exception, comes back unchanged. + """ + + try: + result = evaluate() + except refusals as refusal: + self.check( + entry_id, + context, + LegacyVerdict.from_failures([str(refusal)]), + site=site, + ) + raise + except Exception as exc: + self.check(entry_id, context, LegacyVerdict.from_exception(exc), site=site) + raise + try: + legacy = verdict(result) + except Exception as exc: # noqa: BLE001 - recorded, never raised + self.record_error( + entry_id, + f"today's verdict is not comparable: {type(exc).__name__}: {exc}", + ) + return result + self.check(entry_id, context, legacy, site=site) + return result + def not_run(self, entry_id: str, reason: str, *, site: str | None = None) -> None: """Record that today's code did not evaluate ``entry_id`` on this build. @@ -1011,6 +1055,22 @@ def _comparison_payload( _ACTIVE: list[GateBatteryShadow] = [] +def arm_gate_shadow(shadow: GateBatteryShadow) -> None: + """Arm ``shadow`` until :func:`disarm_gate_shadow`; prefer the context + manager, :func:`active_gate_shadow`, where one block holds the run.""" + + with _ACTIVE_LOCK: + _ACTIVE.append(shadow) + + +def disarm_gate_shadow(shadow: GateBatteryShadow) -> None: + """Disarm a shadow :func:`arm_gate_shadow` armed; a no-op otherwise.""" + + with _ACTIVE_LOCK: + if shadow in _ACTIVE: + _ACTIVE.remove(shadow) + + @contextmanager def active_gate_shadow(shadow: GateBatteryShadow) -> Iterator[GateBatteryShadow]: """Arm ``shadow`` for the gate sites while the block runs. @@ -1076,6 +1136,25 @@ def shadow_failures( return shadow.failures(entry_id, evaluate, context, site=site) +def shadow_value( + entry_id: str, + evaluate: Callable[[], Any], + context: EvidenceContext | Callable[[], EvidenceContext], + *, + verdict: Callable[[Any], LegacyVerdict], + refusals: tuple[type[BaseException], ...] = (), + site: str | None = None, +) -> Any: + """:func:`shadow_gate` for a check that returns another value.""" + + shadow = current_gate_shadow(entry_id) + if shadow is None: + return evaluate() + return shadow.value( + entry_id, evaluate, context, verdict=verdict, refusals=refusals, site=site + ) + + def shadow_check( entry_id: str, context: EvidenceContext | Callable[[], EvidenceContext], diff --git a/packages/microcosm-build/tests/engine_free/us/test_us_battery_bindings.py b/packages/microcosm-build/tests/engine_free/us/test_us_battery_bindings.py index a56a8c20af..e2943728f8 100644 --- a/packages/microcosm-build/tests/engine_free/us/test_us_battery_bindings.py +++ b/packages/microcosm-build/tests/engine_free/us/test_us_battery_bindings.py @@ -39,9 +39,11 @@ ) from microcosm.build.us_runtime.gate_shadow import ( GateBatteryShadow, + LegacyVerdict, active_gate_shadow, shadow_file_paths, shadow_gate, + shadow_value, ) from test_support.microcosm_build.us_gate_shadow import ( load_us_gate_tool, @@ -49,7 +51,7 @@ ) #: The scopes PR 2 has declared so far, each wired in its tool. -WIRED_SCOPES = ("us_base", "us_pool") +WIRED_SCOPES = ("us_base", "us_pool", "us_national") #: Each scope's pinned digests. They move only when the scope's entries, #: parameters, phases or the manifest's policy line do. @@ -76,6 +78,22 @@ "cc1eeadceb9ea05efe81b5594c23832dd05e9fedbdd25c3cb1cfc52355c12047" ), }, + "us_national": { + "gates_manifest_sha256": ( + "db5578411c6a3a17ede8a28e85bfa641590016580e51307f1bd3da3b8fe4b7cd" + ), + "policy_sha256": ( + "fa4a2eb355e35271e2bc79be903649f333cd5ed62c899d359029db0ac5387ac6" + ), + "spec_fingerprint": ( + "898315b5b0fd8cd782c4238d5003008a5237bcac1e205c45676b089252b4a9b0" + ), + }, +} + +#: The arguments each tool's parser needs to report its defaults. +MINIMAL_ARGV = { + "us_national": ["--ledger-facts", "facts.jsonl", "--out", "out"], } @@ -174,11 +192,16 @@ def test_every_routed_threshold_equals_todays_default(scope) -> None: continue gate = resolve_reference(spec.gate, tool=binding.tool) defaults = inspect.signature(gate).parameters + parsed = ( + binding.tool["_parse_args"](MINIMAL_ARGV[scope]) if spec.flags else None + ) for key in spec.parameters: - assert _same(entry.parameters[key], defaults[key].default), ( - entry.id, - key, + today = ( + getattr(parsed, spec.flags[key]) + if key in spec.flags + else defaults[key].default ) + assert _same(entry.parameters[key], today), (entry.id, key) @pytest.mark.parametrize("scope", WIRED_SCOPES) @@ -266,12 +289,21 @@ def test_an_injected_fault_fails_both_verdicts_alike( target = tool if namespace == "tool" else vars(importlib.import_module(namespace)) lines = (f"{entry_id}: injected failure.",) + failing = GateResult(name=spec.legacy_name, passed=False, failures=lines) + def injected(*args, **kwargs): if fault == "crashes": raise KeyError(f"{entry_id}: injected crash") - if spec.returns_failures: - return list(lines) - return GateResult(name=spec.legacy_name, passed=False, failures=lines) + if spec.refusals: + raise spec.refusals[0](lines[0]) + return { + "result": failing, + "failures": list(lines), + "failures_and_details": (list(lines), {}), + "result_and_details": (failing, {}), + "failure_or_none": lines[0], + "mapping": {"passed": False, "failures": list(lines)}, + }[spec.returns] monkeypatch.setitem(target, gate_name, injected) evidence = _evidence(spec) @@ -284,13 +316,33 @@ def today(): ), ) + # Today's verdict as each kind of site reads it. + verdicts = { + "result": LegacyVerdict.from_result, + "receipt": lambda value: LegacyVerdict.from_failures(()), + "failures": LegacyVerdict.from_failures, + "failures_and_details": lambda value: LegacyVerdict.from_failures(value[0]), + "result_and_details": lambda value: LegacyVerdict.from_result(value[0]), + "failure_or_none": lambda value: LegacyVerdict.from_failures( + [] if value is None else [value] + ), + "mapping": lambda value: LegacyVerdict.from_failures( + () if value["passed"] else value["failures"] + ), + } + expected = (KeyError,) if fault == "crashes" else spec.refusals with active_gate_shadow(shadow): - if fault == "crashes": - with pytest.raises(KeyError): - shadow_gate(entry_id, today, evidence) + if expected: + with pytest.raises(expected): + shadow_value( + entry_id, + today, + evidence, + verdict=verdicts[spec.returns], + refusals=spec.refusals, + ) else: - result = shadow_gate(entry_id, today, evidence) - assert result.failures == lines + shadow_value(entry_id, today, evidence, verdict=verdicts[spec.returns]) outcome = shadow.outcome(entry_id) assert outcome is not None and outcome.status is GateStatus.FAILED assert outcome.entry.phase == entry.phase @@ -301,7 +353,7 @@ def today(): assert shadow.differences() == () -@pytest.mark.parametrize("scope", WIRED_SCOPES) +@pytest.mark.parametrize("scope", ["us_base", "us_pool"]) def test_the_shared_weights_audit_fails_both_verdicts_alike(tmp_path, scope) -> None: shadow = _shadow(tmp_path, scope) tool = vars(load_us_gate_tool(scope)) diff --git a/packages/microcosm-build/tests/engine_free/us/test_us_fiscal_refresh_gate_shadow.py b/packages/microcosm-build/tests/engine_free/us/test_us_fiscal_refresh_gate_shadow.py new file mode 100644 index 0000000000..4894286157 --- /dev/null +++ b/packages/microcosm-build/tests/engine_free/us/test_us_fiscal_refresh_gate_shadow.py @@ -0,0 +1,243 @@ +"""The national release runs the gate battery in shadow (microcosm#1585 item 11). + +``tools/build_us_fiscal_refresh_release.py`` arms the ``us_national`` scope +once the release id is known and finishes it in ``main``: after a finished +build (a verdict difference then fails it), at a dry run's deliberate stop +(which never fails it), or with today's exception. These tests drive those +seams with stand-in gates; no release is built. +""" + +from __future__ import annotations + +import importlib +import json +from types import SimpleNamespace + +import pytest + +from microcosm.build import GateResult +from microcosm.build.gate_battery import EvidenceContext +from microcosm.build.us_runtime.battery_bindings import ( + FRAME, + us_flag_overrides, + us_gate_specs, +) +from microcosm.build.us_runtime.gate_scopes import us_scoped_gate_manifest +from microcosm.build.us_runtime.gate_shadow import ( + GateBatteryShadowMismatchError, + LegacyVerdict, + shadow_file_paths, + shadow_value, +) +from test_support.microcosm_build.us_gate_shadow import load_us_gate_tool + + +@pytest.fixture +def release(monkeypatch): + module = load_us_gate_tool("us_national") + monkeypatch.setattr(module, "_ACTIVE_EMITTER", None, raising=False) + monkeypatch.setattr(module, "_ACTIVE_PROGRESS", None, raising=False) + yield module + module._finish_national_gate_shadow(stopped_at="test teardown") + + +def _args(tmp_path, **overrides): + values = { + "out": tmp_path / "out", + "dry_run_gates_report": None, + "allow_input_mass_drift": False, + "allow_ecps_parity_gaps": False, + "allow_input_coverage_gaps": False, + "allow_esi_premium_gaps": False, + "allow_unpinned_feed": False, + "allow_qrf_tail_concentration": False, + "evidence_release": False, + "input_mass_relative_tolerance": 0.5, + "input_mass_minimum_reference_total": 1e9, + } + values.update(overrides) + return SimpleNamespace(**values) + + +def _specs(): + return {spec.check: spec for spec in us_gate_specs("us_national")} + + +def _target(release, reference): + namespace, _, name = reference.partition(":") + if namespace == "tool": + return vars(release), name + return vars(importlib.import_module(namespace)), name + + +_VERDICTS = { + "result": LegacyVerdict.from_result, + "receipt": lambda value: LegacyVerdict.from_failures(()), + "failures": LegacyVerdict.from_failures, + "failures_and_details": lambda value: LegacyVerdict.from_failures(value[0]), + "result_and_details": lambda value: LegacyVerdict.from_result(value[0]), + "failure_or_none": lambda value: LegacyVerdict.from_failures( + [] if value is None else [value] + ), + "mapping": lambda value: LegacyVerdict.from_failures( + () if value["passed"] else value["failures"] + ), +} + + +def _stand_in_gates(monkeypatch, release, *, failing=()): + """Every national gate the bindings call, standing in with a verdict.""" + + for spec in _specs().values(): + target, name = _target(release, spec.gate) + failed = spec.check in failing + result = ( + GateResult( + name=spec.legacy_name, + passed=False, + failures=(f"{spec.check}: stand-in.",), + ) + if failed + else GateResult(name=spec.legacy_name, passed=True) + ) + lines = list(result.failures) + value = { + "result": result, + "receipt": {"passed": True}, + "failures": lines, + "failures_and_details": (lines, {}), + "result_and_details": (result, {}), + "failure_or_none": lines[0] if lines else None, + }[spec.returns] + monkeypatch.setitem(target, name, lambda *a, _value=value, **k: _value) + + +def _observe_every_entry(release, *, legacy_override=None): + specs = _specs() + for entry in us_scoped_gate_manifest("us_national").gates: + spec = specs[entry.parameters["check"]] + target, name = _target(release, spec.gate) + evidence = EvidenceContext( + frame=object() if spec.needs_frame else None, + artifacts={key: object() for key in spec.artifact_keys}, + ) + today = (legacy_override or {}).get(entry.id) or ( + lambda target=target, name=name, spec=spec, evidence=evidence: target[name]( + *( + evidence.frame if source == FRAME else evidence.artifacts[source] + for source in spec.positional + ) + ) + ) + shadow_value( + entry.id, + today, + evidence, + verdict=_VERDICTS[spec.returns], + refusals=spec.refusals, + ) + + +def _comparison(directory): + _, comparison = shadow_file_paths(directory, "us_national") + return json.loads(comparison.read_text()) + + +def test_main_finishes_the_shadow_a_build_armed(tmp_path, monkeypatch, release): + args = _args(tmp_path) + _stand_in_gates(monkeypatch, release) + + def build(argv): + release._start_national_gate_shadow(args, release_id="microcosm-us-test") + _observe_every_entry(release) + return None + + monkeypatch.setattr(release, "_main", build) + release.main([]) + payload = _comparison(args.out.resolve() / "gate_battery_shadow") + assert payload["run_completed"] is True + assert payload["verdict_difference"] is False + assert payload["phases_recorded"] == ["preflight", "assembled", "terminal"] + assert payload["release_id"] == "microcosm-us-test" + + +def test_a_verdict_difference_fails_a_finished_build(tmp_path, monkeypatch, release): + args = _args(tmp_path) + _stand_in_gates(monkeypatch, release, failing={"pregnancy_signal"}) + passing = GateResult(name="pregnancy_signal", passed=True) + + def build(argv): + release._start_national_gate_shadow(args, release_id="microcosm-us-test") + _observe_every_entry( + release, legacy_override={"us_national_pregnancy": lambda: passing} + ) + return None + + monkeypatch.setattr(release, "_main", build) + with pytest.raises(GateBatteryShadowMismatchError, match="us_national_pregnancy"): + release.main([]) + + +def test_a_dry_run_stops_on_purpose_and_never_fails(tmp_path, monkeypatch, release): + report = tmp_path / "dry" / "gates.json" + args = _args(tmp_path, dry_run_gates_report=report) + _stand_in_gates(monkeypatch, release) + + def dry_run(argv): + release._start_national_gate_shadow(args, release_id="microcosm-us-test") + return 0 + + monkeypatch.setattr(release, "_main", dry_run) + with pytest.raises(SystemExit) as stopped: + release.main([]) + assert stopped.value.code == 0 + # Beside the dry run's own report; a dry run creates no --out. + payload = _comparison(tmp_path / "dry" / "gates.gate_battery_shadow") + assert payload["run_completed"] is False + assert payload["stopped_at"].startswith("dry run") + assert payload["verdict_difference"] is False + assert not args.out.exists() + + +def test_todays_exception_propagates_and_the_shadow_records_it( + tmp_path, monkeypatch, release +): + args = _args(tmp_path) + + def refused(argv): + release._start_national_gate_shadow(args, release_id="microcosm-us-test") + raise RuntimeError("Release gates failed: something upstream") + + monkeypatch.setattr(release, "_main", refused) + with pytest.raises(RuntimeError, match="something upstream"): + release.main([]) + payload = _comparison(args.out.resolve() / "gate_battery_shadow") + assert payload["stopped_by"]["type"] == "RuntimeError" + assert payload["run_completed"] is False + + +def test_waivers_and_flag_overrides_are_recorded_by_entry(tmp_path, release): + gates = us_scoped_gate_manifest("us_national") + args = _args( + tmp_path, + allow_input_mass_drift=True, + allow_esi_premium_gaps=True, + input_mass_relative_tolerance=0.2, + ) + waivers = release._national_gate_waivers(args, gates) + assert waivers["us_national_input_mass_reference"] == ["--allow-input-mass-drift"] + assert waivers["us_national_esi_premiums_anchor"] == ["--allow-esi-premium-gaps"] + assert "us_national_ecps_parity" not in waivers + overrides = us_flag_overrides(gates, us_gate_specs("us_national"), args) + assert overrides == { + entry_id: {"relative_tolerance": {"declared": 0.5, "runtime": 0.2}} + for entry_id in ( + "us_national_input_mass_reference", + "us_national_export_input_mass", + ) + } + evidence = release._national_gate_waivers( + _args(tmp_path, evidence_release=True), gates + ) + assert evidence["us_national_release_gates"] == ["--evidence-release"] + assert "us_national_pregnancy" not in evidence diff --git a/packages/microcosm-build/tests/engine_free/us/test_us_gate_shadow.py b/packages/microcosm-build/tests/engine_free/us/test_us_gate_shadow.py index 994d9811fe..826e122523 100644 --- a/packages/microcosm-build/tests/engine_free/us/test_us_gate_shadow.py +++ b/packages/microcosm-build/tests/engine_free/us/test_us_gate_shadow.py @@ -592,7 +592,7 @@ def spm_lines(value, *, cap=1.0): gate="tool:spm_lines", positional=("value",), parameters=frozenset({"cap"}), - returns_failures=True, + returns="failures", ), ) gates = _manifest( diff --git a/test_support/microcosm_build/us_gate_shadow.py b/test_support/microcosm_build/us_gate_shadow.py index 5f22164501..9682b7657b 100644 --- a/test_support/microcosm_build/us_gate_shadow.py +++ b/test_support/microcosm_build/us_gate_shadow.py @@ -75,8 +75,10 @@ def _lambda_call_name(node: ast.AST) -> str | None: "shadow_failures", "shadow_check", "shadow_not_run", + "shadow_value", "_shadow_frame_gate", "_observe_frame_gate", + "_shadow_tail_survival", } ) diff --git a/tools/build_us_fiscal_refresh_release.py b/tools/build_us_fiscal_refresh_release.py index e560f543e1..37c011de01 100644 --- a/tools/build_us_fiscal_refresh_release.py +++ b/tools/build_us_fiscal_refresh_release.py @@ -69,6 +69,8 @@ calibration_epoch_stride, forwards_calibration_epoch, ) +from microcosm.build.country_spec import GatesManifest +from microcosm.build.gate_battery import EvidenceContext from microcosm.build.gates import ( GateResult, TargetFitRequirement, @@ -248,6 +250,11 @@ from microcosm.build.us_runtime.acs_release_predictors import ( join_acs_release_predictors, ) +from microcosm.build.us_runtime.battery_bindings import ( + us_flag_overrides, + us_gate_registry, + us_gate_specs, +) from microcosm.build.us_runtime.chronicle_feed import ( USChronicleFeed, load_us_chronicle_feed, @@ -284,6 +291,19 @@ fsa_student_loan_target_receipt, plan_fsa_student_loan_targets, ) +from microcosm.build.us_runtime.gate_scopes import us_scoped_gate_manifest +from microcosm.build.us_runtime.gate_shadow import ( + GATE_BATTERY_SHADOW_DIRECTORY, + GateBatteryShadow, + LegacyVerdict, + arm_gate_shadow, + disarm_gate_shadow, + shadow_failures, + shadow_file_paths, + shadow_gate, + shadow_not_run, + shadow_value, +) from microcosm.build.us_runtime.h5_io import ( AuthenticatedPoolH5, assert_h5_unchanged, @@ -7939,17 +7959,36 @@ def _input_mass_reference_gate( before calibration burns hours on a base that cannot score those reforms. """ if reference_h5 is None: + shadow_not_run( + "us_national_input_mass_reference", + "no --input-mass-reference-h5 was given", + ) return None input_variables = _engine_input_variables() reference_frame = load_us_frame(reference_h5) - return us_input_mass_parity_gate( - us_input_mass_totals(base_frame, columns=input_variables), - us_input_mass_totals(reference_frame, columns=input_variables), - carriers=us_line_32_carriers(base_frame, reference_frame), - candidate_name="base_frame", - reference_name=reference_h5.name, - relative_tolerance=relative_tolerance, - minimum_reference_total=minimum_reference_total, + candidate_totals = us_input_mass_totals(base_frame, columns=input_variables) + reference_totals = us_input_mass_totals(reference_frame, columns=input_variables) + carriers = us_line_32_carriers(base_frame, reference_frame) + return shadow_gate( + "us_national_input_mass_reference", + lambda: us_input_mass_parity_gate( + candidate_totals, + reference_totals, + carriers=carriers, + candidate_name="base_frame", + reference_name=reference_h5.name, + relative_tolerance=relative_tolerance, + minimum_reference_total=minimum_reference_total, + ), + lambda: EvidenceContext( + artifacts={ + "candidate_input_mass_totals": candidate_totals, + "reference_input_mass_totals": reference_totals, + "input_mass_carriers": carriers, + "input_mass_candidate_name": "base_frame", + "input_mass_reference_name": reference_h5.name, + } + ), ) @@ -8650,9 +8689,17 @@ def _record_qrf_tail_concentration_gate( """ try: register = _load_qrf_tail_concentration_exclusions(exclusions_path) - gate, surface = _qrf_tail_concentration_gate( - export_frame, - reviewed_exclusions=register, + gate, surface = shadow_value( + "us_national_qrf_tail_concentration", + lambda: _qrf_tail_concentration_gate( + export_frame, + reviewed_exclusions=register, + ), + lambda: EvidenceContext( + frame=export_frame, + artifacts={"qrf_tail_reviewed_exclusions": register}, + ), + verdict=lambda value: LegacyVerdict.from_result(value[0]), ) mismatch = _qrf_tail_register_mismatch(register, gate) surface = { @@ -9385,8 +9432,18 @@ def _enforce_ssi_take_up_delivery( written. """ - delivery_gate = us_ssi_take_up_delivery_gate( - diagnostics, targets=targets, enforcement_fences=enforcement_fences + delivery_gate = shadow_gate( + "us_national_ssi_take_up_delivery", + lambda: us_ssi_take_up_delivery_gate( + diagnostics, targets=targets, enforcement_fences=enforcement_fences + ), + lambda: EvidenceContext( + artifacts={ + "ssi_take_up_diagnostics": diagnostics, + "ssi_band_targets": targets, + "ssi_enforcement_fences": enforcement_fences, + } + ), ) if delivery_gate.passed: return [], delivery_gate @@ -13145,6 +13202,163 @@ def _is_release_refusal(error: BaseException) -> bool: return isinstance(error, Exception) +#: This tool's scope of us/gates.json, evaluated in shadow beside today's +#: gates (microcosm#1585 item 11, PR 2 of 4). +US_NATIONAL_GATE_SCOPE = "us_national" +_ACTIVE_GATE_SHADOW: GateBatteryShadow | None = None + +#: The waiver flags, each with the entries it waives today. +_NATIONAL_GATE_WAIVERS: tuple[tuple[str, str, tuple[str, ...]], ...] = ( + ( + "allow_input_mass_drift", + "--allow-input-mass-drift", + ("us_national_input_mass_reference", "us_national_export_input_mass"), + ), + ( + "allow_ecps_parity_gaps", + "--allow-ecps-parity-gaps", + ("us_national_ecps_parity",), + ), + ( + "allow_input_coverage_gaps", + "--allow-input-coverage-gaps", + ("us_national_release_input_coverage",), + ), + ( + "allow_esi_premium_gaps", + "--allow-esi-premium-gaps", + ( + "us_national_esi_anchor_feed", + "us_national_esi_premiums", + "us_national_esi_premiums_export", + "us_national_esi_premiums_anchor", + ), + ), + ("allow_unpinned_feed", "--allow-unpinned-feed", ("us_national_esi_anchor_feed",)), + ( + "allow_qrf_tail_concentration", + "--allow-qrf-tail-concentration", + ("us_national_qrf_tail_concentration",), + ), +) + + +def _national_gate_shadow_directory(args: argparse.Namespace) -> Path: + """Beside the outputs: ``/gate_battery_shadow``, never a release dir. + + A dry run writes no output directory, so its shadow goes beside its + report instead. + """ + + if args.dry_run_gates_report is not None: + report = Path(args.dry_run_gates_report).resolve() + return report.parent / f"{report.stem}.{GATE_BATTERY_SHADOW_DIRECTORY}" + return Path(args.out).resolve() / GATE_BATTERY_SHADOW_DIRECTORY + + +def _national_gate_waivers( + args: argparse.Namespace, gates: GatesManifest +) -> dict[str, list[str]]: + waivers: dict[str, list[str]] = {} + for destination, flag, entry_ids in _NATIONAL_GATE_WAIVERS: + if getattr(args, destination, False): + for entry_id in entry_ids: + waivers.setdefault(entry_id, []).append(flag) + if getattr(args, "evidence_release", False): + # The evidence tier owns its terminal failures instead of raising. + for entry in gates.gates: + if entry.phase == "terminal": + waivers.setdefault(entry.id, []).append("--evidence-release") + return waivers + + +def _start_national_gate_shadow(args: argparse.Namespace, *, release_id: str) -> None: + """Arm this run's gate battery in shadow (finished in :func:`main`).""" + + global _ACTIVE_GATE_SHADOW + _finish_national_gate_shadow(stopped_at="a previous run in this process") + gates = us_scoped_gate_manifest(US_NATIONAL_GATE_SCOPE) + report, comparison = shadow_file_paths( + _national_gate_shadow_directory(args), US_NATIONAL_GATE_SCOPE + ) + shadow = GateBatteryShadow( + gates, + scope=US_NATIONAL_GATE_SCOPE, + release_id=release_id, + report_path=report, + comparison_path=comparison, + registry=us_gate_registry(US_NATIONAL_GATE_SCOPE, tool=globals()), + waivers=_national_gate_waivers(args, gates), + overrides=us_flag_overrides(gates, us_gate_specs(US_NATIONAL_GATE_SCOPE), args), + ) + arm_gate_shadow(shadow) + _ACTIVE_GATE_SHADOW = shadow + + +def _finish_national_gate_shadow( + *, + stopped_by: BaseException | None = None, + stopped_at: str | None = None, +) -> None: + """Finish the armed shadow, if any; only a finished build can fail it.""" + + global _ACTIVE_GATE_SHADOW + shadow, _ACTIVE_GATE_SHADOW = _ACTIVE_GATE_SHADOW, None + if shadow is None: + return + disarm_gate_shadow(shadow) + if stopped_by is not None: + shadow.stop(stopped_by) + elif stopped_at is not None: + shadow.finish(stopped_at=stopped_at) + else: + shadow.finish() + + +def _shadow_frame_gate( + entry_id: str, evaluate: Callable[[], GateResult], frame: Frame +) -> GateResult: + """Today's frame signal gate, with the battery's entry beside it.""" + + return shadow_gate(entry_id, evaluate, lambda: EvidenceContext(frame=frame)) + + +def _shadow_exact_k_puf_tail_support_gate( + frame: Frame, support: np.ndarray +) -> GateResult: + """The exact-k arm's tail gate, with the battery's entry beside it.""" + + return shadow_gate( + "us_national_exact_k_puf_capital_gains_tail", + lambda: _exact_k_puf_tail_support_gate(frame, support), + lambda: EvidenceContext(frame=frame, artifacts={"exact_k_support": support}), + ) + + +def _shadow_tail_survival( + entry_id: str, candidate: Frame, selected: Frame +) -> dict[str, object]: + """Today's PUF tail survival check, observed: its refusal is its failure.""" + + return shadow_value( + entry_id, + lambda: assert_puf_capital_gains_tail_survives_selection( + candidate, + selected, + require_present=True, + ), + lambda: EvidenceContext( + frame=selected, + artifacts={ + "tail_candidate_frame": candidate, + "tail_require_present": True, + }, + ), + verdict=lambda receipt: LegacyVerdict.from_failures(()), + refusals=(ValueError,), + ) + + def main(argv: Sequence[str] | None = None) -> None: """Run the build and mark its staging run failed if it does not finish. @@ -13159,9 +13373,18 @@ def main(argv: Sequence[str] | None = None) -> None: global _ACTIVE_DRY_RUN _ACTIVE_DRY_RUN = None + _finish_national_gate_shadow(stopped_at="a previous run in this process") try: dry_run_exit = _main(argv) + _finish_national_gate_shadow( + stopped_at=( + "dry run: the release stops before target materialization" + if dry_run_exit is not None + else None + ) + ) except BaseException as error: + _finish_national_gate_shadow(stopped_by=error) dry_run = _ACTIVE_DRY_RUN if dry_run is not None and _is_release_refusal(error): # A dry run the release refuses before its stop point: the @@ -13286,7 +13509,11 @@ def _with_scf_education_debt_stage( time_period=PERIOD, scf_education_debt_donor=donor, ) - gate = us_scf_education_debt_signal_gate(base_frame) + gate = _shadow_frame_gate( + "us_national_scf_education_debt", + lambda: us_scf_education_debt_signal_gate(base_frame), + base_frame, + ) if not gate.passed: if telemetry is not None: telemetry.stage( @@ -13378,7 +13605,11 @@ def _check_us_esi_anchor_against_feed( either way and written to ``esi_premiums.json``. """ - mismatches = us_esi_premiums_anchor_feed_mismatches(facts) + mismatches = shadow_failures( + "us_national_esi_anchor_feed", + lambda: us_esi_premiums_anchor_feed_mismatches(facts), + lambda: EvidenceContext(artifacts={"ledger_facts": facts}), + ) if mismatches and not (allow_unpinned_feed or allow_esi_premium_gaps): raise SystemExit( "error: the meps_esi_premiums anchor differs from the Chronicle " @@ -13547,6 +13778,7 @@ def _main(argv: Sequence[str] | None = None) -> int | None: _assert_us_release_id(release_id, evidence_release=args.evidence_release) if args.exact_k is not None: _assert_exact_k_release_id(release_id, args.exact_k) + _start_national_gate_shadow(args, release_id=release_id) # Every build, exact-k builds included, writes its dataset and calibration # weights under the names its release's new builds declare # (microcosm#1570); the build ID carries the exact count. @@ -13582,7 +13814,11 @@ def _main(argv: Sequence[str] | None = None) -> int | None: # checked against the live PolicyEngine-US graph so a stale entry cannot mask # a real gap. assert_validation_leaf_registry_current() - validation_input_coverage_gate = us_validation_input_coverage_gate() + validation_input_coverage_gate = shadow_gate( + "us_national_validation_input_coverage", + lambda: us_validation_input_coverage_gate(), + EvidenceContext(), + ) if not validation_input_coverage_gate.passed: raise RuntimeError( "Release gates failed: " @@ -13604,10 +13840,22 @@ def _main(argv: Sequence[str] | None = None) -> int | None: # documented-absent). Such a pincer aborts every build AFTER the expensive # source stages — the stale TANF exclusion did exactly that on Build G and # Build I. Fail it here, in seconds. - register_consistency_gate = us_register_consistency_gate( - degenerate_reviewed_exclusions=US_DEGENERATE_INPUT_REVIEWED_EXCLUSIONS, - documented_absent_inputs=US_DOCUMENTED_ABSENT_INPUTS, - nonconstant_required_columns=US_HEALTH_INPUT_NONCONSTANT_COLUMNS, + register_consistency_gate = shadow_gate( + "us_national_register_consistency", + lambda: us_register_consistency_gate( + degenerate_reviewed_exclusions=US_DEGENERATE_INPUT_REVIEWED_EXCLUSIONS, + documented_absent_inputs=US_DOCUMENTED_ABSENT_INPUTS, + nonconstant_required_columns=US_HEALTH_INPUT_NONCONSTANT_COLUMNS, + ), + lambda: EvidenceContext( + artifacts={ + "degenerate_reviewed_exclusions": ( + US_DEGENERATE_INPUT_REVIEWED_EXCLUSIONS + ), + "documented_absent_inputs": US_DOCUMENTED_ABSENT_INPUTS, + "nonconstant_required_columns": US_HEALTH_INPUT_NONCONSTANT_COLUMNS, + } + ), ) if not register_consistency_gate.passed: raise RuntimeError( @@ -13710,7 +13958,11 @@ def _main(argv: Sequence[str] | None = None) -> int | None: # the one-surface parity contract until that stage is default. parity_registry = _without_opt_in_student_loan_targets(target_registry) assert_target_parity_manifest_current(registry=parity_registry) - target_parity_gate = us_release_target_parity_gate(parity_registry) + target_parity_gate = shadow_gate( + "us_national_target_parity", + lambda: us_release_target_parity_gate(parity_registry), + lambda: EvidenceContext(artifacts={"target_parity_registry": parity_registry}), + ) if not target_parity_gate.passed: raise RuntimeError( "Release gates failed: " @@ -13731,9 +13983,18 @@ def _main(argv: Sequence[str] | None = None) -> int | None: targets=ssi_band_targets, expected_sha256=args.ssi_take_up_prior_weight_basis_sha256, ) - target_profile_gate = target_profile_coverage_gate( - target_specs, - US_FISCAL_TARGET_COVERAGE_REQUIREMENTS, + target_profile_gate = shadow_gate( + "us_national_target_profile_coverage", + lambda: target_profile_coverage_gate( + target_specs, + US_FISCAL_TARGET_COVERAGE_REQUIREMENTS, + ), + lambda: EvidenceContext( + artifacts={ + "target_specs": target_specs, + "target_coverage_requirements": US_FISCAL_TARGET_COVERAGE_REQUIREMENTS, + } + ), ) if not target_profile_gate.passed: raise RuntimeError( @@ -13801,10 +14062,8 @@ def _main(argv: Sequence[str] | None = None) -> int | None: base_frame = _load_frame(base_h5, expected_sha256=base_dataset_sha256) else: base_frame = pool_frame - capital_gains_tail_presence = assert_puf_capital_gains_tail_survives_selection( - base_frame, - base_frame, - require_present=True, + capital_gains_tail_presence = _shadow_tail_survival( + "us_national_capital_gains_tail_presence", base_frame, base_frame ) if telemetry is not None: telemetry.stage( @@ -13845,7 +14104,11 @@ def _main(argv: Sequence[str] | None = None) -> int | None: "Verified measured ASEC LKWEEKS before selection and target " "materialization." ) - weeks_unemployed_gate = us_weeks_unemployed_signal_gate(base_frame) + weeks_unemployed_gate = _shadow_frame_gate( + "us_national_weeks_unemployed", + lambda: us_weeks_unemployed_signal_gate(base_frame), + base_frame, + ) if not weeks_unemployed_gate.passed: if telemetry is not None: telemetry.stage( @@ -13881,6 +14144,12 @@ def _main(argv: Sequence[str] | None = None) -> int | None: # ~57k support instead of the ~338k pool. selection_source, _selection_join_key = _resolve_selection_source(args) selection_source_payload: dict | None = None + if selection_source is None: + for entry_id in ( + "us_national_capital_gains_tail_retention", + "us_national_weeks_unemployed_post_selection", + ): + shadow_not_run(entry_id, "no frozen-support selection source was given") if selection_source is not None: if args.selection_mode != "frozen_support": raise ValueError( @@ -13901,10 +14170,10 @@ def _main(argv: Sequence[str] | None = None) -> int | None: ) selection_source_payload = selection_report.as_manifest() selection_source_payload["puf_capital_gains_tail_retention"] = ( - assert_puf_capital_gains_tail_survives_selection( + _shadow_tail_survival( + "us_national_capital_gains_tail_retention", selection_candidate_frame, base_frame, - require_present=True, ) ) if telemetry is not None: @@ -13915,8 +14184,10 @@ def _main(argv: Sequence[str] | None = None) -> int | None: n_base_candidates=selection_report.n_base_candidates, n_unmapped=selection_report.n_unmapped, ) - post_selection_weeks_unemployed_gate = us_weeks_unemployed_signal_gate( - base_frame + post_selection_weeks_unemployed_gate = _shadow_frame_gate( + "us_national_weeks_unemployed_post_selection", + lambda: us_weeks_unemployed_signal_gate(base_frame), + base_frame, ) if not post_selection_weeks_unemployed_gate.passed: if telemetry is not None: @@ -13993,9 +14264,16 @@ def _main(argv: Sequence[str] | None = None) -> int | None: target=non_sch_d_cgd_repair.get("target"), initial_estimate=non_sch_d_cgd_repair.get("initial_estimate"), ) - base_population_gate = _base_population_scale_gate( - base_frame, - mass_repair=base_population_repair, + base_population_gate = shadow_gate( + "us_national_base_population_scale", + lambda: _base_population_scale_gate( + base_frame, + mass_repair=base_population_repair, + ), + lambda: EvidenceContext( + frame=base_frame, + artifacts={"base_population_mass_repair": base_population_repair}, + ), ) if not base_population_gate.passed: if telemetry is not None: @@ -14015,7 +14293,11 @@ def _main(argv: Sequence[str] | None = None) -> int | None: ) if pool_frame is None: base_frame = with_us_qbi_input_reconciliation(base_frame) - qbi_inputs_gate = us_qbi_inputs_signal_gate(base_frame) + qbi_inputs_gate = _shadow_frame_gate( + "us_national_qbi_inputs", + lambda: us_qbi_inputs_signal_gate(base_frame), + base_frame, + ) if not qbi_inputs_gate.passed: if telemetry is not None: telemetry.stage( @@ -14032,7 +14314,11 @@ def _main(argv: Sequence[str] | None = None) -> int | None: for failure in qbi_inputs_gate.failures ) ) - farm_business_income_gate = us_farm_business_income_signal_gate(base_frame) + farm_business_income_gate = _shadow_frame_gate( + "us_national_farm_business_income", + lambda: us_farm_business_income_signal_gate(base_frame), + base_frame, + ) if not farm_business_income_gate.passed: if telemetry is not None: telemetry.stage( @@ -14049,7 +14335,11 @@ def _main(argv: Sequence[str] | None = None) -> int | None: for failure in farm_business_income_gate.failures ) ) - domestic_production_ald_gate = us_domestic_production_ald_signal_gate(base_frame) + domestic_production_ald_gate = _shadow_frame_gate( + "us_national_domestic_production_ald", + lambda: us_domestic_production_ald_signal_gate(base_frame), + base_frame, + ) if not domestic_production_ald_gate.passed: if telemetry is not None: telemetry.stage( @@ -14066,7 +14356,11 @@ def _main(argv: Sequence[str] | None = None) -> int | None: for failure in domestic_production_ald_gate.failures ) ) - child_support_gate = us_child_support_signal_gate(base_frame) + child_support_gate = _shadow_frame_gate( + "us_national_child_support", + lambda: us_child_support_signal_gate(base_frame), + base_frame, + ) if not child_support_gate.passed: if telemetry is not None: telemetry.stage( @@ -14083,7 +14377,11 @@ def _main(argv: Sequence[str] | None = None) -> int | None: for failure in child_support_gate.failures ) ) - disability_benefits_gate = us_disability_benefits_signal_gate(base_frame) + disability_benefits_gate = _shadow_frame_gate( + "us_national_disability_benefits", + lambda: us_disability_benefits_signal_gate(base_frame), + base_frame, + ) if not disability_benefits_gate.passed: if telemetry is not None: telemetry.stage( @@ -14100,7 +14398,11 @@ def _main(argv: Sequence[str] | None = None) -> int | None: for failure in disability_benefits_gate.failures ) ) - workers_compensation_gate = us_workers_compensation_signal_gate(base_frame) + workers_compensation_gate = _shadow_frame_gate( + "us_national_workers_compensation", + lambda: us_workers_compensation_signal_gate(base_frame), + base_frame, + ) if not workers_compensation_gate.passed: if telemetry is not None: telemetry.stage( @@ -14117,7 +14419,11 @@ def _main(argv: Sequence[str] | None = None) -> int | None: for failure in workers_compensation_gate.failures ) ) - educator_expense_gate = us_educator_expense_signal_gate(base_frame) + educator_expense_gate = _shadow_frame_gate( + "us_national_educator_expense", + lambda: us_educator_expense_signal_gate(base_frame), + base_frame, + ) if not educator_expense_gate.passed: if telemetry is not None: telemetry.stage( @@ -14134,7 +14440,11 @@ def _main(argv: Sequence[str] | None = None) -> int | None: for failure in educator_expense_gate.failures ) ) - form_4952_election_gate = us_form_4952_election_signal_gate(base_frame) + form_4952_election_gate = _shadow_frame_gate( + "us_national_form_4952_election", + lambda: us_form_4952_election_signal_gate(base_frame), + base_frame, + ) if not form_4952_election_gate.passed: if telemetry is not None: telemetry.stage( @@ -14151,7 +14461,11 @@ def _main(argv: Sequence[str] | None = None) -> int | None: for failure in form_4952_election_gate.failures ) ) - salt_refund_income_gate = us_salt_refund_income_signal_gate(base_frame) + salt_refund_income_gate = _shadow_frame_gate( + "us_national_salt_refund_income", + lambda: us_salt_refund_income_signal_gate(base_frame), + base_frame, + ) if not salt_refund_income_gate.passed: if telemetry is not None: telemetry.stage( @@ -14168,7 +14482,11 @@ def _main(argv: Sequence[str] | None = None) -> int | None: for failure in salt_refund_income_gate.failures ) ) - capital_gain_details_gate = us_capital_gain_details_signal_gate(base_frame) + capital_gain_details_gate = _shadow_frame_gate( + "us_national_capital_gain_details", + lambda: us_capital_gain_details_signal_gate(base_frame), + base_frame, + ) if not capital_gain_details_gate.passed: if telemetry is not None: telemetry.stage( @@ -14192,7 +14510,11 @@ def _main(argv: Sequence[str] | None = None) -> int | None: time_period=PERIOD, allow_existing_without_source=True, ) - childcare_gate = us_childcare_signal_gate(base_frame) + childcare_gate = _shadow_frame_gate( + "us_national_childcare", + lambda: us_childcare_signal_gate(base_frame), + base_frame, + ) if not childcare_gate.passed: if telemetry is not None: telemetry.stage( @@ -14216,7 +14538,11 @@ def _main(argv: Sequence[str] | None = None) -> int | None: time_period=PERIOD, allow_existing_without_source=True, ) - energy_subsidy_gate = us_energy_subsidy_signal_gate(base_frame) + energy_subsidy_gate = _shadow_frame_gate( + "us_national_energy_subsidy", + lambda: us_energy_subsidy_signal_gate(base_frame), + base_frame, + ) if not energy_subsidy_gate.passed: if telemetry is not None: telemetry.stage( @@ -14233,7 +14559,9 @@ def _main(argv: Sequence[str] | None = None) -> int | None: for failure in energy_subsidy_gate.failures ) ) - alimony_gate = us_alimony_signal_gate(base_frame) + alimony_gate = _shadow_frame_gate( + "us_national_alimony", lambda: us_alimony_signal_gate(base_frame), base_frame + ) if not alimony_gate.passed: if telemetry is not None: telemetry.stage( @@ -14250,7 +14578,11 @@ def _main(argv: Sequence[str] | None = None) -> int | None: for failure in alimony_gate.failures ) ) - casualty_loss_gate = us_casualty_loss_signal_gate(base_frame) + casualty_loss_gate = _shadow_frame_gate( + "us_national_casualty_loss", + lambda: us_casualty_loss_signal_gate(base_frame), + base_frame, + ) if not casualty_loss_gate.passed: if telemetry is not None: telemetry.stage( @@ -14267,7 +14599,11 @@ def _main(argv: Sequence[str] | None = None) -> int | None: for failure in casualty_loss_gate.failures ) ) - misc_itemized_gate = us_misc_itemized_signal_gate(base_frame) + misc_itemized_gate = _shadow_frame_gate( + "us_national_misc_itemized", + lambda: us_misc_itemized_signal_gate(base_frame), + base_frame, + ) if not misc_itemized_gate.passed: if telemetry is not None: telemetry.stage( @@ -14295,7 +14631,11 @@ def _main(argv: Sequence[str] | None = None) -> int | None: seed=args.seed, time_period=PERIOD, ) - retirement_contributions_gate = us_retirement_contributions_signal_gate(base_frame) + retirement_contributions_gate = _shadow_frame_gate( + "us_national_retirement_contributions", + lambda: us_retirement_contributions_signal_gate(base_frame), + base_frame, + ) if not retirement_contributions_gate.passed: if telemetry is not None: telemetry.stage( @@ -14323,7 +14663,11 @@ def _main(argv: Sequence[str] | None = None) -> int | None: seed=args.seed, time_period=PERIOD, ) - immigration_gate = us_immigration_composition_gate(base_frame) + immigration_gate = _shadow_frame_gate( + "us_national_immigration_composition", + lambda: us_immigration_composition_gate(base_frame), + base_frame, + ) if not immigration_gate.passed: if telemetry is not None: telemetry.stage( @@ -14351,7 +14695,9 @@ def _main(argv: Sequence[str] | None = None) -> int | None: seed=args.seed, time_period=PERIOD, ) - take_up_gate = us_take_up_signal_gate(base_frame) + take_up_gate = _shadow_frame_gate( + "us_national_take_up", lambda: us_take_up_signal_gate(base_frame), base_frame + ) if not take_up_gate.passed: if telemetry is not None: telemetry.stage( @@ -14378,7 +14724,11 @@ def _main(argv: Sequence[str] | None = None) -> int | None: seed=args.seed, time_period=PERIOD, ) - hours_worked_gate = us_hours_worked_signal_gate(base_frame) + hours_worked_gate = _shadow_frame_gate( + "us_national_hours_worked", + lambda: us_hours_worked_signal_gate(base_frame), + base_frame, + ) if not hours_worked_gate.passed: if telemetry is not None: telemetry.stage( @@ -14405,7 +14755,11 @@ def _main(argv: Sequence[str] | None = None) -> int | None: seed=args.seed, time_period=PERIOD, ) - snap_take_up_gate = us_snap_take_up_signal_gate(base_frame) + snap_take_up_gate = _shadow_frame_gate( + "us_national_snap_take_up", + lambda: us_snap_take_up_signal_gate(base_frame), + base_frame, + ) if not snap_take_up_gate.passed: if telemetry is not None: telemetry.stage( @@ -14433,7 +14787,11 @@ def _main(argv: Sequence[str] | None = None) -> int | None: seed=args.seed, time_period=PERIOD, ) - relationship_inputs_gate = us_relationship_inputs_signal_gate(base_frame) + relationship_inputs_gate = _shadow_frame_gate( + "us_national_relationship_inputs", + lambda: us_relationship_inputs_signal_gate(base_frame), + base_frame, + ) if not relationship_inputs_gate.passed: if telemetry is not None: telemetry.stage( @@ -14464,7 +14822,11 @@ def _main(argv: Sequence[str] | None = None) -> int | None: seed=args.seed, time_period=PERIOD, ) - spm_independence_role_gate = us_spm_independence_role_signal_gate(base_frame) + spm_independence_role_gate = _shadow_frame_gate( + "us_national_spm_independence_role", + lambda: us_spm_independence_role_signal_gate(base_frame), + base_frame, + ) if not spm_independence_role_gate.passed: if telemetry is not None: telemetry.stage( @@ -14492,7 +14854,11 @@ def _main(argv: Sequence[str] | None = None) -> int | None: seed=args.seed, time_period=PERIOD, ) - medicare_take_up_gate = us_medicare_take_up_signal_gate(base_frame) + medicare_take_up_gate = _shadow_frame_gate( + "us_national_medicare_take_up", + lambda: us_medicare_take_up_signal_gate(base_frame), + base_frame, + ) if not medicare_take_up_gate.passed: if telemetry is not None: telemetry.stage( @@ -14509,7 +14875,11 @@ def _main(argv: Sequence[str] | None = None) -> int | None: for failure in medicare_take_up_gate.failures ) ) - prior_year_income_gate = us_prior_year_income_signal_gate(base_frame) + prior_year_income_gate = _shadow_frame_gate( + "us_national_prior_year_income", + lambda: us_prior_year_income_signal_gate(base_frame), + base_frame, + ) if not prior_year_income_gate.passed: if telemetry is not None: telemetry.stage( @@ -14532,7 +14902,11 @@ def _main(argv: Sequence[str] | None = None) -> int | None: message="Verified restored adjacent-ASEC prior-year income inputs.", details=dict(prior_year_income_gate.details), ) - housing_inputs_gate = us_housing_inputs_signal_gate(base_frame) + housing_inputs_gate = _shadow_frame_gate( + "us_national_housing_inputs", + lambda: us_housing_inputs_signal_gate(base_frame), + base_frame, + ) if not housing_inputs_gate.passed: if telemetry is not None: telemetry.stage( @@ -14568,7 +14942,11 @@ def _main(argv: Sequence[str] | None = None) -> int | None: seed=args.seed, time_period=PERIOD, ) - retirement_distributions_gate = us_retirement_distributions_signal_gate(base_frame) + retirement_distributions_gate = _shadow_frame_gate( + "us_national_retirement_distributions", + lambda: us_retirement_distributions_signal_gate(base_frame), + base_frame, + ) early_terminal_gate_failures: list[str] = [] if not retirement_distributions_gate.passed: # A selected support is consume-only at this boundary. Preserve the @@ -14603,7 +14981,11 @@ def _main(argv: Sequence[str] | None = None) -> int | None: seed=args.seed, time_period=PERIOD, ) - eligibility_inputs_gate = us_eligibility_inputs_signal_gate(base_frame) + eligibility_inputs_gate = _shadow_frame_gate( + "us_national_eligibility_inputs", + lambda: us_eligibility_inputs_signal_gate(base_frame), + base_frame, + ) if not eligibility_inputs_gate.passed: if telemetry is not None: telemetry.stage( @@ -14634,7 +15016,11 @@ def _main(argv: Sequence[str] | None = None) -> int | None: seed=args.seed, time_period=PERIOD, ) - education_inputs_gate = us_education_inputs_signal_gate(base_frame) + education_inputs_gate = _shadow_frame_gate( + "us_national_education_inputs", + lambda: us_education_inputs_signal_gate(base_frame), + base_frame, + ) if not education_inputs_gate.passed: if telemetry is not None: telemetry.stage( @@ -14662,7 +15048,11 @@ def _main(argv: Sequence[str] | None = None) -> int | None: seed=args.seed, time_period=PERIOD, ) - pregnancy_gate = us_pregnancy_signal_gate(base_frame) + pregnancy_gate = _shadow_frame_gate( + "us_national_pregnancy", + lambda: us_pregnancy_signal_gate(base_frame), + base_frame, + ) if not pregnancy_gate.passed: if telemetry is not None: telemetry.stage( @@ -14679,8 +15069,10 @@ def _main(argv: Sequence[str] | None = None) -> int | None: for failure in pregnancy_gate.failures ) ) - reported_coverage_vintage_gate = us_reported_coverage_vintage_signal_gate( - base_frame + reported_coverage_vintage_gate = _shadow_frame_gate( + "us_national_reported_coverage_vintage", + lambda: us_reported_coverage_vintage_signal_gate(base_frame), + base_frame, ) if not reported_coverage_vintage_gate.passed: receipt_path = ( @@ -14717,7 +15109,11 @@ def _main(argv: Sequence[str] | None = None) -> int | None: seed=args.seed, time_period=PERIOD, ) - wic_claim_gate = us_wic_claim_signal_gate(base_frame) + wic_claim_gate = _shadow_frame_gate( + "us_national_wic_claim", + lambda: us_wic_claim_signal_gate(base_frame), + base_frame, + ) if not wic_claim_gate.passed: if telemetry is not None: telemetry.stage( @@ -14744,8 +15140,10 @@ def _main(argv: Sequence[str] | None = None) -> int | None: seed=args.seed, time_period=PERIOD, ) - snap_discretionary_exemption_gate = us_snap_discretionary_exemption_signal_gate( - base_frame + snap_discretionary_exemption_gate = _shadow_frame_gate( + "us_national_snap_discretionary_exemption", + lambda: us_snap_discretionary_exemption_signal_gate(base_frame), + base_frame, ) if not snap_discretionary_exemption_gate.passed: if telemetry is not None: @@ -14823,9 +15221,15 @@ def _main(argv: Sequence[str] | None = None) -> int | None: scf_donor=scf_wealth_donor, sipp_donor=sipp_financial_asset_donor, ) - scf_wealth_gate = us_scf_wealth_signal_gate( - base_frame, - require_sipp_blend=True, + scf_wealth_gate = shadow_gate( + "us_national_scf_wealth", + lambda: us_scf_wealth_signal_gate( + base_frame, + require_sipp_blend=True, + ), + lambda: EvidenceContext( + frame=base_frame, artifacts={"scf_require_sipp_blend": True} + ), ) if not scf_wealth_gate.passed: if telemetry is not None: @@ -14868,7 +15272,11 @@ def _main(argv: Sequence[str] | None = None) -> int | None: time_period=PERIOD, sipp_donor=ssi_disability_donor, ) - ssi_disability_gate = us_ssi_disability_criteria_signal_gate(base_frame) + ssi_disability_gate = _shadow_frame_gate( + "us_national_ssi_disability_criteria", + lambda: us_ssi_disability_criteria_signal_gate(base_frame), + base_frame, + ) if not ssi_disability_gate.passed: if telemetry is not None: telemetry.stage( @@ -14905,7 +15313,11 @@ def _main(argv: Sequence[str] | None = None) -> int | None: time_period=PERIOD, sipp_donor=head_start_donor, ) - head_start_gate = us_sipp_head_start_signal_gate(base_frame) + head_start_gate = _shadow_frame_gate( + "us_national_sipp_head_start", + lambda: us_sipp_head_start_signal_gate(base_frame), + base_frame, + ) if not head_start_gate.passed: if telemetry is not None: telemetry.stage( @@ -14954,8 +15366,17 @@ def _main(argv: Sequence[str] | None = None) -> int | None: reporter_source_ids=ssi_reporter_source_ids, prior_basis=ssi_take_up_prior_basis, ) - ssi_take_up_gate = us_ssi_take_up_gate( - ssi_take_up_stage_diagnostics, targets=ssi_band_targets + ssi_take_up_gate = shadow_gate( + "us_national_ssi_take_up", + lambda: us_ssi_take_up_gate( + ssi_take_up_stage_diagnostics, targets=ssi_band_targets + ), + lambda: EvidenceContext( + artifacts={ + "ssi_take_up_diagnostics": ssi_take_up_stage_diagnostics, + "ssi_band_targets": ssi_band_targets, + } + ), ) if not ssi_take_up_gate.passed: if telemetry is not None: @@ -15017,7 +15438,11 @@ def _main(argv: Sequence[str] | None = None) -> int | None: time_period=PERIOD, scf_auto_loan_donor=scf_auto_loan_donor, ) - scf_auto_loan_gate = us_scf_auto_loans_signal_gate(base_frame) + scf_auto_loan_gate = _shadow_frame_gate( + "us_national_scf_auto_loans", + lambda: us_scf_auto_loans_signal_gate(base_frame), + base_frame, + ) if not scf_auto_loan_gate.passed: if telemetry is not None: telemetry.stage( @@ -15049,6 +15474,11 @@ def _main(argv: Sequence[str] | None = None) -> int | None: else None ), ) + else: + shadow_not_run( + "us_national_scf_education_debt", + "the SCF education-debt stage runs only with --scf-education-debt", + ) if telemetry is not None: telemetry.stage( "sipp_vehicle_inputs", @@ -15069,7 +15499,11 @@ def _main(argv: Sequence[str] | None = None) -> int | None: time_period=PERIOD, sipp_donor=sipp_vehicle_donor, ) - sipp_vehicles_gate = us_sipp_vehicles_signal_gate(base_frame) + sipp_vehicles_gate = _shadow_frame_gate( + "us_national_sipp_vehicles", + lambda: us_sipp_vehicles_signal_gate(base_frame), + base_frame, + ) if not sipp_vehicles_gate.passed: if telemetry is not None: telemetry.stage( @@ -15105,7 +15539,11 @@ def _main(argv: Sequence[str] | None = None) -> int | None: time_period=PERIOD, sipp_donor=voluntary_filing_donor, ) - voluntary_filing_gate = us_voluntary_filing_signal_gate(base_frame) + voluntary_filing_gate = _shadow_frame_gate( + "us_national_voluntary_filing", + lambda: us_voluntary_filing_signal_gate(base_frame), + base_frame, + ) if not voluntary_filing_gate.passed: if telemetry is not None: telemetry.stage( @@ -15145,7 +15583,11 @@ def _main(argv: Sequence[str] | None = None) -> int | None: time_period=PERIOD, sipp_donor=sipp_tip_donor, ) - sipp_tips_gate = us_sipp_tips_signal_gate(base_frame) + sipp_tips_gate = _shadow_frame_gate( + "us_national_sipp_tips", + lambda: us_sipp_tips_signal_gate(base_frame), + base_frame, + ) if not sipp_tips_gate.passed: if telemetry is not None: telemetry.stage( @@ -15186,7 +15628,11 @@ def _main(argv: Sequence[str] | None = None) -> int | None: time_period=PERIOD, org_donor=org_wages_donor, ) - org_wages_gate = us_org_wages_signal_gate(base_frame) + org_wages_gate = _shadow_frame_gate( + "us_national_org_wages", + lambda: us_org_wages_signal_gate(base_frame), + base_frame, + ) if not org_wages_gate.passed: if telemetry is not None: telemetry.stage( @@ -15214,7 +15660,11 @@ def _main(argv: Sequence[str] | None = None) -> int | None: seed=args.seed, maximum_microsim_batch_size=args.maximum_microsim_batch_size, ) - health_input_gate = _health_input_signal_gate(base_frame) + health_input_gate = _shadow_frame_gate( + "us_national_health_input", + lambda: _health_input_signal_gate(base_frame), + base_frame, + ) if not health_input_gate.passed: if telemetry is not None: telemetry.stage( @@ -15246,7 +15696,13 @@ def _main(argv: Sequence[str] | None = None) -> int | None: substitutions=medicaid_enrollment_substitutions, maximum_microsim_batch_size=args.maximum_microsim_batch_size, ) - medicaid_take_up_gate = us_medicaid_take_up_gate(medicaid_take_up_diagnostics) + medicaid_take_up_gate = shadow_gate( + "us_national_medicaid_take_up", + lambda: us_medicaid_take_up_gate(medicaid_take_up_diagnostics), + lambda: EvidenceContext( + artifacts={"medicaid_take_up_diagnostics": medicaid_take_up_diagnostics} + ), + ) if not medicaid_take_up_gate.passed: if telemetry is not None: telemetry.stage( @@ -15274,7 +15730,13 @@ def _main(argv: Sequence[str] | None = None) -> int | None: seed=args.seed, maximum_microsim_batch_size=args.maximum_microsim_batch_size, ) - snap_state_take_up_gate = us_snap_state_take_up_gate(snap_state_take_up_diagnostics) + snap_state_take_up_gate = shadow_gate( + "us_national_snap_state_take_up", + lambda: us_snap_state_take_up_gate(snap_state_take_up_diagnostics), + lambda: EvidenceContext( + artifacts={"snap_state_take_up_diagnostics": snap_state_take_up_diagnostics} + ), + ) if not snap_state_take_up_gate.passed: if telemetry is not None: telemetry.stage( @@ -15305,7 +15767,11 @@ def _main(argv: Sequence[str] | None = None) -> int | None: time_period=PERIOD, maximum_microsim_batch_size=args.maximum_microsim_batch_size, ) - other_health_insurance_gate = us_other_health_insurance_signal_gate(base_frame) + other_health_insurance_gate = _shadow_frame_gate( + "us_national_other_health_insurance", + lambda: us_other_health_insurance_signal_gate(base_frame), + base_frame, + ) if not other_health_insurance_gate.passed: if telemetry is not None: telemetry.stage( @@ -15324,7 +15790,11 @@ def _main(argv: Sequence[str] | None = None) -> int | None: ) # microcosm#454: the meps_esi_premiums base stage owns the ESI employer # premium input; refuse a base that lacks or flattens it before the solve. - esi_premiums_base_gate = us_esi_premiums_signal_gate(base_frame) + esi_premiums_base_gate = _shadow_frame_gate( + "us_national_esi_premiums", + lambda: us_esi_premiums_signal_gate(base_frame), + base_frame, + ) if not esi_premiums_base_gate.passed and not args.allow_esi_premium_gaps: if telemetry is not None: telemetry.stage( @@ -15396,8 +15866,14 @@ def _main(argv: Sequence[str] | None = None) -> int | None: for failure in input_mass_reference_gate.failures ) ) - degenerate_input_gate = _degenerate_input_signal_gate( - base_frame, PolicyEngineUSEngine() + degenerate_input_engine = PolicyEngineUSEngine() + degenerate_input_gate = shadow_gate( + "us_national_degenerate_input", + lambda: _degenerate_input_signal_gate(base_frame, degenerate_input_engine), + lambda: EvidenceContext( + frame=base_frame, + artifacts={"policyengine_engine": degenerate_input_engine}, + ), ) if not degenerate_input_gate.passed: # Same degraded contract as the input-mass gate above: the gate @@ -15445,7 +15921,9 @@ def _main(argv: Sequence[str] | None = None) -> int | None: "ecps_parity_gate", message="Gating candidate layers against the incumbent eCPS reference.", ) - ecps_parity_gate = _ecps_parity_gate(base_frame) + ecps_parity_gate = _shadow_frame_gate( + "us_national_ecps_parity", lambda: _ecps_parity_gate(base_frame), base_frame + ) if not ecps_parity_gate.passed and not args.allow_ecps_parity_gaps: # Same degraded contract as the input-mass/degenerate gates above # (PR #557 round 3 finding 1): the pinned parity reference requires @@ -15769,6 +16247,12 @@ def _main(argv: Sequence[str] | None = None) -> int | None: calibration_runtime = _calibration_runtime() ladder_outcome = None exact_k_puf_tail_gate: GateResult | None = None + if args.exact_k is None: + for entry_id in ( + "us_national_exact_k_puf_capital_gains_tail", + "us_national_exact_k_frozen_register_fit", + ): + shadow_not_run(entry_id, "the exact-k gates run on the exact-k arm only") if args.exact_k is not None: if ( pool_original_household_ids is None @@ -15811,7 +16295,9 @@ def _main(argv: Sequence[str] | None = None) -> int | None: ) assert_exact_k_realized_count(ladder_outcome, args.exact_k) result = ladder_outcome.result - exact_k_puf_tail_gate = _exact_k_puf_tail_support_gate( + # A helper, not a lambda over target_frame: the frame is deleted + # below to free it, and a closure must not keep it alive. + exact_k_puf_tail_gate = _shadow_exact_k_puf_tail_support_gate( target_frame, ladder_outcome.support, ) @@ -16001,8 +16487,15 @@ def _main(argv: Sequence[str] | None = None) -> int | None: # weight-safe, so any downstream transform that corrupted the frozen # decisions fails the build here instead of shipping (PR #477 review # finding 3). The SSA-count miss itself stays scorecard-only. - final_ssi_take_up_gate = us_ssi_take_up_gate( - ssi_take_up_diagnostics, targets=ssi_band_targets + final_ssi_take_up_gate = shadow_gate( + "us_national_ssi_take_up_final", + lambda: us_ssi_take_up_gate(ssi_take_up_diagnostics, targets=ssi_band_targets), + lambda: EvidenceContext( + artifacts={ + "ssi_take_up_diagnostics": ssi_take_up_diagnostics, + "ssi_band_targets": ssi_band_targets, + } + ), ) # SSI gate failures join the #437 batched terminal gates instead of # raising here: an early raise destroyed the failed run's calibration @@ -16068,7 +16561,11 @@ def _main(argv: Sequence[str] | None = None) -> int | None: # rows, and a column nonconstant on the candidate base can flatten on the # selected support. try: - health_input_gate = _health_input_signal_gate(export_frame) + health_input_gate = _shadow_frame_gate( + "us_national_health_input_export", + lambda: _health_input_signal_gate(export_frame), + export_frame, + ) except Exception as error: # Degraded-mode guard (microcosm#547): record instead of masking; the # downstream gate-failure evaluation is itself guarded, so a None @@ -16081,8 +16578,10 @@ def _main(argv: Sequence[str] | None = None) -> int | None: f"recorded instead of masking earlier failures: {error}" ) try: - reported_coverage_vintage_gate = us_reported_coverage_vintage_signal_gate( - export_frame + reported_coverage_vintage_gate = _shadow_frame_gate( + "us_national_reported_coverage_vintage_export", + lambda: us_reported_coverage_vintage_signal_gate(export_frame), + export_frame, ) except Exception as error: if not early_terminal_gate_failures: @@ -16093,8 +16592,10 @@ def _main(argv: Sequence[str] | None = None) -> int | None: f"mode; recorded instead of masking earlier failures: {error}" ) try: - other_health_insurance_gate = us_other_health_insurance_signal_gate( - export_frame + other_health_insurance_gate = _shadow_frame_gate( + "us_national_other_health_insurance_export", + lambda: us_other_health_insurance_signal_gate(export_frame), + export_frame, ) except Exception as error: if not early_terminal_gate_failures: @@ -16115,7 +16616,11 @@ def _main(argv: Sequence[str] | None = None) -> int | None: for failure in other_health_insurance_gate.failures ) try: - esi_premiums_export_gate = us_esi_premiums_signal_gate(export_frame) + esi_premiums_export_gate = _shadow_frame_gate( + "us_national_esi_premiums_export", + lambda: us_esi_premiums_signal_gate(export_frame), + export_frame, + ) except Exception as error: if not early_terminal_gate_failures: raise @@ -16237,13 +16742,26 @@ def _main(argv: Sequence[str] | None = None) -> int | None: ) if current_target_surface is None: current_target_surface = target_surface_payload(result) - exact_k_incumbent_fit_gate = _exact_k_frozen_register_fit_gate( - result, - incumbent_diagnostics, - target_registry=registry, - target_loss_weights=target_loss_weights, - configured_loss_basis=target_loss_basis, - incumbent_loss_basis=incumbent_loss_basis, + exact_k_incumbent_fit_gate = shadow_gate( + "us_national_exact_k_frozen_register_fit", + lambda: _exact_k_frozen_register_fit_gate( + result, + incumbent_diagnostics, + target_registry=registry, + target_loss_weights=target_loss_weights, + configured_loss_basis=target_loss_basis, + incumbent_loss_basis=incumbent_loss_basis, + ), + lambda: EvidenceContext( + artifacts={ + "calibration_result": result, + "incumbent_diagnostics": incumbent_diagnostics, + "target_registry": registry, + "target_loss_weights": target_loss_weights, + "configured_loss_basis": target_loss_basis, + "incumbent_loss_basis": incumbent_loss_basis, + } + ), ) exact_k_ladder_provenance = _exact_k_ladder_manifest_payload( args=args, @@ -16264,24 +16782,36 @@ def _main(argv: Sequence[str] | None = None) -> int | None: None if args.allow_ecps_parity_gaps else ecps_parity_gate ) try: - gate_failures = _release_gate_failures( - result, - compilation, - target_profile_gate, - health_input_gate, - base_population_gate, - incumbent_diagnostics, - immigration_gate, - enforced_input_mass_reference_gate, - degenerate_input_gate, - ecps_parity_gate=enforced_ecps_parity_gate, - hours_worked_gate=hours_worked_gate, - snap_take_up_gate=snap_take_up_gate, - eligibility_inputs_gate=eligibility_inputs_gate, - pregnancy_gate=pregnancy_gate, - reported_coverage_vintage_gate=reported_coverage_vintage_gate, - snap_discretionary_exemption_gate=snap_discretionary_exemption_gate, - target_registry=registry, + release_gate_inputs = { + "target_profile_gate": target_profile_gate, + "health_input_gate": health_input_gate, + "base_population_gate": base_population_gate, + "incumbent_diagnostics": incumbent_diagnostics, + "immigration_gate": immigration_gate, + "input_mass_reference_gate": enforced_input_mass_reference_gate, + "degenerate_input_gate": degenerate_input_gate, + "ecps_parity_gate": enforced_ecps_parity_gate, + "hours_worked_gate": hours_worked_gate, + "snap_take_up_gate": snap_take_up_gate, + "eligibility_inputs_gate": eligibility_inputs_gate, + "pregnancy_gate": pregnancy_gate, + "reported_coverage_vintage_gate": reported_coverage_vintage_gate, + "snap_discretionary_exemption_gate": snap_discretionary_exemption_gate, + "target_registry": registry, + } + gate_failures = shadow_failures( + "us_national_release_gates", + lambda: _release_gate_failures(result, compilation, **release_gate_inputs), + lambda: EvidenceContext( + artifacts={ + "calibration_result": result, + "target_compilation": compilation, + **{ + f"release_gates_{name}": value + for name, value in release_gate_inputs.items() + }, + } + ), ) except Exception as error: # Degraded-mode guard (microcosm#547): the batch must still form and @@ -16416,8 +16946,13 @@ def _main(argv: Sequence[str] | None = None) -> int | None: # SPM-measured, so reform validation below reaches the engine's own # refusal; that is the declared, owner-checked, manifest-recorded choice an # evidence release makes about any pre-export gate, not a hole here. - spm_composition_failures, export_frame_spm_composition = ( - _spm_composition_gate_failures(export_frame, stage="export frame") + spm_composition_failures, export_frame_spm_composition = shadow_value( + "us_national_spm_composition", + lambda: _spm_composition_gate_failures(export_frame, stage="export frame"), + lambda: EvidenceContext( + frame=export_frame, artifacts={"spm_composition_stage": "export frame"} + ), + verdict=lambda value: LegacyVerdict.from_failures(value[0]), ) terminal_gate_failures.extend(spm_composition_failures) terminal_batch_telemetry.stage( @@ -16453,8 +16988,16 @@ def _main(argv: Sequence[str] | None = None) -> int | None: # build.built_with_model_package. Column names only: no rows are read, and # the verdict joins the one batched pre-export raise below, so a refusal # names every other failing gate too and mints no H5. - stored_input_failures_, export_frame_stored_inputs = _stored_input_gate_failures( - export_frame, stage=US_FISCAL_STORED_INPUTS_STAGE + stored_input_failures_, export_frame_stored_inputs = shadow_value( + "us_national_stored_inputs", + lambda: _stored_input_gate_failures( + export_frame, stage=US_FISCAL_STORED_INPUTS_STAGE + ), + lambda: EvidenceContext( + frame=export_frame, + artifacts={"stored_inputs_stage": US_FISCAL_STORED_INPUTS_STAGE}, + ), + verdict=lambda value: LegacyVerdict.from_failures(value[0]), ) terminal_gate_failures.extend(stored_input_failures_) terminal_batch_telemetry.stage( @@ -16510,8 +17053,12 @@ def _main(argv: Sequence[str] | None = None) -> int | None: # RED on today's asset-less artifacts by design (Deliverable 2 turns it # green); that is the gate doing its job, not a bug. try: - input_coverage_gate = us_release_input_coverage_gate( - export_frame, release_engine + input_coverage_gate = shadow_gate( + "us_national_release_input_coverage", + lambda: us_release_input_coverage_gate(export_frame, release_engine), + lambda: EvidenceContext( + frame=export_frame, artifacts={"release_engine": release_engine} + ), ) except Exception as exc: # Degraded mode only: with earlier pre-export failures on record, a @@ -16570,8 +17117,12 @@ def _main(argv: Sequence[str] | None = None) -> int | None: # evidence, with the base and export signal verdicts beside it so a waived # assignment failure stays on the record. try: - esi_premiums_anchor_gate = us_esi_premiums_anchor_gate( - export_frame, time_period=PERIOD + esi_premiums_anchor_gate = shadow_gate( + "us_national_esi_premiums_anchor", + lambda: us_esi_premiums_anchor_gate(export_frame, time_period=PERIOD), + lambda: EvidenceContext( + frame=export_frame, artifacts={"time_period": PERIOD} + ), ) except Exception as exc: if not terminal_gate_failures: @@ -16666,20 +17217,34 @@ def _main(argv: Sequence[str] | None = None) -> int | None: if args.export_input_mass_reference_h5 is not None else None ) - export_input_mass_gate = _export_input_mass_gate( - export_frame, - base_frame, - relative_tolerance=args.input_mass_relative_tolerance, - minimum_reference_total=args.input_mass_minimum_reference_total, - reference_frame=export_reference_frame, - reference_name=export_reference_name, - # Build H (microcosm#299): the two SOI-identified columns whose true - # target level provably cannot sit inside the live-default reference - # band (estate_income, non_sch_d_capital_gains). miscellaneous_income - # and both mortgage columns are deliberately NOT excluded so the run - # adjudicates their actual gate outcome. See the constant's band-math - # rationale above. - reviewed_exclusions=US_EXPORT_INPUT_MASS_REVIEWED_EXCLUSIONS, + # Build H (microcosm#299): the two SOI-identified columns whose true + # target level provably cannot sit inside the live-default reference + # band (estate_income, non_sch_d_capital_gains). miscellaneous_income + # and both mortgage columns are deliberately NOT excluded so the run + # adjudicates their actual gate outcome. See the constant's band-math + # rationale above. + export_input_mass_gate = shadow_gate( + "us_national_export_input_mass", + lambda: _export_input_mass_gate( + export_frame, + base_frame, + relative_tolerance=args.input_mass_relative_tolerance, + minimum_reference_total=args.input_mass_minimum_reference_total, + reference_frame=export_reference_frame, + reference_name=export_reference_name, + reviewed_exclusions=US_EXPORT_INPUT_MASS_REVIEWED_EXCLUSIONS, + ), + lambda: EvidenceContext( + frame=export_frame, + artifacts={ + "base_frame": base_frame, + "export_input_mass_reference_frame": export_reference_frame, + "export_input_mass_reference_name": export_reference_name, + "export_input_mass_reviewed_exclusions": ( + US_EXPORT_INPUT_MASS_REVIEWED_EXCLUSIONS + ), + }, + ), ) except Exception as exc: # Same degraded-mode contract as the coverage gate above. @@ -16854,8 +17419,20 @@ def _main(argv: Sequence[str] | None = None) -> int | None: # writer's output; the written bytes are graded whatever the gate reached # and must earn the same verdict (no refusal, if the gate could not # evaluate). - stored_input_premise_failure = _written_stored_input_verdict_mismatch( - dataset_path, export_frame_stored_inputs + stored_input_premise_failure = shadow_value( + "us_national_stored_inputs_written", + lambda: _written_stored_input_verdict_mismatch( + dataset_path, export_frame_stored_inputs + ), + lambda: EvidenceContext( + artifacts={ + "dataset_path": dataset_path, + "pre_export_stored_inputs": export_frame_stored_inputs, + } + ), + verdict=lambda mismatch: LegacyVerdict.from_failures( + [] if mismatch is None else [mismatch] + ), ) if stored_input_premise_failure is not None: raise RuntimeError(stored_input_premise_failure) From 85c1289d7c139cc834465271c69e3d0da91c18b9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mar=C3=ADa=20Juaristi?= <127882282+juaristi22@users.noreply.github.com> Date: Sun, 15 Nov 2026 14:27:23 +0000 Subject: [PATCH 06/31] Declare ACS local's gates and run them in shadow, stage by stage (us_local) PR 2 of 4 for microcosm#1585 item 11. us_local holds 24 gates of tools/build_us_acs_local_release.py: the staging-frame checks at materialize and calibrate (local hours, the self-employment identity, and SSI/Medicaid take-up), finalize's gate-function entries and its district ESS entry, and package's re-grades of the bytes it packages. Its stages may run as separate processes, as on Modal, so each stage saves what it observed to /gate_battery_shadow, and the scope's report and comparison there are rebuilt from every stage saved so far after each one. Only a finished package stage decides; rerunning a stage discards its own and every later stage's observations. Nothing goes into the release directory, whose *.json files its checksum ledger and manifest take in, and gate_summary.json, its raises and its fields are as before. The district ESS entry is declared diagnostic, as a default run treats it; --district-ess-gate-blocking reaches the battery as that run's own setting, and its two floors are flags declared at their defaults. Gates imported inside the finalize stage are bound to their package modules. Not declared: the five staging-receipt refusals (they re-read verdicts the staging build recorded), finalize's inline calibration and consumer-ready criteria, and its report-only entries. Co-Authored-By: Claude Opus 5.5 --- .../src/microcosm/build/us/gates.json | 268 ++++++++++++ .../build/us_runtime/battery_bindings.py | 159 +++++++ .../us/test_us_acs_local_gate_shadow.py | 161 +++++++ .../us/test_us_battery_bindings.py | 23 +- .../microcosm_build/us_gate_shadow.py | 120 +++++ tools/build_us_acs_local_release.py | 411 ++++++++++++++++-- 6 files changed, 1093 insertions(+), 49 deletions(-) create mode 100644 packages/microcosm-build/tests/engine_free/us/test_us_acs_local_gate_shadow.py diff --git a/packages/microcosm-build/src/microcosm/build/us/gates.json b/packages/microcosm-build/src/microcosm/build/us/gates.json index 9383733dfa..05840bf1e5 100644 --- a/packages/microcosm-build/src/microcosm/build/us/gates.json +++ b/packages/microcosm-build/src/microcosm/build/us/gates.json @@ -2224,6 +2224,274 @@ "check": "stored_inputs_written" }, "notes": "US national release (tools/build_us_fiscal_refresh_release.py): the written H5's stored inputs are the ones the pre-export gate graded. Raises at once today, after the H5 write." + }, + { + "id": "us_local_hours_materialize", + "gate": "stage_health", + "phase": "assembled", + "criticality": "release_blocking", + "parameters": { + "check": "local_hours_staging" + }, + "notes": "US ACS local release (tools/build_us_acs_local_release.py): local hours on the staging frame as materialize loads it. Its refusal exits at once." + }, + { + "id": "us_local_self_employment_identity_materialize", + "gate": "stage_health", + "phase": "assembled", + "criticality": "release_blocking", + "parameters": { + "check": "self_employment_identity" + }, + "notes": "US ACS local release (tools/build_us_acs_local_release.py): the ACS self-employment leaves add to SEMP on the staging frame. Its refusal exits at once." + }, + { + "id": "us_local_ssi_medicaid_take_up_materialize", + "gate": "stage_health", + "phase": "assembled", + "criticality": "release_blocking", + "parameters": { + "check": "ssi_medicaid_take_up_signal", + "residual_relative_tolerance": 1e-09, + "saturated_relative_tolerance": 1e-06 + }, + "notes": "US ACS local release (tools/build_us_acs_local_release.py): ACS SSI and Medicaid take-up after materialize assigns them; the verdict is recorded in run_identity.json. Exits at once on failure." + }, + { + "id": "us_local_hours_calibrate", + "gate": "stage_health", + "phase": "assembled", + "criticality": "release_blocking", + "parameters": { + "check": "local_hours_staging" + }, + "notes": "US ACS local release (tools/build_us_acs_local_release.py): local hours again on a fresh staging frame, when calibrate writes the calibrated artifact. Its refusal exits at once." + }, + { + "id": "us_local_self_employment_identity_calibrate", + "gate": "stage_health", + "phase": "assembled", + "criticality": "release_blocking", + "parameters": { + "check": "self_employment_identity" + }, + "notes": "US ACS local release (tools/build_us_acs_local_release.py): the self-employment identity again, when calibrate writes the calibrated artifact. Its refusal exits at once." + }, + { + "id": "us_local_hours_finalize", + "gate": "stage_health", + "phase": "terminal", + "criticality": "release_blocking", + "parameters": { + "check": "local_hours_signal" + }, + "notes": "US ACS local release (tools/build_us_acs_local_release.py): local hours on the calibrated H5. Finalize collects it into gate_summary.json, writes the file, then raises on a hard failure." + }, + { + "id": "us_local_puma_ladder", + "gate": "stage_health", + "phase": "terminal", + "criticality": "release_blocking", + "parameters": { + "check": "puma_ladder", + "assign_tract": false, + "nyc_share_bounds": [ + 0.005, + 0.06 + ], + "nyc_share_of_new_york_bounds": [ + 0.2, + 0.65 + ] + }, + "notes": "US ACS local release (tools/build_us_acs_local_release.py): the PUMA ladder on the calibrated households. Finalize collects it into gate_summary.json, writes the file, then raises on a hard failure. Its gate_summary.json key is us_puma_ladder_gate." + }, + { + "id": "us_local_block_location", + "gate": "stage_health", + "phase": "terminal", + "criticality": "release_blocking", + "parameters": { + "check": "block_location" + }, + "notes": "US ACS local release (tools/build_us_acs_local_release.py): every geography equals its block's ladder lookup, on block_v1 staging only. Finalize collects it into gate_summary.json, writes the file, then raises on a hard failure." + }, + { + "id": "us_local_hours_worked", + "gate": "stage_health", + "phase": "terminal", + "criticality": "release_blocking", + "parameters": { + "check": "hours_worked_signal", + "worked_share_band": [ + 0.35, + 0.62 + ], + "mean_weekly_hours_band": [ + 30.0, + 45.0 + ] + }, + "notes": "US ACS local release (tools/build_us_acs_local_release.py): hours worked over the two pool hours columns. Finalize collects it into gate_summary.json, writes the file, then raises on a hard failure." + }, + { + "id": "us_local_take_up", + "gate": "stage_health", + "phase": "terminal", + "criticality": "release_blocking", + "parameters": { + "check": "take_up_signal", + "medicare_aged_share_floor": 0.8 + }, + "notes": "US ACS local release (tools/build_us_acs_local_release.py): SNAP and TANF take-up on both spines. Finalize collects it into gate_summary.json, writes the file, then raises on a hard failure." + }, + { + "id": "us_local_immigration", + "gate": "stage_health", + "phase": "terminal", + "criticality": "release_blocking", + "parameters": { + "check": "immigration_signal" + }, + "notes": "US ACS local release (tools/build_us_acs_local_release.py): immigration labels and entry clocks. Finalize collects it into gate_summary.json, writes the file, then raises on a hard failure." + }, + { + "id": "us_local_work_disability", + "gate": "stage_health", + "phase": "terminal", + "criticality": "release_blocking", + "parameters": { + "check": "work_disability_signal" + }, + "notes": "US ACS local release (tools/build_us_acs_local_release.py): the native ACS disability items, with their staging receipt. Finalize collects it into gate_summary.json, writes the file, then raises on a hard failure." + }, + { + "id": "us_local_income_transfer", + "gate": "stage_health", + "phase": "terminal", + "criticality": "release_blocking", + "parameters": { + "check": "income_transfer_signal" + }, + "notes": "US ACS local release (tools/build_us_acs_local_release.py): the transferred ACS income leaves, with their staging receipt. Finalize collects it into gate_summary.json, writes the file, then raises on a hard failure." + }, + { + "id": "us_local_ssi_disability", + "gate": "stage_health", + "phase": "terminal", + "criticality": "release_blocking", + "parameters": { + "check": "ssi_disability_signal" + }, + "notes": "US ACS local release (tools/build_us_acs_local_release.py): the ACS SSI disability criteria, with their staging receipt. Finalize collects it into gate_summary.json, writes the file, then raises on a hard failure." + }, + { + "id": "us_local_ssi_medicaid_take_up_finalize", + "gate": "stage_health", + "phase": "terminal", + "criticality": "release_blocking", + "parameters": { + "check": "ssi_medicaid_take_up_signal", + "residual_relative_tolerance": 1e-09, + "saturated_relative_tolerance": 1e-06 + }, + "notes": "US ACS local release (tools/build_us_acs_local_release.py): ACS SSI and Medicaid take-up on the calibrated bytes. Finalize collects it into gate_summary.json, writes the file, then raises on a hard failure." + }, + { + "id": "us_local_receipt_anchors", + "gate": "stage_health", + "phase": "terminal", + "criticality": "release_blocking", + "parameters": { + "check": "receipt_anchor_signal", + "acs_snap_household_share_band": [ + 0.09, + 0.15 + ] + }, + "notes": "US ACS local release (tools/build_us_acs_local_release.py): SNAP reporters are the native household FS. Finalize collects it into gate_summary.json, writes the file, then raises on a hard failure." + }, + { + "id": "us_local_reviewed_fill_consumers_finalize", + "gate": "stage_health", + "phase": "terminal", + "criticality": "release_blocking", + "parameters": { + "check": "reviewed_fill_consumers" + }, + "notes": "US ACS local release (tools/build_us_acs_local_release.py): every reviewed default fill both engine passes applied has its register entry and consumer notes. Finalize collects it into gate_summary.json, writes the file, then raises on a hard failure." + }, + { + "id": "us_local_district_ess_collapse", + "gate": "stage_health", + "phase": "terminal", + "criticality": "diagnostic", + "parameters": { + "check": "district_ess_collapse", + "relative_floor": 0.25, + "absolute_floor": 15.0 + }, + "notes": "US ACS local release (tools/build_us_acs_local_release.py): congressional districts keep their Kish ESS against the design weights. Report-only unless --district-ess-gate-blocking, which the shadow passes to the battery as the run's own; its floors are flags, and the entry declares their defaults." + }, + { + "id": "us_local_stored_inputs", + "gate": "stage_health", + "phase": "terminal", + "criticality": "release_blocking", + "parameters": { + "check": "stored_inputs" + }, + "notes": "US ACS local release (tools/build_us_acs_local_release.py): the artifact stores no model input the installed engine lacks. Package re-grades the bytes it packages and raises at once." + }, + { + "id": "us_local_work_experience_inputs", + "gate": "stage_health", + "phase": "terminal", + "criticality": "release_blocking", + "parameters": { + "check": "work_experience_inputs" + }, + "notes": "US ACS local release (tools/build_us_acs_local_release.py): the occupation and work-experience inputs are complete. Package re-grades the bytes it packages and raises at once." + }, + { + "id": "us_local_spm_measurement", + "gate": "stage_health", + "phase": "terminal", + "criticality": "release_blocking", + "parameters": { + "check": "spm_measurement" + }, + "notes": "US ACS local release (tools/build_us_acs_local_release.py): the engine the release records can measure SPM on the bytes. Package re-grades the bytes it packages and raises at once." + }, + { + "id": "us_local_hours_package", + "gate": "stage_health", + "phase": "terminal", + "criticality": "release_blocking", + "parameters": { + "check": "local_hours_signal" + }, + "notes": "US ACS local release (tools/build_us_acs_local_release.py): local hours on the packaged bytes. Package re-grades the bytes it packages and raises at once." + }, + { + "id": "us_local_self_employment_identity_package", + "gate": "stage_health", + "phase": "terminal", + "criticality": "release_blocking", + "parameters": { + "check": "self_employment_identity" + }, + "notes": "US ACS local release (tools/build_us_acs_local_release.py): the self-employment identity on the packaged bytes. Package re-grades the bytes it packages and raises at once." + }, + { + "id": "us_local_reviewed_fill_consumers_package", + "gate": "stage_health", + "phase": "terminal", + "criticality": "release_blocking", + "parameters": { + "check": "reviewed_fill_consumers" + }, + "notes": "US ACS local release (tools/build_us_acs_local_release.py): the reviewed fills against the packaged register. Package re-grades the bytes it packages and raises at once." } ] } diff --git a/packages/microcosm-build/src/microcosm/build/us_runtime/battery_bindings.py b/packages/microcosm-build/src/microcosm/build/us_runtime/battery_bindings.py index 98bbc5da09..c902774a41 100644 --- a/packages/microcosm-build/src/microcosm/build/us_runtime/battery_bindings.py +++ b/packages/microcosm-build/src/microcosm/build/us_runtime/battery_bindings.py @@ -1289,11 +1289,170 @@ def _us_national_specs() -> tuple[USGateSpec, ...]: ) +def _us_local_specs() -> tuple[USGateSpec, ...]: + refuses = (SystemExit,) + return ( + # Staging-frame checks at materialize and calibrate: the tool's own + # refusal helpers, whose SystemExit is the failure. + USGateSpec( + check="local_hours_staging", + legacy_name="local_hours_staging", + gate="tool:_require_local_hours", + positional=(FRAME, "staging_summary"), + refusals=refuses, + returns="receipt", + ), + USGateSpec( + check="self_employment_identity", + legacy_name="acs_self_employment_identity", + gate="tool:_require_acs_self_employment_identity", + positional=(FRAME,), + refusals=refuses, + returns="receipt", + ), + USGateSpec( + check="ssi_medicaid_take_up_signal", + legacy_name="acs_local_ssi_medicaid_take_up_signal", + gate="tool:acs_local_ssi_medicaid_take_up_signal_gate", + positional=(FRAME,), + arguments={"receipt": "ssi_medicaid_receipt"}, + pinned=_pins( + "acs_local_ssi_medicaid_take_up", + "_RESIDUAL_RELATIVE_TOLERANCE", + "_SATURATED_RELATIVE_TOLERANCE", + ), + ), + # The calibrated artifact's gates at finalize, and package's re-checks. + USGateSpec( + check="local_hours_signal", + legacy_name="acs_local_hours_signal", + gate="tool:_local_hours_gate", + positional=(FRAME, "staging_summary"), + ), + USGateSpec( + # Imported inside the finalize stage, so not a tool global; nor + # are the hours gate and the block-location gate below. + check="puma_ladder", + legacy_name="us_puma_ladder", + gate=f"{_US}.puma_ladder:us_puma_ladder_gate", + positional=("household", "household_weights"), + parameters=_PUMA_LADDER_KEYWORDS, + ), + USGateSpec( + check="block_location", + legacy_name="us_block_location", + gate=f"{_US}.block_location:us_block_location_gate", + positional=("household", "location_ladder"), + ), + USGateSpec( + check="hours_worked_signal", + legacy_name="hours_worked_signal", + gate=f"{_US}.hours_worked:us_hours_worked_signal_gate", + positional=(FRAME,), + arguments={"required_columns": "hours_required_columns"}, + pinned=_pins( + "hours_worked", "_WORKED_SHARE_BAND", "_MEAN_WEEKLY_HOURS_BAND" + ), + ), + USGateSpec( + check="take_up_signal", + legacy_name="acs_local_take_up_signal", + gate="tool:acs_local_take_up_signal_gate", + positional=(FRAME,), + pinned=_pins("acs_local_take_up", "_MEDICARE_AGED_SHARE_FLOOR"), + ), + USGateSpec( + check="immigration_signal", + legacy_name="acs_local_immigration_signal", + gate="tool:acs_local_immigration_signal_gate", + positional=(FRAME,), + ), + USGateSpec( + check="work_disability_signal", + legacy_name="acs_local_work_disability_signal", + gate="tool:acs_local_work_disability_signal_gate", + positional=(FRAME,), + arguments={ + "receipt": "work_disability_receipt", + "require_weeks_worked": "require_weeks_worked", + }, + ), + USGateSpec( + check="income_transfer_signal", + legacy_name="acs_local_income_transfer_signal", + gate="tool:acs_local_income_transfer_signal_gate", + positional=(FRAME,), + arguments={"receipt": "income_transfer_receipt"}, + ), + USGateSpec( + check="ssi_disability_signal", + legacy_name="acs_local_ssi_disability_signal", + gate="tool:acs_local_ssi_disability_signal_gate", + positional=(FRAME,), + arguments={"receipt": "ssi_disability_receipt"}, + ), + USGateSpec( + check="receipt_anchor_signal", + legacy_name="acs_local_receipt_anchor_signal", + gate="tool:acs_local_receipt_anchor_signal_gate", + positional=(FRAME,), + arguments={"receipt": "receipt_anchors_receipt"}, + pinned=_pins("acs_local_receipt_anchors", "ACS_SNAP_HOUSEHOLD_SHARE_BAND"), + ), + USGateSpec( + check="reviewed_fill_consumers", + legacy_name="acs_local_reviewed_fill_consumers", + gate="tool:_reviewed_fill_consumer_gate", + positional=("fill_manifests",), + arguments={"document": "fill_register"}, + ), + USGateSpec( + check="district_ess_collapse", + legacy_name="district_ess_collapse", + gate="tool:district_ess_collapse_gate", + positional=("weight_origin",), + arguments={"blocking": "district_ess_blocking"}, + parameters=frozenset({"relative_floor", "absolute_floor"}), + flags={ + "relative_floor": "district_ess_relative_floor", + "absolute_floor": "district_ess_floor", + }, + returns="mapping", + ), + USGateSpec( + check="stored_inputs", + legacy_name="stored_inputs", + gate="tool:_require_stored_inputs", + positional=("calibrated_h5",), + refusals=refuses, + returns="receipt", + ), + USGateSpec( + check="work_experience_inputs", + legacy_name="work_experience_inputs", + gate="tool:require_us_occupation_and_work_experience_inputs", + positional=("person",), + arguments={"label": "work_experience_label"}, + refusals=(ValueError,), + returns="receipt", + ), + USGateSpec( + check="spm_measurement", + legacy_name="spm_measurement_composition", + gate="tool:_require_spm_measurement", + positional=(FRAME,), + refusals=refuses, + returns="receipt", + ), + ) + + _SCOPE_SPECS: Mapping[str, Callable[[], tuple[USGateSpec, ...]]] = MappingProxyType( { "us_base": _us_base_specs, "us_pool": _us_pool_specs, "us_national": _us_national_specs, + "us_local": _us_local_specs, } ) diff --git a/packages/microcosm-build/tests/engine_free/us/test_us_acs_local_gate_shadow.py b/packages/microcosm-build/tests/engine_free/us/test_us_acs_local_gate_shadow.py new file mode 100644 index 0000000000..498a52fbe8 --- /dev/null +++ b/packages/microcosm-build/tests/engine_free/us/test_us_acs_local_gate_shadow.py @@ -0,0 +1,161 @@ +"""ACS local runs the gate battery in shadow, stage by stage (#1585 item 11). + +``tools/build_us_acs_local_release.py`` may run each ``--stage`` as its own +process, so every stage saves what it observed beside the checkpoint and the +scope's report and comparison are rebuilt from every stage saved so far. +Only a finished package stage decides. These tests drive the stage seam with +stand-in gates; no stage runs. +""" + +from __future__ import annotations + +import json +from types import SimpleNamespace + +import pytest + +from microcosm.build.gates import GateResult +from microcosm.build.us_runtime.gate_scopes import us_scoped_gate_manifest +from microcosm.build.us_runtime.gate_shadow import ( + GateBatteryShadowMismatchError, + shadow_file_paths, + shadow_not_run, +) +from test_support.microcosm_build.us_gate_shadow import ( + load_us_gate_tool, + observe_entries, + stand_in_gates, +) + +#: Which stage evaluates each entry (the qa stage has none). +STAGE_ENTRIES = { + "materialize": ( + "us_local_hours_materialize", + "us_local_self_employment_identity_materialize", + "us_local_ssi_medicaid_take_up_materialize", + ), + "calibrate": ( + "us_local_hours_calibrate", + "us_local_self_employment_identity_calibrate", + ), + "qa": (), + "finalize": ( + "us_local_hours_finalize", + "us_local_puma_ladder", + "us_local_hours_worked", + "us_local_take_up", + "us_local_immigration", + "us_local_work_disability", + "us_local_income_transfer", + "us_local_ssi_disability", + "us_local_ssi_medicaid_take_up_finalize", + "us_local_receipt_anchors", + "us_local_reviewed_fill_consumers_finalize", + "us_local_district_ess_collapse", + ), + "package": ( + "us_local_stored_inputs", + "us_local_work_experience_inputs", + "us_local_spm_measurement", + "us_local_hours_package", + "us_local_self_employment_identity_package", + "us_local_reviewed_fill_consumers_package", + ), +} + + +@pytest.fixture +def acs(): + return load_us_gate_tool("us_local") + + +def _args(tmp_path): + return SimpleNamespace( + checkpoint_dir=tmp_path / "checkpoints", + district_ess_relative_floor=0.25, + district_ess_floor=15.0, + ) + + +def _run_stage(acs, args, stage, *, legacy=None): + with acs._local_gate_shadow_stage(args, stage): + observe_entries("us_local", acs, STAGE_ENTRIES[stage], legacy=legacy) + if stage == "finalize": + shadow_not_run( + "us_local_block_location", + "the staging used the legacy location rule; no block ladder", + ) + + +def _comparison(args): + _, comparison = shadow_file_paths(acs_directory(args), "us_local") + return json.loads(comparison.read_text()) + + +def acs_directory(args): + return args.checkpoint_dir / "gate_battery_shadow" + + +def test_the_stage_map_covers_the_scope() -> None: + covered = {entry_id for ids in STAGE_ENTRIES.values() for entry_id in ids} + covered.add("us_local_block_location") + assert covered == {entry.id for entry in us_scoped_gate_manifest("us_local").gates} + + +def test_separate_stage_processes_add_up_to_one_finished_run( + tmp_path, monkeypatch, acs +) -> None: + args = _args(tmp_path) + stand_in_gates(monkeypatch, "us_local", acs) + _run_stage(acs, args, "materialize") + after_materialize = _comparison(args) + assert after_materialize["run_completed"] is False + assert after_materialize["stopped_at"] == "after the materialize stage" + for stage in ("calibrate", "qa", "finalize", "package"): + _run_stage(acs, args, stage) + payload = _comparison(args) + assert payload["run_completed"] is True + assert payload["verdict_difference"] is False + assert payload["phases_recorded"] == ["assembled", "terminal"] + for stage in STAGE_ENTRIES: + assert (acs_directory(args) / f"{stage}.observations.json").is_file() + + +def test_a_finalize_stop_is_recorded_and_its_rerun_starts_clean( + tmp_path, monkeypatch, acs +) -> None: + args = _args(tmp_path) + stand_in_gates(monkeypatch, "us_local", acs, failing={"take_up_signal"}) + for stage in ("materialize", "calibrate", "qa"): + _run_stage(acs, args, stage) + with pytest.raises(SystemExit, match="hard gate failure"): + with acs._local_gate_shadow_stage(args, "finalize"): + observe_entries("us_local", acs, STAGE_ENTRIES["finalize"]) + raise SystemExit("finalize: hard gate failure(s): take-up") + payload = _comparison(args) + assert payload["stopped_by"]["type"] == "SystemExit" + (take_up,) = [row for row in payload["entries"] if row["id"] == "us_local_take_up"] + assert take_up["match"] is True and take_up["battery"]["status"] == "failed" + # Rerunning an earlier stage discards its own and every later stage's file. + (acs_directory(args) / "package.observations.json").write_text("{}") + _run_stage(acs, args, "calibrate") + assert not (acs_directory(args) / "finalize.observations.json").exists() + assert not (acs_directory(args) / "package.observations.json").exists() + + +def test_a_difference_fails_the_finished_package_stage( + tmp_path, monkeypatch, acs +) -> None: + args = _args(tmp_path) + stand_in_gates(monkeypatch, "us_local", acs, failing={"local_hours_signal"}) + for stage in ("materialize", "calibrate", "qa"): + _run_stage(acs, args, stage) + passing = GateResult(name="acs_local_hours_signal", passed=True) + legacy = { + entry_id: (lambda: passing) + for entry_id in ("us_local_hours_finalize", "us_local_hours_package") + } + # Earlier stages record and go on, whatever they saw. + _run_stage(acs, args, "finalize", legacy=legacy) + with pytest.raises(GateBatteryShadowMismatchError, match="us_local_hours"): + _run_stage(acs, args, "package", legacy=legacy) diff --git a/packages/microcosm-build/tests/engine_free/us/test_us_battery_bindings.py b/packages/microcosm-build/tests/engine_free/us/test_us_battery_bindings.py index e2943728f8..b7608ca319 100644 --- a/packages/microcosm-build/tests/engine_free/us/test_us_battery_bindings.py +++ b/packages/microcosm-build/tests/engine_free/us/test_us_battery_bindings.py @@ -51,7 +51,7 @@ ) #: The scopes PR 2 has declared so far, each wired in its tool. -WIRED_SCOPES = ("us_base", "us_pool", "us_national") +WIRED_SCOPES = ("us_base", "us_pool", "us_national", "us_local") #: Each scope's pinned digests. They move only when the scope's entries, #: parameters, phases or the manifest's policy line do. @@ -89,11 +89,32 @@ "898315b5b0fd8cd782c4238d5003008a5237bcac1e205c45676b089252b4a9b0" ), }, + "us_local": { + "gates_manifest_sha256": ( + "6b4286429c8ad369b8b3d2fbbcc4e3f16dcb553915969d72f02873fd87f56f60" + ), + "policy_sha256": ( + "a1fe120a37dbc2f4e55091872f06c2fe6f2d0ecf504cf1c08323aac4514dfda5" + ), + "spec_fingerprint": ( + "139d82665b455eb86f5c2c9a4f597cb3bdeff61a6ef666a9fc415241568195b2" + ), + }, } #: The arguments each tool's parser needs to report its defaults. MINIMAL_ARGV = { "us_national": ["--ledger-facts", "facts.jsonl", "--out", "out"], + "us_local": [ + "--staging-h5", + "staging.h5", + "--checkpoint-dir", + "checkpoints", + "--stage", + "qa", + "--out-h5", + "out.h5", + ], } diff --git a/test_support/microcosm_build/us_gate_shadow.py b/test_support/microcosm_build/us_gate_shadow.py index 9682b7657b..95c78dda22 100644 --- a/test_support/microcosm_build/us_gate_shadow.py +++ b/test_support/microcosm_build/us_gate_shadow.py @@ -125,3 +125,123 @@ def shadow_wiring(scope: str) -> list[tuple[str, str | None, str]]: for module in US_GATE_SCOPE_RUNTIME_SITES.get(scope, ()): sites.extend(_sites(_module_path(module), module)) return sites + + +# --------------------------------------------------------------------------- +# Stand-in gates: every gate a scope's bindings call, answering a verdict +# --------------------------------------------------------------------------- + + +def _verdicts(): + from microcosm.build.us_runtime.gate_shadow import LegacyVerdict + + return { + "result": LegacyVerdict.from_result, + "receipt": lambda value: LegacyVerdict.from_failures(()), + "failures": LegacyVerdict.from_failures, + "failures_and_details": lambda value: LegacyVerdict.from_failures(value[0]), + "result_and_details": lambda value: LegacyVerdict.from_result(value[0]), + "failure_or_none": lambda value: LegacyVerdict.from_failures( + [] if value is None else [value] + ), + "mapping": lambda value: LegacyVerdict.from_failures( + () if value["passed"] else value["failures"] + ), + } + + +def gate_namespace(tool: ModuleType, reference: str) -> tuple[dict, str]: + """The namespace a binding resolves ``reference`` in, and the name.""" + + namespace, _, name = reference.partition(":") + if namespace == "tool": + return vars(tool), name + return vars(importlib.import_module(namespace)), name + + +def stand_in_gates(monkeypatch, scope: str, tool: ModuleType, *, failing=()) -> None: + """Replace every gate the scope's bindings call with a stand-in verdict. + + A check in ``failing`` fails with one line; a refusal-style check + raises its refusal instead. + """ + + from microcosm.build.gates import GateResult + from microcosm.build.us_runtime.battery_bindings import us_gate_specs + + for spec in us_gate_specs(scope): + target, name = gate_namespace(tool, spec.gate) + failed = spec.check in failing + result = ( + GateResult( + name=spec.legacy_name, + passed=False, + failures=(f"{spec.check}: stand-in.",), + ) + if failed + else GateResult(name=spec.legacy_name, passed=True) + ) + lines = list(result.failures) + if failed and spec.refusals: + + def gate(*args, _refusal=spec.refusals[0], _line=lines[0], **kwargs): + raise _refusal(_line) + + else: + value = { + "result": result, + "receipt": {"passed": True}, + "failures": lines, + "failures_and_details": (lines, {}), + "result_and_details": (result, {}), + "failure_or_none": lines[0] if lines else None, + "mapping": {"passed": not failed, "failures": lines}, + }[spec.returns] + + def gate(*args, _value=value, **kwargs): + return _value + + monkeypatch.setitem(target, name, gate) + + +def observe_entries(scope: str, tool: ModuleType, entry_ids, *, legacy=None) -> None: + """Observe ``entry_ids`` as their sites do, calling the stand-in gates. + + ``legacy`` maps an entry id to today's own call, to make today's verdict + differ from the battery's. + """ + + from microcosm.build.gate_battery import EvidenceContext + from microcosm.build.us_runtime.battery_bindings import FRAME, us_gate_specs + from microcosm.build.us_runtime.gate_scopes import us_scoped_gate_manifest + from microcosm.build.us_runtime.gate_shadow import shadow_value + + specs = {spec.check: spec for spec in us_gate_specs(scope)} + entries = {entry.id: entry for entry in us_scoped_gate_manifest(scope).gates} + verdicts = _verdicts() + for entry_id in entry_ids: + spec = specs[entries[entry_id].parameters["check"]] + target, name = gate_namespace(tool, spec.gate) + evidence = EvidenceContext( + frame=object() if spec.needs_frame else None, + artifacts={key: object() for key in spec.artifact_keys}, + ) + + def today(target=target, name=name, spec=spec, evidence=evidence): + return target[name]( + *( + evidence.frame if source == FRAME else evidence.artifacts[source] + for source in spec.positional + ) + ) + + try: + shadow_value( + entry_id, + (legacy or {}).get(entry_id) or today, + evidence, + verdict=verdicts[spec.returns], + refusals=spec.refusals, + ) + except spec.refusals: + pass diff --git a/tools/build_us_acs_local_release.py b/tools/build_us_acs_local_release.py index f819b2c7b2..aea094adb9 100644 --- a/tools/build_us_acs_local_release.py +++ b/tools/build_us_acs_local_release.py @@ -122,12 +122,14 @@ import threading import time from collections import defaultdict +from contextlib import contextmanager from datetime import UTC, datetime from pathlib import Path import numpy as np import pandas as pd +from microcosm.build.gate_battery import EvidenceContext from microcosm.build.program_telemetry import program_telemetry from microcosm.build.us_runtime import target_loss_weights as loss_weighting from microcosm.build.us_runtime.acs_inputs import acs_self_employment_identity_gate @@ -201,7 +203,23 @@ ) from microcosm.build.us_runtime.acs_pums import ACS_2024_1YR_SPINE from microcosm.build.us_runtime.base_pool import spine_column +from microcosm.build.us_runtime.battery_bindings import ( + us_flag_overrides, + us_gate_registry, + us_gate_specs, +) from microcosm.build.us_runtime.esi_premiums import refuse_unassigned_us_esi_premiums +from microcosm.build.us_runtime.gate_scopes import us_scoped_gate_manifest +from microcosm.build.us_runtime.gate_shadow import ( + GATE_BATTERY_SHADOW_DIRECTORY, + GateBatteryShadow, + LegacyVerdict, + active_gate_shadow, + shadow_file_paths, + shadow_gate, + shadow_not_run, + shadow_value, +) from microcosm.build.us_runtime.org_wages import ( US_ORG_OCCUPATION_AND_WORK_EXPERIENCE_OUTPUT_COLUMNS, require_us_occupation_and_work_experience_inputs, @@ -2069,7 +2087,13 @@ def _with_local_ssi_medicaid_take_up( hh_chunk=hh_chunk, peak_rss_gb=round(rss(), 2), ) - gate = acs_local_ssi_medicaid_take_up_signal_gate(frame, receipt=receipt) + gate = shadow_gate( + "us_local_ssi_medicaid_take_up_materialize", + lambda: acs_local_ssi_medicaid_take_up_signal_gate(frame, receipt=receipt), + lambda: EvidenceContext( + frame=frame, artifacts={"ssi_medicaid_receipt": receipt} + ), + ) receipt["gate"] = { "name": gate.name, "passed": gate.passed, @@ -2270,8 +2294,17 @@ def do_materialize(args) -> None: staging_sha = _sha256(args.staging_h5) ladder_sha = _sha256(args.ladder) frame = _load_staging_frame(args.staging_h5) - _require_local_hours(frame, staging_summary) - _require_acs_self_employment_identity(frame) + _shadow_local_refusal( + "us_local_hours_materialize", + lambda frame=frame: _require_local_hours(frame, staging_summary), + frame, + staging_summary=staging_summary, + ) + _shadow_local_refusal( + "us_local_self_employment_identity_materialize", + lambda frame=frame: _require_acs_self_employment_identity(frame), + frame, + ) # microcosm#1019: seed ACS take-up on the full staging frame, before # any development rung is drawn, so a rung keeps the flags the full # build assigns and the export can re-derive them the same way. @@ -3292,8 +3325,17 @@ def _write_calibrated_artifact( identity, args.checkpoint_dir ) frame = _load_staging_frame(args.staging_h5) - _require_local_hours(frame, staging_summary) - _require_acs_self_employment_identity(frame) + _shadow_local_refusal( + "us_local_hours_calibrate", + lambda frame=frame: _require_local_hours(frame, staging_summary), + frame, + staging_summary=staging_summary, + ) + _shadow_local_refusal( + "us_local_self_employment_identity_calibrate", + lambda frame=frame: _require_acs_self_employment_identity(frame), + frame, + ) frame, take_up = _with_local_take_up(frame, seed=recorded_take_up["seed"]) if take_up["assigned_sha256"] != recorded_take_up["assigned_sha256"]: raise SystemExit( @@ -5478,11 +5520,23 @@ def do_finalize(args) -> None: stage="finalize", ) frame = _load_staging_frame(args.out_h5) - local_hours_gate = _local_hours_gate(frame, staging_summary) + local_hours_gate = shadow_gate( + "us_local_hours_finalize", + lambda frame=frame: _local_hours_gate(frame, staging_summary), + lambda frame=frame: EvidenceContext( + frame=frame, artifacts={"staging_summary": staging_summary} + ), + ) households = frame.table("household") weights = np.asarray(frame.weights_for("household").values, dtype=np.float64) load_us_puma_ladder(args.ladder) - ladder_gate = us_puma_ladder_gate(households, weights) + ladder_gate = shadow_gate( + "us_local_puma_ladder", + lambda: us_puma_ladder_gate(households, weights), + lambda: EvidenceContext( + artifacts={"household": households, "household_weights": weights} + ), + ) block_location_gate = None require_block_v1_targets_ladder(staging_summary, ladder_sha) block_ladder = load_staging_block_ladder( @@ -5491,57 +5545,137 @@ def do_finalize(args) -> None: if block_ladder is not None: from microcosm.build.us_runtime.block_location import us_block_location_gate - block_location_gate = us_block_location_gate(households, block_ladder) + block_location_gate = shadow_gate( + "us_local_block_location", + lambda: us_block_location_gate(households, block_ladder), + lambda: EvidenceContext( + artifacts={"household": households, "location_ladder": block_ladder} + ), + ) + else: + shadow_not_run( + "us_local_block_location", + "the staging used the legacy location rule; no block ladder", + ) composition = spine_composition(households, frame.table("person"), weights) # microcosm#765: refuse to package an artifact whose usual-weekly-hours # surface is the engine's constant-40 default (or otherwise out of band), # which silently no-ops SNAP's ABAWD and general work-requirement tests. # weeks_worked is dropped from the pool/ACS surface, so scope the gate to # the two hours columns it carries. - hours_gate = us_hours_worked_signal_gate( - frame, required_columns=US_HOURS_WORKED_POOL_OUTPUT_COLUMNS + hours_gate = shadow_gate( + "us_local_hours_worked", + lambda frame=frame: us_hours_worked_signal_gate( + frame, required_columns=US_HOURS_WORKED_POOL_OUTPUT_COLUMNS + ), + lambda frame=frame: EvidenceContext( + frame=frame, + artifacts={"hours_required_columns": US_HOURS_WORKED_POOL_OUTPUT_COLUMNS}, + ), ) # microcosm#1019: likewise refuse SNAP/TANF take-up that is missing or # constant (the engine-default universal take-up) on either spine, or # unanchored or out of band on the ACS spine this tool seeds. - take_up_gate = acs_local_take_up_signal_gate(frame) + take_up_gate = _shadow_local_frame_gate( + "us_local_take_up", + lambda frame=frame: acs_local_take_up_signal_gate(frame), + frame, + ) # microcosm#1020: refuse immigration labels or entry clocks that are # missing, all-CITIZEN or all at the engine default on either spine, # labels that contradict measured ACS CIT citizenship, and a file outside # the non-citizen and undocumented-anchor bands. - immigration_gate = acs_local_immigration_signal_gate(frame) + immigration_gate = _shadow_local_frame_gate( + "us_local_immigration", + lambda frame=frame: acs_local_immigration_signal_gate(frame), + frame, + ) # microcosm#1021: refuse ACS disability flags that are missing, constant, # or not the native ACS difficulty items on the packaged bytes, or a # staging receipt that shows them imputed. weeks_worked is graded at # staging only: the export holds it back until policyengine-us#9660. - work_disability_gate = acs_local_work_disability_signal_gate( - frame, - receipt=staging_summary.get("acs_local_work_disability"), - require_weeks_worked=False, + work_disability_gate = shadow_gate( + "us_local_work_disability", + lambda frame=frame: acs_local_work_disability_signal_gate( + frame, + receipt=staging_summary.get("acs_local_work_disability"), + require_weeks_worked=False, + ), + lambda frame=frame: EvidenceContext( + frame=frame, + artifacts={ + "work_disability_receipt": staging_summary.get( + "acs_local_work_disability" + ), + "require_weeks_worked": False, + }, + ), ) # microcosm#1022: refuse transferred ACS income leaves that are missing, # negative or carry no signal on the packaged bytes, or a staging receipt # that is not the complete ASEC-channel pass. - income_gate = acs_local_income_transfer_signal_gate( - frame, receipt=staging_summary.get("acs_local_income_transfer") + income_gate = shadow_gate( + "us_local_income_transfer", + lambda frame=frame: acs_local_income_transfer_signal_gate( + frame, receipt=staging_summary.get("acs_local_income_transfer") + ), + lambda frame=frame: EvidenceContext( + frame=frame, + artifacts={ + "income_transfer_receipt": staging_summary.get( + "acs_local_income_transfer" + ) + }, + ), ) # microcosm#1022: refuse ACS SSI disability criteria that are missing or # carry no working-age signal on the packaged bytes, or a staging receipt # that is not the complete SIPP-pinned pass. - ssi_disability_gate = acs_local_ssi_disability_signal_gate( - frame, receipt=staging_summary.get("acs_local_ssi_disability") + ssi_disability_gate = shadow_gate( + "us_local_ssi_disability", + lambda frame=frame: acs_local_ssi_disability_signal_gate( + frame, receipt=staging_summary.get("acs_local_ssi_disability") + ), + lambda frame=frame: EvidenceContext( + frame=frame, + artifacts={ + "ssi_disability_receipt": staging_summary.get( + "acs_local_ssi_disability" + ) + }, + ), ) # microcosm#1022: refuse ACS SSI or Medicaid take-up that is missing, # constant or unanchored on the packaged bytes, or a materialize receipt # whose enforced SSI bands or Medicaid states miss their donor residuals. - ssi_medicaid_gate = acs_local_ssi_medicaid_take_up_signal_gate( - frame, receipt=identity.get("acs_local_ssi_medicaid_take_up") + ssi_medicaid_gate = shadow_gate( + "us_local_ssi_medicaid_take_up_finalize", + lambda frame=frame: acs_local_ssi_medicaid_take_up_signal_gate( + frame, receipt=identity.get("acs_local_ssi_medicaid_take_up") + ), + lambda frame=frame: EvidenceContext( + frame=frame, + artifacts={ + "ssi_medicaid_receipt": identity.get("acs_local_ssi_medicaid_take_up") + }, + ), ) # microcosm#1022: refuse ACS SNAP reporters that are not the native # household FS on the packaged bytes, or a staging receipt that counts # other households, units or anchors. - receipt_anchor_gate = acs_local_receipt_anchor_signal_gate( - frame, receipt=staging_summary.get("acs_local_receipt_anchors") + receipt_anchor_gate = shadow_gate( + "us_local_receipt_anchors", + lambda frame=frame: acs_local_receipt_anchor_signal_gate( + frame, receipt=staging_summary.get("acs_local_receipt_anchors") + ), + lambda frame=frame: EvidenceContext( + frame=frame, + artifacts={ + "receipt_anchors_receipt": staging_summary.get( + "acs_local_receipt_anchors" + ) + }, + ), ) del frame gc.collect() @@ -5554,8 +5688,13 @@ def do_finalize(args) -> None: # microcosm#1022: refuse a reviewed default fill either engine pass applied # without a register entry, or a declared means-tested consumer of one # without a harmless or known-bias note. - reviewed_fill_gate = _reviewed_fill_consumer_gate( - _checkpoint_fill_manifests(args.checkpoint_dir) + fill_manifests = _checkpoint_fill_manifests(args.checkpoint_dir) + reviewed_fill_gate = shadow_gate( + "us_local_reviewed_fill_consumers_finalize", + lambda: _reviewed_fill_consumer_gate(fill_manifests), + lambda: EvidenceContext( + artifacts={"fill_manifests": fill_manifests, "fill_register": None} + ), ) breakdown: dict[str, int] = {} @@ -5825,11 +5964,21 @@ def do_finalize(args) -> None: "artifact_sha256": spine_qa.get("artifact_sha256"), } - gates[DISTRICT_ESS_GATE] = district_ess_collapse_gate( - diagnostics.get("weight_origin"), - relative_floor=args.district_ess_relative_floor, - absolute_floor=args.district_ess_floor, - blocking=args.district_ess_gate_blocking, + gates[DISTRICT_ESS_GATE] = shadow_value( + "us_local_district_ess_collapse", + lambda: district_ess_collapse_gate( + diagnostics.get("weight_origin"), + relative_floor=args.district_ess_relative_floor, + absolute_floor=args.district_ess_floor, + blocking=args.district_ess_gate_blocking, + ), + lambda: EvidenceContext( + artifacts={ + "weight_origin": diagnostics.get("weight_origin"), + "district_ess_blocking": args.district_ess_gate_blocking, + } + ), + verdict=_legacy_mapping_verdict, ) limitations = finalize_reviewed_limitations( @@ -6168,7 +6317,12 @@ def do_package(args) -> dict: # microcosm#1026: the manifest below records the installed policyengine-us # as build.built_with_model_package, so the artifact may store no model # input that engine does not define. A refused artifact leaves nothing. - stored_inputs_gate = _require_stored_inputs(calibrated_h5) + stored_inputs_gate = _shadow_local_refusal( + "us_local_stored_inputs", + lambda: _require_stored_inputs(calibrated_h5), + None, + calibrated_h5=calibrated_h5, + ) # microcosm#1022 (review of #1058): ACS persons the SSI disability-criteria # stage made criteria-positive must not ship at universal SSI take-up. ssi_take_up_block = _require_ssi_take_up_handling( @@ -6283,8 +6437,21 @@ def do_package(args) -> dict: # Historical staging can predate the donor/native work-experience gates. # Grade the actual final rows, even when its old summary is green. try: - require_us_occupation_and_work_experience_inputs( - artifact_frame.table("person"), label="ACS local-area release" + shadow_value( + "us_local_work_experience_inputs", + lambda artifact_frame=artifact_frame: ( + require_us_occupation_and_work_experience_inputs( + artifact_frame.table("person"), label="ACS local-area release" + ) + ), + lambda artifact_frame=artifact_frame: EvidenceContext( + artifacts={ + "person": artifact_frame.table("person"), + "work_experience_label": "ACS local-area release", + } + ), + verdict=lambda value: LegacyVerdict.from_failures(()), + refusals=(ValueError,), ) except ValueError as error: raise SystemExit( @@ -6294,11 +6461,29 @@ def do_package(args) -> dict: work_experience_rows = artifact_frame.n("person") # microcosm#1263: the bytes must also be measurable by the engine the # release records as built-with. - spm_measurement_gate = _require_spm_measurement(artifact_frame) - package_hours_gate = _local_hours_gate(artifact_frame, staging_summary) + spm_measurement_gate = _shadow_local_refusal( + "us_local_spm_measurement", + lambda artifact_frame=artifact_frame: _require_spm_measurement(artifact_frame), + artifact_frame, + ) + package_hours_gate = shadow_gate( + "us_local_hours_package", + lambda artifact_frame=artifact_frame: _local_hours_gate( + artifact_frame, staging_summary + ), + lambda artifact_frame=artifact_frame: EvidenceContext( + frame=artifact_frame, artifacts={"staging_summary": staging_summary} + ), + ) # microcosm#1380: a checkpoint calibrated from pre-fix staging stacks # donor self-employment on SEMP; grade the bytes being packaged. - self_employment_gate = _require_acs_self_employment_identity(artifact_frame) + self_employment_gate = _shadow_local_refusal( + "us_local_self_employment_identity_package", + lambda artifact_frame=artifact_frame: _require_acs_self_employment_identity( + artifact_frame + ), + artifact_frame, + ) del artifact_frame gc.collect() if not package_hours_gate.passed: @@ -6317,12 +6502,19 @@ def do_package(args) -> dict: # microcosm#1022: re-grade the manifests being packaged against the # register being packaged; the finalize verdict covered earlier copies. fill_register = load_reviewed_fill_consumer_register() - package_fill_gate = _reviewed_fill_consumer_gate( - { - "reviewed_null_fills.json": null_fills, - "consumer_reviewed_null_fills.json": consumer_fills, - }, - fill_register, + package_fill_manifests = { + "reviewed_null_fills.json": null_fills, + "consumer_reviewed_null_fills.json": consumer_fills, + } + package_fill_gate = shadow_gate( + "us_local_reviewed_fill_consumers_package", + lambda: _reviewed_fill_consumer_gate(package_fill_manifests, fill_register), + lambda: EvidenceContext( + artifacts={ + "fill_manifests": package_fill_manifests, + "fill_register": fill_register, + } + ), ) if not package_fill_gate.passed: raise SystemExit( @@ -6979,6 +7171,124 @@ def _parse_args(argv: list[str] | None = None) -> argparse.Namespace: TELEMETRY_PIPELINE = "us_acs_local_release" +#: This tool's scope of us/gates.json, evaluated in shadow beside today's +#: gates (microcosm#1585 item 11, PR 2 of 4). +US_LOCAL_GATE_SCOPE = "us_local" +_LOCAL_GATE_SHADOW_STAGES = ("materialize", "calibrate", "qa", "finalize", "package") + + +def _local_gate_shadow_directory(args) -> Path: + """``/gate_battery_shadow``, beside ``gate_summary.json``. + + Never the release directory, whose ``*.json`` files its checksum ledger + and release manifest take in. + """ + + return Path(args.checkpoint_dir) / GATE_BATTERY_SHADOW_DIRECTORY + + +def _local_stage_observations(args, stage: str) -> Path: + return _local_gate_shadow_directory(args) / f"{stage}.observations.json" + + +def _local_gate_shadow(args, directory: Path) -> GateBatteryShadow: + gates = us_scoped_gate_manifest(US_LOCAL_GATE_SCOPE) + report_path, comparison_path = shadow_file_paths(directory, US_LOCAL_GATE_SCOPE) + return GateBatteryShadow( + gates, + scope=US_LOCAL_GATE_SCOPE, + release_id=US_LOCAL_RELEASE_ID, + report_path=report_path, + comparison_path=comparison_path, + registry=us_gate_registry(US_LOCAL_GATE_SCOPE, tool=globals()), + overrides=us_flag_overrides(gates, us_gate_specs(US_LOCAL_GATE_SCOPE), args), + ) + + +def _finish_local_gate_scope(args, *, stage: str, stopped_by=None) -> None: + """Rebuild the scope's shadow files from every stage saved so far. + + Only a package stage that finished decides: a verdict difference then + fails the run. A stage today's code stopped, or one a later process + follows, records and goes on. + """ + + try: + shadow = _local_gate_shadow(args, _local_gate_shadow_directory(args)) + for name in _LOCAL_GATE_SHADOW_STAGES: + observations = _local_stage_observations(args, name) + if observations.is_file(): + shadow.load_observations(observations) + except Exception as error: # noqa: BLE001 - the shadow never stops a stage + if stopped_by is None and stage == "package": + raise + log(f"WARNING: gate battery shadow could not be rebuilt: {error}") + return + if stopped_by is not None: + shadow.stop(stopped_by) + elif stage == "package": + shadow.finish() + else: + shadow.finish(stopped_at=f"after the {stage} stage") + + +@contextmanager +def _local_gate_shadow_stage(args, stage: str): + """Observe one stage's gates in shadow, then bring the scope's files up to date. + + The stages may run as separate processes, so each saves what it observed + beside the checkpoint, and rerunning a stage discards its own and every + later stage's observations. Afterwards the scope's report and comparison + are rebuilt from every stage saved so far. + """ + + for name in _LOCAL_GATE_SHADOW_STAGES[_LOCAL_GATE_SHADOW_STAGES.index(stage) :]: + _local_stage_observations(args, name).unlink(missing_ok=True) + shadow = _local_gate_shadow(args, _local_gate_shadow_directory(args) / stage) + + def save() -> None: + try: + shadow.save_observations(_local_stage_observations(args, stage)) + except Exception as error: # noqa: BLE001 - the shadow never stops a stage + log(f"WARNING: gate battery shadow could not save {stage}: {error}") + + try: + with active_gate_shadow(shadow): + yield shadow + except BaseException as error: + save() + _finish_local_gate_scope(args, stage=stage, stopped_by=error) + raise + save() + _finish_local_gate_scope(args, stage=stage) + + +def _shadow_local_frame_gate(entry_id: str, evaluate, frame): + """Today's frame signal gate, with the battery's entry beside it.""" + + return shadow_gate(entry_id, evaluate, lambda: EvidenceContext(frame=frame)) + + +def _shadow_local_refusal(entry_id: str, evaluate, frame, **artifacts): + """Today's refusal-style check, observed: its SystemExit is its failure.""" + + return shadow_value( + entry_id, + evaluate, + lambda: EvidenceContext(frame=frame, artifacts=artifacts), + verdict=lambda value: LegacyVerdict.from_failures(()), + refusals=(SystemExit,), + ) + + +def _legacy_mapping_verdict(entry: dict) -> LegacyVerdict: + """Today's verdict on a gate entry written as a mapping.""" + + if entry.get("passed"): + return LegacyVerdict.from_failures(()) + return LegacyVerdict.from_failures(entry.get("failures") or ()) + + def main(argv: list[str] | None = None) -> int: args = _parse_args(argv) with program_telemetry(pipeline=TELEMETRY_PIPELINE) as telemetry: @@ -6989,19 +7299,24 @@ def main(argv: list[str] | None = None) -> int: try: if "materialize" in args.stages: telemetry.transition_stage("materialize") - do_materialize(args) + with _local_gate_shadow_stage(args, "materialize"): + do_materialize(args) if "calibrate" in args.stages: telemetry.transition_stage("calibrate") - do_calibrate(args) + with _local_gate_shadow_stage(args, "calibrate"): + do_calibrate(args) if "qa" in args.stages: telemetry.transition_stage("qa") - do_qa(args) + with _local_gate_shadow_stage(args, "qa"): + do_qa(args) if "finalize" in args.stages: telemetry.transition_stage("finalize") - do_finalize(args) + with _local_gate_shadow_stage(args, "finalize"): + do_finalize(args) if "package" in args.stages: telemetry.transition_stage("package") - do_package(args) + with _local_gate_shadow_stage(args, "package"): + do_package(args) finally: sampler.stop() sampler.join(timeout=5) From 660d46c65ac3d82f08ce7a45acd776e137146db8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mar=C3=ADa=20Juaristi?= <127882282+juaristi22@users.noreply.github.com> Date: Sun, 15 Nov 2026 14:28:22 +0000 Subject: [PATCH 07/31] Document the US gate battery in shadow, and add its changelog fragment The gate-battery contract's US line becomes a section: the four scopes, how the shadow compares verdicts and where it writes, and how the US bindings route keyword thresholds and pin constant ones. The release contract's status sentence and its M2 row no longer say us/gates.json does not exist, and say that the US re-evaluates in shadow rather than projecting through an adapter. Co-Authored-By: Claude Opus 5.5 --- .../1585-us-gate-battery-shadow.added.md | 1 + docs/gate-battery-contract.md | 29 ++++++++++++++++++- docs/release-contract.md | 8 +++-- 3 files changed, 34 insertions(+), 4 deletions(-) create mode 100644 changelog.d/1585-us-gate-battery-shadow.added.md diff --git a/changelog.d/1585-us-gate-battery-shadow.added.md b/changelog.d/1585-us-gate-battery-shadow.added.md new file mode 100644 index 0000000000..b5757744f4 --- /dev/null +++ b/changelog.d/1585-us-gate-battery-shadow.added.md @@ -0,0 +1 @@ +The four US build tools (Route A's base, the multispine pool's stacked path, the national release and ACS local) declare their 143 gates in the new `us/gates.json`, one scope per tool, and run the shared gate battery in shadow beside today's gates: each gate's entry is evaluated on the same evidence, the verdicts are compared, the scope's battery report and the comparison are written beside the tool's outputs, and a finished run fails on a verdict difference. Today's raises, written files and manifest keys are unchanged (microcosm#1585 item 11). diff --git a/docs/gate-battery-contract.md b/docs/gate-battery-contract.md index 0fb8571ad8..73c74ce265 100644 --- a/docs/gate-battery-contract.md +++ b/docs/gate-battery-contract.md @@ -322,7 +322,34 @@ 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). +US adoption is in progress (microcosm#1585 item 11), in four steps, and +`us/gates.json` now declares 143 entries, each US build tool's share of +them a scope of its own (`us_runtime/gate_scopes.py`): `us_base` (Route +A's base, 37), `us_pool` (the multispine pool's stacked path, 6), +`us_national` (the national release, 76) and `us_local` (ACS local, 24). A +scope owns the entries whose id starts with its name, checked +closed-world. In this step the battery runs **in shadow**: each tool still +gates as it did, and beside each gate it evaluates the declared entry +through its scope's `GateBatteryRun` on the same evidence, with the +record-without-enforce posture, then compares the verdicts +(`us_runtime/gate_shadow.py`). Verdicts are compared, not enforcement: a +gate an `--allow-*` flag waives today matches if it fails in both, a crash +in today's code matches an `evaluation_error`, and a gate today's code did +not evaluate matches `evidence_absent`. The shadow writes its scope's +report and the comparison beside the tool's outputs (never inside a +release directory), never raises while the tool runs, and fails a finished +run on a verdict difference; today's own exception always propagates +unchanged. + +Most US entries are `stage_health` entries whose `check` names the gate, +and `us_runtime/battery_bindings.py` binds each check to the gate function +its site calls, looked up in the tool's own globals or the runtime module +where the site runs, so a test that patches one reaches both verdicts. A +threshold the gate takes as a keyword is routed from the entry; one it +reads from a module constant is declared at today's value and pinned equal +to it until the flip, when the spec becomes the only source. The flip, +signing, the verifier and head-to-head certification are the next three +steps. ## The reference rule diff --git a/docs/release-contract.md b/docs/release-contract.md index 88c698ce29..f4d8aa29c3 100644 --- a/docs/release-contract.md +++ b/docs/release-contract.md @@ -445,8 +445,10 @@ The 2026-10-09 report's plan brings the US to this shape by adapter at M2: the fiscal-refresh tool declares its gates in `us/gates.json`, projects its own verdicts through the gate battery under `BlockingMode.MARKS_ARTIFACT`, and composes the certification from the projected reports. It projects; it does not -re-evaluate. On 2026-11-12 neither `us/gates.json` nor that adapter exists, and -no US build carries a certification. The US national golden, +re-evaluate. microcosm#1585 item 11 takes another route: `us/gates.json` exists, +and the four US build tools re-evaluate its entries in shadow beside their own +gates, comparing verdicts (see the gate-battery contract), before a later step +makes the battery authoritative. No US build carries a certification. The US national golden, [`v1/c1/microcosm-us-2024-national/`](#golden-fixtures), therefore freezes the two manifests the US fiscal-refresh tool writes today for a run that passes `_build_manifests` only its required arguments and a staging block. A @@ -1139,7 +1141,7 @@ version 1 takes that shape. | --- | --- | --- | --- | --- | | M0 | 2026-10-16 | This document and the golden fixtures; nothing refuses | Max's session | microcosm#1285, which adds this document | | M1 | 2026-10-23 | A UK national cut on policyengine-uk ≥ 2.122.2 with staging version 3, a Logbook row and a certification; the registry's UK default flips to it | juaristi22 | The registry flip, in microcosm#1432 (merged 2026-11-02). Since microcosm#1505 the entry also names release `microcosm-uk-2024-25-national`, and the loader reads that release's current build from `releases.json` where the repository has one. microcosm#1574 (merged 2026-11-11) moved the national certification to schema 2, which adds `reference` and `since_baseline`, and renamed the score receipt to `score_vs_reference.json`. This document does not check the current build's staging, Logbook row or certification on the Hub | -| M2 | 2026-10-30 | `us/gates.json` and the US adapter (C1); the US writes staging version 3 and a Logbook row and records `producer` (C3, C4); staging version 1 goes; the registry gains an entry for the US local-area release, which carries the state and district file (C5); one compatibility rule in both loaders and, at publication, for every role (C2) | Max's session, PavelMakarchuk, anth-volk | None of it: only am, be, nz and uk carry a `gates.json`; the fiscal-refresh tool composes no certification, still writes staging version 1 through `StagingRunBundleWriter` and records no Logbook row; no release manifest records a `producer`; the registry has no entry for `microcosm-us-2024-local`; `_check_local_area_release_manifest` checks no compatibility list; and microcosm.data's loader keeps today's containment rule. policyengine.py, at 5b6d7901c on 2026-11-11, keeps its three bases and the `legacy_compatible_model_package` label | +| M2 | 2026-10-30 | `us/gates.json` and the US adapter (C1); the US writes staging version 3 and a Logbook row and records `producer` (C3, C4); staging version 1 goes; the registry gains an entry for the US local-area release, which carries the state and district file (C5); one compatibility rule in both loaders and, at publication, for every role (C2) | Max's session, PavelMakarchuk, anth-volk | Only `us/gates.json`, which the US tools evaluate in shadow without the adapter (microcosm#1585 item 11); the fiscal-refresh tool composes no certification, still writes staging version 1 through `StagingRunBundleWriter` and records no Logbook row; no release manifest records a `producer`; the registry has no entry for `microcosm-us-2024-local`; `_check_local_area_release_manifest` checks no compatibility list; and microcosm.data's loader keeps today's containment rule. policyengine.py, at 5b6d7901c on 2026-11-11, keeps its three bases and the `legacy_compatible_model_package` label | | M3 | 2026-11-06 | Release manifest schema 2 and declared-country dispatch; the validator refuses unknown countries, which also closes a new country's tagged publish; `microcosm-publish-release-build` refuses non-conforming builds, derived builds included; the staging re-delivery command; policyengine.py's registry check | Max's session, juaristi22, anth-volk | None of it: `RELEASE_MANIFEST_SCHEMA_VERSION` is 1; `required_release_files`, `_expected_model_package` and `publishes_to_build_folder` still key on the release name, and an unknown name still gets the base file set; `microcosm-publish-release-build` runs the nine checks that C5 lists under "Order" and adds none of M3's: no check it runs asks for a `run_outcome`, a Logbook row or a manifest's declared `country`, and `required_release_files` names `release_certification.json` for `microcosm-uk-2024-25-national` alone; C1's other certification rule keys on the gate files a directory carries, not on a declared country. `test_release_contract_keying.py`, which arrives with this document, pins today's keying. This document has not looked for policyengine.py's registry check | Max's rulings still decide anything that changes published numbers, such as From a40807c508b775d2003476bc5a2253ca6523ccbb Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mar=C3=ADa=20Juaristi?= <127882282+juaristi22@users.noreply.github.com> Date: Sun, 15 Nov 2026 14:35:12 +0000 Subject: [PATCH 08/31] Let the wiring scan read ACS's own site helpers and function-local imports ACS local observes most of its gates through two helpers of its own, and its finalize stage imports three gates inside the function, so their bindings name the gates' modules instead of the tool. Co-Authored-By: Claude Opus 5.5 --- .../tests/engine_free/us/test_us_battery_bindings.py | 7 +++++++ test_support/microcosm_build/us_gate_shadow.py | 2 ++ 2 files changed, 9 insertions(+) diff --git a/packages/microcosm-build/tests/engine_free/us/test_us_battery_bindings.py b/packages/microcosm-build/tests/engine_free/us/test_us_battery_bindings.py index b7608ca319..5e1959929a 100644 --- a/packages/microcosm-build/tests/engine_free/us/test_us_battery_bindings.py +++ b/packages/microcosm-build/tests/engine_free/us/test_us_battery_bindings.py @@ -252,11 +252,18 @@ def test_every_entry_is_wired_at_a_site_calling_its_gate(scope) -> None: unknown = sorted({entry_id for entry_id, _, _ in sites} - set(declared)) assert not unknown, unknown assert {entry_id for entry_id, _, _ in sites} == set(declared) + tool = binding.tool for entry_id, reference, where in sites: entry = declared[entry_id] if reference is None or entry.gate != "stage_health": continue spec = binding.checks[entry.parameters["check"]] + name = reference.removeprefix("tool:") + if reference.startswith("tool:") and name not in tool: + # The site imports the gate inside its function, so the binding + # names the gate's own module instead. + assert spec.gate.endswith(f":{name}"), (entry_id, where, spec.gate) + continue assert spec.gate == reference, (entry_id, where, reference, spec.gate) diff --git a/test_support/microcosm_build/us_gate_shadow.py b/test_support/microcosm_build/us_gate_shadow.py index 95c78dda22..65ec6f20ad 100644 --- a/test_support/microcosm_build/us_gate_shadow.py +++ b/test_support/microcosm_build/us_gate_shadow.py @@ -79,6 +79,8 @@ def _lambda_call_name(node: ast.AST) -> str | None: "_shadow_frame_gate", "_observe_frame_gate", "_shadow_tail_survival", + "_shadow_local_frame_gate", + "_shadow_local_refusal", } ) From d1dfdf81535aa9f05f2d8c069ba637bddaafd435 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mar=C3=ADa=20Juaristi?= <127882282+juaristi22@users.noreply.github.com> Date: Sun, 15 Nov 2026 15:13:41 +0000 Subject: [PATCH 09/31] Run the US tools' gate shadows in real builds only; the suite turns them off A finished shadow fails the run on any entry it did not observe, and the existing tests stand stubs in for whole stages (the pool's derive and geography stages, the release's corridor runs through main), so with the shadow armed they would fail at the end of every completed run. Every tool now asks tool_gate_shadows_enabled() before it arms: real builds always do, and tests/conftest.py sets MICROCOSM_US_GATE_SHADOW=off for every test, beside the Logbook guard. The shadow's own tool-seam tests turn it back on with arm_us_tool_gate_shadows and check that, with the switch off, no shadow is armed and no shadow file is touched. Co-Authored-By: Claude Opus 5.5 --- .../microcosm/build/us_runtime/gate_shadow.py | 21 ++++++++++++++ packages/microcosm-build/tests/conftest.py | 16 ++++++++++ .../us/test_us_acs_local_gate_shadow.py | 25 ++++++++++++++++ .../us/test_us_fiscal_refresh_gate_shadow.py | 29 ++++++++++++++++++- .../engine_free/us/test_us_gate_shadow.py | 17 +++++++++++ .../us/test_us_multispine_pool_gate_shadow.py | 23 ++++++++++++++- .../test_us_puf_support_base_gate_shadow.py | 29 ++++++++++++++++++- .../microcosm_build/us_gate_shadow.py | 14 +++++++++ tools/build_us_acs_local_release.py | 7 ++++- tools/build_us_fiscal_refresh_release.py | 3 ++ tools/build_us_multispine_pool.py | 9 +++++- tools/build_us_puf_support_base.py | 17 +++++++---- 12 files changed, 200 insertions(+), 10 deletions(-) diff --git a/packages/microcosm-build/src/microcosm/build/us_runtime/gate_shadow.py b/packages/microcosm-build/src/microcosm/build/us_runtime/gate_shadow.py index b0b384e3aa..bc385ce89c 100644 --- a/packages/microcosm-build/src/microcosm/build/us_runtime/gate_shadow.py +++ b/packages/microcosm-build/src/microcosm/build/us_runtime/gate_shadow.py @@ -35,6 +35,11 @@ so a difference there is recorded as explained by the override and does not fail the run: the spec cannot hold a per-run threshold, and that decision belongs to the flip (PR 3), not to the shadow. + +Every real run arms its tool's shadow. The test suite sets +:data:`US_GATE_SHADOW_SWITCH` to ``off`` for every test, because its tests +stand stubs in for whole stages and a finished shadow would rightly report +the gate sites they skip; the shadow's own tests turn it back on. """ from __future__ import annotations @@ -70,6 +75,7 @@ "GATE_BATTERY_SHADOW_PRODUCER", "GATE_BATTERY_SHADOW_REPORT_SUFFIX", "GATE_BATTERY_SHADOW_SCHEMA_VERSION", + "US_GATE_SHADOW_SWITCH", "GateBatteryShadow", "GateBatteryShadowMismatchError", "LegacyStatus", @@ -86,6 +92,7 @@ "shadow_gate", "shadow_not_run", "shadow_value", + "tool_gate_shadows_enabled", ] GATE_BATTERY_SHADOW_SCHEMA_VERSION = 1 @@ -99,6 +106,20 @@ GATE_BATTERY_SHADOW_REPORT_SUFFIX = ".gate_battery_shadow_report.json" #: ````: the comparison with today's verdicts. GATE_BATTERY_SHADOW_COMPARISON_SUFFIX = ".gate_battery_shadow_comparison.json" +#: Set to ``off`` and a build tool runs without its scope's shadow. Real +#: builds never set it; ``packages/microcosm-build/tests/conftest.py`` sets it +#: for every test. +US_GATE_SHADOW_SWITCH = "MICROCOSM_US_GATE_SHADOW" + + +def tool_gate_shadows_enabled() -> bool: + """Whether a build tool arms its scope's shadow: unless the switch is ``off``. + + Only the tools ask; a shadow built and armed directly behaves the same + either way. + """ + + return os.environ.get(US_GATE_SHADOW_SWITCH, "").strip().lower() != "off" def shadow_file_paths(directory: Path | str, scope: str) -> tuple[Path, Path]: diff --git a/packages/microcosm-build/tests/conftest.py b/packages/microcosm-build/tests/conftest.py index 8de2e3dc35..ade63de493 100644 --- a/packages/microcosm-build/tests/conftest.py +++ b/packages/microcosm-build/tests/conftest.py @@ -219,6 +219,22 @@ def allow_logbook_network( monkeypatch.setattr(logbook._NO_REDIRECT_OPENER, "open", _isolate_logbook["open"]) +# The US build tools evaluate their gates through the shared gate battery in +# shadow (microcosm#1585 item 11). A finished shadow fails the run on any +# entry it did not observe, and the tests here stand stubs in for whole +# stages, whose gate sites a stub skips; so every test runs the tools with +# their shadows off. The shadow's own tests turn them back on with +# ``arm_us_tool_gate_shadows`` (test_support.microcosm_build.us_gate_shadow). +# The name is ``microcosm.build.us_runtime.gate_shadow.US_GATE_SHADOW_SWITCH``, +# spelled out so that this file imports nothing from the US runtime. +_US_GATE_SHADOW_SWITCH = "MICROCOSM_US_GATE_SHADOW" + + +@pytest.fixture(autouse=True) +def _us_tool_gate_shadows_off(monkeypatch: pytest.MonkeyPatch) -> None: + monkeypatch.setenv(_US_GATE_SHADOW_SWITCH, "off") + + @pytest.fixture(scope="session") def _session_primary_qrf_worker_identities(): """Attest the real installed worker once; retain pristine identities by key. diff --git a/packages/microcosm-build/tests/engine_free/us/test_us_acs_local_gate_shadow.py b/packages/microcosm-build/tests/engine_free/us/test_us_acs_local_gate_shadow.py index 498a52fbe8..274c8b4457 100644 --- a/packages/microcosm-build/tests/engine_free/us/test_us_acs_local_gate_shadow.py +++ b/packages/microcosm-build/tests/engine_free/us/test_us_acs_local_gate_shadow.py @@ -17,16 +17,25 @@ from microcosm.build.gates import GateResult from microcosm.build.us_runtime.gate_scopes import us_scoped_gate_manifest from microcosm.build.us_runtime.gate_shadow import ( + US_GATE_SHADOW_SWITCH, GateBatteryShadowMismatchError, + current_gate_shadow, shadow_file_paths, shadow_not_run, ) from test_support.microcosm_build.us_gate_shadow import ( + arm_us_tool_gate_shadows, load_us_gate_tool, observe_entries, stand_in_gates, ) + +@pytest.fixture(autouse=True) +def _tool_shadows_on(monkeypatch) -> None: + arm_us_tool_gate_shadows(monkeypatch) + + #: Which stage evaluates each entry (the qa stage has none). STAGE_ENTRIES = { "materialize": ( @@ -121,6 +130,22 @@ def test_separate_stage_processes_add_up_to_one_finished_run( assert (acs_directory(args) / f"{stage}.observations.json").is_file() +def test_with_the_switch_off_a_stage_touches_no_shadow_file( + tmp_path, monkeypatch, acs +) -> None: + args = _args(tmp_path) + stand_in_gates(monkeypatch, "us_local", acs) + _run_stage(acs, args, "materialize") + saved = acs_directory(args) / "materialize.observations.json" + before = saved.read_bytes() + monkeypatch.setenv(US_GATE_SHADOW_SWITCH, "off") + with acs._local_gate_shadow_stage(args, "materialize") as shadow: + assert shadow is None + assert current_gate_shadow() is None + # A rerun with the switch off neither discards nor rewrites what was saved. + assert saved.read_bytes() == before + + def test_a_finalize_stop_is_recorded_and_its_rerun_starts_clean( tmp_path, monkeypatch, acs ) -> None: diff --git a/packages/microcosm-build/tests/engine_free/us/test_us_fiscal_refresh_gate_shadow.py b/packages/microcosm-build/tests/engine_free/us/test_us_fiscal_refresh_gate_shadow.py index 4894286157..82115f8056 100644 --- a/packages/microcosm-build/tests/engine_free/us/test_us_fiscal_refresh_gate_shadow.py +++ b/packages/microcosm-build/tests/engine_free/us/test_us_fiscal_refresh_gate_shadow.py @@ -24,12 +24,23 @@ ) from microcosm.build.us_runtime.gate_scopes import us_scoped_gate_manifest from microcosm.build.us_runtime.gate_shadow import ( + GATE_BATTERY_SHADOW_DIRECTORY, + US_GATE_SHADOW_SWITCH, GateBatteryShadowMismatchError, LegacyVerdict, + current_gate_shadow, shadow_file_paths, shadow_value, ) -from test_support.microcosm_build.us_gate_shadow import load_us_gate_tool +from test_support.microcosm_build.us_gate_shadow import ( + arm_us_tool_gate_shadows, + load_us_gate_tool, +) + + +@pytest.fixture(autouse=True) +def _tool_shadows_on(monkeypatch) -> None: + arm_us_tool_gate_shadows(monkeypatch) @pytest.fixture @@ -216,6 +227,22 @@ def refused(argv): assert payload["run_completed"] is False +def test_with_the_switch_off_main_arms_no_shadow(tmp_path, monkeypatch, release): + monkeypatch.setenv(US_GATE_SHADOW_SWITCH, "off") + args = _args(tmp_path) + armed = [] + + def build(argv): + release._start_national_gate_shadow(args, release_id="microcosm-us-test") + armed.append(current_gate_shadow("us_national_pregnancy")) + return None + + monkeypatch.setattr(release, "_main", build) + release.main([]) + assert armed == [None] + assert not (args.out / GATE_BATTERY_SHADOW_DIRECTORY).exists() + + def test_waivers_and_flag_overrides_are_recorded_by_entry(tmp_path, release): gates = us_scoped_gate_manifest("us_national") args = _args( diff --git a/packages/microcosm-build/tests/engine_free/us/test_us_gate_shadow.py b/packages/microcosm-build/tests/engine_free/us/test_us_gate_shadow.py index 826e122523..bd371f0002 100644 --- a/packages/microcosm-build/tests/engine_free/us/test_us_gate_shadow.py +++ b/packages/microcosm-build/tests/engine_free/us/test_us_gate_shadow.py @@ -11,6 +11,7 @@ import hashlib import json +import os import pytest @@ -29,6 +30,7 @@ us_check_binding, ) from microcosm.build.us_runtime.gate_shadow import ( + US_GATE_SHADOW_SWITCH, GateBatteryShadow, GateBatteryShadowMismatchError, LegacyStatus, @@ -36,6 +38,7 @@ compare_verdicts, legacy_parameter_overrides, shadow_file_paths, + tool_gate_shadows_enabled, ) @@ -617,6 +620,20 @@ def test_stale_shadow_files_are_removed_when_a_run_starts(tmp_path) -> None: assert not report.exists() and not comparison.exists() +def test_the_suite_runs_the_tools_without_their_shadows(monkeypatch) -> None: + # tests/conftest.py spells the switch out; this holds it to the constant. + assert os.environ.get(US_GATE_SHADOW_SWITCH) == "off" + assert tool_gate_shadows_enabled() is False + for value in (" OFF ", "Off"): + monkeypatch.setenv(US_GATE_SHADOW_SWITCH, value) + assert tool_gate_shadows_enabled() is False + for value in ("", "on", "0", "false"): + monkeypatch.setenv(US_GATE_SHADOW_SWITCH, value) + assert tool_gate_shadows_enabled() is True + monkeypatch.delenv(US_GATE_SHADOW_SWITCH) + assert tool_gate_shadows_enabled() is True + + def test_waivers_and_overrides_must_name_scope_entries(tmp_path) -> None: with pytest.raises(ValueError, match="outside scope"): _shadow(tmp_path, _two_phase_gates(), waivers={"us_elsewhere": ["--allow-x"]}) diff --git a/packages/microcosm-build/tests/engine_free/us/test_us_multispine_pool_gate_shadow.py b/packages/microcosm-build/tests/engine_free/us/test_us_multispine_pool_gate_shadow.py index 4ffe586531..78b683e59d 100644 --- a/packages/microcosm-build/tests/engine_free/us/test_us_multispine_pool_gate_shadow.py +++ b/packages/microcosm-build/tests/engine_free/us/test_us_multispine_pool_gate_shadow.py @@ -18,12 +18,22 @@ from microcosm.build.gate_battery import EvidenceContext from microcosm.build.us_runtime.battery_bindings import us_gate_specs from microcosm.build.us_runtime.gate_shadow import ( + US_GATE_SHADOW_SWITCH, GateBatteryShadowMismatchError, + current_gate_shadow, shadow_file_paths, shadow_gate, shadow_not_run, ) -from test_support.microcosm_build.us_gate_shadow import load_us_gate_tool +from test_support.microcosm_build.us_gate_shadow import ( + arm_us_tool_gate_shadows, + load_us_gate_tool, +) + + +@pytest.fixture(autouse=True) +def _tool_shadows_on(monkeypatch) -> None: + arm_us_tool_gate_shadows(monkeypatch) @pytest.fixture @@ -111,6 +121,17 @@ def test_the_stacked_path_finishes_its_shadow_beside_the_pool( assert json.loads(report.read_text())["shippable"] is False +def test_with_the_switch_off_the_stacked_path_has_no_shadow( + tmp_path, monkeypatch, pool +) -> None: + monkeypatch.setenv(US_GATE_SHADOW_SWITCH, "off") + args = SimpleNamespace(out=tmp_path / "stacked.h5") + with pool._armed_pool_gate_shadow(args) as shadow: + assert shadow is None + assert current_gate_shadow() is None + assert not pool._pool_gate_shadow_directory(args).exists() + + def test_a_terminal_difference_fails_the_build_after_its_files( tmp_path, monkeypatch, pool ) -> None: diff --git a/packages/microcosm-build/tests/engine_free/us/test_us_puf_support_base_gate_shadow.py b/packages/microcosm-build/tests/engine_free/us/test_us_puf_support_base_gate_shadow.py index d1b438fd13..3a212cd796 100644 --- a/packages/microcosm-build/tests/engine_free/us/test_us_puf_support_base_gate_shadow.py +++ b/packages/microcosm-build/tests/engine_free/us/test_us_puf_support_base_gate_shadow.py @@ -19,12 +19,22 @@ from microcosm.build.us_runtime.gate_scopes import us_scoped_gate_manifest from microcosm.build.us_runtime.gate_shadow import ( GATE_BATTERY_SHADOW_DIRECTORY, + US_GATE_SHADOW_SWITCH, GateBatteryShadowMismatchError, active_gate_shadow, + current_gate_shadow, shadow_file_paths, shadow_gate, ) -from test_support.microcosm_build.us_gate_shadow import load_us_gate_tool +from test_support.microcosm_build.us_gate_shadow import ( + arm_us_tool_gate_shadows, + load_us_gate_tool, +) + + +@pytest.fixture(autouse=True) +def _tool_shadows_on(monkeypatch) -> None: + arm_us_tool_gate_shadows(monkeypatch) @pytest.fixture @@ -109,6 +119,23 @@ def test_the_single_process_run_finishes_its_shadow(tmp_path, monkeypatch, base) } +def test_with_the_switch_off_no_shadow_is_armed_or_written(tmp_path, monkeypatch, base): + monkeypatch.setenv(US_GATE_SHADOW_SWITCH, "off") + args = _args(tmp_path, checkpoint_dir=None) + monkeypatch.setattr(base, "_verify_asec_source_digests", lambda args: None) + armed = [] + monkeypatch.setattr( + base, "_run_all", lambda args: armed.append(current_gate_shadow()) + ) + base._dispatch(args, None) + assert armed == [None] + with base._armed_stage_gate_shadow(_args(tmp_path, stage="wic_post_clone")) as save: + assert current_gate_shadow() is None + save() + assert not (args.out / GATE_BATTERY_SHADOW_DIRECTORY).exists() + assert not (tmp_path / "checkpoints" / GATE_BATTERY_SHADOW_DIRECTORY).exists() + + def test_a_verdict_difference_fails_the_single_process_run(tmp_path, monkeypatch, base): args = _args(tmp_path, checkpoint_dir=None) # The battery's gate fails where today's verdict passed. diff --git a/test_support/microcosm_build/us_gate_shadow.py b/test_support/microcosm_build/us_gate_shadow.py index 65ec6f20ad..078f8c0d85 100644 --- a/test_support/microcosm_build/us_gate_shadow.py +++ b/test_support/microcosm_build/us_gate_shadow.py @@ -14,8 +14,22 @@ from pathlib import Path from types import ModuleType +import pytest + +from microcosm.build.us_runtime.gate_shadow import US_GATE_SHADOW_SWITCH from test_support.paths import paths_for + +def arm_us_tool_gate_shadows(monkeypatch: pytest.MonkeyPatch) -> None: + """Let the build tools arm their shadows in this test. + + ``packages/microcosm-build/tests/conftest.py`` turns them off for every + test; a shadow test turns them back on before it drives a tool. + """ + + monkeypatch.delenv(US_GATE_SHADOW_SWITCH, raising=False) + + #: Scope to the build tool that evaluates it. US_GATE_SCOPE_TOOLS = { "us_base": "build_us_puf_support_base", diff --git a/tools/build_us_acs_local_release.py b/tools/build_us_acs_local_release.py index aea094adb9..97c2d12a9e 100644 --- a/tools/build_us_acs_local_release.py +++ b/tools/build_us_acs_local_release.py @@ -219,6 +219,7 @@ shadow_gate, shadow_not_run, shadow_value, + tool_gate_shadows_enabled, ) from microcosm.build.us_runtime.org_wages import ( US_ORG_OCCUPATION_AND_WORK_EXPERIENCE_OUTPUT_COLUMNS, @@ -7239,9 +7240,13 @@ def _local_gate_shadow_stage(args, stage: str): The stages may run as separate processes, so each saves what it observed beside the checkpoint, and rerunning a stage discards its own and every later stage's observations. Afterwards the scope's report and comparison - are rebuilt from every stage saved so far. + are rebuilt from every stage saved so far. With the switch off (the test + suite) the stage runs without a shadow and touches no shadow file. """ + if not tool_gate_shadows_enabled(): + yield None + return for name in _LOCAL_GATE_SHADOW_STAGES[_LOCAL_GATE_SHADOW_STAGES.index(stage) :]: _local_stage_observations(args, name).unlink(missing_ok=True) shadow = _local_gate_shadow(args, _local_gate_shadow_directory(args) / stage) diff --git a/tools/build_us_fiscal_refresh_release.py b/tools/build_us_fiscal_refresh_release.py index 37c011de01..13dc760240 100644 --- a/tools/build_us_fiscal_refresh_release.py +++ b/tools/build_us_fiscal_refresh_release.py @@ -303,6 +303,7 @@ shadow_gate, shadow_not_run, shadow_value, + tool_gate_shadows_enabled, ) from microcosm.build.us_runtime.h5_io import ( AuthenticatedPoolH5, @@ -13277,6 +13278,8 @@ def _start_national_gate_shadow(args: argparse.Namespace, *, release_id: str) -> global _ACTIVE_GATE_SHADOW _finish_national_gate_shadow(stopped_at="a previous run in this process") + if not tool_gate_shadows_enabled(): + return gates = us_scoped_gate_manifest(US_NATIONAL_GATE_SCOPE) report, comparison = shadow_file_paths( _national_gate_shadow_directory(args), US_NATIONAL_GATE_SCOPE diff --git a/tools/build_us_multispine_pool.py b/tools/build_us_multispine_pool.py index ba20a8c9b9..ca75412894 100644 --- a/tools/build_us_multispine_pool.py +++ b/tools/build_us_multispine_pool.py @@ -147,6 +147,7 @@ shadow_file_paths, shadow_gate, shadow_not_run, + tool_gate_shadows_enabled, ) from microcosm.build.us_runtime.h5_io import ( POPULACE_BLOCK_LADDER_SHA256_ATTR, @@ -7028,13 +7029,19 @@ def _pool_gate_shadow(args: argparse.Namespace) -> GateBatteryShadow: @contextmanager -def _armed_pool_gate_shadow(args: argparse.Namespace) -> Iterator[GateBatteryShadow]: +def _armed_pool_gate_shadow( + args: argparse.Namespace, +) -> Iterator[GateBatteryShadow | None]: """Arm the stacked path's shadow; finish it when the build returns. It finishes after every file today's build writes, its Logbook row included, so a verdict difference fails the run without changing them. + With the switch off (the test suite) the build runs without one. """ + if not tool_gate_shadows_enabled(): + yield None + return shadow = _pool_gate_shadow(args) with shadow, active_gate_shadow(shadow): yield shadow diff --git a/tools/build_us_puf_support_base.py b/tools/build_us_puf_support_base.py index 30950f9957..a4ffa93040 100644 --- a/tools/build_us_puf_support_base.py +++ b/tools/build_us_puf_support_base.py @@ -204,6 +204,7 @@ shadow_file_paths, shadow_gate, shadow_not_run, + tool_gate_shadows_enabled, ) from microcosm.build.us_runtime.h5_io import ( assert_h5_unchanged, @@ -997,13 +998,15 @@ def _run_staged_all( def _final_gate_shadow_directory(args: argparse.Namespace) -> Path | None: """Where the finished shadow files go: beside the outputs. - ``None`` only for stand-in arguments without ``--out`` (a test driving - the dispatcher), which have nowhere to write and run without a shadow; - the parser requires ``--out`` of every real run. + ``None``, and the run goes without a shadow, when the switch is off (the + test suite) or for stand-in arguments without ``--out``, which have + nowhere to write; the parser requires ``--out`` of every real run. """ out = getattr(args, "out", None) - return None if out is None else Path(out).resolve() / GATE_BATTERY_SHADOW_DIRECTORY + if out is None or not tool_gate_shadows_enabled(): + return None + return Path(out).resolve() / GATE_BATTERY_SHADOW_DIRECTORY def _stage_gate_shadow_observations(args: argparse.Namespace, stage: str) -> Path: @@ -1058,9 +1061,13 @@ def _armed_stage_gate_shadow(args: argparse.Namespace) -> Iterator[Callable[[], the observations of every stage it does not run again. A stage that raises saves what it saw on the way out, so the parent's report says where the build stopped. A save that fails warns and is otherwise left to - the parent, which then reports the stage's entries as unobserved. + the parent, which then reports the stage's entries as unobserved. With + the switch off the stage runs without a shadow and saves nothing. """ + if not tool_gate_shadows_enabled(): + yield lambda: None + return shadow = _base_gate_shadow( args, args.checkpoint_dir / GATE_BATTERY_SHADOW_DIRECTORY / args.stage ) From 155b96906605e1c650e6c3be00a4885dda404bf0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mar=C3=ADa=20Juaristi?= <127882282+juaristi22@users.noreply.github.com> Date: Sun, 15 Nov 2026 15:13:50 +0000 Subject: [PATCH 10/31] Keep the release gates' call and the engine's lifetime as they are today The shadow site for us_national_release_gates had turned the seven positional arguments of _release_gate_failures into keywords. The #547 corridor tests read them by position (args[8], the degenerate-input gate), and a stub that does so would fail inside today's degraded-mode guard, turning the run's failures into one line. The site now makes today's call argument for argument; only the evidence names them. The degenerate-input gate's engine was hoisted into a local so that the battery sees the same engine, which kept it alive for the rest of _main. It is now bound into the two lambdas and deleted after the gate, as the temporary it was. Co-Authored-By: Claude Opus 5.5 --- tools/build_us_fiscal_refresh_release.py | 74 ++++++++++++++++-------- 1 file changed, 51 insertions(+), 23 deletions(-) diff --git a/tools/build_us_fiscal_refresh_release.py b/tools/build_us_fiscal_refresh_release.py index 13dc760240..2d02a6bf5b 100644 --- a/tools/build_us_fiscal_refresh_release.py +++ b/tools/build_us_fiscal_refresh_release.py @@ -15872,12 +15872,15 @@ def _main(argv: Sequence[str] | None = None) -> int | None: degenerate_input_engine = PolicyEngineUSEngine() degenerate_input_gate = shadow_gate( "us_national_degenerate_input", - lambda: _degenerate_input_signal_gate(base_frame, degenerate_input_engine), - lambda: EvidenceContext( - frame=base_frame, - artifacts={"policyengine_engine": degenerate_input_engine}, + lambda engine=degenerate_input_engine: _degenerate_input_signal_gate( + base_frame, engine + ), + lambda engine=degenerate_input_engine: EvidenceContext( + frame=base_frame, artifacts={"policyengine_engine": engine} ), ) + # Today's call made the engine a temporary; it lives no longer here. + del degenerate_input_engine if not degenerate_input_gate.passed: # Same degraded contract as the input-mass gate above: the gate # object rides _release_gate_failures to the batch; no raise, no @@ -16785,33 +16788,58 @@ def _main(argv: Sequence[str] | None = None) -> int | None: None if args.allow_ecps_parity_gaps else ecps_parity_gate ) try: - release_gate_inputs = { - "target_profile_gate": target_profile_gate, - "health_input_gate": health_input_gate, - "base_population_gate": base_population_gate, - "incumbent_diagnostics": incumbent_diagnostics, - "immigration_gate": immigration_gate, - "input_mass_reference_gate": enforced_input_mass_reference_gate, - "degenerate_input_gate": degenerate_input_gate, - "ecps_parity_gate": enforced_ecps_parity_gate, - "hours_worked_gate": hours_worked_gate, - "snap_take_up_gate": snap_take_up_gate, - "eligibility_inputs_gate": eligibility_inputs_gate, - "pregnancy_gate": pregnancy_gate, - "reported_coverage_vintage_gate": reported_coverage_vintage_gate, - "snap_discretionary_exemption_gate": snap_discretionary_exemption_gate, - "target_registry": registry, - } gate_failures = shadow_failures( "us_national_release_gates", - lambda: _release_gate_failures(result, compilation, **release_gate_inputs), + # Today's call, argument for argument: callers read its + # positional arguments (the #547 corridor tests read args[8]). + lambda: _release_gate_failures( + result, + compilation, + target_profile_gate, + health_input_gate, + base_population_gate, + incumbent_diagnostics, + immigration_gate, + enforced_input_mass_reference_gate, + degenerate_input_gate, + ecps_parity_gate=enforced_ecps_parity_gate, + hours_worked_gate=hours_worked_gate, + snap_take_up_gate=snap_take_up_gate, + eligibility_inputs_gate=eligibility_inputs_gate, + pregnancy_gate=pregnancy_gate, + reported_coverage_vintage_gate=reported_coverage_vintage_gate, + snap_discretionary_exemption_gate=snap_discretionary_exemption_gate, + target_registry=registry, + ), lambda: EvidenceContext( artifacts={ "calibration_result": result, "target_compilation": compilation, **{ f"release_gates_{name}": value - for name, value in release_gate_inputs.items() + for name, value in { + "target_profile_gate": target_profile_gate, + "health_input_gate": health_input_gate, + "base_population_gate": base_population_gate, + "incumbent_diagnostics": incumbent_diagnostics, + "immigration_gate": immigration_gate, + "input_mass_reference_gate": ( + enforced_input_mass_reference_gate + ), + "degenerate_input_gate": degenerate_input_gate, + "ecps_parity_gate": enforced_ecps_parity_gate, + "hours_worked_gate": hours_worked_gate, + "snap_take_up_gate": snap_take_up_gate, + "eligibility_inputs_gate": eligibility_inputs_gate, + "pregnancy_gate": pregnancy_gate, + "reported_coverage_vintage_gate": ( + reported_coverage_vintage_gate + ), + "snap_discretionary_exemption_gate": ( + snap_discretionary_exemption_gate + ), + "target_registry": registry, + }.items() }, } ), From 7ad4c5ff069c053dd97c5f30babc10b796e6dfda Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mar=C3=ADa=20Juaristi?= <127882282+juaristi22@users.noreply.github.com> Date: Sun, 15 Nov 2026 15:13:57 +0000 Subject: [PATCH 11/31] Hold the national shadow's files until the certified-dir refusal, per release The national shadow is armed before the preflight gates, which run ahead of _main's unconditional refusal to reuse a certified release directory (microcosm#568). Its constructor cleared /gate_battery_shadow and its stop wrote there, so a refused rerun replaced the certified build's shadow files with its own refusal. GateBatteryShadow now takes hold_files: until release_files() it neither clears nor writes, and a run that stops while held leaves the directory as it found it. _main releases them on the statement after the refusal; a dry run writes beside its own report and is not held. The national and evidence releases can share an --out, so each now has its own directory, /gate_battery_shadow/. Co-Authored-By: Claude Opus 5.5 --- .../microcosm/build/us_runtime/gate_shadow.py | 55 +++++++++++++++-- .../us/test_us_fiscal_refresh_gate_shadow.py | 60 ++++++++++++++++++- .../engine_free/us/test_us_gate_shadow.py | 52 ++++++++++++++++ tools/build_us_fiscal_refresh_release.py | 28 ++++++++- 4 files changed, 184 insertions(+), 11 deletions(-) diff --git a/packages/microcosm-build/src/microcosm/build/us_runtime/gate_shadow.py b/packages/microcosm-build/src/microcosm/build/us_runtime/gate_shadow.py index bc385ce89c..69a3067746 100644 --- a/packages/microcosm-build/src/microcosm/build/us_runtime/gate_shadow.py +++ b/packages/microcosm-build/src/microcosm/build/us_runtime/gate_shadow.py @@ -428,6 +428,11 @@ class GateBatteryShadow: waive it today. overrides: Entry id to the declared parameters this build's flags overrode, each ``{"declared": ..., "runtime": ...}``. + hold_files: Touch no file until :meth:`release_files`, for a tool + that must refuse before its first side effect: the shadow neither + clears an earlier run's files nor writes its own, and a run that + stops while they are held leaves the directory as it found it. + A finished run writes them regardless. """ def __init__( @@ -441,6 +446,7 @@ def __init__( registry: Mapping[str, GateBinding], waivers: Mapping[str, Sequence[str]] | None = None, overrides: Mapping[str, Mapping[str, Mapping[str, object]]] | None = None, + hold_files: bool = False, ) -> None: declared = {entry.id for entry in gates.gates} self._scope = str(scope) @@ -471,16 +477,39 @@ def __init__( raise ValueError( f"waivers or overrides name entries outside scope {scope!r}: {unknown}." ) - # A rerun into the same output directory must not leave an earlier - # attempt's shadow files looking like this run's when it stops before - # writing its own. - for stale in (self._run.report_path, self._comparison_path): - stale.unlink(missing_ok=True) self._declared = frozenset(declared) self._lock = threading.RLock() self._observations: dict[str, _Observation] = {} self._shadow_errors: list[str] = [] self._finished = False + self._files_held = bool(hold_files) + if not self._files_held: + self._clear_stale_files() + + def _clear_stale_files(self) -> None: + # A rerun into the same output directory must not leave an earlier + # attempt's shadow files looking like this run's when it stops before + # writing its own. + for stale in (self._run.report_path, self._comparison_path): + stale.unlink(missing_ok=True) + + def release_files(self) -> None: + """Let a shadow built with ``hold_files`` clear and write its files. + + Never raises: a fault is recorded as a shadow error. + """ + + with self._lock: + if not self._files_held: + return + self._files_held = False + try: + self._clear_stale_files() + except Exception as exc: # noqa: BLE001 - the shadow never stops the tool + self._shadow_errors.append( + f"shadow could not clear an earlier run's files: " + f"{type(exc).__name__}: {exc}" + ) # -- properties --------------------------------------------------------- @@ -871,7 +900,8 @@ def finish( raises: the tool's own exit stands. Returns: - The comparison payload written to disk. + The comparison payload written to disk, or an empty mapping when a + run stopped while its files were held, which writes nothing. """ with self._lock: @@ -887,6 +917,19 @@ def _finish( raise RuntimeError("the shadow has already finished.") self._finished = True completed = stopped_by is None and stopped_at is None + if self._files_held: + if not completed: + # The tool stopped before it let the shadow write, as on a + # refusal ahead of its first side effect: an earlier run's + # files stay exactly as they were. + print( + f"note: US gate battery shadow for scope {self._scope!r} wrote " + "no files: the run stopped before the tool let it write.", + file=sys.stderr, + ) + return {} + self._files_held = False + self._clear_stale_files() recorded: list[str] = [] not_observed: list[str] = [] try: diff --git a/packages/microcosm-build/tests/engine_free/us/test_us_fiscal_refresh_gate_shadow.py b/packages/microcosm-build/tests/engine_free/us/test_us_fiscal_refresh_gate_shadow.py index 82115f8056..dc4754f43f 100644 --- a/packages/microcosm-build/tests/engine_free/us/test_us_fiscal_refresh_gate_shadow.py +++ b/packages/microcosm-build/tests/engine_free/us/test_us_fiscal_refresh_gate_shadow.py @@ -9,8 +9,10 @@ from __future__ import annotations +import ast import importlib import json +from pathlib import Path from types import SimpleNamespace import pytest @@ -165,13 +167,23 @@ def build(argv): monkeypatch.setattr(release, "_main", build) release.main([]) - payload = _comparison(args.out.resolve() / "gate_battery_shadow") + payload = _comparison(release._national_gate_shadow_directory(args)) assert payload["run_completed"] is True assert payload["verdict_difference"] is False assert payload["phases_recorded"] == ["preflight", "assembled", "terminal"] assert payload["release_id"] == "microcosm-us-test" +def test_each_release_keeps_its_own_shadow_files(tmp_path, release) -> None: + national = release._national_gate_shadow_directory(_args(tmp_path)) + evidence = release._national_gate_shadow_directory( + _args(tmp_path, evidence_release=True) + ) + shared = (tmp_path / "out").resolve() / GATE_BATTERY_SHADOW_DIRECTORY + assert national == shared / release.US_NATIONAL_RELEASE_ID + assert evidence == shared / release.US_EVIDENCE_RELEASE_ID + + def test_a_verdict_difference_fails_a_finished_build(tmp_path, monkeypatch, release): args = _args(tmp_path) _stand_in_gates(monkeypatch, release, failing={"pregnancy_signal"}) @@ -217,16 +229,60 @@ def test_todays_exception_propagates_and_the_shadow_records_it( def refused(argv): release._start_national_gate_shadow(args, release_id="microcosm-us-test") + # Past the certified-directory refusal, where _main lets it write. + release._release_national_gate_shadow_files() raise RuntimeError("Release gates failed: something upstream") monkeypatch.setattr(release, "_main", refused) with pytest.raises(RuntimeError, match="something upstream"): release.main([]) - payload = _comparison(args.out.resolve() / "gate_battery_shadow") + payload = _comparison(release._national_gate_shadow_directory(args)) assert payload["stopped_by"]["type"] == "RuntimeError" assert payload["run_completed"] is False +def test_a_run_refused_before_its_outputs_leaves_earlier_files_alone( + tmp_path, monkeypatch, release +): + args = _args(tmp_path) + report, comparison = shadow_file_paths( + release._national_gate_shadow_directory(args), "us_national" + ) + comparison.parent.mkdir(parents=True) + comparison.write_text('{"the certified build": true}') + report.write_text("{}") + + def refused(argv): + release._start_national_gate_shadow(args, release_id="microcosm-us-test") + raise RuntimeError("the release directory already carries a certified build") + + monkeypatch.setattr(release, "_main", refused) + with pytest.raises(RuntimeError, match="already carries"): + release.main([]) + assert json.loads(comparison.read_text()) == {"the certified build": True} + assert report.read_text() == "{}" + + +def test_main_lets_the_shadow_write_only_after_the_certified_dir_refusal( + release, +) -> None: + tree = ast.parse(Path(release.__file__).read_text()) + main_fn = next( + node + for node in tree.body + if isinstance(node, ast.FunctionDef) and node.name == "_main" + ) + statements = [ast.unparse(statement) for statement in main_fn.body] + refusal = statements.index("_refuse_certified_release_dir_reuse(release_dir)") + assert statements[refusal + 1] == "_release_national_gate_shadow_files()" + starts = [ + index + for index, statement in enumerate(statements) + if statement.startswith("_start_national_gate_shadow(") + ] + assert len(starts) == 1 and starts[0] < refusal + + def test_with_the_switch_off_main_arms_no_shadow(tmp_path, monkeypatch, release): monkeypatch.setenv(US_GATE_SHADOW_SWITCH, "off") args = _args(tmp_path) diff --git a/packages/microcosm-build/tests/engine_free/us/test_us_gate_shadow.py b/packages/microcosm-build/tests/engine_free/us/test_us_gate_shadow.py index bd371f0002..1830dac311 100644 --- a/packages/microcosm-build/tests/engine_free/us/test_us_gate_shadow.py +++ b/packages/microcosm-build/tests/engine_free/us/test_us_gate_shadow.py @@ -620,6 +620,58 @@ def test_stale_shadow_files_are_removed_when_a_run_starts(tmp_path) -> None: assert not report.exists() and not comparison.exists() +def _earlier_files(tmp_path): + report, comparison = shadow_file_paths(tmp_path, "us_test") + report.write_text('{"earlier": "report"}') + comparison.write_text('{"earlier": "comparison"}') + return report, comparison + + +def test_held_files_survive_a_run_that_stops_before_it_lets_them_go( + tmp_path, +) -> None: + report, comparison = _earlier_files(tmp_path) + shadow = _shadow(tmp_path, _two_phase_gates(), hold_files=True) + shadow.gate( + "us_test_alpha", + lambda: ALPHA(0.5), + EvidenceContext(artifacts={"alpha_value": 0.5}), + ) + shadow.stop(RuntimeError("refused before the first side effect")) + assert json.loads(report.read_text()) == {"earlier": "report"} + assert json.loads(comparison.read_text()) == {"earlier": "comparison"} + + +def test_released_files_are_cleared_and_then_written(tmp_path) -> None: + report, comparison = _earlier_files(tmp_path) + shadow = _shadow(tmp_path, _two_phase_gates(), hold_files=True) + shadow.release_files() + assert not report.exists() and not comparison.exists() + shadow.release_files() # once is enough; a second call changes nothing + shadow.stop(RuntimeError("a later failure")) + payload = json.loads(comparison.read_text()) + assert payload["stopped_by"]["type"] == "RuntimeError" + + +def test_a_finished_run_writes_its_files_even_while_held(tmp_path) -> None: + _, comparison = _earlier_files(tmp_path) + gates = _two_phase_gates() + with _shadow(tmp_path, gates, hold_files=True) as shadow: + for entry_id, value in ( + ("us_test_alpha", 0.5), + ("us_test_beta", 2.0), + ("us_test_final", 0.1), + ): + gate = BETA if entry_id == "us_test_beta" else ALPHA + key = "beta_value" if entry_id == "us_test_beta" else "alpha_value" + shadow.gate( + entry_id, + lambda gate=gate, value=value: gate(value), + EvidenceContext(artifacts={key: value}), + ) + assert json.loads(comparison.read_text())["run_completed"] is True + + def test_the_suite_runs_the_tools_without_their_shadows(monkeypatch) -> None: # tests/conftest.py spells the switch out; this holds it to the constant. assert os.environ.get(US_GATE_SHADOW_SWITCH) == "off" diff --git a/tools/build_us_fiscal_refresh_release.py b/tools/build_us_fiscal_refresh_release.py index 2d02a6bf5b..5faa9fbb98 100644 --- a/tools/build_us_fiscal_refresh_release.py +++ b/tools/build_us_fiscal_refresh_release.py @@ -13245,7 +13245,9 @@ def _is_release_refusal(error: BaseException) -> bool: def _national_gate_shadow_directory(args: argparse.Namespace) -> Path: - """Beside the outputs: ``/gate_battery_shadow``, never a release dir. + """``/gate_battery_shadow/``: beside the outputs, never in a + release directory, and one per release, since the national and evidence + releases can share an ``--out``. A dry run writes no output directory, so its shadow goes beside its report instead. @@ -13254,7 +13256,11 @@ def _national_gate_shadow_directory(args: argparse.Namespace) -> Path: if args.dry_run_gates_report is not None: report = Path(args.dry_run_gates_report).resolve() return report.parent / f"{report.stem}.{GATE_BATTERY_SHADOW_DIRECTORY}" - return Path(args.out).resolve() / GATE_BATTERY_SHADOW_DIRECTORY + return ( + Path(args.out).resolve() + / GATE_BATTERY_SHADOW_DIRECTORY + / _release_for_build(args) + ) def _national_gate_waivers( @@ -13274,7 +13280,14 @@ def _national_gate_waivers( def _start_national_gate_shadow(args: argparse.Namespace, *, release_id: str) -> None: - """Arm this run's gate battery in shadow (finished in :func:`main`).""" + """Arm this run's gate battery in shadow (finished in :func:`main`). + + The preflight gates run before ``_main`` refuses to reuse a certified + release directory, so a build's shadow holds its files until + :func:`_release_national_gate_shadow_files`: a refused rerun leaves the + certified build's shadow files as they were. A dry run's files go beside + its own report and are not held. + """ global _ACTIVE_GATE_SHADOW _finish_national_gate_shadow(stopped_at="a previous run in this process") @@ -13293,11 +13306,19 @@ def _start_national_gate_shadow(args: argparse.Namespace, *, release_id: str) -> registry=us_gate_registry(US_NATIONAL_GATE_SCOPE, tool=globals()), waivers=_national_gate_waivers(args, gates), overrides=us_flag_overrides(gates, us_gate_specs(US_NATIONAL_GATE_SCOPE), args), + hold_files=args.dry_run_gates_report is None, ) arm_gate_shadow(shadow) _ACTIVE_GATE_SHADOW = shadow +def _release_national_gate_shadow_files() -> None: + """Let the armed shadow write, once no certified release dir is reused.""" + + if _ACTIVE_GATE_SHADOW is not None: + _ACTIVE_GATE_SHADOW.release_files() + + def _finish_national_gate_shadow( *, stopped_by: BaseException | None = None, @@ -14023,6 +14044,7 @@ def _main(argv: Sequence[str] | None = None) -> int | None: # --checkpoint-root beneath releases/ must not mutate a certified # directory before the raise (microcosm#568 round 4). _refuse_certified_release_dir_reuse(release_dir) + _release_national_gate_shadow_files() checkpoint_root, target_materialization_cache_dir, target_frame_checkpoint_path = ( _resolve_checkpoint_paths(args, artifact_root=artifact_root) ) From 3dc196651a2eede04221fb3ae70b43b838a6fd80 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mar=C3=ADa=20Juaristi?= <127882282+juaristi22@users.noreply.github.com> Date: Sun, 15 Nov 2026 15:13:57 +0000 Subject: [PATCH 12/31] Pin the weights-audit sites to the shared binding's own gate The audit entries use PR 1's shared weights_audit binding, which holds the gate function itself rather than looking it up in the tool, so the base and pool sites must call that same object. Co-Authored-By: Claude Opus 5.5 --- .../tests/engine_free/us/test_us_battery_bindings.py | 10 +++++++++- 1 file changed, 9 insertions(+), 1 deletion(-) diff --git a/packages/microcosm-build/tests/engine_free/us/test_us_battery_bindings.py b/packages/microcosm-build/tests/engine_free/us/test_us_battery_bindings.py index 5e1959929a..d1fa339d83 100644 --- a/packages/microcosm-build/tests/engine_free/us/test_us_battery_bindings.py +++ b/packages/microcosm-build/tests/engine_free/us/test_us_battery_bindings.py @@ -20,7 +20,7 @@ from microcosm.build import FitWeightRecord from microcosm.build.country_spec import load_gates_manifest -from microcosm.build.gate_battery import EvidenceContext, GateStatus +from microcosm.build.gate_battery import DEFAULT_REGISTRY, EvidenceContext, GateStatus from microcosm.build.gates import UNWEIGHTED_KIND, GateResult from microcosm.build.us_runtime.battery_bindings import ( FRAME, @@ -399,6 +399,14 @@ def test_the_shared_weights_audit_fails_both_verdicts_alike(tmp_path, scope) -> assert shadow.differences() == () +@pytest.mark.parametrize("scope", ["us_base", "us_pool"]) +def test_the_audit_site_calls_the_shared_bindings_own_gate(scope) -> None: + # The one binding not looked up in the tool: PR 1's shared weights_audit + # holds the gate function itself, so the tool must call that same object. + tool = load_us_gate_tool(scope) + assert tool.weights_audit_gate is DEFAULT_REGISTRY["weights_audit"].gate + + def test_a_declared_threshold_off_todays_constant_is_a_difference(tmp_path) -> None: # The pin is live: a spec edit that today's constant does not follow is # caught at the next evaluation, as a verdict difference. From d466ad841b5a14255b21b1748fb33ac9c1f6ff20 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mar=C3=ADa=20Juaristi?= <127882282+juaristi22@users.noreply.github.com> Date: Sun, 15 Nov 2026 15:15:03 +0000 Subject: [PATCH 13/31] Check the base's shadow on real gates in the opt-in equivalence workflow Three locked builds of the opt-in sample: single-process with the shadow, single-process without it, and staged with it. The battery must reach today's verdict on every entry, observe every one, change no byte of the dataset, and the staged children's saved observations must add up to the single process's comparison. Written for the engine job; it runs only where POPULACE_US_PUF_EQUIVALENCE_INPUT_DIR is set, and has not been run here. Co-Authored-By: Claude Opus 5.5 --- .../test_us_puf_support_base_equivalence.py | 69 +++++++++++++++++++ 1 file changed, 69 insertions(+) diff --git a/packages/microcosm-build/tests/engine_workflow/us/test_us_puf_support_base_equivalence.py b/packages/microcosm-build/tests/engine_workflow/us/test_us_puf_support_base_equivalence.py index b25961e170..736c590faf 100644 --- a/packages/microcosm-build/tests/engine_workflow/us/test_us_puf_support_base_equivalence.py +++ b/packages/microcosm-build/tests/engine_workflow/us/test_us_puf_support_base_equivalence.py @@ -23,6 +23,11 @@ PUF_TAX_DETAIL_DEFAULT_PERSON_OUTPUTS, PUF_TAX_DETAIL_DEFAULT_TAX_UNIT_OUTPUTS, ) +from microcosm.build.us_runtime.gate_shadow import ( + GATE_BATTERY_SHADOW_DIRECTORY, + US_GATE_SHADOW_SWITCH, + shadow_file_paths, +) from microcosm.frame import Frame from test_support.paths import paths_for @@ -129,6 +134,70 @@ def test_monolith_and_staged_builds_are_bit_exact_at_every_boundary( ) +@pytest.mark.slow +def test_the_gate_battery_shadow_agrees_and_changes_no_output(tmp_path: Path) -> None: + """microcosm#1585 item 11 (PR 2): the base's gates in shadow, on real gates. + + Three locked builds of one sample: single-process with the shadow, + single-process without it, and staged with it. On every entry the + battery reaches today's verdict; the shadow changes no byte of the + dataset; and the staged children's saved observations add up to the + single process's comparison. + """ + + fixture = _prepare_builder_fixture(tmp_path) + locked = {**os.environ, **_LOCKED_ENVIRONMENT} + # tests/conftest.py turns the tools' shadows off for every test. + shadowed = { + key: value for key, value in locked.items() if key != US_GATE_SHADOW_SWITCH + } + unshadowed = {**locked, US_GATE_SHADOW_SWITCH: "off"} + staged_checkpoints = tmp_path / "staged_checkpoints" + runs = { + "monolith": (tmp_path / "monolith", (), shadowed), + "unshadowed": (tmp_path / "unshadowed", (), unshadowed), + "staged": ( + tmp_path / "staged", + ("--checkpoint-dir", str(staged_checkpoints)), + shadowed, + ), + } + for out, extra, environment in runs.values(): + _run_builder( + [*fixture.common_command, "--out", str(out), *extra], + cwd=fixture.root, + environment=environment, + ) + + shadowed_h5 = runs["monolith"][0] / _DATASET_FILENAME + unshadowed_h5 = runs["unshadowed"][0] / _DATASET_FILENAME + assert shadowed_h5.read_bytes() == unshadowed_h5.read_bytes() + assert not (runs["unshadowed"][0] / GATE_BATTERY_SHADOW_DIRECTORY).exists() + verdicts = {} + for name in ("monolith", "staged"): + _, path = shadow_file_paths( + runs[name][0] / GATE_BATTERY_SHADOW_DIRECTORY, "us_base" + ) + payload = json.loads(path.read_text(encoding="utf-8")) + assert payload["run_completed"] is True, name + assert payload["verdict_difference"] is False, ( + name, + payload["differences"], + payload["shadow_errors"], + ) + assert payload["not_observed"] == [], name + verdicts[name] = { + row["id"]: ( + row["legacy"]["status"], + row["legacy"].get("failures"), + row["battery"]["status"], + row["battery"].get("failures"), + ) + for row in payload["entries"] + } + assert verdicts["monolith"] == verdicts["staged"] + + @pytest.mark.slow def test_staged_build_completes_with_production_threading(tmp_path: Path) -> None: """Opt-in stress run: validate production-width execution, not equality.""" From 3294497fe7dcd04a882895672562017d42de5596 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mar=C3=ADa=20Juaristi?= <127882282+juaristi22@users.noreply.github.com> Date: Sun, 15 Nov 2026 15:15:51 +0000 Subject: [PATCH 14/31] Say where the national shadow writes, and that the test suite turns it off Co-Authored-By: Claude Opus 5.5 --- docs/gate-battery-contract.md | 10 +++++++++- 1 file changed, 9 insertions(+), 1 deletion(-) diff --git a/docs/gate-battery-contract.md b/docs/gate-battery-contract.md index 73c74ce265..9e0b633844 100644 --- a/docs/gate-battery-contract.md +++ b/docs/gate-battery-contract.md @@ -339,7 +339,15 @@ not evaluate matches `evidence_absent`. The shadow writes its scope's report and the comparison beside the tool's outputs (never inside a release directory), never raises while the tool runs, and fails a finished run on a verdict difference; today's own exception always propagates -unchanged. +unchanged. The national release's shadow is armed before its preflight +gates, which run ahead of the refusal to reuse a certified release +directory, so it holds its files until that refusal has passed: a refused +rerun leaves the certified build's shadow files as they were, and each +release keeps its own, in `/gate_battery_shadow/`. Real +builds always arm the shadow. The test suite turns it off for every test +(`MICROCOSM_US_GATE_SHADOW=off`, in `packages/microcosm-build/tests/conftest.py`), +because its tests stand stubs in for whole stages, and the shadow's own +tests turn it back on. Most US entries are `stage_health` entries whose `check` names the gate, and `us_runtime/battery_bindings.py` binds each check to the gate function From ac94c682110a674d30f0533d9b15a1b8916d96c3 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mar=C3=ADa=20Juaristi?= <127882282+juaristi22@users.noreply.github.com> Date: Sun, 15 Nov 2026 20:30:28 +0000 Subject: [PATCH 15/31] Never name unreached a gate today's code reached, here or in another process #1609 now refuses a phase that marks unreached an entry the run evaluated (da67e41dc), but a shadow names unreached the entries it holds no outcome for, and that is not the same set. Today's code may have reached an entry the shadow could not evaluate (its evidence builder raised), and a scope rebuilt from stages run as other processes holds only their outcomes, which the run's own check cannot see. The shadow now keeps every entry today's code reached, saves it with its observations as `reached`, and requires it on load. A file that cannot be read, or a stage a tool says saved nothing (`note_missing_observations`), is listed under `observations_missing` in the comparison. The phase a stopped run ends in is recorded only when none of its entries without an outcome was reached and no observations are missing; otherwise it stays unrecorded, as when no gate explains the stop. A note alone does not fail a finished run: the entries a missing stage observed are unobserved, which does. A fault while recording, the run's new refusal among them, no longer resets `phases_recorded` and `report_file`: the phases the run already wrote stay listed, so the comparison matches the report on disk. With the new check disabled, the four tests of it fail: the phase is recorded with a reached gate marked unreached. Co-Authored-By: Claude Opus 5.5 --- .../microcosm/build/us_runtime/gate_shadow.py | 106 +++++++++--- .../engine_free/us/test_us_gate_shadow.py | 161 ++++++++++++++++++ 2 files changed, 247 insertions(+), 20 deletions(-) diff --git a/packages/microcosm-build/src/microcosm/build/us_runtime/gate_shadow.py b/packages/microcosm-build/src/microcosm/build/us_runtime/gate_shadow.py index 69a3067746..8daa4aa0f4 100644 --- a/packages/microcosm-build/src/microcosm/build/us_runtime/gate_shadow.py +++ b/packages/microcosm-build/src/microcosm/build/us_runtime/gate_shadow.py @@ -15,7 +15,9 @@ are written beside its outputs as shadow files. A verdict difference then fails the run, so a build proves parity on its own inputs. When today's code raises, the files are written with what the battery saw up to that point, and -today's exception propagates unchanged. +today's exception propagates unchanged. The phase it stopped in is recorded +only when every entry there without an outcome is one today's code never +reached, here or in a process whose observations were loaded. The comparison follows the waiver proposal posted on microcosm#1609, which is still for Max and MarĂ­a to settle: @@ -480,6 +482,13 @@ def __init__( self._declared = frozenset(declared) self._lock = threading.RLock() self._observations: dict[str, _Observation] = {} + # Entries today's code reached, here or in a process whose saved + # observations were loaded, whatever the shadow made of them: a + # stopped phase never marks one of them unreached. + self._reached: set[str] = set() + # Observations of this scope that are missing: a saved file that could + # not be read, or a stage that ran and saved none. + self._observations_missing: list[str] = [] self._shadow_errors: list[str] = [] self._finished = False self._files_held = bool(hold_files) @@ -585,6 +594,9 @@ def _check( site: str | None, ) -> GateOutcome | None: try: + # Today's code reached this entry, whatever the shadow makes of it + # (as text, so a miswired id cannot stop the stage's save). + self._reached.add(str(entry_id)) if self._finished: raise RuntimeError("the shadow has already finished.") if entry_id in self._observations: @@ -747,7 +759,9 @@ def save_observations(self, path: Path | str) -> None: stage's gates in its own process and leaves them here; the process that finishes the scope loads every stage's file. The file is bound to the scope's manifest digest, so a later process with another - policy refuses it instead of mixing two. + policy refuses it instead of mixing two. It also names every entry + today's code reached here, including those the shadow could not + evaluate, so a later process never marks one of them unreached. """ with self._lock: @@ -757,6 +771,7 @@ def save_observations(self, path: Path | str) -> None: "producer": GATE_BATTERY_SHADOW_PRODUCER, "scope": self._scope, "gates_manifest_sha256": self._run.gates_manifest_sha256, + "reached": sorted(self._reached), "observations": [ { "id": observation.entry_id, @@ -779,7 +794,9 @@ def load_observations(self, path: Path | str) -> None: Each stored observation is compared again under this shadow's own rule and overrides. A file for another scope or manifest, an entry - already observed, or an unreadable file is a shadow error. + already observed, or an unreadable file is a shadow error; a file + not read whole also counts as missing observations (see + :meth:`note_missing_observations`). """ source = Path(path) @@ -799,6 +816,12 @@ def load_observations(self, path: Path | str) -> None: != self._run.gates_manifest_sha256 ): raise ValueError("observations made under another gate manifest.") + reached = payload.get("reached") + if not isinstance(reached, list) or not all( + isinstance(entry_id, str) for entry_id in reached + ): + raise ValueError("reached must be a list of entry ids.") + self._reached.update(reached) rows = payload.get("observations") if not isinstance(rows, list): raise ValueError("observations must be a list.") @@ -811,9 +834,25 @@ def load_observations(self, path: Path | str) -> None: f"could not load shadow observations {source}: " f"{type(exc).__name__}: {exc}" ) + self._observations_missing.append(f"{source.name} was not read whole") + + def note_missing_observations(self, source: str) -> None: + """Note that a process which may have reached this scope's entries left + no observations here, such as a stage that ran and saved none. + + It does not fail a finished run by itself: an entry that process + observed is then unobserved, which does. A stopped run cannot tell + that process's entries from the ones never reached, so it leaves the + phase it stopped in unrecorded. Never raises. + """ + + with self._lock: + self._observations_missing.append(str(source)) def _load_row(self, row: Mapping, source: Path) -> None: entry_id = str(row["id"]) + # Another process observed it, so today's code reached it there. + self._reached.add(entry_id) if entry_id in self._observations: self._shadow_errors.append( f"[{entry_id}] observed again in {source.name}; kept the first." @@ -897,7 +936,10 @@ def finish( stops on purpose before its last phase (``stopped_at``: why, as the release's dry run does) records the phases it completed, plus the phase it stopped in when a battery outcome there blocks, and never - raises: the tool's own exit stands. + raises: the tool's own exit stands. That phase names unreached the + entries without an outcome, so it is recorded only when today's code + reached none of them and no observations are missing; otherwise it + stays unrecorded rather than mark a gate that ran as never reached. Returns: The comparison payload written to disk, or an empty mapping when a @@ -933,7 +975,10 @@ def _finish( recorded: list[str] = [] not_observed: list[str] = [] try: - recorded, not_observed = self._record_phases(completed=completed) + not_observed = self._not_observed() + # Phases recorded before a fault stay listed: the run has already + # written them to its report. + self._record_phases(recorded, completed=completed) except Exception as exc: # noqa: BLE001 - written down, decided below self._shadow_errors.append( f"shadow could not record its phases: {type(exc).__name__}: {exc}" @@ -973,12 +1018,25 @@ def _finish( ) return payload - def _record_phases(self, *, completed: bool) -> tuple[list[str], list[str]]: - """Assemble and record each phase the tool reached, in order.""" + def _not_observed(self) -> list[str]: + """Applicable entries without a battery outcome, phase by phase.""" + + return [ + entry.id + for phase in self._gates.phases + for entry in self._gates.gates + if entry.phase == phase + and entry.not_applicable is None + and self.outcome(entry.id) is None + ] + + def _record_phases(self, recorded: list[str], *, completed: bool) -> None: + """Assemble and record each phase the tool reached, in order. + + Each recorded phase is appended to ``recorded`` as soon as the run + has written it, so a later fault leaves the list true to the report. + """ - recorded: list[str] = [] - not_observed: list[str] = [] - stop = False for phase in self._gates.phases: entries = [entry for entry in self._gates.gates if entry.phase == phase] ran = [ @@ -991,9 +1049,6 @@ def _record_phases(self, *, completed: bool) -> tuple[list[str], list[str]]: for entry in entries if entry.not_applicable is None and self.outcome(entry.id) is None ] - not_observed.extend(missing) - if stop: - continue outcomes = [self.outcome(entry.id) for entry in ran] if not missing: self._run.record_phase( @@ -1001,12 +1056,22 @@ def _record_phases(self, *, completed: bool) -> tuple[list[str], list[str]]: ) recorded.append(phase) continue - stop = True if completed or not ran: - continue - # The tool stopped inside this phase. Name the last observed entry - # that blocks as the blocker, as the battery would have stopped - # there; without one the phase stays unrecorded. + return + # The tool stopped inside this phase, and its entries without an + # outcome would be named unreached. That is untrue of one today's + # code reached but the shadow could not evaluate (here or in the + # process that saved it), and may be untrue when a stage's + # observations are missing, so then the phase stays unrecorded. + # The run itself refuses a phase that marks unreached an entry it + # evaluated, but it sees only this process's stages. + if self._observations_missing or any( + entry_id in self._reached for entry_id in missing + ): + return + # Otherwise name the last observed entry that blocks as the + # blocker, as the battery would have stopped there; without one + # the phase stays unrecorded. observed_order = [ observation.entry_id for observation in self._observations.values() @@ -1019,7 +1084,7 @@ def _record_phases(self, *, completed: bool) -> tuple[list[str], list[str]]: } blockers = [entry_id for entry_id in observed_order if entry_id in blocking] if not blockers: - continue + return self._run.record_phase( assemble_phase_report( self._gates, @@ -1031,7 +1096,7 @@ def _record_phases(self, *, completed: bool) -> tuple[list[str], list[str]]: ) ) recorded.append(phase) - return recorded, not_observed + return def _comparison_payload( self, @@ -1104,6 +1169,7 @@ def _comparison_payload( "overrides": self._overrides, "entries": entries, "not_observed": not_observed, + "observations_missing": list(self._observations_missing), "differences": unexplained, "explained_differences": explained, "shadow_errors": list(self._shadow_errors), diff --git a/packages/microcosm-build/tests/engine_free/us/test_us_gate_shadow.py b/packages/microcosm-build/tests/engine_free/us/test_us_gate_shadow.py index 1830dac311..0fcfd99d7d 100644 --- a/packages/microcosm-build/tests/engine_free/us/test_us_gate_shadow.py +++ b/packages/microcosm-build/tests/engine_free/us/test_us_gate_shadow.py @@ -501,6 +501,10 @@ def test_a_stop_inside_a_phase_names_the_last_blocking_entry(tmp_path) -> None: "type": "RuntimeError", "message": "Release gates failed: beta", } + # The run took the stopped phase: it marks unreached no entry it + # evaluated (#1609), and no observations are missing. + assert payload["shadow_errors"] == [] + assert payload["observations_missing"] == [] def test_a_stop_that_no_gate_explains_leaves_its_phase_unrecorded(tmp_path) -> None: @@ -520,6 +524,163 @@ def test_a_stop_that_no_gate_explains_leaves_its_phase_unrecorded(tmp_path) -> N assert not shadow.report_path.exists() +def _stopping_gates() -> GatesManifest: + return _manifest( + [ + _entry("us_test_first", "alpha"), + _entry("us_test_second", "beta"), + _entry("us_test_third", "alpha"), + _entry("us_test_final", "alpha", phase="terminal"), + ] + ) + + +def _broken_context(): + raise ValueError("cannot build evidence") + + +def _stop_on_a_failed_beta(shadow: GateBatteryShadow) -> None: + """Observe a failing second entry and stop as today's code would.""" + + with pytest.raises(RuntimeError, match="Release gates failed: beta"): + with shadow: + result = shadow.gate( + "us_test_second", + lambda: BETA(4.0), + EvidenceContext(artifacts={"beta_value": 4.0}), + ) + if not result.passed: + raise RuntimeError("Release gates failed: beta") + + +def test_a_stop_never_names_unreached_a_gate_today_reached(tmp_path) -> None: + # Review of #1609: a stopped phase names unreached the entries without an + # outcome. Today's code reached the first entry; the shadow only failed to + # build its evidence, so the phase stays unrecorded. + shadow = _shadow(tmp_path, _stopping_gates()) + shadow.gate("us_test_first", lambda: ALPHA(0.5), _broken_context) + _stop_on_a_failed_beta(shadow) + payload = json.loads(shadow.comparison_path.read_text()) + assert payload["phases_recorded"] == [] + assert payload["report_file"] is None + assert not shadow.report_path.exists() + assert payload["not_observed"] == [ + "us_test_first", + "us_test_third", + "us_test_final", + ] + (error,) = payload["shadow_errors"] + assert "[us_test_first]" in error and "cannot build evidence" in error + + +def test_a_later_process_never_names_unreached_what_an_earlier_one_reached( + tmp_path, +) -> None: + gates = _stopping_gates() + earlier = _shadow(tmp_path / "earlier", gates) + earlier.gate("us_test_first", lambda: ALPHA(0.5), _broken_context) + saved = tmp_path / "earlier.observations.json" + earlier.save_observations(saved) + stored = json.loads(saved.read_text()) + assert stored["reached"] == ["us_test_first"] + assert stored["observations"] == [] + + later = _shadow(tmp_path / "later", gates) + later.load_observations(saved) + _stop_on_a_failed_beta(later) + payload = json.loads(later.comparison_path.read_text()) + assert payload["phases_recorded"] == [] + assert not later.report_path.exists() + (error,) = payload["shadow_errors"] + assert "cannot build evidence" in error + + +@pytest.mark.parametrize("missing", ["a stage saved nothing", "a file is torn"]) +def test_missing_observations_leave_the_stopped_phase_unrecorded( + tmp_path, missing +) -> None: + # The first entry may have been reached by the stage whose observations + # are missing, so the shadow cannot name it unreached. + shadow = _shadow(tmp_path, _stopping_gates()) + if missing == "a stage saved nothing": + note = "the first stage saved no observations" + shadow.note_missing_observations(note) + else: + torn = tmp_path / "first.observations.json" + torn.write_text("{") + shadow.load_observations(torn) + note = "first.observations.json was not read whole" + _stop_on_a_failed_beta(shadow) + payload = json.loads(shadow.comparison_path.read_text()) + assert payload["phases_recorded"] == [] + assert not shadow.report_path.exists() + assert payload["observations_missing"] == [note] + # A file that cannot be read is also a shadow error; a stage that saved + # nothing is only a note. + assert len(payload["shadow_errors"]) == (1 if missing == "a file is torn" else 0) + + +def test_a_note_of_missing_observations_alone_passes_a_finished_run( + tmp_path, +) -> None: + # A stage that saved nothing and observed nothing (ACS's qa stage + # declares no entry) leaves a finished run's verdict to its entries. + shadow = _shadow(tmp_path, _two_phase_gates()) + shadow.note_missing_observations("the qa stage saved no observations") + with shadow: + for entry_id, gate, key in ( + ("us_test_alpha", ALPHA, "alpha_value"), + ("us_test_beta", BETA, "beta_value"), + ("us_test_final", ALPHA, "alpha_value"), + ): + shadow.gate( + entry_id, + lambda gate=gate: gate(0.5), + EvidenceContext(artifacts={key: 0.5}), + ) + payload = json.loads(shadow.comparison_path.read_text()) + assert payload["run_completed"] is True + assert payload["verdict_difference"] is False + assert payload["phases_recorded"] == ["assembled", "terminal"] + assert payload["observations_missing"] == ["the qa stage saved no observations"] + + +def test_the_run_refuses_a_stopped_phase_that_drops_an_entry_it_evaluated( + tmp_path, +) -> None: + # In one process the run's own refusal (#1609) backs the shadow up: an + # entry evaluated through the run but never observed would otherwise be + # named unreached. The shadow records the refusal, never raises, and still + # lists the phase the run had already written. + gates = _manifest( + [ + _entry("us_test_alpha", "alpha"), + _entry("us_test_first", "alpha", phase="terminal"), + _entry("us_test_second", "beta", phase="terminal"), + _entry("us_test_third", "alpha", phase="terminal"), + ] + ) + shadow = _shadow(tmp_path, gates) + shadow.gate( + "us_test_alpha", + lambda: ALPHA(0.5), + EvidenceContext(artifacts={"alpha_value": 0.5}), + ) + # A wiring fault: the run evaluates an entry the shadow never observes. + shadow.run.evaluate_entries( + ("us_test_first",), EvidenceContext(artifacts={"alpha_value": 0.5}) + ) + _stop_on_a_failed_beta(shadow) + payload = json.loads(shadow.comparison_path.read_text()) + assert payload["phases_recorded"] == ["assembled"] + assert payload["report_file"] == shadow.report_path.name + report = json.loads(shadow.report_path.read_text()) + assert report["blocked_at_phase"] is None + assert report["gates"]["us_test_alpha"]["status"] == "passed" + (error,) = payload["shadow_errors"] + assert "marks ['us_test_first'] unreached, but this run evaluated" in error + + def test_the_shadow_never_raises_while_the_tool_runs(tmp_path) -> None: gates = _two_phase_gates() shadow = _shadow(tmp_path, gates) From 5018faf5c7bfa20227f901b5f8238fe2152b51ca Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mar=C3=ADa=20Juaristi?= <127882282+juaristi22@users.noreply.github.com> Date: Sun, 15 Nov 2026 20:30:28 +0000 Subject: [PATCH 16/31] Note the base stages that ran and saved no shadow observations (us_base) The staged parent rebuilds the us_base scope from its children's files. It now loads the stages that ran, the checkpoint's completed prefix and the stages it started, and notes each one without a file (its save failed, or it ran with the shadow off), so a stopped run never names that stage's entries unreached. A stage after the one that failed never ran and is not noted. Today's control flow and exit are unchanged. Co-Authored-By: Claude Opus 5.5 --- .../test_us_puf_support_base_gate_shadow.py | 39 ++++++++++++++++++- tools/build_us_puf_support_base.py | 24 +++++++++--- 2 files changed, 57 insertions(+), 6 deletions(-) diff --git a/packages/microcosm-build/tests/engine_free/us/test_us_puf_support_base_gate_shadow.py b/packages/microcosm-build/tests/engine_free/us/test_us_puf_support_base_gate_shadow.py index 3a212cd796..5b39ba9c4f 100644 --- a/packages/microcosm-build/tests/engine_free/us/test_us_puf_support_base_gate_shadow.py +++ b/packages/microcosm-build/tests/engine_free/us/test_us_puf_support_base_gate_shadow.py @@ -227,7 +227,7 @@ def test_checkpointed_stages_carry_their_observations_to_the_parent( parent = _args(tmp_path) shadow = base._base_gate_shadow(parent, base._final_gate_shadow_directory(parent)) base._load_stage_gate_shadows( - shadow, parent, ("wic_post_clone", "medicare_post_clone", "never_ran") + shadow, parent, ("wic_post_clone", "medicare_post_clone") ) shadow.stop(SystemExit("Checkpointed stage 'medicare_post_clone' failed")) payload = json.loads(shadow.comparison_path.read_text()) @@ -241,6 +241,43 @@ def test_checkpointed_stages_carry_their_observations_to_the_parent( "failed" ) assert payload["shadow_errors"] == [] + assert payload["observations_missing"] == [] + + +def test_the_parent_notes_each_stage_that_ran_and_saved_nothing( + tmp_path, monkeypatch, base +): + # A stage that ran but left no file (its save failed, or it ran with the + # shadow off) may have reached entries the parent then lacks, so it is + # noted and a stopped run never names them unreached. The stage after the + # one that failed never ran, so it is not. + steps = ("source_construction", "pre_clone_enrichment", "clone_feature_extraction") + + class Runtime: + def __init__(self, *_args, **_kwargs) -> None: + self.context = SimpleNamespace(completed=steps[:1]) + + monkeypatch.setattr(base, "_pipeline_steps_for", lambda args: steps) + monkeypatch.setattr(base, "_pipeline_for", lambda args: None) + monkeypatch.setattr(base, "StageRuntime", Runtime) + monkeypatch.setattr(base, "_stage_run_config", lambda args: {}) + monkeypatch.setattr(base, "_stage_cli_args", lambda args, stage: ["--stage", stage]) + monkeypatch.setattr( + base.subprocess, "run", lambda command, **kwargs: SimpleNamespace(returncode=1) + ) + args = _args(tmp_path) + with pytest.raises(SystemExit, match="'pre_clone_enrichment' failed"): + base._run_staged_all(args) + _, comparison = shadow_file_paths( + base._final_gate_shadow_directory(args), "us_base" + ) + payload = json.loads(comparison.read_text()) + assert payload["run_completed"] is False + assert payload["observations_missing"] == [ + "the source_construction stage saved no observations", + "the pre_clone_enrichment stage saved no observations", + ] + assert payload["phases_recorded"] == [] def test_the_geography_waiver_is_recorded_by_entry(tmp_path, base) -> None: diff --git a/tools/build_us_puf_support_base.py b/tools/build_us_puf_support_base.py index a4ffa93040..dd293e351a 100644 --- a/tools/build_us_puf_support_base.py +++ b/tools/build_us_puf_support_base.py @@ -961,8 +961,13 @@ def _run_staged_all( # shadow scope from what they saved, completed stages included. directory = _final_gate_shadow_directory(args) shadow = None if directory is None else _base_gate_shadow(args, directory) + # The stages that ran, in an earlier run of this checkpoint or here: each + # one should have saved its observations. + stages_run = list(completed_prefix) try: for stage in remaining: + if stage not in stages_run: + stages_run.append(stage) if telemetry is not None: telemetry.transition_stage(stage) completed = subprocess.run( @@ -981,11 +986,11 @@ def _run_staged_all( ) except BaseException as error: if shadow is not None: - _load_stage_gate_shadows(shadow, args, pipeline_steps) + _load_stage_gate_shadows(shadow, args, stages_run) shadow.stop(error) raise if shadow is not None: - _load_stage_gate_shadows(shadow, args, pipeline_steps) + _load_stage_gate_shadows(shadow, args, stages_run) shadow.finish() @@ -1061,7 +1066,8 @@ def _armed_stage_gate_shadow(args: argparse.Namespace) -> Iterator[Callable[[], the observations of every stage it does not run again. A stage that raises saves what it saw on the way out, so the parent's report says where the build stopped. A save that fails warns and is otherwise left to - the parent, which then reports the stage's entries as unobserved. With + the parent, which then notes that the stage saved nothing and reports its + entries as unobserved. With the switch off the stage runs without a shadow and saves nothing. """ @@ -1100,12 +1106,20 @@ def save() -> None: def _load_stage_gate_shadows( shadow: GateBatteryShadow, args: argparse.Namespace, - pipeline_steps: Sequence[str], + stages_run: Sequence[str], ) -> None: - for stage in pipeline_steps: + """Load what each stage that ran saved. + + A stage that ran but saved nothing (its save failed, or it ran with the + shadow off) is noted, so a stopped run never names its entries unreached. + """ + + for stage in stages_run: path = _stage_gate_shadow_observations(args, stage) if path.is_file(): shadow.load_observations(path) + else: + shadow.note_missing_observations(f"the {stage} stage saved no observations") def _shadow_frame_gate( From a0d25a636d31bc14f8567792b08f9d941b4b1469 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mar=C3=ADa=20Juaristi?= <127882282+juaristi22@users.noreply.github.com> Date: Sun, 15 Nov 2026 20:30:28 +0000 Subject: [PATCH 17/31] Note the ACS stages that ran and saved no shadow observations (us_local) Each stage rebuilds the us_local scope from every stage saved so far. A stage up to the current one without a file (its save failed, or it ran with the shadow off) is now noted, so the stop that follows never names its entries unreached: with finalize's file lost, a package stop records only the assembled phase. The note is made inside the guard that keeps the shadow from stopping a stage. Co-Authored-By: Claude Opus 5.5 --- .../us/test_us_acs_local_gate_shadow.py | 24 +++++++++++++++++++ tools/build_us_acs_local_release.py | 10 ++++++++ 2 files changed, 34 insertions(+) diff --git a/packages/microcosm-build/tests/engine_free/us/test_us_acs_local_gate_shadow.py b/packages/microcosm-build/tests/engine_free/us/test_us_acs_local_gate_shadow.py index 274c8b4457..a7d4c77650 100644 --- a/packages/microcosm-build/tests/engine_free/us/test_us_acs_local_gate_shadow.py +++ b/packages/microcosm-build/tests/engine_free/us/test_us_acs_local_gate_shadow.py @@ -168,6 +168,30 @@ def test_a_finalize_stop_is_recorded_and_its_rerun_starts_clean( assert not (acs_directory(args) / "package.observations.json").exists() +def test_a_stage_that_saved_nothing_is_never_named_unreached( + tmp_path, monkeypatch, acs +) -> None: + # A phase carried in from other processes holds outcomes, not the ids the + # run evaluated (#1609), so the shadow's own unreached list is the only + # check here. Finalize's entries ran, but its file is gone, as when its + # save failed: the package stop must not name them unreached. + args = _args(tmp_path) + stand_in_gates(monkeypatch, "us_local", acs, failing={"stored_inputs"}) + for stage in ("materialize", "calibrate", "qa", "finalize"): + _run_stage(acs, args, stage) + (acs_directory(args) / "finalize.observations.json").unlink() + with pytest.raises(SystemExit, match="hard gate failure"): + with acs._local_gate_shadow_stage(args, "package"): + observe_entries("us_local", acs, ("us_local_stored_inputs",)) + raise SystemExit("package: hard gate failure(s): stored inputs") + payload = _comparison(args) + assert payload["observations_missing"] == [ + "the finalize stage saved no observations" + ] + assert payload["phases_recorded"] == ["assembled"] + assert payload["blocked_at_phase"] is None + + def test_a_difference_fails_the_finished_package_stage( tmp_path, monkeypatch, acs ) -> None: diff --git a/tools/build_us_acs_local_release.py b/tools/build_us_acs_local_release.py index 97c2d12a9e..500a3a603b 100644 --- a/tools/build_us_acs_local_release.py +++ b/tools/build_us_acs_local_release.py @@ -7215,11 +7215,21 @@ def _finish_local_gate_scope(args, *, stage: str, stopped_by=None) -> None: """ try: + # The stages run before this one, and this one: each should have saved. + stages_run = _LOCAL_GATE_SHADOW_STAGES[ + : _LOCAL_GATE_SHADOW_STAGES.index(stage) + 1 + ] shadow = _local_gate_shadow(args, _local_gate_shadow_directory(args)) for name in _LOCAL_GATE_SHADOW_STAGES: observations = _local_stage_observations(args, name) if observations.is_file(): shadow.load_observations(observations) + elif name in stages_run: + # Its save failed, or it ran with the shadow off: a stopped + # run then never names its entries unreached. + shadow.note_missing_observations( + f"the {name} stage saved no observations" + ) except Exception as error: # noqa: BLE001 - the shadow never stops a stage if stopped_by is None and stage == "package": raise From 40bbddce2ca1fcc922bb9fa16f37b5441164ebe6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mar=C3=ADa=20Juaristi?= <127882282+juaristi22@users.noreply.github.com> Date: Sun, 15 Nov 2026 20:30:28 +0000 Subject: [PATCH 18/31] Say when the US shadow records the phase a run stopped in Co-Authored-By: Claude Opus 5.5 --- docs/gate-battery-contract.md | 15 +++++++++++---- 1 file changed, 11 insertions(+), 4 deletions(-) diff --git a/docs/gate-battery-contract.md b/docs/gate-battery-contract.md index 9e0b633844..43f3bfc72e 100644 --- a/docs/gate-battery-contract.md +++ b/docs/gate-battery-contract.md @@ -339,10 +339,17 @@ not evaluate matches `evidence_absent`. The shadow writes its scope's report and the comparison beside the tool's outputs (never inside a release directory), never raises while the tool runs, and fails a finished run on a verdict difference; today's own exception always propagates -unchanged. The national release's shadow is armed before its preflight -gates, which run ahead of the refusal to reuse a certified release -directory, so it holds its files until that refusal has passed: a refused -rerun leaves the certified build's shadow files as they were, and each +unchanged. When today's code stops, the phase it stopped in is recorded +only if every entry there without an outcome is one today's code never +reached. The run refuses a phase that marks unreached an entry it +evaluated, but a scope rebuilt from stages run as separate processes +(Route A's checkpointed base, ACS local) holds only their outcomes, so each +stage's saved observations also name every entry it reached, and a stage +that ran and saved none leaves the stopped phase unrecorded. The national +release's shadow is armed before its preflight gates, which run ahead of +the refusal to reuse a certified release directory, so it holds its files +until that refusal has passed: a refused rerun leaves the certified +build's shadow files as they were, and each release keeps its own, in `/gate_battery_shadow/`. Real builds always arm the shadow. The test suite turns it off for every test (`MICROCOSM_US_GATE_SHADOW=off`, in `packages/microcosm-build/tests/conftest.py`), From 44050a6c45ad6769fd66f4b712c37009588ea6df Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mar=C3=ADa=20Juaristi?= <127882282+juaristi22@users.noreply.github.com> Date: Sun, 15 Nov 2026 20:42:21 +0000 Subject: [PATCH 19/31] Let ACS's staging-check test read a check inside its shadow site (us_local) `test_release_checks_self_employment_wherever_it_loads_staging` pinned the self-employment identity check to the line after the hours check. Both now run inside the lambda their shadow site evaluates at once, so the test compares the function's statements instead: the self-employment check is still the statement right after the hours check at both staging loads. It accepts today's direct calls as well, so the flip can drop the shadow without touching it again. Co-Authored-By: Claude Opus 5.5 --- .../us/test_us_acs_local_release_tool.py | 14 ++++++++++---- 1 file changed, 10 insertions(+), 4 deletions(-) diff --git a/packages/microcosm-build/tests/engine_free/us/test_us_acs_local_release_tool.py b/packages/microcosm-build/tests/engine_free/us/test_us_acs_local_release_tool.py index 1abf078c76..463c9e15c3 100644 --- a/packages/microcosm-build/tests/engine_free/us/test_us_acs_local_release_tool.py +++ b/packages/microcosm-build/tests/engine_free/us/test_us_acs_local_release_tool.py @@ -2,6 +2,7 @@ from __future__ import annotations +import ast import functools import importlib.util import inspect @@ -11,6 +12,7 @@ import shlex import subprocess import sys +import textwrap from pathlib import Path from types import SimpleNamespace @@ -1309,13 +1311,17 @@ def test_release_checks_self_employment_wherever_it_loads_staging() -> None: module = _load_tool_module() for stage in (module.do_materialize, module._write_calibrated_artifact): - lines = [line.strip() for line in inspect.getsource(stage).splitlines()] + # Each check may run inside the lambda its gate battery shadow site + # evaluates at once (microcosm#1585 item 11), so the statements are + # compared, not the lines. + (function,) = ast.parse(textwrap.dedent(inspect.getsource(stage))).body + statements = [ast.unparse(statement) for statement in function.body] hours = next( index - for index, line in enumerate(lines) - if line.startswith("_require_local_hours(frame") + for index, statement in enumerate(statements) + if "_require_local_hours(frame" in statement ) - assert lines[hours + 1] == "_require_acs_self_employment_identity(frame)" + assert "_require_acs_self_employment_identity(frame)" in statements[hours + 1] def test_local_hours_failure_propagates_to_release_boundary(monkeypatch) -> None: From 5de94d6e91364b5fd388db27fa7dce690a49e87f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mar=C3=ADa=20Juaristi?= <127882282+juaristi22@users.noreply.github.com> Date: Sun, 15 Nov 2026 20:43:23 +0000 Subject: [PATCH 20/31] Let the national source-shape tests read a call inside its shadow site (us_national) Two tests pinned where today's calls sit in the release tool's source, and those calls now run inside their shadow sites. The preflight test also reads the names in `_main`'s lambdas, where `us_register_consistency_gate` now runs. The frozen-support order test matches the two tail checks through `_shadow_tail_survival`, and checks that the helper makes today's call, and matches the regate inside the lambda its site evaluates at once. Both still accept today's direct calls, so the flip can drop the shadow without touching them again. Co-Authored-By: Claude Opus 5.5 --- .../us/test_us_fiscal_refresh_builder.py | 45 ++++++++++++++----- 1 file changed, 33 insertions(+), 12 deletions(-) diff --git a/packages/microcosm-build/tests/engine_free/us/test_us_fiscal_refresh_builder.py b/packages/microcosm-build/tests/engine_free/us/test_us_fiscal_refresh_builder.py index 01f8de7da1..b0733e528c 100644 --- a/packages/microcosm-build/tests/engine_free/us/test_us_fiscal_refresh_builder.py +++ b/packages/microcosm-build/tests/engine_free/us/test_us_fiscal_refresh_builder.py @@ -4,11 +4,12 @@ import inspect import json import os +import re import sys from dataclasses import replace from datetime import UTC, datetime from pathlib import Path -from types import SimpleNamespace +from types import CodeType, SimpleNamespace import h5py import hypothesis @@ -2820,21 +2821,32 @@ def test_frozen_support_selection_is_followed_by_weeks_unemployed_regate() -> No builder = _load_builder_module() source = Path(builder.__file__).read_text(encoding="utf-8") + # The tail checks and the regate may run inside their gate battery shadow + # sites (microcosm#1585 item 11): `_shadow_tail_survival` makes today's + # tail call, and the regate runs in the lambda its site evaluates at once. + tail_check = ( + r"(?:assert_puf_capital_gains_tail_survives_selection|_shadow_tail_survival)\(" + ) + if hasattr(builder, "_shadow_tail_survival"): + assert "assert_puf_capital_gains_tail_survives_selection(" in ( + inspect.getsource(builder._shadow_tail_survival) + ) base_load = source.index( "base_frame = _load_frame(base_h5, expected_sha256=base_dataset_sha256)" ) - tail_presence = source.index( - "capital_gains_tail_presence = assert_puf_capital_gains_tail_survives_selection(", - base_load, + tail_presence = ( + re.compile(r"capital_gains_tail_presence = " + tail_check) + .search(source, base_load) + .start() ) selection = source.index("base_frame, selection_report = select_frozen_support(") - tail_retention = source.index( - "assert_puf_capital_gains_tail_survives_selection(", - selection, - ) - regate = source.index( - "post_selection_weeks_unemployed_gate = us_weeks_unemployed_signal_gate(" - ) + tail_retention = re.compile(tail_check).search(source, selection).start() + regate = re.search( + r"post_selection_weeks_unemployed_gate = (?:_shadow_frame_gate\(\s*" + r'"us_national_weeks_unemployed_post_selection",\s*lambda: )?' + r"us_weeks_unemployed_signal_gate\(", + source, + ).start() mass_repair = source.index( "base_frame, base_population_repair = _with_base_population_mass_repair(" ) @@ -16030,7 +16042,16 @@ def test_main_runs_cross_register_and_take_up_contract_preflights() -> None: are looked up by name inside ``main``). """ builder = _load_builder_module() - called = set(builder._main.__code__.co_names) + code = builder._main.__code__ + # A preflight may run inside the lambda its gate battery shadow site + # evaluates at once (microcosm#1585 item 11), so main's lambdas count. + called = set(code.co_names).union( + *( + constant.co_names + for constant in code.co_consts + if isinstance(constant, CodeType) and constant.co_name == "" + ) + ) for preflight in ( "assert_release_input_coverage_manifest_current", "us_register_consistency_gate", From 335a14458305546a9cba6388b93ae57565dbc4fd Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mar=C3=ADa=20Juaristi?= <127882282+juaristi22@users.noreply.github.com> Date: Sun, 15 Nov 2026 20:48:13 +0000 Subject: [PATCH 21/31] Re-pin the US F0 contracts for the us/gates.json row Registering `us/gates.json` as a `legacy_json` row in `country_package.json` adds the row's three normative fields: 42397 configuration fields (32612 authored), the `country_manifest` claim at 107 pointers, and a new pointer inventory digest. The row also moves the US bundle's semantic `spec_sha256` to d7e232d9, which pool builds record in their run config's spec binding. Run with `tools/repin_us_spec_engine_contracts.py --legacy-only` (no change), then without it, then `tools/spec_engine_coverage.py`, all with the country engines blocked. The generator step was skipped: it needs the US engine, and it would write the `country_package.json` row already committed. Both tools' `--check` modes now pass, and coverage reads 42397/42397 fields and 41/41 inventory checks. The engine-contract and engine-workflow pins the re-pin rewrites were not run here. Co-Authored-By: Claude Opus 5.5 --- docs/evidence/spec-engine/us-f0-coverage.json | 20 +++++++++---------- .../build/spec_engine/field_usage.py | 8 ++++---- .../us/test_spec_engine_coverage_tool.py | 10 +++++----- .../shared/test_spec_engine_field_usage.py | 10 +++++----- .../us/test_us_multispine_pool_tool.py | 2 +- tools/spec_engine_coverage.py | 2 +- 6 files changed, 26 insertions(+), 26 deletions(-) diff --git a/docs/evidence/spec-engine/us-f0-coverage.json b/docs/evidence/spec-engine/us-f0-coverage.json index 41a33cb193..5621be2a65 100644 --- a/docs/evidence/spec-engine/us-f0-coverage.json +++ b/docs/evidence/spec-engine/us-f0-coverage.json @@ -6,7 +6,7 @@ "country": "us", "documentation_sha256": "fda6ec0dd925077f4d84d30a1c206dd81d82c5e16bd94506e81fe1b9f7e2f466", "field_usage": { - "authored_normative_field_count": 32609, + "authored_normative_field_count": 32612, "claim_count": 48, "claims": [ { @@ -16,8 +16,8 @@ "legacy_sinks": [], "mode": "front_end_validation", "pointer_class": "all", - "pointer_count": 104, - "pointer_sha256": "8a186065f5b8ffc59bc3f62fe927975e6f36bc1e913aa61761652c9a8aa67988", + "pointer_count": 107, + "pointer_sha256": "2c2099d3d5ef3d664f74a2e732870391022a852cf49d5cf96810c9a984d2b20b", "rationale": null, "relative_sink_prefix": null, "source_prefix": "/authored/country_package.json", @@ -758,20 +758,20 @@ "verifier": "vintages" } ], - "configuration_field_count": 42394, - "consumed_field_count": 42394, + "configuration_field_count": 42397, + "consumed_field_count": 42397, "generation0_effect_counts": { "legacy_behavior": 38780, - "no_generation0_effect": 3614 + "no_generation0_effect": 3617 }, "mode_counts": { "compiler_semantic": 27673, - "front_end_validation": 349, + "front_end_validation": 352, "identity_only": 103, "legacy_behavior": 14269 }, "multiple_primary_use_field_count": 0, - "pointer_inventory_sha256": "f6832e8d2892af22e41afd0b0bea0cba354bbff8b84bebcc652e765a3ae7df92", + "pointer_inventory_sha256": "d4790ceb07a80ddf63c9fe394497c2e45de5c7ebd43481f725592f73be83f7d4", "resolved_binding_field_count": 9785, "unused_field_count": 0 }, @@ -2585,7 +2585,7 @@ "country": "us", "schema_id": "country_spec", "schema_version": 1, - "spec_sha256": "98d583653d37fe58edcace1cf3e21a139b69ebe7d1c3dac6a58f08b2b5aab8cf" + "spec_sha256": "d7e232d9e85d2e29bb576ad7f05921e4c2ac1ec578925431fbf3e5f0c9740d7f" } }, "report_schema_version": 3, @@ -2595,7 +2595,7 @@ "country": "us", "schema_id": "country_spec", "schema_version": 1, - "spec_sha256": "98d583653d37fe58edcace1cf3e21a139b69ebe7d1c3dac6a58f08b2b5aab8cf" + "spec_sha256": "d7e232d9e85d2e29bb576ad7f05921e4c2ac1ec578925431fbf3e5f0c9740d7f" }, "status": "pass" } diff --git a/packages/microcosm-build/src/microcosm/build/spec_engine/field_usage.py b/packages/microcosm-build/src/microcosm/build/spec_engine/field_usage.py index e0be9d2e11..52fcb68a72 100644 --- a/packages/microcosm-build/src/microcosm/build/spec_engine/field_usage.py +++ b/packages/microcosm-build/src/microcosm/build/spec_engine/field_usage.py @@ -26,9 +26,9 @@ ) from .schemas import load_schema_registry -EXPECTED_AUTHORED_FIELD_COUNT = 32609 +EXPECTED_AUTHORED_FIELD_COUNT = 32612 EXPECTED_RESOLVED_BINDING_FIELD_COUNT = 9_785 -EXPECTED_CONFIGURATION_FIELD_COUNT = 42394 +EXPECTED_CONFIGURATION_FIELD_COUNT = 42397 class FieldUsageError(AssertionError): @@ -369,8 +369,8 @@ def _path_inventory(rows: Sequence[tuple[str, object]]) -> tuple[int, str]: "bdd9e79157590fade42d28cc2b5d5c8b58e13903af75375a0e3235c94d2a8339", ), "country_manifest": ( - 104, - "8a186065f5b8ffc59bc3f62fe927975e6f36bc1e913aa61761652c9a8aa67988", + 107, + "2c2099d3d5ef3d664f74a2e732870391022a852cf49d5cf96810c9a984d2b20b", ), "generated_authorities": ( 8_614, diff --git a/packages/microcosm-build/tests/engine_contract/us/test_spec_engine_coverage_tool.py b/packages/microcosm-build/tests/engine_contract/us/test_spec_engine_coverage_tool.py index 519651a171..ba0d6a6e62 100644 --- a/packages/microcosm-build/tests/engine_contract/us/test_spec_engine_coverage_tool.py +++ b/packages/microcosm-build/tests/engine_contract/us/test_spec_engine_coverage_tool.py @@ -82,22 +82,22 @@ def test_us_coverage_is_exact_complete_and_honest( assert_coverage_complete(coverage_report) assert coverage_report["status"] == "pass" fields = coverage_report["field_usage"] - assert fields["configuration_field_count"] == 42394 - assert fields["authored_normative_field_count"] == 32609 + assert fields["configuration_field_count"] == 42397 + assert fields["authored_normative_field_count"] == 32612 assert fields["resolved_binding_field_count"] == 9_785 - assert fields["consumed_field_count"] == 42394 + assert fields["consumed_field_count"] == 42397 assert fields["unused_field_count"] == 0 assert fields["multiple_primary_use_field_count"] == 0 assert fields["claim_count"] == 48 assert fields["mode_counts"] == { "legacy_behavior": 14_269, "compiler_semantic": 27673, - "front_end_validation": 349, + "front_end_validation": 352, "identity_only": 103, } assert fields["generation0_effect_counts"] == { "legacy_behavior": 38_780, - "no_generation0_effect": 3614, + "no_generation0_effect": 3617, } inventory = coverage_report["inventory_coverage"] diff --git a/packages/microcosm-build/tests/engine_free/shared/test_spec_engine_field_usage.py b/packages/microcosm-build/tests/engine_free/shared/test_spec_engine_field_usage.py index 63120bd15d..a2f55a1b7e 100644 --- a/packages/microcosm-build/tests/engine_free/shared/test_spec_engine_field_usage.py +++ b/packages/microcosm-build/tests/engine_free/shared/test_spec_engine_field_usage.py @@ -95,22 +95,22 @@ def _mutated_bundle( def test_exact_complete_ledger_has_one_primary_mode_per_pointer(field_ledger) -> None: - assert len(field_ledger.fields) == EXPECTED_CONFIGURATION_FIELD_COUNT == 42394 + assert len(field_ledger.fields) == EXPECTED_CONFIGURATION_FIELD_COUNT == 42397 assert field_ledger.source_counts == { - "authored": 32609, + "authored": 32612, "resolved_bindings": 9_785, } assert field_ledger.mode_counts == { "legacy_behavior": 14_269, "compiler_semantic": 27673, - "front_end_validation": 349, + "front_end_validation": 352, "identity_only": 103, } assert field_ledger.generation0_effect_counts == { "legacy_behavior": 38_780, - "no_generation0_effect": 3614, + "no_generation0_effect": 3617, } - assert len({field.pointer for field in field_ledger.fields}) == 42394 + assert len({field.pointer for field in field_ledger.fields}) == 42397 def test_eligibility_concepts_are_validation_not_generation0_behavior( diff --git a/packages/microcosm-build/tests/engine_workflow/us/test_us_multispine_pool_tool.py b/packages/microcosm-build/tests/engine_workflow/us/test_us_multispine_pool_tool.py index 68df1f8a78..7c0657b44e 100644 --- a/packages/microcosm-build/tests/engine_workflow/us/test_us_multispine_pool_tool.py +++ b/packages/microcosm-build/tests/engine_workflow/us/test_us_multispine_pool_tool.py @@ -355,7 +355,7 @@ def capture_equality(expected: object, actual: object) -> None: # through the bundle's source stages. # The hierarchy value ranks move it through medicaid_take_up's # attested bytes. - "spec_sha256": "98d583653d37fe58edcace1cf3e21a139b69ebe7d1c3dac6a58f08b2b5aab8cf", + "spec_sha256": "d7e232d9e85d2e29bb576ad7f05921e4c2ac1ec578925431fbf3e5f0c9740d7f", }, } diff --git a/tools/spec_engine_coverage.py b/tools/spec_engine_coverage.py index 8e6c05a0c8..ab6ef40453 100644 --- a/tools/spec_engine_coverage.py +++ b/tools/spec_engine_coverage.py @@ -41,7 +41,7 @@ REPORT_SCHEMA_VERSION = 3 EXPECTED_POINTER_INVENTORY_SHA256 = ( - "f6832e8d2892af22e41afd0b0bea0cba354bbff8b84bebcc652e765a3ae7df92" + "d4790ceb07a80ddf63c9fe394497c2e45de5c7ebd43481f725592f73be83f7d4" ) DEFAULT_REPORT_PATH = ( Path(__file__).resolve().parents[1] From 660cb53d57d37f5da34741c1674defbd6d78142c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mar=C3=ADa=20Juaristi?= <127882282+juaristi22@users.noreply.github.com> Date: Sun, 15 Nov 2026 21:32:45 +0000 Subject: [PATCH 22/31] Classify the gate battery's US runtime modules for the spine-blindness guard `battery_bindings.py`, `gate_scopes.py` and `gate_shadow.py` are new us_runtime modules, so the guard's fail-closed inventory refused them as unreviewed, and the stacked pool, which runs its gates in shadow, now reaches 86 runtime modules instead of the pinned 83. All three apply no population treatment, so they join the reviewed non-registry modules, and the pool's pinned graph moves to 86. They stay inside the all-runtime source-identity scan, which they pass. Co-Authored-By: Claude Opus 5.5 --- .../engine_free/us/test_us_spine_blindness.py | 20 ++++++++++++++++--- 1 file changed, 17 insertions(+), 3 deletions(-) diff --git a/packages/microcosm-build/tests/engine_free/us/test_us_spine_blindness.py b/packages/microcosm-build/tests/engine_free/us/test_us_spine_blindness.py index bb7b2c2190..9f1c3f3253 100644 --- a/packages/microcosm-build/tests/engine_free/us/test_us_spine_blindness.py +++ b/packages/microcosm-build/tests/engine_free/us/test_us_spine_blindness.py @@ -299,6 +299,11 @@ # treatment. Remains subject to the all-runtime source-identity scan. "asec_sources.py", "base_pool.py", + # The gate battery's US bindings (#1585 item 11): each declared check + # calls the gate its site calls today, on the evidence it is handed; + # no population treatment. Remains subject to the all-runtime + # source-identity scan. + "battery_bindings.py", "block_ladder_sources.py", "capital_gain_distributions.py", "casualty_losses.py", @@ -343,6 +348,13 @@ # facts into target specs and sums the stored person balances for # them; no population treatment. "fsa_student_loan_targets.py", + # The four tool scopes of us/gates.json (#1585 item 11): manifests and + # their pinned digests only; no population treatment. + "gate_scopes.py", + # The gate battery in shadow beside today's US gates (#1585 item 11): + # compares verdicts and writes shadow files; no population treatment. + # Remains subject to the all-runtime source-identity scan. + "gate_shadow.py", "geography_ladder.py", "hours_worked.py", "h5_io.py", # US artifact I/O; no population treatment. @@ -3847,9 +3859,11 @@ def test_pool_build_tool_import_graph_is_source_spine_blind() -> None: # reached module. 81 adds puf_source_schedule_e.py, the PUF donor's # Schedule E line-32 and passive supplement (#1239). 83 adds # block_location.py and cps_source_geography.py, which the - # --location-rule block_v1 household location reaches (#696). - assert len(runtime_graph) == 83, ( - f"{tool.name} must reach the pinned 83-module runtime graph; " + # --location-rule block_v1 household location reaches (#696). 86 adds + # battery_bindings.py, gate_scopes.py and gate_shadow.py, the gate + # battery the pool runs in shadow beside its gates (#1585 item 11). + assert len(runtime_graph) == 86, ( + f"{tool.name} must reach the pinned 86-module runtime graph; " f"reached {len(runtime_graph)}" ) assert not missing_modules, ( From 3d4f8a6d274068af1ade5fb75197e199ef5b7315 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mar=C3=ADa=20Juaristi?= <127882282+juaristi22@users.noreply.github.com> Date: Mon, 16 Nov 2026 01:10:23 +0000 Subject: [PATCH 23/31] Pin the shadow against the run's evaluate-once refusals #1609 now evaluates each stage entry once and refuses a phase that carries another outcome for one (387046135). The shadow observes each entry once, so a site reached again keeps its first outcome, and its phase records it. When the run itself refuses a second evaluation, as on an entry evaluated outside the shadow, the shadow records the refusal and does not retry: the entry stays unobserved and fails the run. With the shadow's guard disabled the first test fails, since the run's refusal then answers; with the run's refusal disabled the second fails. Co-Authored-By: Claude Opus 5.5 --- .../engine_free/us/test_us_gate_shadow.py | 79 +++++++++++++++++++ 1 file changed, 79 insertions(+) diff --git a/packages/microcosm-build/tests/engine_free/us/test_us_gate_shadow.py b/packages/microcosm-build/tests/engine_free/us/test_us_gate_shadow.py index 0fcfd99d7d..353ea6da75 100644 --- a/packages/microcosm-build/tests/engine_free/us/test_us_gate_shadow.py +++ b/packages/microcosm-build/tests/engine_free/us/test_us_gate_shadow.py @@ -681,6 +681,85 @@ def test_the_run_refuses_a_stopped_phase_that_drops_an_entry_it_evaluated( assert "marks ['us_test_first'] unreached, but this run evaluated" in error +def test_a_gate_reached_twice_keeps_the_outcome_the_run_produced(tmp_path) -> None: + # Review of #1609: the run evaluates each entry once and records the + # outcome its stage produced. The shadow observes each entry once, so a + # site reached again never asks the run for a second evaluation: the + # first outcome stays, and its phase records it. + shadow = _shadow(tmp_path, _two_phase_gates()) + shadow.gate( + "us_test_alpha", + lambda: ALPHA(0.5), + EvidenceContext(artifacts={"alpha_value": 0.5}), + ) + first = shadow.outcome("us_test_alpha") + # Reached again, on evidence that fails the gate. + assert not shadow.gate( + "us_test_alpha", + lambda: ALPHA(2.0), + EvidenceContext(artifacts={"alpha_value": 2.0}), + ).passed + assert shadow.outcome("us_test_alpha") is first + shadow.gate( + "us_test_beta", + lambda: BETA(0.5), + EvidenceContext(artifacts={"beta_value": 0.5}), + ) + shadow.gate( + "us_test_final", + lambda: ALPHA(0.1), + EvidenceContext(artifacts={"alpha_value": 0.1}), + ) + with pytest.raises(GateBatteryShadowMismatchError, match="more than once"): + shadow.finish() + payload = json.loads(shadow.comparison_path.read_text()) + assert payload["phases_recorded"] == ["assembled", "terminal"] + (error,) = payload["shadow_errors"] + assert "[us_test_alpha]" in error and "more than once" in error + report = json.loads(shadow.report_path.read_text()) + assert report["gates"]["us_test_alpha"]["status"] == "passed" + + +def test_the_run_refuses_a_second_evaluation_and_the_shadow_records_it( + tmp_path, +) -> None: + # The run's own refusal (#1609) backs the shadow up: an entry the run + # evaluated outside the shadow (a wiring fault) is not evaluated again + # when its site is reached. The shadow records the refusal, never raises, + # and does not retry, so the entry stays unobserved and fails the run. + shadow = _shadow(tmp_path, _two_phase_gates()) + shadow.run.evaluate_entries( + ("us_test_alpha",), EvidenceContext(artifacts={"alpha_value": 0.5}) + ) + assert shadow.gate( + "us_test_alpha", + lambda: ALPHA(0.5), + EvidenceContext(artifacts={"alpha_value": 0.5}), + ).passed + assert shadow.outcome("us_test_alpha") is None + shadow.gate( + "us_test_beta", + lambda: BETA(0.5), + EvidenceContext(artifacts={"beta_value": 0.5}), + ) + shadow.gate( + "us_test_final", + lambda: ALPHA(0.1), + EvidenceContext(artifacts={"alpha_value": 0.1}), + ) + with pytest.raises(GateBatteryShadowMismatchError): + shadow.finish() + payload = json.loads(shadow.comparison_path.read_text()) + assert payload["phases_recorded"] == [] + assert payload["not_observed"] == ["us_test_alpha"] + refusal, unwired = payload["shadow_errors"] + assert ( + "this run has already evaluated ['us_test_alpha']; each entry is " + "evaluated once" in refusal + ) + assert "[us_test_alpha] today's run finished without observing" in unwired + + def test_the_shadow_never_raises_while_the_tool_runs(tmp_path) -> None: gates = _two_phase_gates() shadow = _shadow(tmp_path, gates) From 425acffa9e50fabdebbf2e8f2dc5c4accab6e50a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mar=C3=ADa=20Juaristi?= <127882282+juaristi22@users.noreply.github.com> Date: Mon, 16 Nov 2026 10:28:08 +0000 Subject: [PATCH 24/31] Finish the national shadow after the build's handler, so its staging run stands Review of #1635 (Vahid, point 2): `main` finished the national shadow inside the `try` whose handler records a build failure. By then a finished build has completed its staging run in `_main` (`telemetry.complete()`). A verdict difference the shadow raised therefore reached `_ACTIVE_PROGRESS.fail()`, which rewrites the completed run as failed with a forced upload. The shadow now finishes after that handler. A difference fails the program's emitter once and leaves the staging run as the build recorded it. Today's handler is unchanged for today's errors. The other tools have no such path: ACS and the base raise inside `program_telemetry`, which records one failure, and the pool has no telemetry. Two tests pin it. One checks a finished build's staging-run and emitter outcomes with and without a difference; the other checks today's handler on a build error. Co-Authored-By: Claude Opus 5.5 --- .../us/test_us_fiscal_refresh_gate_shadow.py | 76 +++++++++++++++++++ tools/build_us_fiscal_refresh_release.py | 24 ++++-- 2 files changed, 93 insertions(+), 7 deletions(-) diff --git a/packages/microcosm-build/tests/engine_free/us/test_us_fiscal_refresh_gate_shadow.py b/packages/microcosm-build/tests/engine_free/us/test_us_fiscal_refresh_gate_shadow.py index dc4754f43f..eaa4dd009b 100644 --- a/packages/microcosm-build/tests/engine_free/us/test_us_fiscal_refresh_gate_shadow.py +++ b/packages/microcosm-build/tests/engine_free/us/test_us_fiscal_refresh_gate_shadow.py @@ -201,6 +201,82 @@ def build(argv): release.main([]) +class _Recorder: + """A stand-in staging run or emitter that records each outcome it is told.""" + + available = True + + def __init__(self) -> None: + self.calls: list[tuple[str, str | None]] = [] + + def complete(self) -> None: + self.calls.append(("complete", None)) + + def fail(self, error: BaseException, **_: object) -> None: + self.calls.append(("fail", type(error).__name__)) + + +@pytest.mark.parametrize("difference", [False, True]) +def test_a_finished_builds_staging_run_keeps_the_outcome_it_recorded( + tmp_path, monkeypatch, release, difference +): + # Review of #1635: _main completes a finished build's staging run before + # main finishes the shadow. A difference raised there must not rewrite + # that run as failed. The program's emitter records one outcome. + args = _args(tmp_path) + _stand_in_gates( + monkeypatch, release, failing={"pregnancy_signal"} if difference else () + ) + passing = GateResult(name="pregnancy_signal", passed=True) + progress, emitter = _Recorder(), _Recorder() + monkeypatch.setattr(release, "_ACTIVE_EMITTER", emitter) + + def build(argv): + release._start_national_gate_shadow(args, release_id="microcosm-us-test") + _observe_every_entry( + release, + legacy_override=( + {"us_national_pregnancy": lambda: passing} if difference else None + ), + ) + release._ACTIVE_PROGRESS = progress + progress.complete() + return None + + monkeypatch.setattr(release, "_main", build) + if difference: + with pytest.raises( + GateBatteryShadowMismatchError, match="us_national_pregnancy" + ): + release.main([]) + else: + release.main([]) + assert progress.calls == [("complete", None)] + assert emitter.calls == [ + ("fail", "GateBatteryShadowMismatchError") if difference else ("complete", None) + ] + + +def test_a_build_error_still_fails_the_staging_run_and_the_emitter( + tmp_path, monkeypatch, release +): + # Today's handler is unchanged: an error inside _main fails both, once. + args = _args(tmp_path) + progress, emitter = _Recorder(), _Recorder() + monkeypatch.setattr(release, "_ACTIVE_EMITTER", emitter) + + def refused(argv): + release._start_national_gate_shadow(args, release_id="microcosm-us-test") + release._ACTIVE_PROGRESS = progress + raise RuntimeError("Release gates failed: something upstream") + + monkeypatch.setattr(release, "_main", refused) + with pytest.raises(RuntimeError, match="something upstream"): + release.main([]) + assert progress.calls == [("fail", "RuntimeError")] + assert emitter.calls == [("fail", "RuntimeError")] + + def test_a_dry_run_stops_on_purpose_and_never_fails(tmp_path, monkeypatch, release): report = tmp_path / "dry" / "gates.json" args = _args(tmp_path, dry_run_gates_report=report) diff --git a/tools/build_us_fiscal_refresh_release.py b/tools/build_us_fiscal_refresh_release.py index a413771823..b3c6b1edda 100644 --- a/tools/build_us_fiscal_refresh_release.py +++ b/tools/build_us_fiscal_refresh_release.py @@ -13398,6 +13398,11 @@ def main(argv: Sequence[str] | None = None) -> None: A build returns ``None``. ``--dry-run-gates-report`` leaves through ``SystemExit`` with the report's exit code: 1 on any certain failure, 2 on AT-RISK only, 0 clean. + + The gate battery's shadow (microcosm#1585 item 11) finishes after the + build's own handler. By then a finished build has completed its staging + run, so a verdict difference that the shadow raises fails the program's + emitter once and leaves the staging run as the build recorded it. """ global _ACTIVE_DRY_RUN @@ -13405,13 +13410,6 @@ def main(argv: Sequence[str] | None = None) -> None: _finish_national_gate_shadow(stopped_at="a previous run in this process") try: dry_run_exit = _main(argv) - _finish_national_gate_shadow( - stopped_at=( - "dry run: the release stops before target materialization" - if dry_run_exit is not None - else None - ) - ) except BaseException as error: _finish_national_gate_shadow(stopped_by=error) dry_run = _ACTIVE_DRY_RUN @@ -13437,6 +13435,18 @@ def main(argv: Sequence[str] | None = None) -> None: if _ACTIVE_EMITTER is not None and _ACTIVE_EMITTER.available: _ACTIVE_EMITTER.fail(error) raise + try: + _finish_national_gate_shadow( + stopped_at=( + "dry run: the release stops before target materialization" + if dry_run_exit is not None + else None + ) + ) + except BaseException as error: + if _ACTIVE_EMITTER is not None and _ACTIVE_EMITTER.available: + _ACTIVE_EMITTER.fail(error) + raise if dry_run_exit is not None: if _ACTIVE_EMITTER is not None and _ACTIVE_EMITTER.available: if dry_run_exit == 0: From 70912184d99907f197fc7d7144b3f9357ede7bd8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mar=C3=ADa=20Juaristi?= <127882282+juaristi22@users.noreply.github.com> Date: Mon, 16 Nov 2026 10:40:19 +0000 Subject: [PATCH 25/31] Count us_runtime.gate_shadow among the modules the gate bindings reach us_runtime.multispine_pool's shadow sites import us_runtime.gate_shadow, so the transport gate bindings reach one more first-party module through us_runtime: 246 rather than 245. The battery's binding-identity test lists it among the modules added after its base, as ec3c8adb3 did for stochastic_assignment. The identity digests every module's source at runtime and pins no value, so nothing else moves. An edit to gate_shadow now re-keys the gates.battery@1 nodes, as an edit to multispine_pool already did. CI's engine-free job (3.13) on 1885fe364 failed on this test alone, then stopped at its first failure. Tests: transport evidence kernels 166, binding identity 32, gate bindings 131, registry 59, Belgium gate manifest 6, measurement prefit 47, weight quality 30. The income evidence kernels file was skipped for memory pressure. Its closure test checks only membership, which holds on this tree. Co-Authored-By: Claude Opus 5.5 --- .../engine_free/shared/test_transport_evidence_kernels.py | 3 +++ 1 file changed, 3 insertions(+) diff --git a/packages/microcosm-build/tests/engine_free/shared/test_transport_evidence_kernels.py b/packages/microcosm-build/tests/engine_free/shared/test_transport_evidence_kernels.py index 6ca5b97ae8..2a89ce08c5 100644 --- a/packages/microcosm-build/tests/engine_free/shared/test_transport_evidence_kernels.py +++ b/packages/microcosm-build/tests/engine_free/shared/test_transport_evidence_kernels.py @@ -150,6 +150,9 @@ # microcosm#1585: the US keyed draws call # stochastic_assignment.stable_identity_uniforms. "microcosm.build.stochastic_assignment", + # microcosm#1585 item 11: us_runtime.multispine_pool's shadow sites + # import us_runtime.gate_shadow. + "microcosm.build.us_runtime.gate_shadow", # microcosm#1405: the gate battery refuses a signing key the committed # registry does not let sign, so it imports # microcosm.data.gate_signing_keys, and with it the microcosm.data From 2829e4fc9788348f3d350fd74d24199920502a36 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mar=C3=ADa=20Juaristi?= <127882282+juaristi22@users.noreply.github.com> Date: Mon, 16 Nov 2026 12:27:11 +0000 Subject: [PATCH 26/31] Let the stored-input wiring test read its checks inside their shadow sites (us_national) CI's first full engine-free run on this branch stopped at test_main_runs_the_gate_in_the_batch_and_checks_the_written_h5. The test pins where `_main` runs the stored-input gate and the post-write check, and took the first call in each assignment, which is now `shadow_value`. It now reads the call inside the site's lambda, which `shadow_value` evaluates at once, and still accepts today's direct calls, so the flip can drop the shadow without touching it again. The test reaches the tool through a test_support helper, so the touched surface, which looked for the tool's name in test files, missed it. Co-Authored-By: Claude Opus 5.5 --- .../us/test_us_stored_input_register.py | 19 ++++++++++++++----- 1 file changed, 14 insertions(+), 5 deletions(-) diff --git a/packages/microcosm-build/tests/engine_free/us/test_us_stored_input_register.py b/packages/microcosm-build/tests/engine_free/us/test_us_stored_input_register.py index f01633d5e1..4b636cac9a 100644 --- a/packages/microcosm-build/tests/engine_free/us/test_us_stored_input_register.py +++ b/packages/microcosm-build/tests/engine_free/us/test_us_stored_input_register.py @@ -404,6 +404,17 @@ def calls(node, name): def assigned_from(node, name): return isinstance(node, ast.Assign) and calls(node.value, name) + def site_call(value, name): + # A check may run inside its gate battery shadow site (microcosm#1585 + # item 11): `shadow_value` evaluates the lambda it is given at once + # and returns its value, so the check still runs once, here. + if isinstance(value, ast.Call) and ast.unparse(value.func) == "shadow_value": + thunk = value.args[1] + assert isinstance(thunk, ast.Lambda) and not thunk.args.args + value = thunk.body + assert isinstance(value, ast.Call) and ast.unparse(value.func) == name + return value + gate = position( lambda node: assigned_from(node, "_stored_input_gate_failures"), "stored-input gate assignment", @@ -412,9 +423,7 @@ def assigned_from(node, name): assert isinstance(target, ast.Tuple) failures_name = target.elts[0].id details_name = target.elts[1].id - gate_call = next( - inner for inner in ast.walk(body[gate].value) if isinstance(inner, ast.Call) - ) + gate_call = site_call(body[gate].value, "_stored_input_gate_failures") assert {kw.arg: ast.unparse(kw.value) for kw in gate_call.keywords} == { "stage": "US_FISCAL_STORED_INPUTS_STAGE" } @@ -447,8 +456,8 @@ def assigned_from(node, name): "post-write check", ) (premise_name,) = (target.id for target in body[premise].targets) - check_call = next( - inner for inner in ast.walk(body[premise].value) if isinstance(inner, ast.Call) + check_call = site_call( + body[premise].value, "_written_stored_input_verdict_mismatch" ) assert [ast.unparse(arg) for arg in check_call.args] == [ "dataset_path", From 034dd8792dd56cb5acd5eb46402e6f735c884945 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mar=C3=ADa=20Juaristi?= <127882282+juaristi22@users.noreply.github.com> Date: Tue, 17 Nov 2026 12:21:30 +0000 Subject: [PATCH 27/31] Answer Max's round 1 on the US gate battery shadow (us_*) From Max's review of 2c34c57f0 (PolicyEngine/microcosm#1635): 1. A blocking district ESS collapse records its counts and no failure line. The binding now reads district_ess_collapse_failures through a new USGateSpec.failure_lines reference (mapping gates only), and today's verdict (_legacy_district_ess_verdict, replacing _legacy_mapping_verdict) reads the same function, so both fail on the line made from the counts. Before, the battery recorded an evaluation error and today's verdict a pass. gate_summary.json's entry is unchanged. 2. A finished run that misses a stage's observations names that stage for each unobserved entry instead of calling its site unwired. The base locks the shadow switch in _stage_run_config when it is off, so a resume cannot mix stages run with and without the shadow; with the shadow on, as in every real build, the config is unchanged. 4. main's docstring no longer says a difference fails the emitter: a finished release's telemetry has closed it by then. The test's stand-in emitter now closes on its first outcome, and its staging run hands its outcome to it, as the real ones do. 5. The QRF tail register and the export input-mass reference can fail to load ahead of their sites, under earlier failures, where the degraded-mode handler swallows the error. Both handlers now record the entry not run then, so a finished --evidence-release build no longer calls it unwired. 7. Starting an ACS stage deletes the scope's report and comparison with the later stages' observations they were built from. 9. Five us_local entries pin the module-constant thresholds they read: the take-up share bands and discretionary share factors, the income and SSI-disability review bands, and the SSI band tolerance at both SSI and Medicaid take-up stages. The us_local scope's pinned digests move. Points 6 and 8 correct the description. Point 3's test is retired in the next commit. Co-Authored-By: Claude Opus 5.5 --- docs/gate-battery-contract.md | 5 +- .../src/microcosm/build/us/gates.json | 34 +++++- .../build/us_runtime/battery_bindings.py | 72 +++++++++-- .../microcosm/build/us_runtime/gate_shadow.py | 11 +- .../us/test_us_acs_local_gate_shadow.py | 24 ++++ .../us/test_us_battery_bindings.py | 63 +++++++++- .../us/test_us_fiscal_refresh_gate_shadow.py | 114 ++++++++++++++++-- .../engine_free/us/test_us_gate_shadow.py | 29 +++++ .../test_us_puf_support_base_gate_shadow.py | 38 ++++++ tools/build_us_acs_local_release.py | 51 +++++++- tools/build_us_fiscal_refresh_release.py | 29 ++++- tools/build_us_puf_support_base.py | 7 ++ 12 files changed, 438 insertions(+), 39 deletions(-) diff --git a/docs/gate-battery-contract.md b/docs/gate-battery-contract.md index c24ed65287..81373ebdc3 100644 --- a/docs/gate-battery-contract.md +++ b/docs/gate-battery-contract.md @@ -349,7 +349,10 @@ reached. The run refuses a phase that marks unreached an entry it evaluated, but a scope rebuilt from stages run as separate processes (Route A's checkpointed base, ACS local) holds only their outcomes, so each stage's saved observations also name every entry it reached, and a stage -that ran and saved none leaves the stopped phase unrecorded. The national +that ran and saved none leaves the stopped phase unrecorded. A finished run +names that stage where it would otherwise call an unobserved entry unwired, +and Route A's base locks the switch in its run config when it is off, so a +resume cannot mix stages run with and without the shadow. The national release's shadow is armed before its preflight gates, which run ahead of the refusal to reuse a certified release directory, so it holds its files until that refusal has passed: a refused rerun leaves the certified diff --git a/packages/microcosm-build/src/microcosm/build/us/gates.json b/packages/microcosm-build/src/microcosm/build/us/gates.json index 05840bf1e5..c57bef3382 100644 --- a/packages/microcosm-build/src/microcosm/build/us/gates.json +++ b/packages/microcosm-build/src/microcosm/build/us/gates.json @@ -2253,7 +2253,8 @@ "parameters": { "check": "ssi_medicaid_take_up_signal", "residual_relative_tolerance": 1e-09, - "saturated_relative_tolerance": 1e-06 + "saturated_relative_tolerance": 1e-06, + "acs_local_ssi_band_relative_tolerance": 0.05 }, "notes": "US ACS local release (tools/build_us_acs_local_release.py): ACS SSI and Medicaid take-up after materialize assigns them; the verdict is recorded in run_identity.json. Exits at once on failure." }, @@ -2341,7 +2342,21 @@ "criticality": "release_blocking", "parameters": { "check": "take_up_signal", - "medicare_aged_share_floor": 0.8 + "medicare_aged_share_floor": 0.8, + "share_bands": { + "takes_up_snap_if_eligible": [ + 0.7, + 0.95 + ], + "takes_up_tanf_if_eligible": [ + 0.1, + 0.4 + ] + }, + "discretionary_share_factors": [ + 0.5, + 1.5 + ] }, "notes": "US ACS local release (tools/build_us_acs_local_release.py): SNAP and TANF take-up on both spines. Finalize collects it into gate_summary.json, writes the file, then raises on a hard failure." }, @@ -2371,7 +2386,11 @@ "phase": "terminal", "criticality": "release_blocking", "parameters": { - "check": "income_transfer_signal" + "check": "income_transfer_signal", + "acs_local_income_review_band": [ + 0.5, + 2.0 + ] }, "notes": "US ACS local release (tools/build_us_acs_local_release.py): the transferred ACS income leaves, with their staging receipt. Finalize collects it into gate_summary.json, writes the file, then raises on a hard failure." }, @@ -2381,7 +2400,11 @@ "phase": "terminal", "criticality": "release_blocking", "parameters": { - "check": "ssi_disability_signal" + "check": "ssi_disability_signal", + "acs_local_ssi_disability_review_band": [ + 0.5, + 2.0 + ] }, "notes": "US ACS local release (tools/build_us_acs_local_release.py): the ACS SSI disability criteria, with their staging receipt. Finalize collects it into gate_summary.json, writes the file, then raises on a hard failure." }, @@ -2393,7 +2416,8 @@ "parameters": { "check": "ssi_medicaid_take_up_signal", "residual_relative_tolerance": 1e-09, - "saturated_relative_tolerance": 1e-06 + "saturated_relative_tolerance": 1e-06, + "acs_local_ssi_band_relative_tolerance": 0.05 }, "notes": "US ACS local release (tools/build_us_acs_local_release.py): ACS SSI and Medicaid take-up on the calibrated bytes. Finalize collects it into gate_summary.json, writes the file, then raises on a hard failure." }, diff --git a/packages/microcosm-build/src/microcosm/build/us_runtime/battery_bindings.py b/packages/microcosm-build/src/microcosm/build/us_runtime/battery_bindings.py index c902774a41..8d893f3508 100644 --- a/packages/microcosm-build/src/microcosm/build/us_runtime/battery_bindings.py +++ b/packages/microcosm-build/src/microcosm/build/us_runtime/battery_bindings.py @@ -170,6 +170,10 @@ class USGateSpec: sets it per run. The entry declares the parser's default; a build that passes another value is a runtime override, which the shadow records and explains. + failure_lines: For a ``mapping`` gate, the reference of the function + that gives a failing mapping's lines, as today's verdict reads + them, for a gate whose failing mapping may carry none (the + district ESS gate fails a blocking collapse on its counts). """ check: str @@ -182,6 +186,7 @@ class USGateSpec: returns: str = "result" refusals: tuple[type[BaseException], ...] = () flags: Mapping[str, str] = field(default_factory=dict) + failure_lines: str | None = None def __post_init__(self) -> None: if not self.check or not self.legacy_name: @@ -210,6 +215,13 @@ def __post_init__(self) -> None: ) if self.returns == "receipt" and not self.refusals: raise ValueError(f"{self.check}: a receipt check fails only by a refusal.") + if self.failure_lines is not None: + if self.returns != "mapping": + raise ValueError( + f"{self.check}: failure_lines reads a mapping; it returns " + f"{self.returns!r}." + ) + _split_reference(self.failure_lines) stray_flags = sorted(set(self.flags) - set(self.parameters)) if stray_flags: raise ValueError( @@ -235,9 +247,17 @@ def artifact_keys(self) -> frozenset[str]: def needs_frame(self) -> bool: return FRAME in self.sources + @property + def callables(self) -> tuple[str, ...]: + """The references the binding calls: the gate and its line maker.""" + + return (self.gate,) + ( + (self.failure_lines,) if self.failure_lines is not None else () + ) + @property def references(self) -> tuple[str, ...]: - return (self.gate, *self.pinned.values()) + return (*self.callables, *self.pinned.values()) def _as_gate_result(value: object, legacy_name: str) -> object: @@ -299,7 +319,7 @@ def __init__( except (AttributeError, ImportError, ValueError) as exc: unresolved.append(f"{spec.check}: {reference} ({exc})") continue - if reference == spec.gate and not callable(target): + if reference in spec.callables and not callable(target): unresolved.append(f"{spec.check}: {reference} is not callable") if unresolved: raise ValueError(f"{name}: unresolved references: {unresolved}.") @@ -389,7 +409,15 @@ def evaluate( ) except spec.refusals as refusal: return GateResult(name=self.name, passed=False, failures=(str(refusal),)) - value = _verdict_of(spec, value) + value = _verdict_of( + spec, + value, + failure_lines=( + resolve_reference(spec.failure_lines, tool=self._tool) + if spec.failure_lines is not None + else None + ), + ) if isinstance(value, GateResult) and value.name == spec.legacy_name: value = replace(value, name=self.name) return value @@ -420,8 +448,18 @@ def _lines(value: object, check: str) -> tuple[str, ...]: return tuple(str(line) for line in value) -def _verdict_of(spec: USGateSpec, value: Any) -> object: - """The gate's return value as its result, by :attr:`USGateSpec.returns`.""" +def _verdict_of( + spec: USGateSpec, + value: Any, + *, + failure_lines: Callable[[Mapping[str, Any]], Sequence[str]] | None = None, +) -> object: + """The gate's return value as its result, by :attr:`USGateSpec.returns`. + + ``failure_lines`` is the resolved :attr:`USGateSpec.failure_lines`: a + failing mapping's lines come from it, since a result that fails must + name why. + """ name = spec.legacy_name if spec.returns == "result": @@ -432,11 +470,17 @@ def _verdict_of(spec: USGateSpec, value: Any) -> object: if spec.returns == "receipt": return GateResult(name=name, passed=True) if spec.returns == "mapping": - failures = _lines(value.get("failures") or (), spec.check) + passed = bool(value.get("passed")) + failures = _lines( + failure_lines(value) + if failure_lines is not None and not passed + else value.get("failures") or (), + spec.check, + ) details = {key: item for key, item in value.items() if key != "failures"} return GateResult( name=name, - passed=bool(value.get("passed")), + passed=passed, failures=failures, details=details, ) @@ -1320,6 +1364,7 @@ def _us_local_specs() -> tuple[USGateSpec, ...]: "acs_local_ssi_medicaid_take_up", "_RESIDUAL_RELATIVE_TOLERANCE", "_SATURATED_RELATIVE_TOLERANCE", + "ACS_LOCAL_SSI_BAND_RELATIVE_TOLERANCE", ), ), # The calibrated artifact's gates at finalize, and package's re-checks. @@ -1359,7 +1404,12 @@ def _us_local_specs() -> tuple[USGateSpec, ...]: legacy_name="acs_local_take_up_signal", gate="tool:acs_local_take_up_signal_gate", positional=(FRAME,), - pinned=_pins("acs_local_take_up", "_MEDICARE_AGED_SHARE_FLOOR"), + pinned=_pins( + "acs_local_take_up", + "_MEDICARE_AGED_SHARE_FLOOR", + "_SHARE_BANDS", + "_DISCRETIONARY_SHARE_FACTORS", + ), ), USGateSpec( check="immigration_signal", @@ -1383,6 +1433,7 @@ def _us_local_specs() -> tuple[USGateSpec, ...]: gate="tool:acs_local_income_transfer_signal_gate", positional=(FRAME,), arguments={"receipt": "income_transfer_receipt"}, + pinned=_pins("acs_local_income", "ACS_LOCAL_INCOME_REVIEW_BAND"), ), USGateSpec( check="ssi_disability_signal", @@ -1390,6 +1441,9 @@ def _us_local_specs() -> tuple[USGateSpec, ...]: gate="tool:acs_local_ssi_disability_signal_gate", positional=(FRAME,), arguments={"receipt": "ssi_disability_receipt"}, + pinned=_pins( + "acs_local_ssi_disability", "ACS_LOCAL_SSI_DISABILITY_REVIEW_BAND" + ), ), USGateSpec( check="receipt_anchor_signal", @@ -1418,6 +1472,8 @@ def _us_local_specs() -> tuple[USGateSpec, ...]: "absolute_floor": "district_ess_floor", }, returns="mapping", + # A blocking collapse records its counts but no failure line. + failure_lines="tool:district_ess_collapse_failures", ), USGateSpec( check="stored_inputs", diff --git a/packages/microcosm-build/src/microcosm/build/us_runtime/gate_shadow.py b/packages/microcosm-build/src/microcosm/build/us_runtime/gate_shadow.py index 8daa4aa0f4..a2bcd4fee4 100644 --- a/packages/microcosm-build/src/microcosm/build/us_runtime/gate_shadow.py +++ b/packages/microcosm-build/src/microcosm/build/us_runtime/gate_shadow.py @@ -984,10 +984,19 @@ def _finish( f"shadow could not record its phases: {type(exc).__name__}: {exc}" ) if completed: + # A process that saved no observations (a stage run with the + # shadow off, or before it existed) explains an unobserved entry + # better than its site does, so it is named instead. + cause = ( + "; ".join(self._observations_missing) + + ", so it may have run there unrecorded" + if self._observations_missing + else "its site is not wired" + ) for entry_id in not_observed: self._shadow_errors.append( f"[{entry_id}] today's run finished without observing this " - "entry; its site is not wired." + f"entry; {cause}." ) payload = self._comparison_payload( recorded=recorded, diff --git a/packages/microcosm-build/tests/engine_free/us/test_us_acs_local_gate_shadow.py b/packages/microcosm-build/tests/engine_free/us/test_us_acs_local_gate_shadow.py index a7d4c77650..60c1d82d47 100644 --- a/packages/microcosm-build/tests/engine_free/us/test_us_acs_local_gate_shadow.py +++ b/packages/microcosm-build/tests/engine_free/us/test_us_acs_local_gate_shadow.py @@ -168,6 +168,30 @@ def test_a_finalize_stop_is_recorded_and_its_rerun_starts_clean( assert not (acs_directory(args) / "package.observations.json").exists() +def test_starting_a_stage_clears_the_scope_files_it_outdates( + tmp_path, monkeypatch, acs +) -> None: + # Starting a stage discards its own and every later stage's observations, + # so the scope's report and comparison built from them go at once: a + # stage killed before its end must not leave a finished run's verdict. + args = _args(tmp_path) + stand_in_gates(monkeypatch, "us_local", acs) + for stage in STAGE_ENTRIES: + _run_stage(acs, args, stage) + report, comparison = shadow_file_paths(acs_directory(args), "us_local") + assert report.is_file() + assert json.loads(comparison.read_text())["run_completed"] is True + # The qa stage declares no entry, and it still outdates the later ones. + with acs._local_gate_shadow_stage(args, "qa"): + assert not comparison.exists() + assert not report.exists() + assert not (acs_directory(args) / "package.observations.json").exists() + # Its end rebuilds them from the stages left: a run stopped after qa. + payload = _comparison(args) + assert payload["run_completed"] is False + assert payload["stopped_at"] == "after the qa stage" + + def test_a_stage_that_saved_nothing_is_never_named_unreached( tmp_path, monkeypatch, acs ) -> None: diff --git a/packages/microcosm-build/tests/engine_free/us/test_us_battery_bindings.py b/packages/microcosm-build/tests/engine_free/us/test_us_battery_bindings.py index d1fa339d83..fcbcedf884 100644 --- a/packages/microcosm-build/tests/engine_free/us/test_us_battery_bindings.py +++ b/packages/microcosm-build/tests/engine_free/us/test_us_battery_bindings.py @@ -90,14 +90,16 @@ ), }, "us_local": { + # Moved by the five entries that pin the thresholds they compare + # against (review of #1635). "gates_manifest_sha256": ( - "6b4286429c8ad369b8b3d2fbbcc4e3f16dcb553915969d72f02873fd87f56f60" + "3356e3f69213870398f2920dbc08b983c994551e61d45175c22ef9efef9c53f8" ), "policy_sha256": ( - "a1fe120a37dbc2f4e55091872f06c2fe6f2d0ecf504cf1c08323aac4514dfda5" + "cb3471437b10de6b4e5c67818007edb5b647c77c25aa055bd26ce50203f9ff88" ), "spec_fingerprint": ( - "139d82665b455eb86f5c2c9a4f597cb3bdeff61a6ef666a9fc415241568195b2" + "28c7f82d14bce4a63c82b20cfbaee5f7caf225c893633e34f91f3855f0344b15" ), }, } @@ -441,3 +443,58 @@ def test_a_declared_threshold_off_todays_constant_is_a_difference(tmp_path) -> N ) (difference,) = shadow.differences() assert "differs from today's" in difference + + +def test_a_blocking_district_collapse_fails_both_verdicts_on_one_line( + tmp_path, +) -> None: + # The district ESS gate fails a blocking collapse on its counts, with no + # failure line, and a result that fails must name why. Both verdicts read + # the line district_ess_collapse_failures makes from the counts; before, + # the battery recorded an evaluation error and today's verdict a pass. + tool = vars(load_us_gate_tool("us_local")) + shadow = _shadow(tmp_path, "us_local") + origin = { + "design": {"effective_sample_size_by_district": {"0601": 100.0, "0602": 80.0}}, + "calibrated": { + "effective_sample_size_by_district": {"0601": 20.0, "0602": 60.0} + }, + } + with active_gate_shadow(shadow): + entry = shadow_value( + "us_local_district_ess_collapse", + lambda: tool["district_ess_collapse_gate"]( + origin, relative_floor=0.25, absolute_floor=15.0, blocking=True + ), + EvidenceContext( + artifacts={"weight_origin": origin, "district_ess_blocking": True} + ), + verdict=tool["_legacy_district_ess_verdict"], + ) + # Today's entry is written as before: failing, with its counts only. + assert (entry["passed"], entry["failures"], entry["n_collapsed"]) == ( + False, + [], + 1, + ) + line = ( + "blocking district ESS gate: congressional districts with a calibrated " + "Kish ESS 1 of 2 below 0.25 x their design-weight Kish ESS; 0 of 2 " + "below 15" + ) + outcome = shadow.outcome("us_local_district_ess_collapse") + assert outcome is not None and outcome.status is GateStatus.FAILED + assert outcome.result.failures == (line,) + assert tool["_legacy_district_ess_verdict"](entry).failures == (line,) + assert shadow.differences() == () + + +def test_only_a_mapping_gate_takes_a_failure_line_maker() -> None: + (spec,) = [ + spec + for spec in us_gate_specs("us_local") + if spec.check == "district_ess_collapse" + ] + assert spec.failure_lines in spec.references + with pytest.raises(ValueError, match="failure_lines reads a mapping"): + replace(spec, returns="failures") diff --git a/packages/microcosm-build/tests/engine_free/us/test_us_fiscal_refresh_gate_shadow.py b/packages/microcosm-build/tests/engine_free/us/test_us_fiscal_refresh_gate_shadow.py index eaa4dd009b..da64967450 100644 --- a/packages/microcosm-build/tests/engine_free/us/test_us_fiscal_refresh_gate_shadow.py +++ b/packages/microcosm-build/tests/engine_free/us/test_us_fiscal_refresh_gate_shadow.py @@ -18,7 +18,7 @@ import pytest from microcosm.build import GateResult -from microcosm.build.gate_battery import EvidenceContext +from microcosm.build.gate_battery import EvidenceContext, GateStatus from microcosm.build.us_runtime.battery_bindings import ( FRAME, us_flag_overrides, @@ -202,33 +202,46 @@ def build(argv): class _Recorder: - """A stand-in staging run or emitter that records each outcome it is told.""" + """A stand-in staging run or emitter that records each outcome it is told. - available = True + It closes on its first outcome, as the build's emitter does, and a + staging run hands its outcome to the emitter it reports to, as + ``_BuildProgress`` does. + """ - def __init__(self) -> None: + def __init__(self, emitter: _Recorder | None = None) -> None: self.calls: list[tuple[str, str | None]] = [] + self.available = True + self._emitter = emitter def complete(self) -> None: self.calls.append(("complete", None)) + self.available = False + if self._emitter is not None: + self._emitter.complete() def fail(self, error: BaseException, **_: object) -> None: self.calls.append(("fail", type(error).__name__)) + self.available = False + if self._emitter is not None: + self._emitter.fail(error) @pytest.mark.parametrize("difference", [False, True]) def test_a_finished_builds_staging_run_keeps_the_outcome_it_recorded( tmp_path, monkeypatch, release, difference ): - # Review of #1635: _main completes a finished build's staging run before - # main finishes the shadow. A difference raised there must not rewrite - # that run as failed. The program's emitter records one outcome. + # Review of #1635: _main completes a finished build's staging run, and + # with it the emitter, before main finishes the shadow. A difference + # raised there fails the program's exit alone: neither record is + # rewritten, and each records one outcome. args = _args(tmp_path) _stand_in_gates( monkeypatch, release, failing={"pregnancy_signal"} if difference else () ) passing = GateResult(name="pregnancy_signal", passed=True) - progress, emitter = _Recorder(), _Recorder() + emitter = _Recorder() + progress = _Recorder(emitter) monkeypatch.setattr(release, "_ACTIVE_EMITTER", emitter) def build(argv): @@ -252,9 +265,7 @@ def build(argv): else: release.main([]) assert progress.calls == [("complete", None)] - assert emitter.calls == [ - ("fail", "GateBatteryShadowMismatchError") if difference else ("complete", None) - ] + assert emitter.calls == [("complete", None)] def test_a_build_error_still_fails_the_staging_run_and_the_emitter( @@ -262,7 +273,8 @@ def test_a_build_error_still_fails_the_staging_run_and_the_emitter( ): # Today's handler is unchanged: an error inside _main fails both, once. args = _args(tmp_path) - progress, emitter = _Recorder(), _Recorder() + emitter = _Recorder() + progress = _Recorder(emitter) monkeypatch.setattr(release, "_ACTIVE_EMITTER", emitter) def refused(argv): @@ -400,3 +412,81 @@ def test_waivers_and_flag_overrides_are_recorded_by_entry(tmp_path, release): ) assert evidence["us_national_release_gates"] == ["--evidence-release"] assert "us_national_pregnancy" not in evidence + + +def test_a_tail_register_that_never_loads_records_its_gate_not_run( + tmp_path, release +) -> None: + # Review of #1635: under earlier failures the degraded-mode handler + # swallows a register that failed to load ahead of the gate's site, and + # the build goes on; a finished --evidence-release build then called the + # entry unwired. + release._start_national_gate_shadow(_args(tmp_path), release_id="microcosm-us-test") + register = tmp_path / "qrf_tail_exclusions.json" + register.write_text("[]") + failures = ["an earlier gate failed"] + assert ( + release._record_qrf_tail_concentration_gate( + object(), + exclusions_path=register, + allow_concentration=False, + terminal_gate_failures=failures, + release_dir=tmp_path, + telemetry=None, + ) + == [] + ) + # Today's line is as before. + assert failures[-1].startswith( + "QRF tail concentration failed: evaluation error under earlier gate " + "failures: ValueError" + ) + shadow = current_gate_shadow("us_national_qrf_tail_concentration") + outcome = shadow.outcome("us_national_qrf_tail_concentration") + assert outcome is not None and outcome.status is GateStatus.EVIDENCE_ABSENT + assert shadow.differences() == () + + +def test_every_degraded_mode_handler_records_a_gate_kept_from_running( + release, +) -> None: + # Each handler that swallows an error under earlier failures guards one + # gate's site. Work ahead of the site can raise before the gate runs (a + # register or a reference that does not load), so the handler must then + # record the entry not run; a handler whose site comes first records + # nothing, since the site itself observed the crash. + tree = ast.parse(Path(release.__file__).read_text(encoding="utf-8")) + handlers = {} + for node in ast.walk(tree): + if not isinstance(node, ast.Try): + continue + for handler in node.handlers: + if not any( + isinstance(statement, ast.If) + and ast.unparse(statement.test) == "not terminal_gate_failures" + for statement in handler.body + ): + continue + ((index, entry_id),) = [ + (index, call.args[0].value) + for index, statement in enumerate(node.body) + for call in ast.walk(statement) + if isinstance(call, ast.Call) + and ast.unparse(call.func) in {"shadow_gate", "shadow_value"} + ] + recorded = { + call.args[0].value + for call in ast.walk(handler) + if isinstance(call, ast.Call) + and ast.unparse(call.func) == "shadow_not_run" + } + handlers[entry_id] = (index > 0, recorded) + assert handlers == { + "us_national_qrf_tail_concentration": ( + True, + {"us_national_qrf_tail_concentration"}, + ), + "us_national_release_input_coverage": (False, set()), + "us_national_esi_premiums_anchor": (False, set()), + "us_national_export_input_mass": (True, {"us_national_export_input_mass"}), + } diff --git a/packages/microcosm-build/tests/engine_free/us/test_us_gate_shadow.py b/packages/microcosm-build/tests/engine_free/us/test_us_gate_shadow.py index 353ea6da75..4ab146752f 100644 --- a/packages/microcosm-build/tests/engine_free/us/test_us_gate_shadow.py +++ b/packages/microcosm-build/tests/engine_free/us/test_us_gate_shadow.py @@ -440,6 +440,35 @@ def test_an_unwired_entry_fails_a_finished_run(tmp_path) -> None: payload = json.loads(shadow.comparison_path.read_text()) assert payload["not_observed"] == ["us_test_final"] assert payload["phases_recorded"] == ["assembled"] + (unwired,) = payload["shadow_errors"] + assert unwired.endswith("this entry; its site is not wired.") + + +def test_a_finished_run_names_the_stage_that_saved_no_observations(tmp_path) -> None: + # As when a pre-merge checkpoint or a stage run with the switch off + # resumes: the entry may have run in that stage, so the site is not + # blamed. The unobserved entry still fails the finished run. + shadow = _shadow(tmp_path, _two_phase_gates()) + shadow.note_missing_observations("the finalize stage saved no observations") + shadow.gate( + "us_test_alpha", + lambda: ALPHA(0.5), + EvidenceContext(artifacts={"alpha_value": 0.5}), + ) + shadow.gate( + "us_test_beta", + lambda: BETA(0.5), + EvidenceContext(artifacts={"beta_value": 0.5}), + ) + with pytest.raises(GateBatteryShadowMismatchError, match="us_test_final"): + shadow.finish() + payload = json.loads(shadow.comparison_path.read_text()) + assert payload["not_observed"] == ["us_test_final"] + assert payload["shadow_errors"] == [ + "[us_test_final] today's run finished without observing this entry; " + "the finalize stage saved no observations, so it may have run there " + "unrecorded." + ] def test_a_deliberate_stop_records_what_ran_and_never_raises(tmp_path) -> None: diff --git a/packages/microcosm-build/tests/engine_free/us/test_us_puf_support_base_gate_shadow.py b/packages/microcosm-build/tests/engine_free/us/test_us_puf_support_base_gate_shadow.py index 5b39ba9c4f..04204916da 100644 --- a/packages/microcosm-build/tests/engine_free/us/test_us_puf_support_base_gate_shadow.py +++ b/packages/microcosm-build/tests/engine_free/us/test_us_puf_support_base_gate_shadow.py @@ -280,6 +280,44 @@ def __init__(self, *_args, **_kwargs) -> None: assert payload["phases_recorded"] == [] +def test_a_resume_cannot_mix_stages_run_with_and_without_the_shadow( + tmp_path, monkeypatch, base +) -> None: + # A stage run with the switch off saves nothing, so the parent could only + # call its entries unwired. The run config locks the switch when it is + # off; with the shadow on, as in every real build, it is unchanged. + puf = tmp_path / "puf.h5" + puf.write_bytes(b"puf") + args = base._parse_args( + [ + "--base-h5", + str(tmp_path / "base.h5"), + "--puf-h5", + str(puf), + "--out", + str(tmp_path / "out"), + "--without-block-ladder", + ] + ) + monkeypatch.setattr( + base, "_builder_code_identity", lambda: {"source_sha256": "builder"} + ) + armed = base._stage_run_config(args) + assert "gate_battery_shadow" not in armed + monkeypatch.setenv(US_GATE_SHADOW_SWITCH, "off") + off = base._stage_run_config(args) + assert off == {**armed, "gate_battery_shadow": "off"} + checkpoints = tmp_path / "checkpoints" + base.StageRuntime(checkpoints, base.OUTER_STAGE_PIPELINE, run_config=off) + monkeypatch.delenv(US_GATE_SHADOW_SWITCH) + with pytest.raises(ValueError, match="run_config differs"): + base.StageRuntime( + checkpoints, + base.OUTER_STAGE_PIPELINE, + run_config=base._stage_run_config(args), + ) + + def test_the_geography_waiver_is_recorded_by_entry(tmp_path, base) -> None: shadow = base._base_gate_shadow( _args(tmp_path, allow_geography_ladder_gate_failures=True), tmp_path diff --git a/tools/build_us_acs_local_release.py b/tools/build_us_acs_local_release.py index 9e1f6a0cf5..f24af5ecbb 100644 --- a/tools/build_us_acs_local_release.py +++ b/tools/build_us_acs_local_release.py @@ -5015,6 +5015,36 @@ def district_ess_collapse_gate( } +def district_ess_collapse_failures(gate: dict) -> list[str]: + """The district ESS gate entry's failure lines; none when it passes. + + An entry that could not be evaluated names why. A blocking entry whose + criteria are not met records only its counts, so its line is made from + them, naming each check that is on, as the reviewed limitation does. Both + verdicts in the gate battery's shadow (microcosm#1585 item 11) read it. + """ + + if gate.get("passed"): + return [] + if gate.get("failures"): + return [str(line) for line in gate["failures"]] + n = gate["n_districts"] + checks = [] + if gate["relative_floor"] > 0: + checks.append( + f"{gate['n_collapsed']} of {n} below {gate['relative_floor']:g} x " + "their design-weight Kish ESS" + ) + if gate["absolute_floor"] > 0: + checks.append( + f"{gate['n_below_floor']} of {n} below {gate['absolute_floor']:g}" + ) + return [ + "blocking district ESS gate: congressional districts with a calibrated " + "Kish ESS " + "; ".join(checks) + ] + + def district_ess_collapse_limitation(gate: dict) -> dict: """The reviewed-limitations entry stating the district ESS gate's result.""" @@ -6106,7 +6136,7 @@ def do_finalize(args) -> None: "district_ess_blocking": args.district_ess_gate_blocking, } ), - verdict=_legacy_mapping_verdict, + verdict=_legacy_district_ess_verdict, ) limitations = finalize_reviewed_limitations( @@ -7395,6 +7425,13 @@ def _local_gate_shadow_stage(args, stage: str): return for name in _LOCAL_GATE_SHADOW_STAGES[_LOCAL_GATE_SHADOW_STAGES.index(stage) :]: _local_stage_observations(args, name).unlink(missing_ok=True) + # The scope's report and comparison were built from observations just + # discarded, so they go too: a stage that never reaches its end, killed + # before it rebuilds them, must not leave an earlier run's verdict. + for stale in shadow_file_paths( + _local_gate_shadow_directory(args), US_LOCAL_GATE_SCOPE + ): + stale.unlink(missing_ok=True) shadow = _local_gate_shadow(args, _local_gate_shadow_directory(args) / stage) def save() -> None: @@ -7432,12 +7469,14 @@ def _shadow_local_refusal(entry_id: str, evaluate, frame, **artifacts): ) -def _legacy_mapping_verdict(entry: dict) -> LegacyVerdict: - """Today's verdict on a gate entry written as a mapping.""" +def _legacy_district_ess_verdict(entry: dict) -> LegacyVerdict: + """Today's verdict on the district ESS gate entry. + + A blocking collapse fails it with the line made from its counts, as the + battery's binding does (:func:`district_ess_collapse_failures`). + """ - if entry.get("passed"): - return LegacyVerdict.from_failures(()) - return LegacyVerdict.from_failures(entry.get("failures") or ()) + return LegacyVerdict.from_failures(district_ess_collapse_failures(entry)) def main(argv: list[str] | None = None) -> int: diff --git a/tools/build_us_fiscal_refresh_release.py b/tools/build_us_fiscal_refresh_release.py index 731394a5dc..b5bc6e562b 100644 --- a/tools/build_us_fiscal_refresh_release.py +++ b/tools/build_us_fiscal_refresh_release.py @@ -8694,8 +8694,10 @@ def _record_qrf_tail_concentration_gate( Returns the register-mismatch failure lines (empty when the register matches) so --evidence-release can refuse them. """ + register_loaded = False try: register = _load_qrf_tail_concentration_exclusions(exclusions_path) + register_loaded = True gate, surface = shadow_value( "us_national_qrf_tail_concentration", lambda: _qrf_tail_concentration_gate( @@ -8729,6 +8731,15 @@ def _record_qrf_tail_concentration_gate( # outright; see _qrf_tail_register_evidence_refusal. if not terminal_gate_failures: raise + if not register_loaded: + # The gate never ran, so the gate battery's shadow (microcosm#1585 + # item 11) records that, or a finished --evidence-release build + # would call the entry unwired. + shadow_not_run( + "us_national_qrf_tail_concentration", + "its reviewed-exclusions register did not load: " + f"{type(exc).__name__}: {exc}", + ) terminal_gate_failures.append( "QRF tail concentration failed: evaluation error under earlier " f"gate failures: {type(exc).__name__}: {exc}" @@ -13401,9 +13412,10 @@ def main(argv: Sequence[str] | None = None) -> None: AT-RISK only, 0 clean. The gate battery's shadow (microcosm#1585 item 11) finishes after the - build's own handler. By then a finished build has completed its staging - run, so a verdict difference that the shadow raises fails the program's - emitter once and leaves the staging run as the build recorded it. + build's own handler. By then a finished build's telemetry has completed + its staging run and its emitter, which closes on that outcome, so a + verdict difference that the shadow raises fails the program's exit + alone: both records stay as the build left them. """ global _ACTIVE_DRY_RUN @@ -13445,6 +13457,9 @@ def main(argv: Sequence[str] | None = None) -> None: ) ) except BaseException as error: + # A finished release's telemetry has closed the emitter by now (see + # the docstring), so this records an outcome only on an emitter that + # something left open. if _ACTIVE_EMITTER is not None and _ACTIVE_EMITTER.available: _ACTIVE_EMITTER.fail(error) raise @@ -17276,6 +17291,7 @@ def _main(argv: Sequence[str] | None = None) -> int | None: "sha256": None, "reference_name": export_reference_name, } + reference_loaded = False try: if args.export_input_mass_reference_h5 is not None: export_input_mass_reference["sha256"] = _sha256( @@ -17286,6 +17302,7 @@ def _main(argv: Sequence[str] | None = None) -> int | None: if args.export_input_mass_reference_h5 is not None else None ) + reference_loaded = True # Build H (microcosm#299): the two SOI-identified columns whose true # target level provably cannot sit inside the live-default reference # band (estate_income, non_sch_d_capital_gains). miscellaneous_income @@ -17319,6 +17336,12 @@ def _main(argv: Sequence[str] | None = None) -> int | None: # Same degraded-mode contract as the coverage gate above. if not terminal_gate_failures: raise + if not reference_loaded: + # As for the QRF tail register: the gate never ran. + shadow_not_run( + "us_national_export_input_mass", + f"its reference did not load: {type(exc).__name__}: {exc}", + ) terminal_gate_failures.append( "Input mass parity failed: evaluation error under earlier gate " f"failures: {type(exc).__name__}: {exc}" diff --git a/tools/build_us_puf_support_base.py b/tools/build_us_puf_support_base.py index dd293e351a..be756eafea 100644 --- a/tools/build_us_puf_support_base.py +++ b/tools/build_us_puf_support_base.py @@ -1353,6 +1353,13 @@ def path(value: Path | None) -> str | None: "thread_environment": thread_environment, "without_block_ladder": bool(args.without_block_ladder), } + if not tool_gate_shadows_enabled(): + # microcosm#1585 item 11: a stage run with the gate battery's shadow + # off saves no observations, and the run that finishes the scope + # could then only call its entries unwired. The switch is locked + # when off only, so a resume cannot mix the two, and a real build's + # config, with the shadow on, is unchanged. + config["gate_battery_shadow"] = "off" if _is_block_v1(args): # Off the legacy rule only, so a legacy run config (and every legacy # checkpoint directory that locked one) is unchanged. The ladder's From 013a34ae2b79f40dcd7b676e6cd9bc7a215ac182 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mar=C3=ADa=20Juaristi?= <127882282+juaristi22@users.noreply.github.com> Date: Tue, 17 Nov 2026 12:21:30 +0000 Subject: [PATCH 28/31] Retire the two opt-in base equivalence tests a real build covers (us_base) This PR's test_the_gate_battery_shadow_agrees_and_changes_no_output and main's test_staged_build_completes_with_production_threading go. - Two of the shadow test's checks, today's verdict on every entry and every entry observed, are what each real build's shadow enforces: a finished build fails on any difference or unobserved entry. Its staged-children check is the same comparison on the staged path. Its fourth, that the shadow changes no output, matters only while the shadow runs; a static audit of the 125 gates the entries bind, reported in the PR description, found no gate that writes into its evidence or draws from the global random state. - The production-threading test checked that a staged build at production thread counts finishes with a valid dataset, which every real build shows. Its two helpers, which no other test used, go too. - Neither has run since #561 and #720 broke the shared fixture, which the bit-exact test still uses; fixing it is a change of its own. Max's review point 3, the shadow test's missing boundary directories, goes with the test. Co-Authored-By: Claude Opus 5.5 --- .../test_us_puf_support_base_equivalence.py | 152 ------------------ 1 file changed, 152 deletions(-) diff --git a/packages/microcosm-build/tests/engine_workflow/us/test_us_puf_support_base_equivalence.py b/packages/microcosm-build/tests/engine_workflow/us/test_us_puf_support_base_equivalence.py index 736c590faf..9cf9c0fa7d 100644 --- a/packages/microcosm-build/tests/engine_workflow/us/test_us_puf_support_base_equivalence.py +++ b/packages/microcosm-build/tests/engine_workflow/us/test_us_puf_support_base_equivalence.py @@ -23,11 +23,6 @@ PUF_TAX_DETAIL_DEFAULT_PERSON_OUTPUTS, PUF_TAX_DETAIL_DEFAULT_TAX_UNIT_OUTPUTS, ) -from microcosm.build.us_runtime.gate_shadow import ( - GATE_BATTERY_SHADOW_DIRECTORY, - US_GATE_SHADOW_SWITCH, - shadow_file_paths, -) from microcosm.frame import Frame from test_support.paths import paths_for @@ -39,7 +34,6 @@ _WEEKS_SOURCE_ENV = "POPULACE_US_PUF_EQUIVALENCE_WEEKS_SOURCE" _MAX_HOUSEHOLDS_ENV = "POPULACE_US_PUF_EQUIVALENCE_MAX_HOUSEHOLDS" _MAX_PUF_TAX_UNITS_ENV = "POPULACE_US_PUF_EQUIVALENCE_MAX_PUF_TAX_UNITS" -_PRODUCTION_THREAD_STRESS_ENV = "POPULACE_US_PUF_PRODUCTION_THREAD_STRESS" _DATASET_FILENAME = "base_populace_us_2024_puf_support.h5" _LOCKED_ENVIRONMENT = { "BLIS_NUM_THREADS": "1", @@ -134,122 +128,6 @@ def test_monolith_and_staged_builds_are_bit_exact_at_every_boundary( ) -@pytest.mark.slow -def test_the_gate_battery_shadow_agrees_and_changes_no_output(tmp_path: Path) -> None: - """microcosm#1585 item 11 (PR 2): the base's gates in shadow, on real gates. - - Three locked builds of one sample: single-process with the shadow, - single-process without it, and staged with it. On every entry the - battery reaches today's verdict; the shadow changes no byte of the - dataset; and the staged children's saved observations add up to the - single process's comparison. - """ - - fixture = _prepare_builder_fixture(tmp_path) - locked = {**os.environ, **_LOCKED_ENVIRONMENT} - # tests/conftest.py turns the tools' shadows off for every test. - shadowed = { - key: value for key, value in locked.items() if key != US_GATE_SHADOW_SWITCH - } - unshadowed = {**locked, US_GATE_SHADOW_SWITCH: "off"} - staged_checkpoints = tmp_path / "staged_checkpoints" - runs = { - "monolith": (tmp_path / "monolith", (), shadowed), - "unshadowed": (tmp_path / "unshadowed", (), unshadowed), - "staged": ( - tmp_path / "staged", - ("--checkpoint-dir", str(staged_checkpoints)), - shadowed, - ), - } - for out, extra, environment in runs.values(): - _run_builder( - [*fixture.common_command, "--out", str(out), *extra], - cwd=fixture.root, - environment=environment, - ) - - shadowed_h5 = runs["monolith"][0] / _DATASET_FILENAME - unshadowed_h5 = runs["unshadowed"][0] / _DATASET_FILENAME - assert shadowed_h5.read_bytes() == unshadowed_h5.read_bytes() - assert not (runs["unshadowed"][0] / GATE_BATTERY_SHADOW_DIRECTORY).exists() - verdicts = {} - for name in ("monolith", "staged"): - _, path = shadow_file_paths( - runs[name][0] / GATE_BATTERY_SHADOW_DIRECTORY, "us_base" - ) - payload = json.loads(path.read_text(encoding="utf-8")) - assert payload["run_completed"] is True, name - assert payload["verdict_difference"] is False, ( - name, - payload["differences"], - payload["shadow_errors"], - ) - assert payload["not_observed"] == [], name - verdicts[name] = { - row["id"]: ( - row["legacy"]["status"], - row["legacy"].get("failures"), - row["battery"]["status"], - row["battery"].get("failures"), - ) - for row in payload["entries"] - } - assert verdicts["monolith"] == verdicts["staged"] - - -@pytest.mark.slow -def test_staged_build_completes_with_production_threading(tmp_path: Path) -> None: - """Opt-in stress run: validate production-width execution, not equality.""" - - if os.environ.get(_PRODUCTION_THREAD_STRESS_ENV) != "1": - pytest.skip(f"set {_PRODUCTION_THREAD_STRESS_ENV}=1 to run the stress test") - fixture = _prepare_builder_fixture(tmp_path) - output_dir = tmp_path / "production_thread_output" - checkpoint_dir = tmp_path / "production_thread_checkpoints" - environment = os.environ.copy() - for variable in _LOCKED_ENVIRONMENT: - environment.pop(variable, None) - # Named stage children require a stable hash seed; numerical workers retain - # their normal production defaults because every thread-width override is - # deliberately absent. - environment["PYTHONHASHSEED"] = "0" - - _run_builder( - [ - *fixture.common_command, - "--out", - str(output_dir), - "--checkpoint-dir", - str(checkpoint_dir), - ], - cwd=fixture.root, - environment=environment, - ) - - runtime = StageRuntime(checkpoint_dir, fixture.builder.OUTER_STAGE_PIPELINE) - assert runtime.context.completed == fixture.builder.PIPELINE_STEPS - for stage in fixture.builder.PIPELINE_STEPS: - loaded = runtime.load(stage) - assert loaded.frame.entities == loaded.frame.schema.entities - for entity in loaded.frame.entities: - table = loaded.frame.table(entity) - assert len(table) > 0 - assert table[loaded.frame.schema.entity_id_column(entity)].is_unique - for entity in loaded.frame.weighted_entities: - weights = loaded.frame.weights_for(entity) - assert len(weights.values) == len(loaded.frame.table(entity)) - assert np.isfinite(weights.values).all() - assert (weights.values >= 0).all() - assert (weights.values > 0).any() - _assert_complete_primary_qrf(checkpoint_dir / "primary_qrf") - _assert_valid_final_h5(output_dir / _DATASET_FILENAME) - _assert_successful_stage_profiles( - checkpoint_dir, - fixture.builder.PIPELINE_STEPS, - ) - - def _prepare_builder_fixture(tmp_path: Path) -> _BuilderFixture: """Resolve opt-in artifacts and construct one deterministic smoke command.""" @@ -662,36 +540,6 @@ def _assert_h5_attrs_identical( ) -def _assert_complete_primary_qrf(root: Path) -> None: - manifest = json.loads((root / "manifest.json").read_text()) - target_order = tuple(manifest["target_order"]) - assert target_order == ( - *PUF_TAX_DETAIL_DEFAULT_PERSON_OUTPUTS, - *PUF_TAX_DETAIL_DEFAULT_TAX_UNIT_OUTPUTS, - ) - for index, target in enumerate(target_order): - path = root / "targets" / _target_checkpoint_name(index, target) - with h5py.File(path, mode="r") as h5: - bits = np.asarray(h5["raw_draw_bits"]) - assert bits.dtype == np.dtype(" None: - assert path.is_file() - assert path.stat().st_size > 0 - with h5py.File(path, mode="r") as h5: - objects = _h5_object_kinds(h5) - datasets = [name for name, kind in objects.items() if kind == "dataset"] - assert datasets - for name in datasets: - dataset = h5[name] - assert isinstance(dataset, h5py.Dataset) - assert dataset.ndim == 1 - assert len(dataset) > 0 - - def _assert_successful_stage_profiles( checkpoint_dir: Path, outer_stages: tuple[str, ...], From 6996343809b21a3f5b53d60affdceaebe0aaab18 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mar=C3=ADa=20Juaristi?= <127882282+juaristi22@users.noreply.github.com> Date: Tue, 17 Nov 2026 19:44:44 +0000 Subject: [PATCH 29/31] Record a shadow difference instead of failing the build (us_*) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Vahid's point 1 on PolicyEngine/microcosm#1635, settled by MarĂ­a: until PR 3 makes the battery authoritative, today's gates decide, so the shadow never fails a build. - GateBatteryShadow.finish flags an unexplained difference, an unobserved entry or a shadow error in the comparison (verdict_difference) and prints a warning after both files are written, instead of raising GateBatteryShadowMismatchError, which goes. - A comparison it cannot write, or earlier files it cannot clear (when armed, or when a held shadow releases its files), is a warning or a shadow error, never an exception. - ACS local: a package stage whose scope cannot be rebuilt, or whose stage-start clearing fails, logs a warning and finishes. - Docstrings in the four tools, docs/gate-battery-contract.md and the changelog fragment say so. The tests that held the old failure now hold the record and the warning, and two new ones cover the file faults. Co-Authored-By: Claude Opus 5.5 --- .../1585-us-gate-battery-shadow.added.md | 2 +- docs/gate-battery-contract.md | 7 +- .../microcosm/build/us_runtime/gate_shadow.py | 128 +++++++++--------- .../us/test_us_acs_local_gate_shadow.py | 35 ++++- .../us/test_us_fiscal_refresh_gate_shadow.py | 30 ++-- .../engine_free/us/test_us_gate_shadow.py | 80 ++++++++--- .../us/test_us_multispine_pool_gate_shadow.py | 18 ++- .../test_us_puf_support_base_gate_shadow.py | 17 ++- tools/build_us_acs_local_release.py | 30 ++-- tools/build_us_fiscal_refresh_release.py | 19 +-- tools/build_us_multispine_pool.py | 5 +- 11 files changed, 230 insertions(+), 141 deletions(-) diff --git a/changelog.d/1585-us-gate-battery-shadow.added.md b/changelog.d/1585-us-gate-battery-shadow.added.md index b5757744f4..19d6519022 100644 --- a/changelog.d/1585-us-gate-battery-shadow.added.md +++ b/changelog.d/1585-us-gate-battery-shadow.added.md @@ -1 +1 @@ -The four US build tools (Route A's base, the multispine pool's stacked path, the national release and ACS local) declare their 143 gates in the new `us/gates.json`, one scope per tool, and run the shared gate battery in shadow beside today's gates: each gate's entry is evaluated on the same evidence, the verdicts are compared, the scope's battery report and the comparison are written beside the tool's outputs, and a finished run fails on a verdict difference. Today's raises, written files and manifest keys are unchanged (microcosm#1585 item 11). +The four US build tools (Route A's base, the multispine pool's stacked path, the national release and ACS local) declare their 143 gates in the new `us/gates.json`, one scope per tool, and run the shared gate battery in shadow beside today's gates: each gate's entry is evaluated on the same evidence, the verdicts are compared, and the scope's battery report and the comparison are written beside the tool's outputs. A verdict difference is flagged in the comparison and printed as a warning. It never fails the build, since today's gates decide until the battery becomes authoritative. Today's raises, exit codes, written files and manifest keys are unchanged (microcosm#1585 item 11). diff --git a/docs/gate-battery-contract.md b/docs/gate-battery-contract.md index 81373ebdc3..09061cc53f 100644 --- a/docs/gate-battery-contract.md +++ b/docs/gate-battery-contract.md @@ -341,9 +341,10 @@ gate an `--allow-*` flag waives today matches if it fails in both, a crash in today's code matches an `evaluation_error`, and a gate today's code did not evaluate matches `evidence_absent`. The shadow writes its scope's report and the comparison beside the tool's outputs (never inside a -release directory), never raises while the tool runs, and fails a finished -run on a verdict difference; today's own exception always propagates -unchanged. When today's code stops, the phase it stopped in is recorded +release directory), and never fails the build. A finished run flags a +verdict difference in the comparison (`verdict_difference`) and prints a +warning, because today's gates decide until the flip, and today's own +exception always propagates unchanged. When today's code stops, the phase it stopped in is recorded only if every entry there without an outcome is one today's code never reached. The run refuses a phase that marks unreached an entry it evaluated, but a scope rebuilt from stages run as separate processes diff --git a/packages/microcosm-build/src/microcosm/build/us_runtime/gate_shadow.py b/packages/microcosm-build/src/microcosm/build/us_runtime/gate_shadow.py index a2bcd4fee4..ebd3f52d54 100644 --- a/packages/microcosm-build/src/microcosm/build/us_runtime/gate_shadow.py +++ b/packages/microcosm-build/src/microcosm/build/us_runtime/gate_shadow.py @@ -8,16 +8,18 @@ :class:`~microcosm.build.gate_battery.GateBatteryRun` per tool scope, on the same evidence, then compares the two verdicts. -Today's code stays authoritative. Its raises, written files and manifest keys -do not change, and nothing here raises while the tool is still running: a -difference, or a fault in the shadow itself, is recorded and decided at the -end. When the tool finishes, the scope's battery report and the comparison -are written beside its outputs as shadow files. A verdict difference then -fails the run, so a build proves parity on its own inputs. When today's code -raises, the files are written with what the battery saw up to that point, and -today's exception propagates unchanged. The phase it stopped in is recorded -only when every entry there without an outcome is one today's code never -reached, here or in a process whose observations were loaded. +Today's code stays authoritative. Its raises, written files, manifest keys +and exit do not change, and the shadow never fails a build: a difference, or +a fault in the shadow itself, is recorded. When the tool finishes, the +scope's battery report and the comparison are written beside its outputs as +shadow files. A verdict difference is then flagged in the comparison +(``verdict_difference``) and printed as a warning, so each build records on +its own inputs whether the battery agrees, while today's gates go on +deciding until the flip (PR 3) makes the battery authoritative. When today's +code raises, the files are written with what the battery saw up to that +point, and today's exception propagates unchanged. The phase it stopped in +is recorded only when every entry there without an outcome is one today's +code never reached, here or in a process whose observations were loaded. The comparison follows the waiver proposal posted on microcosm#1609, which is still for Max and MarĂ­a to settle: @@ -34,9 +36,9 @@ this build (a stage that did not run, a gate a flag skips) matches a battery outcome of ``evidence_absent``. A gate whose threshold the build overrode with a command-line flag is evaluated by the battery at the declared value, -so a difference there is recorded as explained by the override and does not -fail the run: the spec cannot hold a per-run threshold, and that decision -belongs to the flip (PR 3), not to the shadow. +so a difference there is recorded as explained by the override and is not +flagged as a verdict difference: the spec cannot hold a per-run threshold, +and that decision belongs to the flip (PR 3), not to the shadow. Every real run arms its tool's shadow. The test suite sets :data:`US_GATE_SHADOW_SWITCH` to ``off`` for every test, because its tests @@ -79,7 +81,6 @@ "GATE_BATTERY_SHADOW_SCHEMA_VERSION", "US_GATE_SHADOW_SWITCH", "GateBatteryShadow", - "GateBatteryShadowMismatchError", "LegacyStatus", "LegacyVerdict", "active_gate_shadow", @@ -368,23 +369,19 @@ class _Observation: explained_by: tuple[str, ...] -class GateBatteryShadowMismatchError(RuntimeError): - """The battery's verdicts differ from today's on a finished run. +def _disagreement_warning(scope: str, differences: Sequence[str], path: Path) -> str: + """The warning a finished run prints when the battery disagrees. - Raised by :meth:`GateBatteryShadow.finish` only after both shadow files - are on disk, and only when today's code completed: when today's code - raised, its own exception is the one that propagates. + Printed only after both shadow files are on disk. Today's gates still + decide, so the build's exit is the one they gave. """ - def __init__(self, scope: str, differences: Sequence[str], path: Path) -> None: - self.scope = scope - self.differences = tuple(differences) - self.comparison_path = path - lines = "\n".join(f" - {line}" for line in self.differences) - super().__init__( - f"US gate battery shadow for scope {scope!r} disagrees with today's " - f"gates (comparison: {path}):\n{lines}" - ) + lines = "\n".join(f" - {line}" for line in differences) + return ( + f"warning: US gate battery shadow for scope {scope!r} disagrees with " + f"today's gates (comparison: {path}). Today's gates still decide, so " + f"the build's exit is unchanged:\n{lines}" + ) def _sha256_file(path: Path) -> str | None: @@ -414,7 +411,7 @@ class GateBatteryShadow: No observation raises: an unknown entry, a context that cannot be built, or any other fault in the shadow is recorded as a shadow error, which - fails the run at :meth:`finish` like a verdict difference. The battery is + :meth:`finish` flags and reports like a verdict difference. The battery is run with the record-without-enforce posture (``release_candidate`` false, never ``enforce``), so every phase the tool reaches is recorded and the shadow report is never shippable: it is evidence, not an authority. @@ -498,9 +495,16 @@ def __init__( def _clear_stale_files(self) -> None: # A rerun into the same output directory must not leave an earlier # attempt's shadow files looking like this run's when it stops before - # writing its own. - for stale in (self._run.report_path, self._comparison_path): - stale.unlink(missing_ok=True) + # writing its own. Never raises, so arming the shadow cannot stop a + # build: a fault is recorded as a shadow error. + try: + for stale in (self._run.report_path, self._comparison_path): + stale.unlink(missing_ok=True) + except Exception as exc: # noqa: BLE001 - the shadow never fails a build + self._shadow_errors.append( + f"shadow could not clear an earlier run's files: " + f"{type(exc).__name__}: {exc}" + ) def release_files(self) -> None: """Let a shadow built with ``hold_files`` clear and write its files. @@ -512,13 +516,7 @@ def release_files(self) -> None: if not self._files_held: return self._files_held = False - try: - self._clear_stale_files() - except Exception as exc: # noqa: BLE001 - the shadow never stops the tool - self._shadow_errors.append( - f"shadow could not clear an earlier run's files: " - f"{type(exc).__name__}: {exc}" - ) + self._clear_stale_files() # -- properties --------------------------------------------------------- @@ -688,7 +686,8 @@ def failures( def record_error(self, entry_id: str, message: str) -> None: """Record a fault in the shadow's own wiring for ``entry_id``. - It fails a finished run like a verdict difference; it never raises. + A finished run flags and reports it like a verdict difference; it + never raises. """ with self._lock: @@ -840,8 +839,8 @@ def note_missing_observations(self, source: str) -> None: """Note that a process which may have reached this scope's entries left no observations here, such as a stage that ran and saved none. - It does not fail a finished run by itself: an entry that process - observed is then unobserved, which does. A stopped run cannot tell + It is not a difference by itself: an entry that process observed is + then unobserved, which a finished run flags. A stopped run cannot tell that process's entries from the ones never reached, so it leaves the phase it stopped in unrecorded. Never raises. """ @@ -926,20 +925,23 @@ def finish( stopped_by: BaseException | None = None, stopped_at: str | None = None, ) -> dict[str, object]: - """Record the phases, write both shadow files, then decide. - - A finished run (``stopped_by`` and ``stopped_at`` both ``None``) must - have observed every entry of its scope; it raises - :class:`GateBatteryShadowMismatchError` on any unexplained difference, - unobserved entry or shadow error, after the files are written. A run - today's code stopped early (``stopped_by``: its exception) or that - stops on purpose before its last phase (``stopped_at``: why, as the - release's dry run does) records the phases it completed, plus the - phase it stopped in when a battery outcome there blocks, and never - raises: the tool's own exit stands. That phase names unreached the - entries without an outcome, so it is recorded only when today's code - reached none of them and no observations are missing; otherwise it - stays unrecorded rather than mark a gate that ran as never reached. + """Record the phases, write both shadow files, and report. + + It never fails the tool: today's gates decide until the flip, so the + tool's own exit stands whatever the battery found. A finished run + (``stopped_by`` and ``stopped_at`` both ``None``) must have observed + every entry of its scope. An unexplained difference, an unobserved + entry or a shadow error is flagged in the comparison + (``verdict_difference``) and printed as a warning after the files are + written. A run today's code stopped early (``stopped_by``: its + exception) or that stops on purpose before its last phase + (``stopped_at``: why, as the release's dry run does) records the + phases it completed, plus the phase it stopped in when a battery + outcome there blocks. That phase names unreached the entries without + an outcome, so it is recorded only when today's code reached none of + them and no observations are missing; otherwise it stays unrecorded + rather than mark a gate that ran as never reached. A shadow file that + cannot be written is a warning too. Returns: The comparison payload written to disk, or an empty mapping when a @@ -1007,12 +1009,9 @@ def _finish( ) try: _atomic_write_json(self._comparison_path, payload) - except Exception as exc: - if completed: - raise - # Today's own exception (or deliberate stop) is the one that - # propagates; a shadow file that cannot be written must not - # replace it. + except Exception as exc: # noqa: BLE001 - the shadow never fails a build + # A shadow file that cannot be written must neither fail the build + # nor replace today's own exception (or deliberate stop). print( f"warning: US gate battery shadow for scope {self._scope!r} " f"could not write {self._comparison_path}: " @@ -1022,8 +1021,9 @@ def _finish( return payload differences = self.differences() if completed and differences: - raise GateBatteryShadowMismatchError( - self._scope, differences, self._comparison_path + print( + _disagreement_warning(self._scope, differences, self._comparison_path), + file=sys.stderr, ) return payload diff --git a/packages/microcosm-build/tests/engine_free/us/test_us_acs_local_gate_shadow.py b/packages/microcosm-build/tests/engine_free/us/test_us_acs_local_gate_shadow.py index 60c1d82d47..b109c55ab4 100644 --- a/packages/microcosm-build/tests/engine_free/us/test_us_acs_local_gate_shadow.py +++ b/packages/microcosm-build/tests/engine_free/us/test_us_acs_local_gate_shadow.py @@ -18,7 +18,6 @@ from microcosm.build.us_runtime.gate_scopes import us_scoped_gate_manifest from microcosm.build.us_runtime.gate_shadow import ( US_GATE_SHADOW_SWITCH, - GateBatteryShadowMismatchError, current_gate_shadow, shadow_file_paths, shadow_not_run, @@ -216,8 +215,8 @@ def test_a_stage_that_saved_nothing_is_never_named_unreached( assert payload["blocked_at_phase"] is None -def test_a_difference_fails_the_finished_package_stage( - tmp_path, monkeypatch, acs +def test_a_difference_is_recorded_without_failing_the_package_stage( + tmp_path, monkeypatch, acs, capsys ) -> None: args = _args(tmp_path) stand_in_gates(monkeypatch, "us_local", acs, failing={"local_hours_signal"}) @@ -230,5 +229,31 @@ def test_a_difference_fails_the_finished_package_stage( } # Earlier stages record and go on, whatever they saw. _run_stage(acs, args, "finalize", legacy=legacy) - with pytest.raises(GateBatteryShadowMismatchError, match="us_local_hours"): - _run_stage(acs, args, "package", legacy=legacy) + # Today's gates still decide: the package stage finishes. + _run_stage(acs, args, "package", legacy=legacy) + payload = _comparison(args) + assert payload["run_completed"] is True + assert payload["verdict_difference"] is True + differing = [row["id"] for row in payload["differences"]] + assert differing and all(entry.startswith("us_local_hours") for entry in differing) + assert "scope 'us_local' disagrees with today's gates" in capsys.readouterr().err + + +def test_a_package_stage_finishes_when_its_shadow_files_fail( + tmp_path, monkeypatch, acs, capsys +) -> None: + # The shadow never stops a stage: here the package stage's observation + # files can be neither cleared at its start, saved, nor read back. + args = _args(tmp_path) + stand_in_gates(monkeypatch, "us_local", acs) + for stage in ("materialize", "calibrate", "qa", "finalize"): + _run_stage(acs, args, stage) + + def unreachable(args, stage): + raise OSError("observations unreachable") + + monkeypatch.setattr(acs, "_local_stage_observations", unreachable) + _run_stage(acs, args, "package") + out = capsys.readouterr().out + assert "gate battery shadow could not clear earlier files" in out + assert "gate battery shadow could not be rebuilt" in out diff --git a/packages/microcosm-build/tests/engine_free/us/test_us_fiscal_refresh_gate_shadow.py b/packages/microcosm-build/tests/engine_free/us/test_us_fiscal_refresh_gate_shadow.py index da64967450..81500ebc0d 100644 --- a/packages/microcosm-build/tests/engine_free/us/test_us_fiscal_refresh_gate_shadow.py +++ b/packages/microcosm-build/tests/engine_free/us/test_us_fiscal_refresh_gate_shadow.py @@ -28,7 +28,6 @@ from microcosm.build.us_runtime.gate_shadow import ( GATE_BATTERY_SHADOW_DIRECTORY, US_GATE_SHADOW_SWITCH, - GateBatteryShadowMismatchError, LegacyVerdict, current_gate_shadow, shadow_file_paths, @@ -184,7 +183,9 @@ def test_each_release_keeps_its_own_shadow_files(tmp_path, release) -> None: assert evidence == shared / release.US_EVIDENCE_RELEASE_ID -def test_a_verdict_difference_fails_a_finished_build(tmp_path, monkeypatch, release): +def test_a_verdict_difference_is_recorded_without_failing_a_finished_build( + tmp_path, monkeypatch, release, capsys +): args = _args(tmp_path) _stand_in_gates(monkeypatch, release, failing={"pregnancy_signal"}) passing = GateResult(name="pregnancy_signal", passed=True) @@ -197,8 +198,13 @@ def build(argv): return None monkeypatch.setattr(release, "_main", build) - with pytest.raises(GateBatteryShadowMismatchError, match="us_national_pregnancy"): - release.main([]) + # Today's gates still decide: main returns as the build left it. + release.main([]) + payload = _comparison(release._national_gate_shadow_directory(args)) + assert payload["run_completed"] is True + assert payload["verdict_difference"] is True + assert [row["id"] for row in payload["differences"]] == ["us_national_pregnancy"] + assert "scope 'us_national' disagrees with today's gates" in capsys.readouterr().err class _Recorder: @@ -232,9 +238,9 @@ def test_a_finished_builds_staging_run_keeps_the_outcome_it_recorded( tmp_path, monkeypatch, release, difference ): # Review of #1635: _main completes a finished build's staging run, and - # with it the emitter, before main finishes the shadow. A difference - # raised there fails the program's exit alone: neither record is - # rewritten, and each records one outcome. + # with it the emitter, before main finishes the shadow. A difference is + # then recorded without changing the exit: neither record is rewritten, + # and each records one outcome. args = _args(tmp_path) _stand_in_gates( monkeypatch, release, failing={"pregnancy_signal"} if difference else () @@ -257,13 +263,9 @@ def build(argv): return None monkeypatch.setattr(release, "_main", build) - if difference: - with pytest.raises( - GateBatteryShadowMismatchError, match="us_national_pregnancy" - ): - release.main([]) - else: - release.main([]) + release.main([]) + payload = _comparison(release._national_gate_shadow_directory(args)) + assert payload["verdict_difference"] is difference assert progress.calls == [("complete", None)] assert emitter.calls == [("complete", None)] diff --git a/packages/microcosm-build/tests/engine_free/us/test_us_gate_shadow.py b/packages/microcosm-build/tests/engine_free/us/test_us_gate_shadow.py index 4ab146752f..395d773ca1 100644 --- a/packages/microcosm-build/tests/engine_free/us/test_us_gate_shadow.py +++ b/packages/microcosm-build/tests/engine_free/us/test_us_gate_shadow.py @@ -32,7 +32,6 @@ from microcosm.build.us_runtime.gate_shadow import ( US_GATE_SHADOW_SWITCH, GateBatteryShadow, - GateBatteryShadowMismatchError, LegacyStatus, LegacyVerdict, compare_verdicts, @@ -367,7 +366,9 @@ def todays_gate(): assert report["gates"]["us_test_alpha"]["status"] == "unreached" -def test_a_difference_fails_the_finished_run_after_both_files(tmp_path) -> None: +def test_a_difference_is_flagged_and_reported_without_failing_the_run( + tmp_path, capsys +) -> None: gates = _two_phase_gates() shadow = _shadow(tmp_path, gates) # Today's code passes at a looser cap than the spec declares. @@ -386,16 +387,21 @@ def test_a_difference_fails_the_finished_run_after_both_files(tmp_path) -> None: lambda: ALPHA(0.5), EvidenceContext(artifacts={"alpha_value": 0.5}), ) - with pytest.raises(GateBatteryShadowMismatchError, match="us_test_alpha") as raised: - shadow.finish() - assert raised.value.comparison_path.is_file() - payload = json.loads(raised.value.comparison_path.read_text()) + # Today's gates still decide, so the shadow returns instead of raising. + returned = shadow.finish() + assert returned["verdict_difference"] is True + payload = json.loads(shadow.comparison_path.read_text()) assert payload["verdict_difference"] is True assert [row["id"] for row in payload["differences"]] == ["us_test_alpha"] assert shadow.report_path.is_file() + warning = capsys.readouterr().err + assert "scope 'us_test' disagrees with today's gates" in warning + assert str(shadow.comparison_path) in warning + assert "the build's exit is unchanged" in warning + assert " - [us_test_alpha] " in warning -def test_a_runtime_override_explains_its_difference(tmp_path) -> None: +def test_a_runtime_override_explains_its_difference(tmp_path, capsys) -> None: gates = _two_phase_gates() overrides = legacy_parameter_overrides( {"us_test_alpha": {"cap": 1.0}}, {"us_test_alpha": {"cap": 2.0}} @@ -420,9 +426,47 @@ def test_a_runtime_override_explains_its_difference(tmp_path) -> None: payload = shadow.finish() assert payload["verdict_difference"] is False assert [row["id"] for row in payload["explained_differences"]] == ["us_test_alpha"] + # An explained difference is not one the shadow warns about. + assert "disagrees with today's gates" not in capsys.readouterr().err + + +def test_shadow_files_it_cannot_clear_or_write_only_warn(tmp_path, capsys) -> None: + # Neither arming the shadow nor finishing it may fail the build: here the + # comparison's directory is a file, so it can be neither cleared nor + # written, even on a finished run. + blocker = tmp_path / "blocked" + blocker.write_text("a file where the shadow's directory would go\n") + report, _ = shadow_file_paths(tmp_path, "us_test") + shadow = GateBatteryShadow( + _two_phase_gates(), + scope="us_test", + release_id="us-test-build", + report_path=report, + comparison_path=blocker / "us_test.gate_battery_shadow_comparison.json", + registry=_registry(), + ) + shadow.gate( + "us_test_alpha", + lambda: ALPHA(0.5), + EvidenceContext(artifacts={"alpha_value": 0.5}), + ) + shadow.gate( + "us_test_beta", + lambda: BETA(0.5), + EvidenceContext(artifacts={"beta_value": 0.5}), + ) + shadow.gate( + "us_test_final", + lambda: ALPHA(0.5), + EvidenceContext(artifacts={"alpha_value": 0.5}), + ) + payload = shadow.finish() + assert payload["run_completed"] is True + assert any("could not clear" in line for line in payload["shadow_errors"]) + assert "could not write" in capsys.readouterr().err -def test_an_unwired_entry_fails_a_finished_run(tmp_path) -> None: +def test_an_unwired_entry_is_flagged_on_a_finished_run(tmp_path) -> None: gates = _two_phase_gates() shadow = _shadow(tmp_path, gates) shadow.gate( @@ -435,8 +479,7 @@ def test_an_unwired_entry_fails_a_finished_run(tmp_path) -> None: lambda: BETA(0.5), EvidenceContext(artifacts={"beta_value": 0.5}), ) - with pytest.raises(GateBatteryShadowMismatchError, match="us_test_final"): - shadow.finish() + assert shadow.finish()["verdict_difference"] is True payload = json.loads(shadow.comparison_path.read_text()) assert payload["not_observed"] == ["us_test_final"] assert payload["phases_recorded"] == ["assembled"] @@ -447,7 +490,7 @@ def test_an_unwired_entry_fails_a_finished_run(tmp_path) -> None: def test_a_finished_run_names_the_stage_that_saved_no_observations(tmp_path) -> None: # As when a pre-merge checkpoint or a stage run with the switch off # resumes: the entry may have run in that stage, so the site is not - # blamed. The unobserved entry still fails the finished run. + # blamed. The unobserved entry is still flagged on the finished run. shadow = _shadow(tmp_path, _two_phase_gates()) shadow.note_missing_observations("the finalize stage saved no observations") shadow.gate( @@ -460,8 +503,7 @@ def test_a_finished_run_names_the_stage_that_saved_no_observations(tmp_path) -> lambda: BETA(0.5), EvidenceContext(artifacts={"beta_value": 0.5}), ) - with pytest.raises(GateBatteryShadowMismatchError, match="us_test_final"): - shadow.finish() + assert shadow.finish()["verdict_difference"] is True payload = json.loads(shadow.comparison_path.read_text()) assert payload["not_observed"] == ["us_test_final"] assert payload["shadow_errors"] == [ @@ -739,8 +781,7 @@ def test_a_gate_reached_twice_keeps_the_outcome_the_run_produced(tmp_path) -> No lambda: ALPHA(0.1), EvidenceContext(artifacts={"alpha_value": 0.1}), ) - with pytest.raises(GateBatteryShadowMismatchError, match="more than once"): - shadow.finish() + assert shadow.finish()["verdict_difference"] is True payload = json.loads(shadow.comparison_path.read_text()) assert payload["phases_recorded"] == ["assembled", "terminal"] (error,) = payload["shadow_errors"] @@ -755,7 +796,7 @@ def test_the_run_refuses_a_second_evaluation_and_the_shadow_records_it( # The run's own refusal (#1609) backs the shadow up: an entry the run # evaluated outside the shadow (a wiring fault) is not evaluated again # when its site is reached. The shadow records the refusal, never raises, - # and does not retry, so the entry stays unobserved and fails the run. + # and does not retry, so the entry stays unobserved and is flagged. shadow = _shadow(tmp_path, _two_phase_gates()) shadow.run.evaluate_entries( ("us_test_alpha",), EvidenceContext(artifacts={"alpha_value": 0.5}) @@ -776,8 +817,7 @@ def test_the_run_refuses_a_second_evaluation_and_the_shadow_records_it( lambda: ALPHA(0.1), EvidenceContext(artifacts={"alpha_value": 0.1}), ) - with pytest.raises(GateBatteryShadowMismatchError): - shadow.finish() + assert shadow.finish()["verdict_difference"] is True payload = json.loads(shadow.comparison_path.read_text()) assert payload["phases_recorded"] == [] assert payload["not_observed"] == ["us_test_alpha"] @@ -823,8 +863,8 @@ def broken_context(): assert any("us_undeclared" in line for line in differences) assert any("cannot build evidence" in line for line in differences) assert any("more than once" in line for line in differences) - with pytest.raises(GateBatteryShadowMismatchError): - shadow.finish() + # Nor at the end: the differences are flagged, and finish returns. + assert shadow.finish()["verdict_difference"] is True def test_a_gate_today_did_not_run_must_be_evidence_absent(tmp_path) -> None: diff --git a/packages/microcosm-build/tests/engine_free/us/test_us_multispine_pool_gate_shadow.py b/packages/microcosm-build/tests/engine_free/us/test_us_multispine_pool_gate_shadow.py index 78b683e59d..7e5261421a 100644 --- a/packages/microcosm-build/tests/engine_free/us/test_us_multispine_pool_gate_shadow.py +++ b/packages/microcosm-build/tests/engine_free/us/test_us_multispine_pool_gate_shadow.py @@ -19,7 +19,6 @@ from microcosm.build.us_runtime.battery_bindings import us_gate_specs from microcosm.build.us_runtime.gate_shadow import ( US_GATE_SHADOW_SWITCH, - GateBatteryShadowMismatchError, current_gate_shadow, shadow_file_paths, shadow_gate, @@ -132,15 +131,22 @@ def test_with_the_switch_off_the_stacked_path_has_no_shadow( assert not pool._pool_gate_shadow_directory(args).exists() -def test_a_terminal_difference_fails_the_build_after_its_files( - tmp_path, monkeypatch, pool +def test_a_terminal_difference_is_recorded_without_failing_the_build( + tmp_path, monkeypatch, pool, capsys ) -> None: args = SimpleNamespace(out=tmp_path / "stacked.h5") _stand_in_gates(monkeypatch, pool, failing={"by_origin_battery"}) passing = GateResult(name="us_by_origin_battery", passed=True) - with pytest.raises(GateBatteryShadowMismatchError, match="us_pool_by_origin"): - with pool._armed_pool_gate_shadow(args): - _cold_legacy_rule_run(pool, legacy_terminal=lambda: passing) + # Today's gates still decide: the build returns today's exit. + with pool._armed_pool_gate_shadow(args): + assert _cold_legacy_rule_run(pool, legacy_terminal=lambda: passing) == 0 + _, comparison = shadow_file_paths(pool._pool_gate_shadow_directory(args), "us_pool") + payload = json.loads(comparison.read_text()) + assert payload["verdict_difference"] is True + assert [row["id"] for row in payload["differences"]] == [ + "us_pool_by_origin_battery" + ] + assert "scope 'us_pool' disagrees with today's gates" in capsys.readouterr().err def test_a_marked_terminal_failure_is_a_match(tmp_path, monkeypatch, pool) -> None: diff --git a/packages/microcosm-build/tests/engine_free/us/test_us_puf_support_base_gate_shadow.py b/packages/microcosm-build/tests/engine_free/us/test_us_puf_support_base_gate_shadow.py index 04204916da..1a9ea7a9e2 100644 --- a/packages/microcosm-build/tests/engine_free/us/test_us_puf_support_base_gate_shadow.py +++ b/packages/microcosm-build/tests/engine_free/us/test_us_puf_support_base_gate_shadow.py @@ -20,7 +20,6 @@ from microcosm.build.us_runtime.gate_shadow import ( GATE_BATTERY_SHADOW_DIRECTORY, US_GATE_SHADOW_SWITCH, - GateBatteryShadowMismatchError, active_gate_shadow, current_gate_shadow, shadow_file_paths, @@ -136,7 +135,9 @@ def test_with_the_switch_off_no_shadow_is_armed_or_written(tmp_path, monkeypatch assert not (tmp_path / "checkpoints" / GATE_BATTERY_SHADOW_DIRECTORY).exists() -def test_a_verdict_difference_fails_the_single_process_run(tmp_path, monkeypatch, base): +def test_a_verdict_difference_is_recorded_without_failing_the_single_process_run( + tmp_path, monkeypatch, base, capsys +): args = _args(tmp_path, checkpoint_dir=None) # The battery's gate fails where today's verdict passed. _stand_in_gates(monkeypatch, base, failing={"pregnancy_signal"}) @@ -158,8 +159,16 @@ def legacy_passes(entry_id, evaluate, frame): monkeypatch.setattr(base, "_shadow_frame_gate", legacy_passes) monkeypatch.setattr(base, "_run_all", run_all) - with pytest.raises(GateBatteryShadowMismatchError, match="us_base_pregnancy"): - base._dispatch(args, None) + # Today's gates still decide: the run returns, with the difference on record. + base._dispatch(args, None) + _, comparison = shadow_file_paths( + args.out.resolve() / GATE_BATTERY_SHADOW_DIRECTORY, "us_base" + ) + payload = json.loads(comparison.read_text()) + assert payload["run_completed"] is True + assert payload["verdict_difference"] is True + assert [row["id"] for row in payload["differences"]] == ["us_base_pregnancy"] + assert "scope 'us_base' disagrees with today's gates" in capsys.readouterr().err def test_todays_raise_propagates_and_the_shadow_says_where(tmp_path, monkeypatch, base): diff --git a/tools/build_us_acs_local_release.py b/tools/build_us_acs_local_release.py index f24af5ecbb..a92d124e92 100644 --- a/tools/build_us_acs_local_release.py +++ b/tools/build_us_acs_local_release.py @@ -7375,9 +7375,10 @@ def _local_gate_shadow(args, directory: Path) -> GateBatteryShadow: def _finish_local_gate_scope(args, *, stage: str, stopped_by=None) -> None: """Rebuild the scope's shadow files from every stage saved so far. - Only a package stage that finished decides: a verdict difference then - fails the run. A stage today's code stopped, or one a later process - follows, records and goes on. + Only a package stage that finished is a finished run, whose differences + are flagged and printed. A stage today's code stopped, or one a later + process follows, records and goes on. None of this fails a stage: + today's gates decide until the flip. """ try: @@ -7397,8 +7398,6 @@ def _finish_local_gate_scope(args, *, stage: str, stopped_by=None) -> None: f"the {name} stage saved no observations" ) except Exception as error: # noqa: BLE001 - the shadow never stops a stage - if stopped_by is None and stage == "package": - raise log(f"WARNING: gate battery shadow could not be rebuilt: {error}") return if stopped_by is not None: @@ -7423,15 +7422,18 @@ def _local_gate_shadow_stage(args, stage: str): if not tool_gate_shadows_enabled(): yield None return - for name in _LOCAL_GATE_SHADOW_STAGES[_LOCAL_GATE_SHADOW_STAGES.index(stage) :]: - _local_stage_observations(args, name).unlink(missing_ok=True) - # The scope's report and comparison were built from observations just - # discarded, so they go too: a stage that never reaches its end, killed - # before it rebuilds them, must not leave an earlier run's verdict. - for stale in shadow_file_paths( - _local_gate_shadow_directory(args), US_LOCAL_GATE_SCOPE - ): - stale.unlink(missing_ok=True) + try: + for name in _LOCAL_GATE_SHADOW_STAGES[_LOCAL_GATE_SHADOW_STAGES.index(stage) :]: + _local_stage_observations(args, name).unlink(missing_ok=True) + # The scope's report and comparison were built from observations just + # discarded, so they go too: a stage that never reaches its end, killed + # before it rebuilds them, must not leave an earlier run's verdict. + for stale in shadow_file_paths( + _local_gate_shadow_directory(args), US_LOCAL_GATE_SCOPE + ): + stale.unlink(missing_ok=True) + except Exception as error: # noqa: BLE001 - the shadow never stops a stage + log(f"WARNING: gate battery shadow could not clear earlier files: {error}") shadow = _local_gate_shadow(args, _local_gate_shadow_directory(args) / stage) def save() -> None: diff --git a/tools/build_us_fiscal_refresh_release.py b/tools/build_us_fiscal_refresh_release.py index b5bc6e562b..aad13fd49c 100644 --- a/tools/build_us_fiscal_refresh_release.py +++ b/tools/build_us_fiscal_refresh_release.py @@ -13341,7 +13341,8 @@ def _finish_national_gate_shadow( stopped_by: BaseException | None = None, stopped_at: str | None = None, ) -> None: - """Finish the armed shadow, if any; only a finished build can fail it.""" + """Finish the armed shadow, if any. It never fails the build: a finished + build's differences are recorded and printed.""" global _ACTIVE_GATE_SHADOW shadow, _ACTIVE_GATE_SHADOW = _ACTIVE_GATE_SHADOW, None @@ -13412,10 +13413,11 @@ def main(argv: Sequence[str] | None = None) -> None: AT-RISK only, 0 clean. The gate battery's shadow (microcosm#1585 item 11) finishes after the - build's own handler. By then a finished build's telemetry has completed - its staging run and its emitter, which closes on that outcome, so a - verdict difference that the shadow raises fails the program's exit - alone: both records stay as the build left them. + build's own handler, and never changes the program's exit: today's gates + decide until the flip, so a verdict difference is recorded in the + shadow's comparison file and printed as a warning. By then a finished + build's telemetry has completed its staging run and its emitter, which + closes on that outcome. """ global _ACTIVE_DRY_RUN @@ -13457,9 +13459,10 @@ def main(argv: Sequence[str] | None = None) -> None: ) ) except BaseException as error: - # A finished release's telemetry has closed the emitter by now (see - # the docstring), so this records an outcome only on an emitter that - # something left open. + # Only a fault in the wiring reaches here: the shadow reports a + # difference without raising. A finished release's telemetry has + # closed the emitter by now (see the docstring), so this records an + # outcome only on an emitter that something left open. if _ACTIVE_EMITTER is not None and _ACTIVE_EMITTER.available: _ACTIVE_EMITTER.fail(error) raise diff --git a/tools/build_us_multispine_pool.py b/tools/build_us_multispine_pool.py index ca75412894..2c6f05d488 100644 --- a/tools/build_us_multispine_pool.py +++ b/tools/build_us_multispine_pool.py @@ -7035,8 +7035,9 @@ def _armed_pool_gate_shadow( """Arm the stacked path's shadow; finish it when the build returns. It finishes after every file today's build writes, its Logbook row - included, so a verdict difference fails the run without changing them. - With the switch off (the test suite) the build runs without one. + included, and records a verdict difference without failing the run or + changing them. With the switch off (the test suite) the build runs + without one. """ if not tool_gate_shadows_enabled(): From e8a8d1fa25a944289ad29622cada4e08fca2db60 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mar=C3=ADa=20Juaristi?= <127882282+juaristi22@users.noreply.github.com> Date: Tue, 17 Nov 2026 19:44:44 +0000 Subject: [PATCH 30/31] Answer Max's round 2 on the US gate battery shadow (us_local, us_national) From Max's review of 013a34ae2 (PolicyEngine/microcosm#1635): - Point 9: four us_local entries compared against module constants they did not declare. us_local_immigration now pins the non-citizen share band and the undocumented anchor band, as the national entry does, and the three us_local_self_employment_identity_* entries pin the identity tolerance that the tool's refusal helper calls the gate at. - A read of every other spec's gate found five more, now pinned: the Medicaid enrollment tolerance the ACS SSI/Medicaid receipt re-grades at (both entries), ACS take-up's Head Start share factors and the donor share band, the SSI take-up prior epsilon (both national entries), and the release gate's improvement cap for critical targets. Tables graded item by item stay undeclared, as the description lists. - District ESS: report-only, the gate passes an entry it cannot evaluate (no per-district ESS at a weight, or different districts at the two) and keeps the reason as a failure line. The binding kept that line, so GateResult refused a passing result and the shadow recorded a difference. The binding now reads district_ess_collapse_failures whether the entry passes or fails, as today's verdict does; it is the only spec with failure_lines. The us_local and us_national scopes' pinned digests move. Point 6 corrects the description. Co-Authored-By: Claude Opus 5.5 --- .../src/microcosm/build/us/gates.json | 42 +++++++++--- .../build/us_runtime/battery_bindings.py | 62 ++++++++++++------ .../us/test_us_battery_bindings.py | 64 ++++++++++++++++--- 3 files changed, 133 insertions(+), 35 deletions(-) diff --git a/packages/microcosm-build/src/microcosm/build/us/gates.json b/packages/microcosm-build/src/microcosm/build/us/gates.json index c57bef3382..dbe3f346ed 100644 --- a/packages/microcosm-build/src/microcosm/build/us/gates.json +++ b/packages/microcosm-build/src/microcosm/build/us/gates.json @@ -1785,7 +1785,8 @@ "phase": "assembled", "criticality": "release_blocking", "parameters": { - "check": "ssi_take_up" + "check": "ssi_take_up", + "prior_epsilon": 1e-09 }, "notes": "US national release (tools/build_us_fiscal_refresh_release.py): the SSI take-up stage's diagnostics against the registry's band targets. Raises at once today." }, @@ -2051,7 +2052,8 @@ "phase": "terminal", "criticality": "release_blocking", "parameters": { - "check": "ssi_take_up" + "check": "ssi_take_up", + "prior_epsilon": 1e-09 }, "notes": "US national release (tools/build_us_fiscal_refresh_release.py): the SSI take-up law on the export frame. Joins the terminal batch, which raises before the H5 write." }, @@ -2136,7 +2138,8 @@ "phase": "terminal", "criticality": "release_blocking", "parameters": { - "check": "release_gate_failures" + "check": "release_gate_failures", + "us_critical_target_improvement_max_abs_relative_error": 0.25 }, "notes": "US national release (tools/build_us_fiscal_refresh_release.py): the calibration's own gates (critical target fits, the SOI Table 1.4 fit, finite and falling loss) with the pre-solve gates they re-read; build_manifest gates.calibration records them. Joins the terminal batch, which raises before the H5 write." }, @@ -2241,7 +2244,8 @@ "phase": "assembled", "criticality": "release_blocking", "parameters": { - "check": "self_employment_identity" + "check": "self_employment_identity", + "acs_self_employment_identity_tolerance": 1.0 }, "notes": "US ACS local release (tools/build_us_acs_local_release.py): the ACS self-employment leaves add to SEMP on the staging frame. Its refusal exits at once." }, @@ -2254,7 +2258,8 @@ "check": "ssi_medicaid_take_up_signal", "residual_relative_tolerance": 1e-09, "saturated_relative_tolerance": 1e-06, - "acs_local_ssi_band_relative_tolerance": 0.05 + "acs_local_ssi_band_relative_tolerance": 0.05, + "us_medicaid_enrollment_tolerance": 0.02 }, "notes": "US ACS local release (tools/build_us_acs_local_release.py): ACS SSI and Medicaid take-up after materialize assigns them; the verdict is recorded in run_identity.json. Exits at once on failure." }, @@ -2274,7 +2279,8 @@ "phase": "assembled", "criticality": "release_blocking", "parameters": { - "check": "self_employment_identity" + "check": "self_employment_identity", + "acs_self_employment_identity_tolerance": 1.0 }, "notes": "US ACS local release (tools/build_us_acs_local_release.py): the self-employment identity again, when calibrate writes the calibrated artifact. Its refusal exits at once." }, @@ -2356,6 +2362,14 @@ "discretionary_share_factors": [ 0.5, 1.5 + ], + "head_start_share_factors": [ + 0.5, + 1.5 + ], + "eligible_take_up_share_band": [ + 0.005, + 0.25 ] }, "notes": "US ACS local release (tools/build_us_acs_local_release.py): SNAP and TANF take-up on both spines. Finalize collects it into gate_summary.json, writes the file, then raises on a hard failure." @@ -2366,7 +2380,15 @@ "phase": "terminal", "criticality": "release_blocking", "parameters": { - "check": "immigration_signal" + "check": "immigration_signal", + "non_citizen_share_band": [ + 0.03, + 0.12 + ], + "undocumented_anchor_relative_band": [ + 0.5, + 1.6 + ] }, "notes": "US ACS local release (tools/build_us_acs_local_release.py): immigration labels and entry clocks. Finalize collects it into gate_summary.json, writes the file, then raises on a hard failure." }, @@ -2417,7 +2439,8 @@ "check": "ssi_medicaid_take_up_signal", "residual_relative_tolerance": 1e-09, "saturated_relative_tolerance": 1e-06, - "acs_local_ssi_band_relative_tolerance": 0.05 + "acs_local_ssi_band_relative_tolerance": 0.05, + "us_medicaid_enrollment_tolerance": 0.02 }, "notes": "US ACS local release (tools/build_us_acs_local_release.py): ACS SSI and Medicaid take-up on the calibrated bytes. Finalize collects it into gate_summary.json, writes the file, then raises on a hard failure." }, @@ -2503,7 +2526,8 @@ "phase": "terminal", "criticality": "release_blocking", "parameters": { - "check": "self_employment_identity" + "check": "self_employment_identity", + "acs_self_employment_identity_tolerance": 1.0 }, "notes": "US ACS local release (tools/build_us_acs_local_release.py): the self-employment identity on the packaged bytes. Package re-grades the bytes it packages and raises at once." }, diff --git a/packages/microcosm-build/src/microcosm/build/us_runtime/battery_bindings.py b/packages/microcosm-build/src/microcosm/build/us_runtime/battery_bindings.py index 8d893f3508..1ce949326f 100644 --- a/packages/microcosm-build/src/microcosm/build/us_runtime/battery_bindings.py +++ b/packages/microcosm-build/src/microcosm/build/us_runtime/battery_bindings.py @@ -171,9 +171,11 @@ class USGateSpec: build that passes another value is a runtime override, which the shadow records and explains. failure_lines: For a ``mapping`` gate, the reference of the function - that gives a failing mapping's lines, as today's verdict reads - them, for a gate whose failing mapping may carry none (the - district ESS gate fails a blocking collapse on its counts). + that gives the mapping's failure lines, passing or failing, as + today's verdict reads them, for a gate whose own ``failures`` do + not match its verdict. The district ESS gate fails a blocking + collapse on its counts with no line, and passes a report-only + entry it cannot evaluate with one. """ check: str @@ -457,8 +459,8 @@ def _verdict_of( """The gate's return value as its result, by :attr:`USGateSpec.returns`. ``failure_lines`` is the resolved :attr:`USGateSpec.failure_lines`: a - failing mapping's lines come from it, since a result that fails must - name why. + mapping's lines come from it whether it passes or fails, since a result + that fails must name why and one that passes must name nothing. """ name = spec.legacy_name @@ -473,7 +475,7 @@ def _verdict_of( passed = bool(value.get("passed")) failures = _lines( failure_lines(value) - if failure_lines is not None and not passed + if failure_lines is not None else value.get("failures") or (), spec.check, ) @@ -1149,6 +1151,8 @@ def _us_national_specs() -> tuple[USGateSpec, ...]: gate="tool:us_ssi_take_up_gate", positional=("ssi_take_up_diagnostics",), arguments={"targets": "ssi_band_targets"}, + # The slack on each band's documented prior. + pinned=_pins("ssi_take_up", "_PRIOR_EPSILON"), ), USGateSpec( check="health_input_signal", @@ -1256,6 +1260,9 @@ def _us_national_specs() -> tuple[USGateSpec, ...]: "target_registry", ) }, + # The cap on a critical target that improves on the incumbent. Each + # target's own tolerance sits in the critical-target register. + pinned=_tool_pins("US_CRITICAL_TARGET_IMPROVEMENT_MAX_ABS_RELATIVE_ERROR"), returns="failures", ), USGateSpec( @@ -1351,6 +1358,8 @@ def _us_local_specs() -> tuple[USGateSpec, ...]: legacy_name="acs_self_employment_identity", gate="tool:_require_acs_self_employment_identity", positional=(FRAME,), + # The tool calls the gate at its default tolerance. + pinned=_pins("acs_inputs", "ACS_SELF_EMPLOYMENT_IDENTITY_TOLERANCE"), refusals=refuses, returns="receipt", ), @@ -1360,12 +1369,16 @@ def _us_local_specs() -> tuple[USGateSpec, ...]: gate="tool:acs_local_ssi_medicaid_take_up_signal_gate", positional=(FRAME,), arguments={"receipt": "ssi_medicaid_receipt"}, - pinned=_pins( - "acs_local_ssi_medicaid_take_up", - "_RESIDUAL_RELATIVE_TOLERANCE", - "_SATURATED_RELATIVE_TOLERANCE", - "ACS_LOCAL_SSI_BAND_RELATIVE_TOLERANCE", - ), + pinned={ + **_pins( + "acs_local_ssi_medicaid_take_up", + "_RESIDUAL_RELATIVE_TOLERANCE", + "_SATURATED_RELATIVE_TOLERANCE", + "ACS_LOCAL_SSI_BAND_RELATIVE_TOLERANCE", + ), + # The receipt's Medicaid re-grade runs at the gate's default. + **_pins("medicaid_take_up", "US_MEDICAID_ENROLLMENT_TOLERANCE"), + }, ), # The calibrated artifact's gates at finalize, and package's re-checks. USGateSpec( @@ -1404,18 +1417,31 @@ def _us_local_specs() -> tuple[USGateSpec, ...]: legacy_name="acs_local_take_up_signal", gate="tool:acs_local_take_up_signal_gate", positional=(FRAME,), - pinned=_pins( - "acs_local_take_up", - "_MEDICARE_AGED_SHARE_FLOOR", - "_SHARE_BANDS", - "_DISCRETIONARY_SHARE_FACTORS", - ), + pinned={ + **_pins( + "acs_local_take_up", + "_MEDICARE_AGED_SHARE_FLOOR", + "_SHARE_BANDS", + "_DISCRETIONARY_SHARE_FACTORS", + ), + # Head Start: the ACS share's factors around the donor's, and + # the donor share's own band, as the national entry pins it. + **_pins("acs_local_vehicles_head_start", "_HEAD_START_SHARE_FACTORS"), + **_pins("sipp_head_start", "_ELIGIBLE_TAKE_UP_SHARE_BAND"), + }, ), USGateSpec( check="immigration_signal", legacy_name="acs_local_immigration_signal", gate="tool:acs_local_immigration_signal_gate", positional=(FRAME,), + # The ACS spine's non-citizen band, and the whole file's + # composition gate, as the national entry pins them. + pinned=_pins( + "immigration", + "_NON_CITIZEN_SHARE_BAND", + "_UNDOCUMENTED_ANCHOR_RELATIVE_BAND", + ), ), USGateSpec( check="work_disability_signal", diff --git a/packages/microcosm-build/tests/engine_free/us/test_us_battery_bindings.py b/packages/microcosm-build/tests/engine_free/us/test_us_battery_bindings.py index fcbcedf884..5041866acd 100644 --- a/packages/microcosm-build/tests/engine_free/us/test_us_battery_bindings.py +++ b/packages/microcosm-build/tests/engine_free/us/test_us_battery_bindings.py @@ -79,27 +79,29 @@ ), }, "us_national": { + # Moved by the SSI take-up and release-gate entries that pin the + # thresholds they compare against (review of #1635, round 2). "gates_manifest_sha256": ( - "db5578411c6a3a17ede8a28e85bfa641590016580e51307f1bd3da3b8fe4b7cd" + "356b3387360ca77862c6684d4267710601eb96c5e29986615f58eb7346aca71c" ), "policy_sha256": ( - "fa4a2eb355e35271e2bc79be903649f333cd5ed62c899d359029db0ac5387ac6" + "8be8670ce4f58b10c34d58b994645885b0d8758a4996c4f77797ddfbb698d8bb" ), "spec_fingerprint": ( - "898315b5b0fd8cd782c4238d5003008a5237bcac1e205c45676b089252b4a9b0" + "5226397586571f99f94526636a05e7bd4cb91fc9e7ab50c6e3dbe0a2f0952782" ), }, "us_local": { - # Moved by the five entries that pin the thresholds they compare - # against (review of #1635). + # Moved by the entries that pin the thresholds they compare against + # (review of #1635, rounds 1 and 2). "gates_manifest_sha256": ( - "3356e3f69213870398f2920dbc08b983c994551e61d45175c22ef9efef9c53f8" + "50d2d77198074ae355655c4717e3bd108e71b73c518521b8285c53ade37c6adb" ), "policy_sha256": ( - "cb3471437b10de6b4e5c67818007edb5b647c77c25aa055bd26ce50203f9ff88" + "8c0a58ddee2fd707ba2e45d285c197b689c11723281e7f925965ff33d65ace21" ), "spec_fingerprint": ( - "28c7f82d14bce4a63c82b20cfbaee5f7caf225c893633e34f91f3855f0344b15" + "7ac8b2657c007f178afde6c23782c6934b98d120d3ed4f53f68d1ad4e9a88906" ), }, } @@ -489,6 +491,52 @@ def test_a_blocking_district_collapse_fails_both_verdicts_on_one_line( assert shadow.differences() == () +@pytest.mark.parametrize( + "origin", + [ + pytest.param({}, id="no-per-district-ess"), + pytest.param( + { + "design": {"effective_sample_size_by_district": {"0601": 100.0}}, + "calibrated": {"effective_sample_size_by_district": {"0602": 60.0}}, + }, + id="different-districts", + ), + ], +) +def test_a_report_only_district_entry_it_cannot_evaluate_passes_both_verdicts( + tmp_path, origin +) -> None: + # Report-only, the district ESS gate passes an entry it cannot evaluate + # and keeps the reason as a failure line. A result that passes must name + # nothing, so the binding reads district_ess_collapse_failures, which + # gives no line for a passing entry, as today's verdict does; before, + # the binding kept the entry's line and GateResult refused it, which the + # shadow recorded as a difference (review of #1635). + tool = vars(load_us_gate_tool("us_local")) + shadow = _shadow(tmp_path, "us_local") + with active_gate_shadow(shadow): + entry = shadow_value( + "us_local_district_ess_collapse", + lambda: tool["district_ess_collapse_gate"]( + origin, relative_floor=0.25, absolute_floor=15.0, blocking=False + ), + EvidenceContext( + artifacts={"weight_origin": origin, "district_ess_blocking": False} + ), + verdict=tool["_legacy_district_ess_verdict"], + ) + # Today's entry is written as before: passing, with its reason. + assert entry["passed"] is True and entry["criteria_met"] is None + assert len(entry["failures"]) == 1 + outcome = shadow.outcome("us_local_district_ess_collapse") + assert outcome is not None and outcome.status is GateStatus.PASSED + assert outcome.result.failures == () + assert tool["_legacy_district_ess_verdict"](entry).failures == () + # Differences include the shadow's own errors, such as a refused result. + assert shadow.differences() == () + + def test_only_a_mapping_gate_takes_a_failure_line_maker() -> None: (spec,) = [ spec From 455d466e99540b50eea8543f0d788ce015d51191 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mar=C3=ADa=20Juaristi?= <127882282+juaristi22@users.noreply.github.com> Date: Wed, 18 Nov 2026 03:14:27 +0000 Subject: [PATCH 31/31] Print shadow differences when the comparison can't be written (us_*) Max's round 3 on #1635: - finish prints a finished run's differences after a comparison write fault, and the warning says the comparison could not be written, since the warning is then their only record; - us/gates.json's policy line says the shadow records a verdict difference with a warning, rather than failing the run. The line is part of every scope's manifest digest, so the four scopes' gates_manifest_sha256 and spec_fingerprint pins move; no policy_sha256 moves; - the contract doc says the shadow never fails a build once armed, and three comments no longer say a shadow fails the run or that arming it can't stop a build. Co-Authored-By: Claude Opus 5.5 --- docs/gate-battery-contract.md | 5 +- .../src/microcosm/build/us/gates.json | 2 +- .../microcosm/build/us_runtime/gate_shadow.py | 33 ++++++++---- packages/microcosm-build/tests/conftest.py | 4 +- .../us/test_us_battery_bindings.py | 20 ++++---- .../engine_free/us/test_us_gate_shadow.py | 50 +++++++++++++++++-- 6 files changed, 88 insertions(+), 26 deletions(-) diff --git a/docs/gate-battery-contract.md b/docs/gate-battery-contract.md index 09061cc53f..63f0188745 100644 --- a/docs/gate-battery-contract.md +++ b/docs/gate-battery-contract.md @@ -341,10 +341,11 @@ gate an `--allow-*` flag waives today matches if it fails in both, a crash in today's code matches an `evaluation_error`, and a gate today's code did not evaluate matches `evidence_absent`. The shadow writes its scope's report and the comparison beside the tool's outputs (never inside a -release directory), and never fails the build. A finished run flags a +release directory), and, once armed, never fails the build. A finished run flags a verdict difference in the comparison (`verdict_difference`) and prints a warning, because today's gates decide until the flip, and today's own -exception always propagates unchanged. When today's code stops, the phase it stopped in is recorded +exception always propagates unchanged. If the comparison cannot be +written, the warning says so and still lists the differences. When today's code stops, the phase it stopped in is recorded only if every entry there without an outcome is one today's code never reached. The run refuses a phase that marks unreached an entry it evaluated, but a scope rebuilt from stages run as separate processes diff --git a/packages/microcosm-build/src/microcosm/build/us/gates.json b/packages/microcosm-build/src/microcosm/build/us/gates.json index dbe3f346ed..14c7b4d1fa 100644 --- a/packages/microcosm-build/src/microcosm/build/us/gates.json +++ b/packages/microcosm-build/src/microcosm/build/us/gates.json @@ -1,7 +1,7 @@ { "version": 1, "country": "us", - "policy": "US gates declared as data for the shared battery (microcosm#1585 item 11, microcosm#611), one scope per build tool. PR 2 of 4 runs them in shadow: each US tool still gates as it did, evaluates the declared entry beside each gate on the same evidence, and fails the run on a verdict difference. A threshold the gate reads from a module constant is declared at today's value and pinned equal to that constant until the flip makes this file the only source; one the gate takes as a keyword is routed from here. Waivers stay the tools' --allow-* flags, which the shadow records by entry id. Gate names and phases are the shared vocabulary's, pending Max's Step 0 answer.", + "policy": "US gates declared as data for the shared battery (microcosm#1585 item 11, microcosm#611), one scope per build tool. PR 2 of 4 runs them in shadow: each US tool still gates as it did, evaluates the declared entry beside each gate on the same evidence, and records a verdict difference in its comparison file with a warning, while today's gates still decide the run's exit. A threshold the gate reads from a module constant is declared at today's value and pinned equal to that constant until the flip makes this file the only source; one the gate takes as a keyword is routed from here. Waivers stay the tools' --allow-* flags, which the shadow records by entry id. Gate names and phases are the shared vocabulary's, pending Max's Step 0 answer.", "phases": [ "preflight", "assembled", diff --git a/packages/microcosm-build/src/microcosm/build/us_runtime/gate_shadow.py b/packages/microcosm-build/src/microcosm/build/us_runtime/gate_shadow.py index ebd3f52d54..d44d7382cb 100644 --- a/packages/microcosm-build/src/microcosm/build/us_runtime/gate_shadow.py +++ b/packages/microcosm-build/src/microcosm/build/us_runtime/gate_shadow.py @@ -369,17 +369,26 @@ class _Observation: explained_by: tuple[str, ...] -def _disagreement_warning(scope: str, differences: Sequence[str], path: Path) -> str: +def _disagreement_warning( + scope: str, differences: Sequence[str], path: Path, *, written: bool = True +) -> str: """The warning a finished run prints when the battery disagrees. - Printed only after both shadow files are on disk. Today's gates still - decide, so the build's exit is the one they gave. + Printed once the shadow has tried to write its files. When the comparison + could not be written, the warning says so and is the only record of the + differences. Today's gates still decide, so the build's exit is the one + they gave. """ lines = "\n".join(f" - {line}" for line in differences) + where = ( + f"comparison: {path}" + if written + else f"its comparison could not be written to {path}" + ) return ( f"warning: US gate battery shadow for scope {scope!r} disagrees with " - f"today's gates (comparison: {path}). Today's gates still decide, so " + f"today's gates ({where}). Today's gates still decide, so " f"the build's exit is unchanged:\n{lines}" ) @@ -495,7 +504,7 @@ def __init__( def _clear_stale_files(self) -> None: # A rerun into the same output directory must not leave an earlier # attempt's shadow files looking like this run's when it stops before - # writing its own. Never raises, so arming the shadow cannot stop a + # writing its own. Never raises, so clearing them cannot stop a # build: a fault is recorded as a shadow error. try: for stale in (self._run.report_path, self._comparison_path): @@ -941,7 +950,8 @@ def finish( an outcome, so it is recorded only when today's code reached none of them and no observations are missing; otherwise it stays unrecorded rather than mark a gate that ran as never reached. A shadow file that - cannot be written is a warning too. + cannot be written is a warning too, and a finished run's differences + are printed all the same, since the warning is then their only record. Returns: The comparison payload written to disk, or an empty mapping when a @@ -1007,22 +1017,27 @@ def _finish( stopped_by=stopped_by, stopped_at=stopped_at, ) + written = True try: _atomic_write_json(self._comparison_path, payload) except Exception as exc: # noqa: BLE001 - the shadow never fails a build # A shadow file that cannot be written must neither fail the build - # nor replace today's own exception (or deliberate stop). + # nor replace today's own exception (or deliberate stop). The + # differences are still printed below: without the file, the + # warning is their only record. + written = False print( f"warning: US gate battery shadow for scope {self._scope!r} " f"could not write {self._comparison_path}: " f"{type(exc).__name__}: {exc}", file=sys.stderr, ) - return payload differences = self.differences() if completed and differences: print( - _disagreement_warning(self._scope, differences, self._comparison_path), + _disagreement_warning( + self._scope, differences, self._comparison_path, written=written + ), file=sys.stderr, ) return payload diff --git a/packages/microcosm-build/tests/conftest.py b/packages/microcosm-build/tests/conftest.py index ade63de493..22f7fa849e 100644 --- a/packages/microcosm-build/tests/conftest.py +++ b/packages/microcosm-build/tests/conftest.py @@ -220,8 +220,8 @@ def allow_logbook_network( # The US build tools evaluate their gates through the shared gate battery in -# shadow (microcosm#1585 item 11). A finished shadow fails the run on any -# entry it did not observe, and the tests here stand stubs in for whole +# shadow (microcosm#1585 item 11). A finished shadow flags and warns about +# any entry it did not observe, and the tests here stand stubs in for whole # stages, whose gate sites a stub skips; so every test runs the tools with # their shadows off. The shadow's own tests turn them back on with # ``arm_us_tool_gate_shadows`` (test_support.microcosm_build.us_gate_shadow). diff --git a/packages/microcosm-build/tests/engine_free/us/test_us_battery_bindings.py b/packages/microcosm-build/tests/engine_free/us/test_us_battery_bindings.py index 5041866acd..53123ca617 100644 --- a/packages/microcosm-build/tests/engine_free/us/test_us_battery_bindings.py +++ b/packages/microcosm-build/tests/engine_free/us/test_us_battery_bindings.py @@ -54,54 +54,56 @@ WIRED_SCOPES = ("us_base", "us_pool", "us_national", "us_local") #: Each scope's pinned digests. They move only when the scope's entries, -#: parameters, phases or the manifest's policy line do. +#: parameters, phases or the manifest's policy line do. The policy line's +#: shadow sentence moved every scope's manifest digest and fingerprint +#: (review of #1635, round 3). SCOPE_PINS: dict[str, dict[str, str]] = { "us_base": { "gates_manifest_sha256": ( - "b919d3a37e9aeadd507568a30c274d325a84b32c8706e1407dc9ac1626fef5ce" + "edaac2f8318d1abb694d6e88f31e236fb13b5cce74ca8067947541d3a3509463" ), "policy_sha256": ( "1a86c63cc20a6259c3349cc9dd831f0571d8c7e82e1ba77f06e4c4a102274e22" ), "spec_fingerprint": ( - "4ce5ca7abaef48a6026be8d120862761cf8a457904690b0e59e4a501828f43da" + "66cf423d4cf2e9685d2cb58aca3e4a3b8dfad4327a25d9889c0426230957b1b4" ), }, "us_pool": { "gates_manifest_sha256": ( - "31dfdd5dc38129e08979e3a47822b3c61891b489b9140b40ec80dc6aba791355" + "f5e76c30e9f958690777777f2f40dd48bfc4cb804fac62f1c81518006fc3006e" ), "policy_sha256": ( "98ff80d5bbe6f7a11f3ee3f63cae5f953fc6607559de22e2f552fe3e1f06d872" ), "spec_fingerprint": ( - "cc1eeadceb9ea05efe81b5594c23832dd05e9fedbdd25c3cb1cfc52355c12047" + "395968f4f14021d59ca902ecb2a3561da78c617231d12dd4966ae83ef1226215" ), }, "us_national": { # Moved by the SSI take-up and release-gate entries that pin the # thresholds they compare against (review of #1635, round 2). "gates_manifest_sha256": ( - "356b3387360ca77862c6684d4267710601eb96c5e29986615f58eb7346aca71c" + "7a1e5a37e6fb7db69f4872325c6a6beca31f1d6c843dbda55e22477f270742d2" ), "policy_sha256": ( "8be8670ce4f58b10c34d58b994645885b0d8758a4996c4f77797ddfbb698d8bb" ), "spec_fingerprint": ( - "5226397586571f99f94526636a05e7bd4cb91fc9e7ab50c6e3dbe0a2f0952782" + "49d32c78938e3968c0c50b00e55a917bd7bb5ab39e344da0b02f6d4689231ca5" ), }, "us_local": { # Moved by the entries that pin the thresholds they compare against # (review of #1635, rounds 1 and 2). "gates_manifest_sha256": ( - "50d2d77198074ae355655c4717e3bd108e71b73c518521b8285c53ade37c6adb" + "e436bc1fc2ce141270e49684e43e2546881ba93969f42e0ae7092857d509ed0f" ), "policy_sha256": ( "8c0a58ddee2fd707ba2e45d285c197b689c11723281e7f925965ff33d65ace21" ), "spec_fingerprint": ( - "7ac8b2657c007f178afde6c23782c6934b98d120d3ed4f53f68d1ad4e9a88906" + "6b329c7dd72713c127dcd917e62aaa875e6b87f2b072c76db3724e8dace0bc08" ), }, } diff --git a/packages/microcosm-build/tests/engine_free/us/test_us_gate_shadow.py b/packages/microcosm-build/tests/engine_free/us/test_us_gate_shadow.py index 395d773ca1..db6801d587 100644 --- a/packages/microcosm-build/tests/engine_free/us/test_us_gate_shadow.py +++ b/packages/microcosm-build/tests/engine_free/us/test_us_gate_shadow.py @@ -431,9 +431,9 @@ def test_a_runtime_override_explains_its_difference(tmp_path, capsys) -> None: def test_shadow_files_it_cannot_clear_or_write_only_warn(tmp_path, capsys) -> None: - # Neither arming the shadow nor finishing it may fail the build: here the - # comparison's directory is a file, so it can be neither cleared nor - # written, even on a finished run. + # Neither clearing the shadow's files nor writing them may fail the build: + # here the comparison's directory is a file, so it can be neither cleared + # nor written, even on a finished run. blocker = tmp_path / "blocked" blocker.write_text("a file where the shadow's directory would go\n") report, _ = shadow_file_paths(tmp_path, "us_test") @@ -466,6 +466,50 @@ def test_shadow_files_it_cannot_clear_or_write_only_warn(tmp_path, capsys) -> No assert "could not write" in capsys.readouterr().err +def test_a_difference_is_printed_when_the_comparison_cannot_be_written( + tmp_path, capsys +) -> None: + # With no comparison file, the warning is the only record of a difference, + # so a finished run prints it after the write fault. + blocker = tmp_path / "blocked" + blocker.write_text("a file where the shadow's directory would go\n") + report, _ = shadow_file_paths(tmp_path, "us_test") + comparison = blocker / "us_test.gate_battery_shadow_comparison.json" + shadow = GateBatteryShadow( + _two_phase_gates(), + scope="us_test", + release_id="us-test-build", + report_path=report, + comparison_path=comparison, + registry=_registry(), + ) + # Today's code passes at a looser cap than the spec declares. + shadow.gate( + "us_test_alpha", + lambda: ALPHA(1.5, cap=2.0), + EvidenceContext(artifacts={"alpha_value": 1.5}), + ) + shadow.gate( + "us_test_beta", + lambda: BETA(0.5), + EvidenceContext(artifacts={"beta_value": 0.5}), + ) + shadow.gate( + "us_test_final", + lambda: ALPHA(0.5), + EvidenceContext(artifacts={"alpha_value": 0.5}), + ) + payload = shadow.finish() + assert payload["verdict_difference"] is True + assert not comparison.exists() + err = capsys.readouterr().err + assert f"could not write {comparison}" in err + warning = err[err.index("scope 'us_test' disagrees with today's gates") :] + assert f"its comparison could not be written to {comparison}" in warning + assert "the build's exit is unchanged" in warning + assert " - [us_test_alpha] " in warning + + def test_an_unwired_entry_is_flagged_on_a_finished_run(tmp_path) -> None: gates = _two_phase_gates() shadow = _shadow(tmp_path, gates)