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..19d6519022 --- /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, 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/evidence/spec-engine/us-f0-coverage.json b/docs/evidence/spec-engine/us-f0-coverage.json index 348354e26c..eba12bf9cc 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": 32615, + "authored_normative_field_count": 32618, "claim_count": 48, "claims": [ { @@ -16,8 +16,8 @@ "legacy_sinks": [], "mode": "front_end_validation", "pointer_class": "all", - "pointer_count": 110, - "pointer_sha256": "368fe74c5a1ac00cc51079ffc1e13add27471d6daeaf2bf362cb321be9535619", + "pointer_count": 113, + "pointer_sha256": "11b70807bf06832e71367643c7d0e09891c1d4923fe574b471d6632562129897", "rationale": null, "relative_sink_prefix": null, "source_prefix": "/authored/country_package.json", @@ -758,20 +758,20 @@ "verifier": "vintages" } ], - "configuration_field_count": 42401, - "consumed_field_count": 42401, + "configuration_field_count": 42404, + "consumed_field_count": 42404, "generation0_effect_counts": { "legacy_behavior": 38780, - "no_generation0_effect": 3621 + "no_generation0_effect": 3624 }, "mode_counts": { "compiler_semantic": 27674, - "front_end_validation": 355, + "front_end_validation": 358, "identity_only": 103, "legacy_behavior": 14269 }, "multiple_primary_use_field_count": 0, - "pointer_inventory_sha256": "65c75e48867b39bc443891c2bada2fcc6eed80b2c1fa1bf5ced14ae862bad47f", + "pointer_inventory_sha256": "38fc67ba13d62a5c0eaff36abb8f04d4d2974e21baaed6d2966d76480e643608", "resolved_binding_field_count": 9786, "unused_field_count": 0 }, @@ -2585,7 +2585,7 @@ "country": "us", "schema_id": "country_spec", "schema_version": 1, - "spec_sha256": "372858d059a129d7b3bcbd7ac2dbdc314742345bd35aaff8d53943e737c98f84" + "spec_sha256": "0088d3f69666b09e28b94bbf8b1b2f07ebf0b8a32cec6d0a8358b568a7f35ac6" } }, "report_schema_version": 3, @@ -2595,7 +2595,7 @@ "country": "us", "schema_id": "country_spec", "schema_version": 1, - "spec_sha256": "372858d059a129d7b3bcbd7ac2dbdc314742345bd35aaff8d53943e737c98f84" + "spec_sha256": "0088d3f69666b09e28b94bbf8b1b2f07ebf0b8a32cec6d0a8358b568a7f35ac6" }, "status": "pass" } diff --git a/docs/gate-battery-contract.md b/docs/gate-battery-contract.md index 6f26501d48..63f0188745 100644 --- a/docs/gate-battery-contract.md +++ b/docs/gate-battery-contract.md @@ -326,7 +326,54 @@ 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), 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. 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 +(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. 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 +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 +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 a1dc6d0c22..d1c540fc7c 100644 --- a/docs/release-contract.md +++ b/docs/release-contract.md @@ -456,8 +456,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 @@ -1161,7 +1163,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 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 2546782666..d6a9e8751e 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 = 32615 +EXPECTED_AUTHORED_FIELD_COUNT = 32618 EXPECTED_RESOLVED_BINDING_FIELD_COUNT = 9786 -EXPECTED_CONFIGURATION_FIELD_COUNT = 42401 +EXPECTED_CONFIGURATION_FIELD_COUNT = 42404 class FieldUsageError(AssertionError): @@ -369,8 +369,8 @@ def _path_inventory(rows: Sequence[tuple[str, object]]) -> tuple[int, str]: "bdd9e79157590fade42d28cc2b5d5c8b58e13903af75375a0e3235c94d2a8339", ), "country_manifest": ( - 110, - "368fe74c5a1ac00cc51079ffc1e13add27471d6daeaf2bf362cb321be9535619", + 113, + "11b70807bf06832e71367643c7d0e09891c1d4923fe574b471d6632562129897", ), "generated_authorities": ( 8_614, 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 cffc573c90..855a488fe9 100644 --- a/packages/microcosm-build/src/microcosm/build/us/country_package.json +++ b/packages/microcosm-build/src/microcosm/build/us/country_package.json @@ -102,6 +102,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..14c7b4d1fa --- /dev/null +++ b/packages/microcosm-build/src/microcosm/build/us/gates.json @@ -0,0 +1,2545 @@ +{ + "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 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", + "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." + }, + { + "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." + }, + { + "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", + "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." + }, + { + "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", + "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." + }, + { + "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", + "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." + }, + { + "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." + }, + { + "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", + "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." + }, + { + "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, + "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." + }, + { + "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", + "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." + }, + { + "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, + "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 + ], + "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." + }, + { + "id": "us_local_immigration", + "gate": "stage_health", + "phase": "terminal", + "criticality": "release_blocking", + "parameters": { + "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." + }, + { + "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", + "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." + }, + { + "id": "us_local_ssi_disability", + "gate": "stage_health", + "phase": "terminal", + "criticality": "release_blocking", + "parameters": { + "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." + }, + { + "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, + "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." + }, + { + "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", + "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." + }, + { + "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 new file mode 100644 index 0000000000..1ce949326f --- /dev/null +++ b/packages/microcosm-build/src/microcosm/build/us_runtime/battery_bindings.py @@ -0,0 +1,1563 @@ +"""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", + "RETURNS", + "us_flag_overrides", + "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: 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. + failure_lines: For a ``mapping`` gate, the reference of the function + 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 + 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: 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: + 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 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.") + 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( + 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]: + 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 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.callables, *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 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}.") + 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) + 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, + 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 + + def evidence_payload( + self, context: EvidenceContext, parameters: Mapping[str, Any] + ) -> object | None: + 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, + *, + 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 + 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 + 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": + passed = bool(value.get("passed")) + failures = _lines( + failure_lines(value) + if failure_lines is not None + else value.get("failures") or (), + spec.check, + ) + details = {key: item for key, item in value.items() if key != "failures"} + return GateResult( + name=name, + passed=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], + *, + 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. +_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. +_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", + ), + ), + ) + + +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"}, + # The slack on each band's documented prior. + pinned=_pins("ssi_take_up", "_PRIOR_EPSILON"), + ), + 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", + ) + }, + # 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( + 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", + ), + ) + + +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,), + # The tool calls the gate at its default tolerance. + pinned=_pins("acs_inputs", "ACS_SELF_EMPLOYMENT_IDENTITY_TOLERANCE"), + 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", + "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( + 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", + "_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", + 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"}, + pinned=_pins("acs_local_income", "ACS_LOCAL_INCOME_REVIEW_BAND"), + ), + 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"}, + pinned=_pins( + "acs_local_ssi_disability", "ACS_LOCAL_SSI_DISABILITY_REVIEW_BAND" + ), + ), + 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", + # A blocking collapse records its counts but no failure line. + failure_lines="tool:district_ess_collapse_failures", + ), + 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, + } +) + + +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..d44d7382cb --- /dev/null +++ b/packages/microcosm-build/src/microcosm/build/us_runtime/gate_shadow.py @@ -0,0 +1,1356 @@ +"""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, 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: + +- 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 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 +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 + +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", + "US_GATE_SHADOW_SWITCH", + "GateBatteryShadow", + "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", + "tool_gate_shadows_enabled", +] + +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" +#: 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]: + """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, ...] + + +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 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 ({where}). Today's gates still decide, so " + f"the build's exit is unchanged:\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 + :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. + + 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": ...}``. + 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__( + 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, + hold_files: bool = False, + ) -> 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}." + ) + 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) + 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. 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): + 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. + + Never raises: a fault is recorded as a shadow error. + """ + + with self._lock: + if not self._files_held: + return + self._files_held = False + self._clear_stale_files() + + # -- 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: + # 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: + 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``. + + A finished run flags and reports it like a verdict difference; it + never raises. + """ + + 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. + + 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. 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: + 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, + "reached": sorted(self._reached), + "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; a file + not read whole also counts as missing observations (see + :meth:`note_missing_observations`). + """ + + 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.") + 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.") + 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}" + ) + 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 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. + """ + + 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." + ) + 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, 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, 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 + run stopped while its files were held, which writes nothing. + """ + + 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 + 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: + 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}" + ) + 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 " + f"entry; {cause}." + ) + payload = self._comparison_payload( + recorded=recorded, + not_observed=not_observed, + completed=completed, + 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). 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, + ) + differences = self.differences() + if completed and differences: + print( + _disagreement_warning( + self._scope, differences, self._comparison_path, written=written + ), + file=sys.stderr, + ) + return payload + + 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. + """ + + 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 + ] + 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 + if completed or not ran: + 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() + 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: + return + self._run.record_phase( + assemble_phase_report( + self._gates, + phase, + outcomes, + blocked_by=blockers[-1], + unreached=missing, + release_candidate=False, + ) + ) + recorded.append(phase) + return + + 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, + "observations_missing": list(self._observations_missing), + "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] = [] + + +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. + + 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_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], + 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/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/conftest.py b/packages/microcosm-build/tests/conftest.py index 8de2e3dc35..22f7fa849e 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 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). +# 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_contract/us/test_spec_engine_coverage_tool.py b/packages/microcosm-build/tests/engine_contract/us/test_spec_engine_coverage_tool.py index 394d432ee2..2b26ba1a10 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"] == 42401 - assert fields["authored_normative_field_count"] == 32615 + assert fields["configuration_field_count"] == 42404 + assert fields["authored_normative_field_count"] == 32618 assert fields["resolved_binding_field_count"] == 9786 - assert fields["consumed_field_count"] == 42401 + assert fields["consumed_field_count"] == 42404 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": 27674, - "front_end_validation": 355, + "front_end_validation": 358, "identity_only": 103, } assert fields["generation0_effect_counts"] == { "legacy_behavior": 38_780, - "no_generation0_effect": 3621, + "no_generation0_effect": 3624, } inventory = coverage_report["inventory_coverage"] 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"] 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 24e57f6d0d..6db563c643 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 == 42401 + assert len(field_ledger.fields) == EXPECTED_CONFIGURATION_FIELD_COUNT == 42404 assert field_ledger.source_counts == { - "authored": 32615, + "authored": 32618, "resolved_bindings": 9786, } assert field_ledger.mode_counts == { "legacy_behavior": 14_269, "compiler_semantic": 27674, - "front_end_validation": 355, + "front_end_validation": 358, "identity_only": 103, } assert field_ledger.generation0_effect_counts == { "legacy_behavior": 38_780, - "no_generation0_effect": 3621, + "no_generation0_effect": 3624, } - assert len({field.pointer for field in field_ledger.fields}) == 42401 + assert len({field.pointer for field in field_ledger.fields}) == 42404 def test_eligibility_concepts_are_validation_not_generation0_behavior( 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 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..b109c55ab4 --- /dev/null +++ b/packages/microcosm-build/tests/engine_free/us/test_us_acs_local_gate_shadow.py @@ -0,0 +1,259 @@ +"""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 ( + US_GATE_SHADOW_SWITCH, + 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": ( + "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_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: + 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_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: + # 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_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"}) + 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) + # 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_acs_local_release_tool.py b/packages/microcosm-build/tests/engine_free/us/test_us_acs_local_release_tool.py index 58428953c0..fd5998bdcf 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 @@ -1371,13 +1373,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: 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..53123ca617 --- /dev/null +++ b/packages/microcosm-build/tests/engine_free/us/test_us_battery_bindings.py @@ -0,0 +1,550 @@ +"""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 DEFAULT_REGISTRY, 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, + LegacyVerdict, + active_gate_shadow, + shadow_file_paths, + shadow_gate, + shadow_value, +) +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", "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. 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": ( + "edaac2f8318d1abb694d6e88f31e236fb13b5cce74ca8067947541d3a3509463" + ), + "policy_sha256": ( + "1a86c63cc20a6259c3349cc9dd831f0571d8c7e82e1ba77f06e4c4a102274e22" + ), + "spec_fingerprint": ( + "66cf423d4cf2e9685d2cb58aca3e4a3b8dfad4327a25d9889c0426230957b1b4" + ), + }, + "us_pool": { + "gates_manifest_sha256": ( + "f5e76c30e9f958690777777f2f40dd48bfc4cb804fac62f1c81518006fc3006e" + ), + "policy_sha256": ( + "98ff80d5bbe6f7a11f3ee3f63cae5f953fc6607559de22e2f552fe3e1f06d872" + ), + "spec_fingerprint": ( + "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": ( + "7a1e5a37e6fb7db69f4872325c6a6beca31f1d6c843dbda55e22477f270742d2" + ), + "policy_sha256": ( + "8be8670ce4f58b10c34d58b994645885b0d8758a4996c4f77797ddfbb698d8bb" + ), + "spec_fingerprint": ( + "49d32c78938e3968c0c50b00e55a917bd7bb5ab39e344da0b02f6d4689231ca5" + ), + }, + "us_local": { + # Moved by the entries that pin the thresholds they compare against + # (review of #1635, rounds 1 and 2). + "gates_manifest_sha256": ( + "e436bc1fc2ce141270e49684e43e2546881ba93969f42e0ae7092857d509ed0f" + ), + "policy_sha256": ( + "8c0a58ddee2fd707ba2e45d285c197b689c11723281e7f925965ff33d65ace21" + ), + "spec_fingerprint": ( + "6b329c7dd72713c127dcd917e62aaa875e6b87f2b072c76db3724e8dace0bc08" + ), + }, +} + +#: 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", + ], +} + + +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 + parsed = ( + binding.tool["_parse_args"](MINIMAL_ARGV[scope]) if spec.flags else None + ) + for key in spec.parameters: + 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) +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) + 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) + + +# --------------------------------------------------------------------------- +# 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.",) + + 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.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) + + def today(): + return target[gate_name]( + *( + evidence.frame if source == FRAME else evidence.artifacts[source] + for source in spec.positional + ), + ) + + # 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 expected: + with pytest.raises(expected): + shadow_value( + entry_id, + today, + evidence, + verdict=verdicts[spec.returns], + refusals=spec.refusals, + ) + else: + 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 + if fault == "fails": + assert outcome.result.failures == lines + else: + assert "evaluation_error" in outcome.result.details + assert shadow.differences() == () + + +@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)) + 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() == () + + +@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. + 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 + + +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() == () + + +@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 + 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_builder.py b/packages/microcosm-build/tests/engine_free/us/test_us_fiscal_refresh_builder.py index 29f437d2b5..67f902fee7 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 @@ -2826,21 +2827,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(" ) @@ -16040,7 +16052,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", 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..81500ebc0d --- /dev/null +++ b/packages/microcosm-build/tests/engine_free/us/test_us_fiscal_refresh_gate_shadow.py @@ -0,0 +1,494 @@ +"""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 ast +import importlib +import json +from pathlib import Path +from types import SimpleNamespace + +import pytest + +from microcosm.build import GateResult +from microcosm.build.gate_battery import EvidenceContext, GateStatus +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 ( + GATE_BATTERY_SHADOW_DIRECTORY, + US_GATE_SHADOW_SWITCH, + LegacyVerdict, + current_gate_shadow, + shadow_file_paths, + shadow_value, +) +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 +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(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_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) + + 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) + # 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: + """A stand-in staging run or emitter that records each outcome it is told. + + 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, 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, and + # 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 () + ) + passing = GateResult(name="pregnancy_signal", passed=True) + emitter = _Recorder() + progress = _Recorder(emitter) + 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) + 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)] + + +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) + emitter = _Recorder() + progress = _Recorder(emitter) + 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) + _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") + # 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(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) + 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( + 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 + + +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 new file mode 100644 index 0000000000..db6801d587 --- /dev/null +++ b/packages/microcosm-build/tests/engine_free/us/test_us_gate_shadow.py @@ -0,0 +1,1243 @@ +"""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 os + +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 ( + US_GATE_SHADOW_SWITCH, + GateBatteryShadow, + LegacyStatus, + LegacyVerdict, + compare_verdicts, + legacy_parameter_overrides, + shadow_file_paths, + tool_gate_shadows_enabled, +) + + +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_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. + 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}), + ) + # 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, capsys) -> 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"] + # 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 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") + 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_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) + 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}), + ) + 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"] + (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 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( + "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}), + ) + 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"] == [ + "[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: + 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", + } + # 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: + 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 _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_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}), + ) + 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"] + 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 is flagged. + 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}), + ) + 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"] + 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) + + 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) + # 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: + 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", + ), + ) + 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 _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" + 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"]}) + 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/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..7e5261421a --- /dev/null +++ b/packages/microcosm-build/tests/engine_free/us/test_us_multispine_pool_gate_shadow.py @@ -0,0 +1,166 @@ +"""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 ( + US_GATE_SHADOW_SWITCH, + current_gate_shadow, + shadow_file_paths, + shadow_gate, + shadow_not_run, +) +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 +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_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_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) + # 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: + # 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/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..1a9ea7a9e2 --- /dev/null +++ b/packages/microcosm-build/tests/engine_free/us/test_us_puf_support_base_gate_shadow.py @@ -0,0 +1,350 @@ +"""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, + US_GATE_SHADOW_SWITCH, + active_gate_shadow, + current_gate_shadow, + shadow_file_paths, + shadow_gate, +) +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 +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_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_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"}) + 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) + # 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): + 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") + ) + 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"] == [] + 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_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 + ) + 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/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 adb3f593b0..30a4710641 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", @@ -348,6 +353,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. @@ -3852,9 +3864,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, ( 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", 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 a22f1927d5..d95d4e964c 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 @@ -363,7 +363,8 @@ def capture_equality(expected: object, actual: object) -> None: # microcosm#1543's fit input checks in microcosm.fit.qrf move it again. # microcosm#1641 moves it again: docstring and comment wording in # solve and ssi_take_up, and the calibration contract's renamed modes. - "spec_sha256": "372858d059a129d7b3bcbd7ac2dbdc314742345bd35aaff8d53943e737c98f84", + # microcosm#1585's us/gates.json row in country_package.json moves it. + "spec_sha256": "0088d3f69666b09e28b94bbf8b1b2f07ebf0b8a32cec6d0a8358b568a7f35ac6", }, } 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..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 @@ -34,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", @@ -129,58 +128,6 @@ def test_monolith_and_staged_builds_are_bit_exact_at_every_boundary( ) -@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.""" @@ -593,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, ...], 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..078f8c0d85 --- /dev/null +++ b/test_support/microcosm_build/us_gate_shadow.py @@ -0,0 +1,263 @@ +"""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 + +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", + "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 = { + "us_pool": ("microcosm.build.us_runtime.multispine_pool",), +} + +_HELPERS = frozenset( + { + "shadow_gate", + "shadow_failures", + "shadow_check", + "shadow_not_run", + "shadow_value", + "_shadow_frame_gate", + "_observe_frame_gate", + "_shadow_tail_survival", + "_shadow_local_frame_gate", + "_shadow_local_refusal", + } +) + + +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 + + +# --------------------------------------------------------------------------- +# 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 291713023c..a92d124e92 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,24 @@ ) 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, + tool_gate_shadows_enabled, +) from microcosm.build.us_runtime.org_wages import ( US_ORG_OCCUPATION_AND_WORK_EXPERIENCE_OUTPUT_COLUMNS, require_us_occupation_and_work_experience_inputs, @@ -2077,7 +2096,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, @@ -2282,8 +2307,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. @@ -3389,8 +3423,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( @@ -4972,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.""" @@ -5605,11 +5678,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( @@ -5618,57 +5703,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() @@ -5681,8 +5846,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] = {} @@ -5952,11 +6122,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_district_ess_verdict, ) limitations = finalize_reviewed_limitations( @@ -6296,7 +6476,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( @@ -6411,8 +6596,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( @@ -6422,12 +6620,30 @@ 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, #1387: a checkpoint calibrated from pre-fix staging # stacks donor self-employment or partnership income 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: @@ -6446,12 +6662,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( @@ -7115,6 +7338,149 @@ 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 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: + # 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 + 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. 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 + 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: + 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_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`). + """ + + return LegacyVerdict.from_failures(district_ess_collapse_failures(entry)) + + def main(argv: list[str] | None = None) -> int: args = _parse_args(argv) with program_telemetry(pipeline=TELEMETRY_PIPELINE) as telemetry: @@ -7125,19 +7491,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) diff --git a/tools/build_us_fiscal_refresh_release.py b/tools/build_us_fiscal_refresh_release.py index 8e05283457..aad13fd49c 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,20 @@ 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, + tool_gate_shadows_enabled, +) from microcosm.build.us_runtime.h5_io import ( AuthenticatedPoolH5, assert_h5_unchanged, @@ -7945,17 +7966,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, + } + ), ) @@ -8654,11 +8694,21 @@ 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) - gate, surface = _qrf_tail_concentration_gate( - export_frame, - reviewed_exclusions=register, + register_loaded = True + 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 = { @@ -8681,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}" @@ -9391,8 +9450,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 @@ -13151,6 +13220,187 @@ 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: + """``/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. + """ + + 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 + / _release_for_build(args) + ) + + +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`). + + 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") + 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 + ) + 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), + 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, + stopped_at: str | None = None, +) -> None: + """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 + 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. @@ -13161,13 +13411,22 @@ 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, 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 _ACTIVE_DRY_RUN = None + _finish_national_gate_shadow(stopped_at="a previous run in this process") try: dry_run_exit = _main(argv) 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 @@ -13191,6 +13450,22 @@ 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: + # 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 if dry_run_exit is not None: if _ACTIVE_EMITTER is not None and _ACTIVE_EMITTER.available: if dry_run_exit == 0: @@ -13292,7 +13567,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( @@ -13384,7 +13663,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 " @@ -13553,6 +13836,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. @@ -13588,7 +13872,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: " @@ -13610,10 +13898,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( @@ -13716,7 +14016,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: " @@ -13737,9 +14041,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( @@ -13765,6 +14078,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) ) @@ -13807,10 +14121,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( @@ -13851,7 +14163,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( @@ -13887,6 +14203,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( @@ -13907,10 +14229,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: @@ -13921,8 +14243,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: @@ -13999,9 +14323,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: @@ -14021,7 +14352,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( @@ -14038,7 +14373,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( @@ -14055,7 +14394,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( @@ -14072,7 +14415,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( @@ -14089,7 +14436,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( @@ -14106,7 +14457,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( @@ -14123,7 +14478,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( @@ -14140,7 +14499,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( @@ -14157,7 +14520,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( @@ -14174,7 +14541,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( @@ -14198,7 +14569,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( @@ -14222,7 +14597,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( @@ -14239,7 +14618,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( @@ -14256,7 +14637,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( @@ -14273,7 +14658,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( @@ -14301,7 +14690,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( @@ -14329,7 +14722,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( @@ -14357,7 +14754,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( @@ -14384,7 +14783,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( @@ -14411,7 +14814,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( @@ -14439,7 +14846,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( @@ -14470,7 +14881,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( @@ -14498,7 +14913,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( @@ -14515,7 +14934,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( @@ -14538,7 +14961,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( @@ -14574,7 +15001,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 @@ -14609,7 +15040,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( @@ -14640,7 +15075,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( @@ -14668,7 +15107,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( @@ -14685,8 +15128,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 = ( @@ -14723,7 +15168,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( @@ -14750,8 +15199,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: @@ -14829,9 +15280,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: @@ -14874,7 +15331,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( @@ -14911,7 +15372,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( @@ -14960,8 +15425,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: @@ -15023,7 +15497,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( @@ -15055,6 +15533,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", @@ -15075,7 +15558,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( @@ -15111,7 +15598,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( @@ -15151,7 +15642,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( @@ -15192,7 +15687,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( @@ -15220,7 +15719,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( @@ -15252,7 +15755,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( @@ -15280,7 +15789,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( @@ -15311,7 +15826,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( @@ -15330,7 +15849,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( @@ -15402,9 +15925,18 @@ 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 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 @@ -15451,7 +15983,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 @@ -15775,6 +16309,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 @@ -15817,7 +16357,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, ) @@ -16007,8 +16549,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 @@ -16074,7 +16623,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 @@ -16087,8 +16640,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: @@ -16099,8 +16654,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: @@ -16121,7 +16678,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 @@ -16243,13 +16804,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, @@ -16270,24 +16844,61 @@ 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, + gate_failures = shadow_failures( + "us_national_release_gates", + # 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 { + "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() + }, + } + ), ) except Exception as error: # Degraded-mode guard (microcosm#547): the batch must still form and @@ -16422,8 +17033,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( @@ -16459,8 +17075,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( @@ -16516,8 +17140,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 @@ -16576,8 +17204,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: @@ -16662,6 +17294,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( @@ -16672,25 +17305,46 @@ 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, + 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 + # 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. 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}" @@ -16860,8 +17514,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) diff --git a/tools/build_us_multispine_pool.py b/tools/build_us_multispine_pool.py index 6a53ad1e3b..2c6f05d488 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,16 @@ 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, + tool_gate_shadows_enabled, +) from microcosm.build.us_runtime.h5_io import ( POPULACE_BLOCK_LADDER_SHA256_ATTR, POPULACE_BLOCK_LADDER_VINTAGES_ATTR, @@ -2485,10 +2498,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 +2630,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 +4928,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 +5130,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 +5289,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 +6753,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 +6787,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 +6997,55 @@ 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 | 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, 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(): + yield None + return + shadow = _pool_gate_shadow(args) + with shadow, active_gate_shadow(shadow): + yield shadow if __name__ == "__main__": diff --git a/tools/build_us_puf_support_base.py b/tools/build_us_puf_support_base.py index b244dd7e10..be756eafea 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,18 @@ 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, + tool_gate_shadows_enabled, +) from microcosm.build.us_runtime.h5_io import ( assert_h5_unchanged, refuse_denied_frame, @@ -895,9 +909,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 +924,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 +957,203 @@ 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) + # 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( + [ + 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, stages_run) + shadow.stop(error) + raise + if shadow is not None: + _load_stage_gate_shadows(shadow, args, stages_run) + 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``, 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) + 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: + 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 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. + """ + + if not tool_gate_shadows_enabled(): + yield lambda: None + return + 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, + stages_run: Sequence[str], +) -> None: + """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( + 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]: @@ -1156,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 @@ -1390,11 +1594,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 +1743,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 +1759,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 +1774,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 +1788,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 +1804,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 +1815,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 +1830,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 +1843,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 +1897,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 +1970,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 +2001,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 +2064,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 +2078,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 +2096,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 +2115,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 +2171,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 +2185,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 +2199,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 +2238,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 +2260,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 +2279,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 +2291,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 +2370,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 +2383,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 +2716,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 +2793,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 +3068,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 +3083,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 +3096,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 +3121,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 +3132,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 +3145,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 +3156,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 +3208,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 +3301,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 +3582,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 +3606,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 +3658,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 +3672,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 +3686,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 +3714,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 +3760,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 +3772,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 +3784,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 +3820,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 +3837,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 +3856,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 +3918,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 +3931,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 +4210,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 2fbc24d733..bb5fea9a9c 100644 --- a/tools/generate_us_bundle_from_constants.py +++ b/tools/generate_us_bundle_from_constants.py @@ -147,6 +147,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", diff --git a/tools/spec_engine_coverage.py b/tools/spec_engine_coverage.py index 4a7ea7b5e8..06ddab569f 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 = ( - "65c75e48867b39bc443891c2bada2fcc6eed80b2c1fa1bf5ced14ae862bad47f" + "38fc67ba13d62a5c0eaff36abb8f04d4d2974e21baaed6d2966d76480e643608" ) DEFAULT_REPORT_PATH = ( Path(__file__).resolve().parents[1]