diff --git a/README.md b/README.md index f83bc3cf26..fc993bfc39 100644 --- a/README.md +++ b/README.md @@ -482,7 +482,11 @@ for what each mode contains and where the build records it. Its `--l2-basis chi_square` and `--mass-parametrization softmax` options (defaults: the historical `record` and `projection`) penalize distance from the design weights; see [penalized calibration toward the design weights](docs/calibration-l2-basis.md) -for the algebra, the evidence and the measured frontier. +for the algebra, the evidence and the measured frontier. The chain needs a +donor release that carries `employer_sponsored_insurance_premiums`: its +staging build transfers the column onto the ACS spine, and finalize grades it +on the calibrated artifact with both ESI premium gates. See +[ACS local releases](docs/us-esi-employer-premiums.md#acs-local-releases). National and ACS local-area builds now use the same typed calibration diagnostics writer, which publishes schema 9: the schema-8 document builders diff --git a/changelog.d/1154-acs-local-wic-eitc-take-up.fixed.md b/changelog.d/1154-acs-local-wic-eitc-take-up.fixed.md new file mode 100644 index 0000000000..fb13cd8541 --- /dev/null +++ b/changelog.d/1154-acs-local-wic-eitc-take-up.fixed.md @@ -0,0 +1,4 @@ +The ACS local lane draws WIC and EITC take-up for its ACS rows instead of leaving the engine default, `True`, under which every eligible ACS person took WIC up and every eligible ACS tax unit claimed the EITC (microcosm#1154, microcosm#1675). + +- WIC: staging runs the national `wic_claim_input` generator, unchanged, on the ACS-only frame after the shared transfer has completed `is_pregnant` and `own_children_in_household`, and before pooling (`acs_local_wic_take_up`, `build_optional_acs_multispine(wic_take_up=True)`, the design of microcosm#1156). The donor's decisions are kept, and must be complete before the ACS spine is loaded. The release tool refuses a null `takes_up_wic_if_eligible` before any reviewed fill (`NEVER_DEFAULT_FILLED`), the take-up stage refuses an incomplete column, and the take-up gate grades it on both spines. +- EITC: the release tool's take-up stage fills the ACS tax units' `takes_up_eitc` with the take-up contract's seeded draw at the National Taxpayer Advocate's rates by number of qualifying children, as it already draws TANF. At the default, the state SOI EITC targets shrank the weights of eligible ACS units instead of choosing claimants among them. The receipt records the ACS share by number of children, the assignment digest covers the cells, and the take-up gate grades the flag on both spines and the ACS share against the contract's band. diff --git a/changelog.d/1661-acs-local-2145-texts-and-lineage-at-calibrate.fixed.md b/changelog.d/1661-acs-local-2145-texts-and-lineage-at-calibrate.fixed.md new file mode 100644 index 0000000000..939d9d03c9 --- /dev/null +++ b/changelog.d/1661-acs-local-2145-texts-and-lineage-at-calibrate.fixed.md @@ -0,0 +1,7 @@ +The ACS local lane's published limitation texts and staging receipts now describe policyengine-us 2.145.3, and the release tool requires a new national donor's reviewed lineage from calibrate on (microcosm#1661, microcosm#1675). + +- `weeks_worked` is an input on 2.145.3 (policyengine-us#9660), so the consumer export carries it: the work and disability receipt records it as exported (`input_since`), and the limitation texts no longer say it is held back. +- The entry-clock texts name the 2.145.3 readers of `years_since_us_entry`, SNAP's qualified-alien waiting period among them, instead of 2.2.1's. +- The vehicle, CHIP and take-up texts cite 2.145.3; the take-up text says that EITC and WIC take-up are now drawn on ACS rows. +- `_require_reviewed_donor_lineage` runs at the start of calibrate instead of materialize, and finalize checks again. Materialize writes nothing the entry decides, so R1 and materialize can run while the donor's evidence is reviewed; calibrate fixes the commit that package accepts. +- The County Files runbook covers the ESI donor checks, the WIC and EITC draws, the lineage review and when to commit it, and the projection steps that are not automated. diff --git a/changelog.d/1675-acs-local-register-2145.changed.md b/changelog.d/1675-acs-local-register-2145.changed.md new file mode 100644 index 0000000000..6388d70050 --- /dev/null +++ b/changelog.d/1675-acs-local-register-2145.changed.md @@ -0,0 +1,5 @@ +The ACS local lane's reviewed-fill register is re-reviewed on policyengine-us 2.145.3 (microcosm#1675). `reviewed_against` is 2.145.3, and each entry lists every means-tested program the engine's dependency walk reaches, through the engine's helper functions as well (`follow_helpers`), with one note per program; pairs reached only through paths that do nothing in a release pass are listed as harmless. + +- `second_home_mortgage_interest` leaves the register (no longer an engine input, PolicyEngine/policyengine-us#9605), and so does `takes_up_eitc`: R2 now draws it, and it joins `NEVER_DEFAULT_FILLED` and the pre-check's stage-filled list. +- Five entries are added for the next national donor: the four SCF student-debt inputs, which reach no program, and `weeks_worked`, blank on ACS persons under 16. +- Notes that counted California CARE, FERA or CVRP, or Missouri SSP, effects say that those programs pay nothing on these files, and two state-benefit verdicts that rested on them alone are harmless. The PTC's Medicaid bar is named where it sits on 2.145.3, `is_aca_marketplace_enrollee`. diff --git a/changelog.d/454-us-acs-local-esi-premiums.fixed.md b/changelog.d/454-us-acs-local-esi-premiums.fixed.md new file mode 100644 index 0000000000..d4ccc12f8e --- /dev/null +++ b/changelog.d/454-us-acs-local-esi-premiums.fixed.md @@ -0,0 +1 @@ +The US ACS local release lane transfers `employer_sponsored_insurance_premiums` onto its ACS spine (microcosm#454). Before, those rows were null, and the release tool's `fill_reviewed_nulls` refused the staging frame of any donor that carries the column. The staging build now qualifies the donor before the ACS fetch, transfers the column in a lane-only pass fitted on the donor's ASEC observations, which carry measured wages, and runs that pass after the hours and income passes and immediately before the shared transfer; on the test fixture every other value is byte-equal with and without it. A new kernel in `esi_premiums`, `with_us_esi_premium_pool_anchor`, then clears the premium for ACS people without wages and scales the rest so both spines carry the same weighted premium per unit of household mass, which keeps the lane-wide column at the donor release's own. The declared ACS transfer plan does not change. The ESI summary and both ESI gates take a new keyword, `allow_transferred_rows`, so they can grade a frame that mixes CPS rows with transferred rows: with `True`, which only the lane passes, the CPS rows get the MEPS-IC recomputation and the gates compare the transferred rows with them, and a row the CPS record id and raw coverage fields cannot classify fails both gates. The default, `False`, keeps the rule the base build and the fiscal-refresh release tool already applied: every row must carry the raw ASEC coverage fields, and the CPS record id is not read. The lane runs both gates on the staging frame and, in finalize, on the calibrated artifact; the gate report records `esi_premiums_signal` and `esi_premiums_anchor` bound to the artifact bytes, its `input_coverage` entry passes only if both do, and package by default refuses a report without passing verdicts for the bytes it packages. `us/gates.json` also declares the two finalize gates as `us_local_esi_premiums_signal` and `us_local_esi_premiums_anchor`, bound to the lane's own row-kind gates, so the gate battery's shadow compares them like the release's other gates and records `--allow-esi-premium-gaps` as their waiver. `--allow-esi-premium-gaps`, on the staging tool and the release tool, records a refused donor or a red verdict for a diagnostic build instead of failing; with it, package also takes a red verdict bound to the packaged bytes that finalize recorded as waived (`enforced: false`), and no other; the shadow keeps each entry's waiver as finalize had it and shows it only on the gate report bytes that finalize run wrote, or, when that run wrote none, on a package run with no gate report at the selected path, which package refuses; otherwise, or when it cannot read the record, it records the waiver as unknown, with the reason; a Modal plan can pass it to the release tool only. The staging tool refuses a donor with any row that lacks a raw coverage field or a CPS record id, and the ESI gates turn a mixed frame whose CPS rows carry no weighted anchor evidence, or whose household mass, employer premium or MEPS-IC share sums past the largest float, or whose anchor-universe total does, into a red verdict. diff --git a/changelog.d/us-acs-county-agi-check-helper-reads-1675.fixed.md b/changelog.d/us-acs-county-agi-check-helper-reads-1675.fixed.md new file mode 100644 index 0000000000..5ceef5eb5b --- /dev/null +++ b/changelog.d/us-acs-county-agi-check-helper-reads-1675.fixed.md @@ -0,0 +1 @@ +`tools/check_us_acs_county_agi_support.py` reads AGI's dependency closure through the engine's helper functions (`follow_helpers`), so it now sees the AGI inputs read only inside a helper, such as the two Form 7206 inputs of the self-employed health insurance deduction (microcosm#1675). Through the `get_behavioral_response_measurements` helper, the behavioral responses read `household_net_income`, and through it every benefit and the take-up flags R2's stages fill. An engine pass without a reform, as R2's and the check's are, never reads through them: `labor_supply_behavioral_response` and `capital_gains_behavioral_response` return 0 while the simulation has no baseline, and the labor supply elasticity effects are computed only where the labor supply response is nonzero. So the walk stops at those four variables too (`NO_REFORM_UNREAD`), and the report lists them in `agi_closure_stops_at`. diff --git a/changelog.d/us-acs-county-agi-check-year-closure-922.fixed.md b/changelog.d/us-acs-county-agi-check-year-closure-922.fixed.md new file mode 100644 index 0000000000..1e1a7747a3 --- /dev/null +++ b/changelog.d/us-acs-county-agi-check-year-closure-922.fixed.md @@ -0,0 +1 @@ +`tools/check_us_acs_county_agi_support.py` decides which never-default nulls it may hold back from the AGI computation with AGI's dependency closure in its own year (R2's, 2024): the walk stops at an above-the-line deduction that year's `gov.irs.ald.deductions` does not list, whose formula then reads nothing. On policyengine-us 2.145.3 the 2020-only charitable deduction for non-itemizers reads the itemization choice, so the static closure reached four take-up flags R2's stages fill (SSI, Medicare, TANF and housing assistance), and the check would have refused every staging file R2 accepts. The report records where the walk stopped (`agi_closure_stops_at`). diff --git a/changelog.d/us-acs-county-agi-support-check-922.added.md b/changelog.d/us-acs-county-agi-support-check-922.added.md new file mode 100644 index 0000000000..2ffda9003e --- /dev/null +++ b/changelog.d/us-acs-county-agi-support-check-922.added.md @@ -0,0 +1 @@ +`tools/check_us_acs_county_agi_support.py` lists, before the ACS local release (R2) runs, the counties whose county IRS SOI AGI row R2 would build empty: counties with households but none with a nonzero AGI (microcosm#922; microcosm#1630 review, finding 1). The state AGI row stores no zero, so such a county makes `attach_surface` refuse the run after the materialize engine pass. The check computes the value R2 stores: it loads the staging frame and its summary as R2 does, holds back the formula-owned columns, fills the reviewed nulls with R2's own functions, and runs policyengine-us for the household sum of `adjusted_gross_income` in household chunks. That sum is the production SOI materializer's AGI measure (an engine-tier test compares them), so income held by a dependent, or by a tax unit without an adult, counts as the engine counts it: not at all. A null in a never-default column that one of R2's own stages fills (the set the reviewed-fill pre-check uses) is held back only while its nulls are on ACS rows and the AGI does not read it; every other never-default null is refused, as R2's fill step refuses it: a null on a donor row, in a column no R2 stage fills, or in one the AGI reads. An engine-tier test checks that no stage-filled column is an AGI input. With `--puma-ladder` it applies R2's own minimum-support moves first, and lists the counties that R2's `check_support` refuses before its engine pass: a county outside the ladder, and a ladder county without a household-universe record after the moves (as R2 does, it moves no household when a county is outside the ladder). It exits 2 when a county is at risk, and 3 when R2 would refuse the run (3 takes precedence). diff --git a/changelog.d/us-acs-county-soi-support-1661.added.md b/changelog.d/us-acs-county-soi-support-1661.added.md new file mode 100644 index 0000000000..dd146e0d9c --- /dev/null +++ b/changelog.d/us-acs-county-soi-support-1661.added.md @@ -0,0 +1 @@ +On a county SOI surface, minimum county support in the ACS local release also gives every county's SOI rows support (microcosm#1661). Materialize computes each household's AGI as the state SOI AGI row stores it, one 100,000-household chunk at a time, before the support step. The step then moves `--county-min-support` same-PUMA households with a positive AGI into any county whose households all store an AGI of 0, whose county AGI row would otherwise be empty and refused after the engine pass. A county it fills because it has no household gets one with a positive AGI: when none of its K picks in rank order has one, the K-th gives way to the next household in rank order that has one (`"reason": "positive_agi"`), so the other picks keep their PUMA's AGI mix, and `minimum_support.soi_support.first_pass` reports the movers' share with a positive AGI beside their PUMAs' share. No donor county is left without a household with a nonzero AGI. A county that still has none is refused before the engine pass. The moves are recorded in `county_support.json` (`minimum_support.soi_support`, moves with `"reason": "soi_support"`) and replay as before. `tools/check_us_acs_county_agi_support.py` applies the same moves. diff --git a/changelog.d/us-acs-donor-lineage-limitations-1661.changed.md b/changelog.d/us-acs-donor-lineage-limitations-1661.changed.md new file mode 100644 index 0000000000..b14874c958 --- /dev/null +++ b/changelog.d/us-acs-donor-lineage-limitations-1661.changed.md @@ -0,0 +1 @@ +The ACS local release keeps its five inherited Build O donor limitations (the SSI aged-band collapse, the miscellaneous income loss side, the tip-return count, the 57,240-household selection and the Social Security erasure) for the donors they describe. It refuses, at the start of materialize and in finalize, a staging whose donor is a US national build of `microcosm-us-2024-national` or `microcosm-us-2024-evidence` that has no entry in `REVIEWED_DONOR_LINEAGES`, so a release on a new national donor cannot publish the Build O lineage's limitations as its own (microcosm#1661). An entry lists the inherited limitations that a review of the donor's own evidence found to hold; the others leave its releases' register. diff --git a/changelog.d/us-acs-reviewed-fills-precheck-922.added.md b/changelog.d/us-acs-reviewed-fills-precheck-922.added.md new file mode 100644 index 0000000000..ee88b6cd91 --- /dev/null +++ b/changelog.d/us-acs-reviewed-fills-precheck-922.added.md @@ -0,0 +1 @@ +`tools/check_us_acs_local_reviewed_fills.py` grades a staging summary's reviewed engine-input nulls against the ACS local release's fill rules in seconds, before the release runs (microcosm#922). It refuses what materialize would refuse (a null in a never-default-filled column, unless the null is on the ACS spine alone and in a column that one of the release's own stages fills there first: the take-up stage's SPM-unit take-up flags and engine-free fills, or the SSI and Medicaid take-up flags; a null ESI premium), builds the fill records the release would write with the engine defaults the release resolves, and runs the release's own finalize gate (`acs_local_reviewed_fill_consumer_gate`) on them, which otherwise refuses an unregistered fill hours into the run. It exits 2 when the release would refuse. diff --git a/changelog.d/us-acs-staging-engine-and-donor-location-922.changed.md b/changelog.d/us-acs-staging-engine-and-donor-location-922.changed.md new file mode 100644 index 0000000000..82143adba7 --- /dev/null +++ b/changelog.d/us-acs-staging-engine-and-donor-location-922.changed.md @@ -0,0 +1 @@ +ACS staging (`tools/_legacy/build_us_acs_multispine_base.py`) records the policyengine-us and policyengine-core it ran on (`engine_versions`) and, under either location rule, the donor base's recorded location rule (`base.location`). The ACS local release refuses at the start of materialize a staging summary that records another policyengine-us, or none, since staging audits only its own engine's input nulls (microcosm#922). `tools/check_us_acs_local_reviewed_fills.py` reports the same refusal. A test checks that the legacy rule keeps a `block_v1` donor's block and the geography derived from it, as the County Files staging on a `block_v1` national donor relies on. diff --git a/changelog.d/us-acs-strike-benefits-reviewed-fill-922.fixed.md b/changelog.d/us-acs-strike-benefits-reviewed-fill-922.fixed.md new file mode 100644 index 0000000000..db5a10ca08 --- /dev/null +++ b/changelog.d/us-acs-strike-benefits-reviewed-fill-922.fixed.md @@ -0,0 +1 @@ +The ACS local lane's reviewed-fill register (`acs_local_reviewed_fill_consumers.yaml`) lists `person.strike_benefits` (microcosm#922). Since the local income pass's OIP predictor took strike benefits as a component, every ACS staging donor carries the column, but nothing transfers it, so the release fills 0 on every ACS person, and finalize's reviewed-fill gate refused that fill as unregistered. The entry names its 13 means-tested consumers with the verdict harmless: no pinned ASEC respondent reports strike benefits, so every donor value is 0 as well. diff --git a/changelog.d/us-index-follows-helper-reads-1675.added.md b/changelog.d/us-index-follows-helper-reads-1675.added.md new file mode 100644 index 0000000000..8b25656450 --- /dev/null +++ b/changelog.d/us-index-follows-helper-reads-1675.added.md @@ -0,0 +1 @@ +`PolicyEngineUSVariableMetadataIndex(follow_helpers=True)` reads through the engine's module-level helper functions in `variables/` (microcosm#1675). The static consumer index interprets such a helper once per distinct call context and records its reads under the helper's own name, which `variable_dependency_closure` does not follow, so a variable's graph stopped where its formula called one. On policyengine-us 2.145.3 that hid, among others, free and reduced-price school meals' reads through `school_meal_daily_rate` and the self-employed health insurance deduction's Form 7206 inputs. The index now also records each helper read under every variable whose formula reaches that call context, directly or through other helpers (`helper_consumers`), and the `follow_helpers` view walks them. The default view is unchanged, receipt for receipt, so the pool's pinned SSI dependency contract and the US engine ABI lock stay as they are. The reviewed-fill register's engine-tier walk uses the new view. diff --git a/docs/agent-guide.md b/docs/agent-guide.md index 40216f3617..d1954a05f1 100644 --- a/docs/agent-guide.md +++ b/docs/agent-guide.md @@ -571,6 +571,21 @@ A source-enrichment publisher claim widens the range consumers accept, not what was checked: the bundle's `compatibility.claim_measurement` names the one version the probe measured. +The ACS local-area chain produces `employer_sponsored_insurance_premiums` on +its ACS spine itself (microcosm#454): the staging build +(`tools/build_us_acs_multispine_base.py`) transfers it from the donor +release's ASEC observations and holds it to the donor rows' premium per unit +of household mass, and both ESI premium gates run on the staging frame and +again in finalize on the calibrated artifact. A donor built before the +`meps_esi_premiums` stage is refused. `--allow-esi-premium-gaps`, on the +staging tool and the release tool, is for diagnostic builds only: it records a +red verdict in the staging summary and the gate report instead of failing. +Modal staging plans cannot pass it. The lane's calls to the ESI gates pass +`allow_transferred_rows=True`; the base build and the fiscal-refresh release +tool keep the default, which refuses any row without the raw ASEC coverage +fields, so do not pass it on those paths. See +[the ESI premium note](us-esi-employer-premiums.md#acs-local-releases). + A US release or release-gate preflight that receives a multispine pool through `--base-h5` must authenticate its sibling terminal manifest. A current stacked pool whose terminal battery is red remains fail-closed unless the operator diff --git a/docs/gate-battery-contract.md b/docs/gate-battery-contract.md index 63f0188745..0e0dcaa26d 100644 --- a/docs/gate-battery-contract.md +++ b/docs/gate-battery-contract.md @@ -327,10 +327,10 @@ local publication work in #146; they are evaluated in their own signed accounting. 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 +`us/gates.json` now declares 145 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 +`us_national` (the national release, 76) and `us_local` (ACS local, 26). 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 diff --git a/docs/us-acs-local-county-rung.md b/docs/us-acs-local-county-rung.md index 99c0dcd94f..c40dc3cefd 100644 --- a/docs/us-acs-local-county-rung.md +++ b/docs/us-acs-local-county-rung.md @@ -27,9 +27,11 @@ into any county the staging frame leaves empty. ACS validation families never enter the loss, the target registry, the matrix or the weights. - Minimum support never moves a household into a county that already has - one, never changes a household's state or PUMA, rewrites only the county - columns, moves exactly the configured number of households into each - county it fills (or none), and is deterministic. + one, except to give a county's SOI rows support (below), never changes a + household's state or PUMA, rewrites only the county columns, moves exactly + the configured number of households into each county it fills (or none), + never leaves a donor county without a household whose AGI is nonzero, and + is deterministic. - Kalawao (`15005`) shares one declared SOI cell with Maui (`15009`) for the SOI families only; any other county missing from SOI is refused. - Reliability reports show supporting rows, distinct source households, Kish @@ -250,6 +252,28 @@ moves' SHA256; the export stage re-applies the recorded moves to the reloaded staging frame and refuses moves that no longer match. Filled counties are graded normally with status `minimum_support`. +On a county SOI surface (`--soi-mode state_county` with county geography and +`--county-min-support` above 0) the step also gives every county's SOI rows +support (microcosm#1661). A county whose households all store an AGI of 0 +gets an empty county AGI row, which `attach_surface` refuses after the engine +pass. So materialize first computes each household's AGI as the state SOI AGI +row stores it, with the engine pass's own input projection and reviewed-null +fill, one 100,000-household chunk at a time (in the build's year the AGI reads +no county column, so the moves leave it unchanged). In the first pass, when +none of a county's K picks has a positive AGI, the K-th gives way to the next +eligible household in rank order that has one (its move carries +`"reason": "positive_agi"`), so the other picks keep their PUMA's AGI mix. +`minimum_support.soi_support.first_pass` reports the first-pass movers' share +with a positive AGI beside the share among their PUMAs' eligible households, +and names the counties where the swap happened. A second pass moves K more same-PUMA +households with a positive AGI, chosen and ranked as above, into each county +that has supporting households but none with a nonzero AGI. These moves carry +`"reason": "soi_support"`, and `county_support.json` records the pass under +`minimum_support.soi_support`. No move leaves a donor county without a +household whose AGI is nonzero. A county still without one is refused here, +before the engine pass. The moves replay in calibrate and export as the first +pass's do. + The step is for legacy-location staging. Under `--location-rule block_v1` ([US household location](us-location-v1.md)) every household carries a `block_geoid` and `tract_geoid`, so no household is eligible: an empty county @@ -353,8 +377,33 @@ for `22incyallnoagi.csv` and `abcc8720d669e793bbfdcd440eeec37a78db3b452adbe4ccd1eadf7c72b522b9` for `co-est2024-alldata.csv`. +## Checks between staging and R2 (microcosm#922) + +Two checks read the staging output in minutes and say whether R2 would refuse +it hours later. Run both after the staging (R1) and before R2: + +- `tools/check_us_acs_local_reviewed_fills.py --staging-summary + --out ` reads the summary's `reviewed_engine_input_nulls` (names and + counts only), builds the fill records R2 writes with the installed engine's + defaults, and runs R2's own finalize gate on them, in seconds. Exit 0: R2's + fill rules pass. Exit 2: R2 would refuse; the report says why. A missing + register entry is a reviewed ruling, committed before R2's calibrate stage. +- `tools/check_us_acs_county_agi_support.py --h5 --county-column + county_fips_2023 --puma-ladder --out ` computes each + household's AGI as R2 stores it, with R2's own load, fill and engine + functions, and applies R2's minimum-support moves, its SOI support moves + included. Exit 0: every county's SOI rows have support. Exit 2: a county + that still has households but none with a nonzero AGI, which R2 refuses. + Exit 3 (precedence over 2): a county outside the ladder or without a + household-universe record, which R2's `check_support` refuses before its + engine pass. It needs memory for the full staging frame (40.7 GiB on the + 17 November proof-of-concept staging, in 3.6 minutes). + ## Full-run requirements and command +The final County Files build's operator steps, from the national donor to +the preflight, are in [the final build runbook](us-county-files-final-build.md). + A full run needs the pinned main feed and its SHA256, the pinned county facts file and its SHA256, a staging H5 and summary with household support in every county (after the diff --git a/docs/us-county-files-final-build.md b/docs/us-county-files-final-build.md new file mode 100644 index 0000000000..5bf48d09d1 --- /dev/null +++ b/docs/us-county-files-final-build.md @@ -0,0 +1,233 @@ +# County Files final build runbook (microcosm#1661) + +This runbook is for the operator who runs the final County Files build: the +ACS staging (R1), the 2024 county release (R2), then the projection to 2026 +and 2027. It runs on the next US national build as its donor, on +policyengine-us 2.145.3 (microcosm#1676). The proof of concept (#1660, +#1647) ran with a temporary setup. None of it is used here: no patched donor, +no `--allow-default-donor-column`, no `--county-drop-empty-soi-rows`, and a +published donor manifest. + +The final run starts once the national build is certified and published. +Before that, the same commands run files-only as a rehearsal (section 5). + +## 1. Host and checkout + +- Memory: 128 GiB. Peaks on the 17 November proof of concept: R1 48.0 GiB, + the AGI check 40.7 GiB, R2 materialize 59.7 GiB, calibrate 47.7 GiB. Earlier + full materialize runs peaked at 75.6 to 93.9 GB ([the rung doc](us-acs-local-county-rung.md)). + Run nothing heavy beside it. +- Disk: keep 60 GB free. The staging H5 is about 11.5 GB and the calibrated + file about 10.6 GB. +- Checkout: a clean worktree at the commit María names, outside which `$RUN` + and every log live. R2 records the commit, and package refuses a dirty tree + (an untracked file counts). Run `uv sync --python 3.14 --all-packages + --locked --extra us` there (policyengine-us 2.145.3), then + `uv run --no-sync` for every command. + +## 2. Inputs + +```bash +export RUN=/abs/path/county-files-final # outside the checkout +export DONOR_H5=/abs/path/microcosm_us_2024.h5 # the national build's H5 +export DONOR_MANIFEST=/abs/path/release_manifest.json # its certified release manifest +export LADDER=/abs/path/us_puma_ladder_2020.npz # SHA-256 39a2ab2abeab07a88362af7ab2940e0e1d50a297c919e4bbc6fb65bab51147d8 +export FEED=/abs/path/consumer_facts_us_41b2fb2.jsonl +export FEED_SHA256=1d45a89c28177a95371b4cc4068d3657c7bf12bd8edad7c82fe25bf453f9ea07 +export COUNTY_FACTS=/abs/path/consumer_facts_us_county_3e9d3a0.jsonl +export COUNTY_FACTS_SHA256=67b0998aa2ee1aeed6637dab6a846f405246706508074b1c1b5bab7bd98c8bea +export PYTHONUNBUFFERED=1 +``` + +- The donor is the national build's dataset (`microcosm_us_2024.h5`) and its + release manifest from `releases/microcosm-us-2024-national//`, from + the Hub once published or from the certified build's folder. R1 checks the + H5's SHA-256 against the manifest's one microdata artifact. +- The ladder is the one the proof of concept used. A copy is in the private + `policyengine/populace-us-staging` dataset at + `inputs/us-puma-ladder/39a2ab2a/`. +- The feed is the national build's feed: the same pin. +- Build the county facts at Chronicle + `3e9d3a0694e8ca7e31ed5319c3ceb1bde92b12e0` (about 8 minutes), or copy them + from the staging dataset's `inputs/`. Either way the loader checks the + digest. +- R1 fetches the pinned ACS PUMS archives into `--inputs-dir` and the pinned + SIPP 2023 file (3.73 GB) into its cache on first use. + +## 3. Before you start + +Two data entries, both María's rulings, must be committed before R2's +calibrate starts. Calibrate fixes the commit that package accepts, so commit +them before calibrate, never while it runs: + +- the reviewed-fill register re-reviewed on 2.145.3 (microcosm#1675), + with `reviewed_against` at the installed engine. Finalize refuses without + it. +- the national donor's entry in `REVIEWED_DONOR_LINEAGES` + (`tools/build_us_acs_local_release.py`), from the review below. Calibrate + refuses the staging without it, and finalize does again. R1 and + materialize do not need it, so they can run while the donor's evidence is + reviewed. + +### The donor's lineage review + +R2's inherited limitations describe the Build O donor. For a new national +build, each one is kept or dropped from that build's own evidence, one ruling +per item. The entry lists the ones that hold; the release drops the others: + +- `ssi_aged_band_collapse_inherited` (microcosm#507): the aged SSI + baseline. Compare the build's weighted SSI recipients aged 65 and over with + SSA's count. It holds if the aged band still falls well short of it. +- `miscellaneous_income_loss_side_donor_defect` (microcosm#393): the + prevalence of a negative `miscellaneous_income` against SOI's loss-return + prevalence. It holds while that distortion remains. +- `tips_return_count_carrier_deficit_inherited`: the tip-return count + against its ledger target, in the build's calibration diagnostics. It holds + if the build still misses it by a material margin. +- `donor_sparse_selection_training_set`: the donor manifest's microdata + artifact. It holds only for a sparse selection, and drops for a dense + full-row donor. +- `social_security_cps_reporters_erased_inherited` (microcosm#1178): whether + the build's PUF-support records keep their CPS-reported Social Security, + which microcosm#1186 fixed where a national base is built. It drops when + they do. + +## 4. Steps + +### Step 1: R1, the staging (about 4 hours) + +```bash +POPULACE_ACS_POOL_PEAK_LIMIT_BYTES=100000000000 \ +POPULACE_STAGING_EXPORT_PEAK_LIMIT_BYTES=100000000000 \ +uv run --no-sync python tools/build_us_acs_multispine_base.py \ + --base-h5 "$DONOR_H5" --donor-release-manifest "$DONOR_MANIFEST" \ + --out-h5 "$RUN/acs_multispine_staging.h5" \ + --summary "$RUN/acs_multispine_staging.summary.json" \ + --inputs-dir --puma-ladder "$LADDER" \ + --period 2024 --seed 0 --geography-seed 0 --acs-share 0.5 \ + --n-estimators 32 --max-targets-per-fit 8 --chunksize 100000 \ + --donor-channel auto --location-rule legacy \ + --hours-under15-policy us_hours_under15_zero_completion_v1 +``` + +- `--location-rule legacy` keeps each donor's own `block_v1` tract, district, + county and 2023 county. The ACS rows get the PUMA ladder's counties, as in + the proof of concept. The summary records the donor's rule + (`base.location`) and the engine (`engine_versions`). +- R1 checks the donor in its first minutes: the work columns, + `strike_benefits`, the partnership and S-corp split, the SPM role, the + take-up inputs, complete WIC take-up decisions, and the ESI employer + premium with the raw ASEC coverage fields and CPS record id on every donor + row (microcosm#454). A refusal there means the donor lacks one. Stop and + send the log. +- Never pass `--allow-esi-premium-gaps`, to R1 or R2: it records red ESI + gates instead of failing, for diagnostic runs only, and a release built + with it cannot be published as the County Files. +- R1 transfers the ESI premium onto ACS rows and draws their WIC take-up with + the national generator before pooling (microcosm#1154); R2 draws the ACS + tax units' EITC take-up in its take-up stage. None of them needs a flag. + +### Step 2: the two checks (minutes) + +```bash +uv run --no-sync python tools/check_us_acs_local_reviewed_fills.py \ + --staging-summary "$RUN/acs_multispine_staging.summary.json" \ + --out "$RUN/reviewed_fills_precheck.json" +uv run --no-sync python tools/check_us_acs_county_agi_support.py \ + --h5 "$RUN/acs_multispine_staging.h5" \ + --staging-summary "$RUN/acs_multispine_staging.summary.json" \ + --county-column county_fips_2023 --puma-ladder "$LADDER" --county-min-support 3 \ + --out "$RUN/county_agi_support.json" +``` + +- Both must exit 0. A fill without a register entry (exit 2) needs a ruling + and a commit before step 3. The AGI check applies R2's minimum-support + moves, its SOI support included. Exit 2 or 3 names the counties R2 would + refuse. Stop and send both reports. + +### Step 3: R2, the 2024 county release (about 4.5 hours) + +```bash +R2="uv run --no-sync python tools/build_us_acs_local_release.py" +C="--staging-h5 $RUN/acs_multispine_staging.h5 --staging-summary $RUN/acs_multispine_staging.summary.json \ + --checkpoint-dir $RUN/checkpoints --ladder $LADDER --out-h5 $RUN/populace_us_2024_acs_local.h5 \ + --families snap,medicaid,soi --geographies state,cd,county --soi-mode state_county \ + --county-column county_fips_2023 --county-holdout-fraction 0.1 --county-holdout-salt acs-local-county-v1 \ + --county-min-support 3 --county-target-loss-cap 10 --county-max-weight-ratio 5 --hh-chunk 20000 --seed 0" +clean() { test -z "$(git status --porcelain)" || { git status --porcelain; echo "dirty tree"; return 1; }; } +clean && $R2 --stage materialize $C --feed "$FEED" --feed-sha256 "$FEED_SHA256" \ + --county-facts "$COUNTY_FACTS" --county-facts-sha256 "$COUNTY_FACTS_SHA256" --sample-fraction 1.0 +clean && $R2 --stage calibrate $C +$R2 --stage qa $C +$R2 --stage finalize $C +clean && $R2 --stage package $C --out "$RUN/release" +``` + +- Materialize refuses a staging made on another engine in its first + minutes. It then computes each household's AGI (minutes) and runs minimum + support, SOI support included (`county_support.json`). The engine pass + takes about 3 hours. +- If the register or the donor's lineage entry is not in the checkout yet, + commit it after materialize and before calibrate (section 3). The `clean` + check before calibrate then holds, and calibrate refuses a donor without + its entry before it solves. +- One stage per process, so a stop resumes at its stage. + +### Step 4: the publisher's preflight (seconds; publishes nothing) + +```bash +uv run --no-sync microcosm-publish-release-build "$RUN/release/releases/microcosm-us-2024-local" \ + --repo-id policyengine/populace-us --artifact-root "$RUN/release" --preflight-only +``` + +- It must print a valid result. This runs the local-area release contract, + which R2 does not run itself. Do not publish: publication is María's call + with Max. + +### Step 5: the projection to 2026 and 2027 + +Follow [the projection guide](us-local-annual-projection.md#running-it-on-the-2024-county-build) +with `$PKG=$RUN/release`, on policyengine-us 2.145.3 (the build's +`built_with_model_package`). Two of its steps are not automated (#1627): +step 3, each projected year's household measures, and step 4, the acceptance +report. The report needs six passing checks per year (schema, source +identity, year, demographics, input aggregates and runtime), and their +criteria are not set yet, a tolerance for county and state share drift among +them. Until they are, the 2024 county release can be published without the +projected years. + +## 5. The rehearsal, before certification ends (files only) + +Run steps 1 to 4 on the built but not yet certified national H5, without +`--donor-release-manifest`. Use production settings: R1 is deterministic, +so its staging and both checks' results are the final run's. Expected +differences from the final run: + +- The staging records `donor_release: null`. So neither calibrate nor + finalize asks for the donor's `REVIEWED_DONOR_LINEAGES` entry, and + finalize writes the Build O limitations. +- The preflight refuses `donor_release` null. Any other refusal is a finding. +- Until the re-reviewed register is in the checkout, finalize refuses the + engine mismatch. It writes `gate_summary.json` first, so read the other + gates there. Package and the preflight then need a run whose calibrate ran + at a commit with the register, since package refuses another commit. + +The PUF-derived donor stays on the build laptop until it is published, so +the rehearsal runs there. + +## 6. What to send, and when to stop + +Send the logs and JSON records after step 2, and after step 4 or any stop, +never the H5s: + +```bash +( cd "$RUN" && out="$HOME/county-files-evidence-$(date -u +%Y%m%dT%H%M%SZ).tar.gz" && find . -type f \( -name '*.json' -o -name '*.log' -o -name '*.csv' \) -not -name '*.h5' -print0 | tar -czf "$out" --null -T - && echo "$out" ) +``` + +Stop, keep every file, and send it when: + +- R1 refuses the donor; +- a check exits other than 0; +- a stage refuses; +- the preflight is invalid (other than the rehearsal's `donor_release` + refusal). diff --git a/docs/us-esi-employer-premiums.md b/docs/us-esi-employer-premiums.md index d6b3f92c40..8656d1c8e6 100644 --- a/docs/us-esi-employer-premiums.md +++ b/docs/us-esi-employer-premiums.md @@ -1,7 +1,9 @@ # US employer-sponsored insurance premiums (#454) -Status as of 2026-10-11. Code: `microcosm.build.us_runtime.esi_premiums` -(stage `meps_esi_premiums`). Receipts: `experiments/us-esi-454/`. +Status as of 2026-11-18. Code: `microcosm.build.us_runtime.esi_premiums` +(stage `meps_esi_premiums`) and, for ACS local releases, +`microcosm.build.us_runtime.acs_local_esi_premiums`. Receipts: +`experiments/us-esi-454/`. ## What the stage produces @@ -298,12 +300,244 @@ class, and 0.1M have no labor-force status (0). Both the signal gate and the anchor gate pass on each pool, before and after the PUF-support clone, and the clone conserves both totals. +## ACS local releases + +The ACS local lane (`tools/build_us_acs_multispine_base.py`, then +`tools/build_us_acs_local_release.py`) pools a dense donor release with the +ACS 2024 1-year spine. `with_optional_acs_spine` multiplies every donor +household weight by `1 - acs_share` and gives ACS the rest of the donor's +household mass (half each by default). The donor rows arrive with the column +and the raw coverage columns the release carries. ACS rows have neither. +`microcosm.build.us_runtime.acs_local_esi_premiums` puts the column on them: +it qualifies the donor, transfers the column and holds the ACS rows to the +donor rows' scale. + +### The lane transfers the column in its own pass + +`acs_local_esi_premium_transfer_target_families` is a one-family plan, +`source_operator_esi_premiums`, that only the lane's staging build uses, as it +does for usual hours (#765) and the ASEC income families (#1022). The pass +runs after those two and immediately before the lane's shared transfer, so the +hours and income passes see the frame they would see without it. The declared +ACS plan (`declared_acs_transfer_target_families`) does not gain the column: + +- The shared transfer fits every declared family on the PUF-detail role by + default (`--donor-channel auto`), the wrong donor for this column (next + section). +- Other plans start from the declared one: the multispine pool's transfer plan + (`pool_transfer_target_families`) and the spine-agreement battery's default + registry (`spine_agreement`). A column declared there would reach both. + +The transfer's predictors are fixed lists (`ACS_PERSON_TRANSFER_PREDICTORS`, +`ACS_OPTIONAL_PERSON_TRANSFER_PREDICTORS`) that do not include the premium, so +the premium the pass writes cannot enter another family's fit. On the test +fixture, the shared transfer draws the same values with and without the pass, +every other column of every table is byte-equal, and the hours and income +passes make the same calls and draws +(`test_the_esi_pass_moves_no_other_value_on_any_row`, +`test_the_esi_pass_changes_no_call_or_draw_of_the_other_passes`). + +### The donor rows are the ASEC observations + +The transfer fits on the donor's ASEC observation role (support clone 0). The +lane's tax-detail families fit on the PUF-detail role, which is the wrong +donor for this column: + +- On the observation role, `employment_income_before_lsr` is the measured CPS + wage, and a person has a premium only if they hold a job with an employer. +- PUF support imputation writes the clone's wages + (`PUF_TAX_DETAIL_DEFAULT_PERSON_OUTPUTS`), while the clone's premium is a + copy of its source person's. On those rows the premium no longer follows the + wage. + +The recipient side is the measured ACS wage (`WAGP`), so both sides of the fit +see a measured wage. On the test fixture, where only wages tell the employed +from the rest, a fit on ASEC observations gives no ACS person without wages a +premium; a fit on the PUF-detail role gives one to more than a tenth of them +and to fewer workers +(`test_the_puf_detail_role_would_put_premiums_on_people_without_wages`). + +`prepare_acs_local_esi_premium_donor` qualifies the donor before the staging +build loads the SIPP donor or fetches the ACS sources. It refuses a donor +without the column, the raw coverage columns, the CPS record id (`PERIDNUM`), +wages or legacy support roles, one with a row that lacks any raw coverage +column or a record id, one whose ASEC observations have a missing wage, and +one that fails the stage's signal gate. Every donor row is a CPS record, so a +row that lost those fields stops the build here, in minutes, not after the +transfer, even one that lost both: the signal gate grades the donor as the +pooled frame will be graded (see "The gates grade the lane's frame by row +kind") and would read such a row as a transferred one. + +### The ACS rows are held to the donor rows' scale + +Nothing in a QRF draw keeps a total. Once the frame is pooled, +`with_acs_local_esi_premium_anchor` runs the mixed-frame kernel in +`esi_premiums`, `with_us_esi_premium_pool_anchor`, on it. The kernel tells the +donor rows from the ACS rows by the CPS record id and the raw coverage +columns, which only the donor rows carry. On the ACS rows it: + +1. clears the premium where the person reports zero wages; then +2. scales the rest by one factor so the ACS rows carry the same weighted + premium per unit of household mass as the donor rows. + +The kernel refuses a transferred row whose wage is missing: a missing wage is +not a zero wage. ACS PUMS leaves `WAGP` blank below age 15, outside its +earnings universe, and the lane keeps that blank in the staging frame; the +release tool's reviewed null fill (`fill_reviewed_nulls`) sets it to zero for +the engine. The anchor reads those people's wages as zero under the universe +rule `acs_income_universe` names (`acs_2024_pums_wagp_age_15_plus`), in its +own view of the frame, and writes no zero into the frame. The rest of the rule +stops the build: + +- a blank raw `WAGP` at age 15 or older, or at an unknown age, however the + mapped wage was filled; +- below 15, a raw `WAGP` that is not blank, or a mapped wage that is neither + null nor zero. + +The kernel resolves the same rule itself +(`resolve_acs_pums_earnings_universe`), but only on rows whose support channel +is `acs`. This lane's ACS rows carry the late spine's channel +(`acs_2024_1yr`), so the kernel's check sees none of them and its receipt +counts no rows. The lane applies the rule before calling the kernel, and its +receipt (`wage_universe`) counts what it checked. + +The anchor never rewrites a donor row. These hold for every lane frame +(`tests/engine_free/us/test_us_acs_local_esi_premiums.py`, property-tested +over the ACS share, both spines' weights and the transferred premiums and +wages): + +- the lane-wide weighted column equals the donor rows' total divided by their + share of household mass, `1 - acs_share`. Pooling multiplied every donor + household weight by that share, so the lane-wide column is the donor + release's own column; +- both spines carry the same weighted premium per unit of household mass, so + moving mass from one spine to the other does not move the total; +- an ACS person with zero wages, or below age 15, carries nothing; +- the frame's own wage blanks are never overwritten; +- an anchored frame is returned unchanged. + +The lane runs the kernel and both gates on a narrow view of the frame, for two +reasons: + +- **Source ids.** The kernel finds a support clone's wages and draw by + `person_source_id` across the whole frame, so it needs that id unique there. + This lane's is not: ACS rows keep their ids from before the pooling remap as + source ids, and those can repeat a donor's. Every ACS row here is its own + source record, so the view leaves the source id out and the kernel reads + each row's own wages (`test_acs_ids_that_repeat_the_donors_change_nothing`). + The view keeps the clone index, which the kernel's earnings universe + requires, and the lane refuses a transferred row that is not clone 0. +- **Memory.** The kernel copies every table it is given and each gate copies + the person table. The staging frame holds two full spines, and the view + carries only the columns they read. + +**Assumption.** ACS rows have no policyholder flag, so the lane's +anchor-universe total is the donor rows' total plus the ACS column over the +donor rows' employed share of the anchor universe. That assumes employed +policyholders carry the same share of employer premiums on the ACS rows as on +the donor rows. + +The donor is a calibrated release. Its anchor-universe total is within the +release tolerance of the anchor, not on it, and the staging frame starts from +the same place. + +### The gates grade the lane's frame by row kind + +`us_esi_premiums_summary` and both gates take `allow_transferred_rows`, +`False` by default. The lane passes `True` everywhere it grades: in the donor +qualifier's signal gate and in `acs_local_esi_premium_signal_gate` and +`acs_local_esi_premium_anchor_gate`. The staging build calls the two through +`acs_local_esi_premium_gates`; finalize calls them one by one, each beside its +entry of the gate battery's shadow. The anchor kernel applies the same rule +itself. The donor rows then get the full MEPS-IC recomputation, and the ACS +rows are compared with them ("What the gates need", under "Gates", has the +rule and its refusals). + +The base build (`tools/build_us_puf_support_base.py`), the release tool +(`tools/build_us_fiscal_refresh_release.py`) and the stage itself, when it +re-checks a frame that already carries the column, keep the default. Under it +every row must carry every raw coverage column, a row without them fails both +gates with each missing column and its row count named, and the CPS record id +is not read. The lane's frame is red under the default +(`test_the_lane_frame_is_red_under_route_as_default_rule`), and Route A's +callers grade as they did before a mixed frame could be graded. +`tests/engine_free/us/test_us_esi_premiums_route_a_differential.py` checks +this against a vendored copy of the earlier gates +(`test_support/microcosm_build/us_esi_premiums_main_oracle.py`): on Route +A-shaped frames every verdict agrees, and where the copy grades a frame +without refusing it, the failures and every recorded figure agree bit for bit. + +### What the lane records + +- **Staging.** The donor is qualified before the SIPP donor and the ACS + sources are loaded. Both gates run on the frame the staging H5 is written + from, after the last stage that replaces it. A red gate fails the build + before the H5 is written. The verdicts, the donor receipt and the anchor + receipt are in the staging summary under `local_esi_premiums`. +- **Finalize.** Both gates run on the calibrated artifact. The gate report + carries them as `esi_premiums_signal` and `esi_premiums_anchor`, each bound + to the artifact's SHA-256, and either one red fails finalize once the report + is written. The report's `input_coverage` entry used to be a fixed pass; it + now passes only if both gates do. Each gate is also a `us_local` entry of + `us/gates.json` (`us_local_esi_premiums_signal`, + `us_local_esi_premiums_anchor`), bound to the lane's row-kind gates, so the + gate battery's shadow (microcosm#1585 item 11) evaluates it beside today's + call and compares the verdicts. +- **Package.** By default, package refuses a report without both verdicts, + with a verdict bound to other bytes, or with a red verdict, before a + release directory exists. With `--allow-esi-premium-gaps`, package also + takes a red verdict bound to those bytes that finalize recorded as waived + (`enforced: false`), and nothing else (see below). +- **`fill_reviewed_nulls`** still refuses a frame whose column is null on some + rows. A current staging frame has none. A staging H5 built before this + change has them, and so does one whose donor qualification a diagnostic + build waived. + +`--allow-esi-premium-gaps`, on both tools, is for diagnostic builds only, for +example from a donor that predates the stage. In staging it turns a refused +donor and red gates into records in `local_esi_premiums` instead of failures. +From a refused donor the lane transfers nothing: if the donor lacks the +column, no row carries it; if it carries the column but fails qualification, +the ACS rows stay null and `fill_reviewed_nulls` refuses the frame. In +finalize the flag records a red verdict without failing, and the gate entry +keeps the failures with `enforced: false`. Package takes a red verdict only as +that recorded waiver: with the flag it still refuses a red verdict finalize +enforced. The gate battery's shadow records the waiver on each ESI entry as +the finalize run that evaluated it had it, so a package run with other flags +does not rewrite it. Finalize keeps that record beside its shadow +observations, with the SHA-256 of the gate report bytes that run wrote (null +if it wrote none), and the shadow attaches the record only to those bytes. It +compares the digest of the bytes package parsed or, when package stopped +before it read the report, of the file at the selected path when the stage +ends. It records the ESI entries' waiver as unknown, with the reason, rather +than as none when the record names another gate report, names none while a +gate report exists, or lacks the digest, as older records do; when it cannot +open or read the file as a waiver record; or when a finalize checkpoint saved +before finalize kept a record has observations and no record. When the +record's digest is null and the selected path holds no gate report, the two +match: the shadow shows the recorded flags on that package run, which package +refuses ("No gate report") when it reaches that check. The shadow matches +only the waiver to the report: it reads the latest saved finalize observations, +whichever gate report package selects. A release that package ships under the +waiver still fails the local-area release contract (`microcosm.data.contract`), +which accepts only gates that passed. A Modal plan can set the waiver for the +release tool (`allow_esi_premium_gaps`) but not for staging: the staging +runner owns the flag and never passes it, so every Modal staging run qualifies +the donor and enforces both gates. + +No ACS local build has run this pass on real inputs yet, so the lane's fill +is unmeasured. The first staging build records it in `local_esi_premiums`. +That build's finalize is also the first grading of both gates at calibrated +weights: calibration reweights each household, so the anchor-universe total +and the ratio between the spines can move after staging, and these gates are +what hold them. + ## Gates | Gate | Where | Checks | |---|---|---| -| `us_esi_premiums_signal_gate` | base build, before and after the clone; release tool, on the base and on the calibrated export | Column present, finite, nonnegative and non-constant; support clones agree; the weighted share of people with a positive value is plausible; no employer premium outside the column universe or where the employer pays none; every premium is one common multiple of its MEPS-IC share. | -| `us_esi_premiums_anchor_gate` | release tool, on the calibrated export, for both the dense and the sparse default | The column absent or zero-mass is red. The anchor-universe total, recomputed at the release's weights, must be within **5%** of BEA NIPA 7.8 line 17 for the release period. Employed policyholders must carry 80% to 95% of it. | +| `us_esi_premiums_signal_gate` | base build, before and after the clone; release tool, on the base and on the calibrated export; ACS local lane, on the donor release, the staging frame and the calibrated artifact | Column present, finite, nonnegative and non-constant; support clones agree; the weighted share of people with a positive value is plausible; no employer premium outside the column universe or where the employer pays none; every premium is one common multiple of its MEPS-IC share. On a mixed frame (`allow_transferred_rows=True`) these proofs cover the rows with raw coverage columns; the other rows must carry the premium with a weighted positive share and mean within 0.5 to 2 times those rows'. | +| `us_esi_premiums_anchor_gate` | release tool, on the calibrated export, for both the dense and the sparse default; ACS local lane, on the staging frame and the calibrated artifact | The column absent or zero-mass is red. The anchor-universe total, recomputed at the release's weights, must be within **5%** of BEA NIPA 7.8 line 17 for the release period. Employed policyholders must carry 80% to 95% of it. On a mixed frame (`allow_transferred_rows=True`) the total adds the transferred column at the source-derived rows' employed share, and the transferred rows' column per unit of household mass must stay within 0.8 to 1.25 times the source-derived rows'. | | `us_release_input_coverage_gate` | release tool | The input is `required` with no reviewed exclusion, so an export that drops or flattens it fails. | | `assert_required_us_release_source_columns` | the L0/refit export (`l0_refit_export.export_us_l0_refit_h5`, run by `tools/export_us_l0_refit_h5.py`), unless `--allow-missing-source-columns` is passed | The column must be present and non-constant. | | reform-coverage smoke | release tool, on the written file | Neutralizing the employer premium must lower `cbo_household_market_income` by at least $500B. | @@ -316,6 +550,38 @@ What the gates need, and what they do not catch: cannot be certified. Published release files carry raw ASEC person fields today (`PEIO1COW`, `PHIP_VAL`, `WSAL_VAL`, `NOW_MCAID`); a release path that dropped the restored columns would turn both gates red. +- **A mixed frame is graded by row kind, only when the caller allows it.** + With `allow_transferred_rows=True`, which only the ACS local lane passes, + rows with every raw coverage column get the full recomputation. Rows with + none of them and no CPS record id (`PERIDNUM`) are the ones a transfer + filled; the gates compare them with the first kind and cannot check them + against MEPS-IC cells. Four things fail both gates: a row with only some of + the columns; a CPS record without them (lost coverage codes are never graded + as a transfer); a row with them but no record id, in a frame that has the id + column; and a row without them in a frame that has no id column. The signal + gate also fails when a transferred person's support clones disagree. When + the transferred rows hold no household mass, the gates skip the comparison + between the two kinds: there is no second half to compare. When the rows + with the raw columns hold no household mass, or their policyholders or + employed policyholders carry no weighted MEPS-IC share, or the employed + policyholders' part of it rounds to zero, there is nothing to price the + transferred rows against, and both gates fail with that refusal. Both also + fail, and name the term, when finite weights sum past the largest float: + the household mass of either kind of row or of both together, the + weighted employer premium of either kind or of both together, the + anchor-universe total formed from it, or, on the rows with the raw + columns, the weighted MEPS-IC share or the weight of the employed + policyholders with a positive share. When the + transferred rows hold household mass and the premium per unit of household + mass on the rows with the raw columns rounds to zero, the per-mass + comparison has no value and the anchor gate fails it. The anchor gate's + private-sector cross-check scales those rows' sector total by their share + of household mass. When that share rounds to zero, or the sector total or + the scaled total is not finite, the cross-check is recorded without a value + and its `unavailable` reason names which. Under the + default, which the base build and the release tool keep, every row must + carry every raw coverage column and the record id is not read (see "The + gates grade the lane's frame by row kind"). - **The raw-mean band catches unit errors only.** The signal gate requires the unscaled share per holder to sit between $6k and $20k, which catches a cell table in the wrong units. A cell table that is 20% low passes: the @@ -362,10 +628,20 @@ file. scaling to a national total there needs its own design. Until then the coverage and anchor gates are red on that lineage. The raw-stage operator boundary already refuses a source frame that carries the output. -- **ACS local releases.** An ACS spine pooled beside a donor that carries the - input has it null on its ACS rows. `fill_reviewed_nulls` refuses that frame - instead of default-filling it to zero, so this lineage does not build until - the input is assigned or transferred for every spine. +- **An ACS local release from an older donor.** The lane transfers the column + from its donor release. A donor built before the stage has nothing to + transfer, and the lane refuses it unless a diagnostic build waives the + gates. +- **ACS-native predictors for the fill.** The ACS local lane fills ACS rows + from the transfer's fixed predictors: age, sex and State, and wages, + self-employment income, Social Security, retirement and investment income, + household head and tenure where both sources observe them. It does not use + ACS's own employer-coverage (`HINS1`), class-of-worker (`COW`) or + employment-status (`ESR`) items. +- **A second verdict on the transferred rows' cells.** The gates recompute the + MEPS-IC assignment on the rows that carry the raw coverage columns. They + compare the transferred rows with those rows and cannot check them against + the cells. - **A calibration target.** The column is the employed part of the BEA fact, so the fact cannot be compiled as a sum target on it. The target-parity manifest keeps the BEA family and the two `cms_nhe` ESI families as @@ -376,6 +652,6 @@ file. refuses a frame whose column is absent or constant, and its generic input-mass parity check (default tolerance 50%) compares the column's weighted total with the base or reference, as for every input. Neither ESI - gate runs there: they run only in the base build and in - `tools/build_us_fiscal_refresh_release.py`. + gate runs in that export. The table under "Gates" lists where they run, + among them the ACS local lane's staging and finalize. - **The pre-tax employee premium.** See the section above. diff --git a/packages/microcosm-build/src/microcosm/build/us/gates.json b/packages/microcosm-build/src/microcosm/build/us/gates.json index f29eab7f52..9c8260ee29 100644 --- a/packages/microcosm-build/src/microcosm/build/us/gates.json +++ b/packages/microcosm-build/src/microcosm/build/us/gates.json @@ -2458,6 +2458,51 @@ }, "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_esi_premiums_signal", + "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 + ], + "transferred_to_source_band": [ + 0.5, + 2.0 + ] + }, + "notes": "US ACS local release (tools/build_us_acs_local_release.py): ESI employer premiums on the calibrated artifact, graded by row kind (allow_transferred_rows=True): the donor rows get the MEPS-IC checks and the ACS rows are compared with them (microcosm#454). Finalize collects it into gate_summary.json, writes the file, then raises on a hard failure unless --allow-esi-premium-gaps waives it." + }, + { + "id": "us_local_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 + ], + "transferred_per_mass_band": [ + 0.8, + 1.25 + ] + }, + "notes": "US ACS local release (tools/build_us_acs_local_release.py): the ESI employer premium's anchor-universe total against its national anchor at the calibrated weights, graded by row kind (allow_transferred_rows=True; microcosm#454). Finalize collects it into gate_summary.json, writes the file, then raises on a hard failure unless --allow-esi-premium-gaps waives it." + }, { "id": "us_local_reviewed_fill_consumers_finalize", "gate": "stage_health", diff --git a/packages/microcosm-build/src/microcosm/build/us_runtime/acs_local_esi_premiums.py b/packages/microcosm-build/src/microcosm/build/us_runtime/acs_local_esi_premiums.py new file mode 100644 index 0000000000..ff0352842b --- /dev/null +++ b/packages/microcosm-build/src/microcosm/build/us_runtime/acs_local_esi_premiums.py @@ -0,0 +1,581 @@ +"""Employer premiums on the ACS spine of the retained ACS local lane (#454). + +The lane's staging frame pools a dense ASEC-by-PUF donor release with the ACS +spine (:func:`~.base_pool.with_optional_acs_spine`). The donor carries +``employer_sponsored_insurance_premiums`` from the ``meps_esi_premiums`` stage. +ACS has no policyholder flag, payment status, coverage tier or firm size, so +the stage cannot run on its rows, and the declared ACS transfer plan does not +name the column. Three steps put it on every row, on the stage's scale: + +1. **Qualify the donor** (:func:`prepare_acs_local_esi_premium_donor`). The + donor must carry the column and the raw ASEC fields the stage read, and + pass the stage's own signal gate. The transfer then fits on its ASEC + observation role only (support clone 0), whose wages are the measured CPS + wages. The lane's other transfers fit on the PUF-detail role, whose wages + are PUF-imputed while its premium is a copy of the source person's: on + those rows the premium no longer follows the wage predictor. +2. **Transfer** the column onto the ACS rows with the lane's own one-family + plan (:func:`acs_local_esi_premium_transfer_target_families`). The declared + ACS plan and the shared pool plan are untouched; neither names the column. +3. **Anchor** the pooled frame (:func:`with_acs_local_esi_premium_anchor`) + with the mixed-frame kernel, + :func:`~.esi_premiums.with_us_esi_premium_pool_anchor`: it clears the + premium where the ACS person reports zero wages and scales the rest so both + spines carry the same weighted premium per unit of household mass. The + donor rows are never rewritten. + +The kernel tells the two kinds of row apart by the CPS record id +(``PERIDNUM``) and the raw ASEC fields, which the donor rows carry and the ACS +rows do not, as the ESI gates do with ``allow_transferred_rows=True``. Every +call this module makes to those gates passes it: the pooled frame holds +transferred rows by design. The kernel refuses a transferred row whose wage +is missing. ACS PUMS leaves ``WAGP`` blank below age 15, outside its earnings +universe, and the lane keeps that blank in the staging frame. The anchor +therefore reads those +people's wages as zero under the named universe rule of +:mod:`.acs_income_universe`, in its view of the frame only. A blank raw +``WAGP`` at age 15 or older is refused, however the mapped wage was filled. + +The kernel also resolves that rule itself +(:func:`~.acs_income_universe.resolve_acs_pums_earnings_universe`), but only +on rows whose support channel is ``"acs"``. This lane's ACS rows carry the +late spine's channel (``acs_2024_1yr``), so the kernel's check sees none of +them, and the lane applies the rule before calling it +(:func:`_wages_under_the_acs_universe`). + +Invariant: the lane-wide weighted column equals the donor rows' weighted +column divided by their share of household mass. Pooling multiplies every +donor household weight by that share, so the lane-wide column is the donor +release's own. + +The kernel and both gates read a handful of columns, but the kernel copies +every table it is given and each gate copies the person table. This module +hands them a narrow view of the pooled frame: the staging frame holds two full +spines, and the lane's memory budget has no room for further copies of them. +""" + +from __future__ import annotations + +import math +from collections.abc import Mapping +from typing import Any + +import numpy as np +import pandas as pd + +from microcosm.build.gates import GateResult +from microcosm.build.source_runtime import SourceRuntimeError +from microcosm.build.us_runtime.acs_income_universe import ( + ACS_PUMS_EARNINGS_MINIMUM_AGE, + ACS_PUMS_EARNINGS_SOURCE_COLUMNS, +) +from microcosm.build.us_runtime.acs_transfer import ( + TargetFamilies, + resolve_acs_donor_channel, +) +from microcosm.build.us_runtime.esi_premiums import ( + US_ESI_EMPLOYER_PREMIUM_COLUMN, + US_ESI_PREMIUMS_OUTPUT_COLUMNS, + US_ESI_PREMIUMS_POOL_ANCHOR_PERSON_INPUTS, + US_ESI_PREMIUMS_REQUIRED_SOURCE_COLUMNS, + US_ESI_PREMIUMS_WAGE_COLUMN, + _cps_record_evidence, + us_esi_premiums_anchor_gate, + us_esi_premiums_signal_gate, + with_us_esi_premium_pool_anchor, +) +from microcosm.build.us_runtime.support_provenance import ( + BASE_ASEC_SUPPORT_CHANNEL, + has_assembled_support_metadata, + has_support_role_metadata, + support_clone_index_column, + support_source_id_column, +) +from microcosm.frame import Frame +from microcosm.frame.units import US_SCHEMA + +__all__ = [ + "ACS_LOCAL_ESI_PREMIUM_FAMILY", + "acs_local_esi_premium_anchor_gate", + "acs_local_esi_premium_gate_payload", + "acs_local_esi_premium_gates", + "acs_local_esi_premium_signal_gate", + "acs_local_esi_premium_transfer_target_families", + "prepare_acs_local_esi_premium_donor", + "with_acs_local_esi_premium_anchor", +] + +#: The lane plan's family name. No other transfer plan names the premium: the +#: declared ACS plan and the shared pool plan +#: (``multispine_pool.pool_transfer_target_families``) carry no ESI family. +ACS_LOCAL_ESI_PREMIUM_FAMILY = "source_operator_esi_premiums" + +_PERSON = US_SCHEMA.person_entity +_STATE_COLUMN = "state_fips" +#: Raw ASEC person fields whose presence marks a row the stage derived itself. +_RAW_EVIDENCE_COLUMNS: tuple[str, ...] = tuple( + column + for column in US_ESI_PREMIUMS_REQUIRED_SOURCE_COLUMNS + if column != _STATE_COLUMN +) +#: The CPS record id. The kernel requires it beside the raw fields on every +#: row the stage derived, and blank on every transferred row. +_CPS_RECORD_ID_COLUMN = "PERIDNUM" +_CLONE_INDEX_COLUMN = support_clone_index_column(_PERSON) +_SOURCE_ID_COLUMN = support_source_id_column(_PERSON) +_AGE_COLUMN = "age" +#: The raw PUMS field the ACS wage is mapped from, and the named rule that +#: makes its blank a zero: the field applies to people aged 15 and older. +_ACS_WAGE_SOURCE_COLUMN = ACS_PUMS_EARNINGS_SOURCE_COLUMNS[US_ESI_PREMIUMS_WAGE_COLUMN] +_ACS_WAGE_UNIVERSE_RULE = ( + f"acs_2024_pums_{_ACS_WAGE_SOURCE_COLUMN.lower()}" + f"_age_{ACS_PUMS_EARNINGS_MINIMUM_AGE}_plus" +) +#: Person columns the pool anchor kernel reads, without the support source +#: id. Given both the source id and the clone index, the kernel looks a +#: clone's wages up by ``person_source_id`` across the whole frame, so it +#: needs that id unique there. This lane does not make it so: ACS rows keep +#: their pre-remap ids as source ids, which can repeat a donor's. Every ACS +#: row here is its own source record, so the view omits the source id and the +#: kernel reads each row's own wages. The clone index stays: the kernel's +#: ACS earnings universe requires it. +_ANCHOR_PERSON_COLUMNS: tuple[str, ...] = ( + *US_ESI_PREMIUMS_OUTPUT_COLUMNS, + *( + column + for column in US_ESI_PREMIUMS_POOL_ANCHOR_PERSON_INPUTS + if column != _SOURCE_ID_COLUMN + ), +) +#: Person columns the two ESI gates read: the output, the raw fields and +#: State the cells are recomputed from, the record id that settles each +#: row's kind, wages and support provenance for the transferred-row summary, +#: and the stable source identity the donor's clones are compared by. +_GATE_PERSON_COLUMNS: tuple[str, ...] = tuple( + dict.fromkeys( + ( + *US_ESI_PREMIUMS_OUTPUT_COLUMNS, + *US_ESI_PREMIUMS_REQUIRED_SOURCE_COLUMNS, + *US_ESI_PREMIUMS_POOL_ANCHOR_PERSON_INPUTS, + "source_year", + "source_household_id", + "source_person_id", + ) + ) +) +_GATE_HOUSEHOLD_COLUMNS: tuple[str, ...] = (_STATE_COLUMN,) + + +def acs_local_esi_premium_transfer_target_families() -> TargetFamilies: + """The lane's separate ASEC-only pass for the employer premium.""" + + return {_PERSON: {ACS_LOCAL_ESI_PREMIUM_FAMILY: US_ESI_PREMIUMS_OUTPUT_COLUMNS}} + + +def _narrow_view( + frame: Frame, + *, + person_columns: tuple[str, ...], + household_columns: tuple[str, ...] = (), + person_values: Mapping[str, np.ndarray] | None = None, +) -> Frame: + """The frame's structure and weights with only the named value columns. + + ``person_values`` replaces a person column in the view; the frame's own + column is not touched. + """ + + schema = frame.schema + tables: dict[str, pd.DataFrame] = {} + for entity in frame.entities: + table = frame.table(entity) + if entity == schema.person_entity: + keep = [ + schema.entity_id_column(entity), + *(schema.membership_column(group) for group in schema.group_entities), + *person_columns, + ] + else: + keep = [schema.entity_id_column(entity)] + if entity == "household": + keep.extend(household_columns) + present = list(dict.fromkeys(column for column in keep if column in table)) + tables[entity] = table.loc[:, present] + if person_values: + person = tables[schema.person_entity].copy(deep=False) + for column, values in person_values.items(): + person[column] = values + tables[schema.person_entity] = person + return Frame( + tables, + schema, + {entity: frame.weights_for(entity) for entity in frame.weighted_entities}, + frame.strata, + mass_log=frame.mass_log, + metadata=frame.metadata, + ) + + +def prepare_acs_local_esi_premium_donor( + frame: Frame, +) -> tuple[Frame, dict[str, object]]: + """Qualify the dense donor and select the rows the lane's transfer fits on. + + Refuses a donor that lacks the stage's output or the raw ASEC fields it + read, that has a row without every raw field or without a CPS record id, + that fails the stage's signal gate, or whose support roles cannot be told + apart. Returns the ASEC observation role (support clone 0) and a receipt. + The donor frame itself is not changed. + """ + + if frame.schema != US_SCHEMA: + raise ValueError("Local ESI premium donor requires the US schema.") + person = frame.table(_PERSON) + missing = [ + column + for column in (*US_ESI_PREMIUMS_OUTPUT_COLUMNS, *_RAW_EVIDENCE_COLUMNS) + if column not in person + ] + if missing: + raise ValueError( + f"Local ESI premium donor lacks {missing}: the donor release was " + "built without the meps_esi_premiums stage (microcosm#454). The " + "lane transfers the employer premium from a donor that carries it " + "and never defaults it." + ) + if _CPS_RECORD_ID_COLUMN not in person: + raise ValueError( + f"Local ESI premium donor lacks {_CPS_RECORD_ID_COLUMN!r}, the CPS " + "record id that marks its rows as the ones the stage derived. " + "Without it the pooled frame cannot tell them from the ACS rows." + ) + if US_ESI_PREMIUMS_WAGE_COLUMN not in person: + raise ValueError( + f"Local ESI premium donor lacks {US_ESI_PREMIUMS_WAGE_COLUMN!r}, the " + "wage the transfer conditions the premium on." + ) + if not has_support_role_metadata( + person, entity=_PERSON + ) or has_assembled_support_metadata(person, entity=_PERSON): + raise ValueError( + "Local ESI premium donor requires explicit legacy ASEC observation " + "roles; unclassified or multispine records need their own source " + "lineage." + ) + # Every donor row is a CPS record the stage derived its premium from, so + # it carries every raw field and a record id, refused here before any fit. + # The gate below grades by row kind, as it grades the pooled frame: a row + # that lost both would pass it as a transferred row, without a ratio check + # when its household holds no weight, and its observation role would + # still reach the fit. + complete = ( + person[list(_RAW_EVIDENCE_COLUMNS)].notna().all(axis=1).to_numpy(dtype=bool) + ) + recorded = _cps_record_evidence(person) + gaps = [ + f"{int(count)} row(s) {what}" + for count, what in ( + ((~complete).sum(), "without every raw ASEC field"), + ( + (~recorded).sum(), + f"without a CPS record id ({_CPS_RECORD_ID_COLUMN!r})", + ), + ) + if count + ] + if gaps: + raise ValueError( + f"Local ESI premium donor has {' and '.join(gaps)}. Every donor row " + "is a CPS record whose premium the stage derived, so it carries " + "both; the lane never fits the transfer on a row that lost them." + ) + gate = us_esi_premiums_signal_gate( + _narrow_view( + frame, + person_columns=_GATE_PERSON_COLUMNS, + household_columns=_GATE_HOUSEHOLD_COLUMNS, + ), + allow_transferred_rows=True, + ) + if not gate.passed: + raise ValueError( + "Local ESI premium donor fails the meps_esi_premiums signal gate: " + + "; ".join(gate.failures) + ) + donor, role = resolve_acs_donor_channel(frame, BASE_ASEC_SUPPORT_CHANNEL) + donor_person = donor.table(_PERSON) + employer = donor_person[US_ESI_EMPLOYER_PREMIUM_COLUMN].to_numpy(dtype=np.float64) + wages = pd.to_numeric( + donor_person[US_ESI_PREMIUMS_WAGE_COLUMN], errors="coerce" + ).to_numpy(dtype=np.float64, na_value=np.nan) + if not np.isfinite(wages).all(): + raise ValueError( + "Local ESI premium donor has ASEC observations with no " + f"{US_ESI_PREMIUMS_WAGE_COLUMN!r}; the transfer never treats a " + "missing wage as zero." + ) + weights = np.asarray(frame.resolve_weights(_PERSON).values, dtype=np.float64) + donor_weights = np.asarray(donor.resolve_weights(_PERSON).values, dtype=np.float64) + positive = employer > 0 + return donor, { + "producer": "meps_esi_premiums", + "donor_channel": role, + "donor_wage_column": US_ESI_PREMIUMS_WAGE_COLUMN, + "donor_wage_basis": "measured CPS ASEC wages of the observation role", + "donor_rows": int(frame.n(_PERSON)), + "asec_observation_rows": int(donor.n(_PERSON)), + "donor_employer_premium_total": float( + weights @ person[US_ESI_EMPLOYER_PREMIUM_COLUMN].to_numpy(dtype=np.float64) + ), + "asec_observation_positive_share": ( + float(donor_weights[positive].sum() / donor_weights.sum()) + if donor_weights.sum() + else 0.0 + ), + # The structural zero the transfer has to learn: how much of the + # observation role's premium mass sits on people with no measured + # wages (employed at interview, no wages in the income year). + "asec_observation_premium_share_without_wages": ( + float( + donor_weights[positive & ~(wages > 0)] + @ employer[positive & ~(wages > 0)] + ) + / float(donor_weights @ employer) + if float(donor_weights @ employer) + else 0.0 + ), + "donor_signal_gate": {"passed": True, "failures": []}, + } + + +def _wages_under_the_acs_universe( + person: pd.DataFrame, +) -> tuple[np.ndarray, dict[str, object]]: + """Wages for the anchor's view, under the ACS PUMS earnings universe. + + PUMS asks ``WAGP`` of people aged 15 and older and leaves it blank below. + The lane keeps that blank in the staging frame, and the anchor refuses a + missing wage, so a transferred row below the age floor whose raw field is + blank and whose mapped wage is null reads as a zero wage here, in the view + only. The rest of the rule is refused as + :func:`~.acs_income_universe.resolve_acs_pums_earnings_universe` refuses + it on rows with the ``"acs"`` support channel: + + - a blank raw field at 15 or older, or at an unknown age, is missing + evidence however a producer filled the mapped wage; + - below 15, a raw field that is not blank or a mapped wage that is + neither null nor zero is a mapping fault. + + Any other missing wage stays missing, and the kernel refuses it. + """ + + wages = pd.to_numeric( + person[US_ESI_PREMIUMS_WAGE_COLUMN], errors="coerce" + ).to_numpy(dtype=np.float64, na_value=np.nan) + transferred = person[list(_RAW_EVIDENCE_COLUMNS)].isna().all(axis=1).to_numpy() + age = pd.to_numeric(person[_AGE_COLUMN], errors="coerce").to_numpy( + dtype=np.float64, na_value=np.nan + ) + raw_blank = person[_ACS_WAGE_SOURCE_COLUMN].isna().to_numpy() + below = transferred & (age < ACS_PUMS_EARNINGS_MINIMUM_AGE) + # An unknown age is not evidence of being outside the universe. + eligible = transferred & ~below + unasked = eligible & raw_blank + if unasked.any(): + raise SourceRuntimeError( + f"Local ESI premium anchor: {int(unasked.sum())} transferred row(s) " + f"aged {ACS_PUMS_EARNINGS_MINIMUM_AGE} or older, or of unknown age, " + f"have a blank raw {_ACS_WAGE_SOURCE_COLUMN!r}, which PUMS asks of " + "them. A missing wage is not a zero wage, even after a producer " + "filled the mapped column." + ) + mapped_nonzero = np.isfinite(wages) & (wages != 0.0) + off_universe = below & (~raw_blank | mapped_nonzero) + if off_universe.any(): + raise SourceRuntimeError( + f"Local ESI premium anchor: {int(off_universe.sum())} transferred " + f"row(s) below age {ACS_PUMS_EARNINGS_MINIMUM_AGE} carry a raw " + f"{_ACS_WAGE_SOURCE_COLUMN!r} or a nonzero mapped wage. PUMS leaves " + "the field blank there, so this is a mapping fault, not the " + "universe rule." + ) + blank = transferred & np.isnan(wages) + outside = below & np.isnan(wages) + wages = np.where(outside, 0.0, wages) + return wages, { + "rule_id": _ACS_WAGE_UNIVERSE_RULE, + "minimum_age": ACS_PUMS_EARNINGS_MINIMUM_AGE, + "raw_source_column": _ACS_WAGE_SOURCE_COLUMN, + "eligible_transferred_rows": int(eligible.sum()), + "transferred_rows_below_minimum_age": int(below.sum()), + "transferred_rows_with_blank_wage": int(blank.sum()), + "transferred_rows_outside_universe_read_as_zero": int(outside.sum()), + # The staging frame keeps the source's blanks; the zeros exist in the + # anchor's view only. + "frame_cells_written": 0, + } + + +def with_acs_local_esi_premium_anchor(frame: Frame) -> tuple[Frame, dict[str, object]]: + """Hold the pooled lane frame's transferred premiums to the donor's scale. + + Runs :func:`~.esi_premiums.with_us_esi_premium_pool_anchor` on a narrow + view of ``frame`` and writes the anchored column back. Rows with the raw + ASEC fields (the donor spine) are never rewritten. On the other rows the + premium is cleared where the person reports zero wages and the rest is + scaled by one factor, so both spines carry the same weighted premium per + unit of household mass. A blank ACS wage below age 15 is a zero wage + (:func:`_wages_under_the_acs_universe`); any other missing wage is + refused. A frame already on that scale, or with no transferred row, is + returned unchanged. Returns the frame and the kernel's receipt. + """ + + if frame.schema != US_SCHEMA: + raise ValueError("Local ESI premium anchor requires the US schema.") + person = frame.table(_PERSON) + absent = [column for column in _ANCHOR_PERSON_COLUMNS if column not in person] + if absent: + raise SourceRuntimeError( + f"Local ESI premium anchor: the person table lacks {absent}; it " + "needs the transferred premium on every row, the raw ASEC fields " + "that mark the donor rows and the wages that place the structural " + "zeros." + ) + if _CLONE_INDEX_COLUMN in person: + transferred = person[list(_RAW_EVIDENCE_COLUMNS)].isna().all(axis=1) + clone_index = pd.to_numeric(person[_CLONE_INDEX_COLUMN], errors="coerce") + clones = transferred & ~clone_index.eq(0) + if clones.any(): + raise SourceRuntimeError( + f"Local ESI premium anchor: {int(clones.sum())} row(s) without " + "raw ASEC fields are not clone-0 source records. The lane reads " + "each transferred person's own wages; support clones of " + "transferred rows would need the kernel's lookup by a unique " + "'person_source_id', which this lane's ids are not." + ) + wages, wage_universe = _wages_under_the_acs_universe(person) + view = _narrow_view( + frame, + person_columns=_ANCHOR_PERSON_COLUMNS, + person_values={US_ESI_PREMIUMS_WAGE_COLUMN: wages}, + ) + anchored, receipt = with_us_esi_premium_pool_anchor(view) + receipt = dict(receipt) | { + "kernel": "with_us_esi_premium_pool_anchor", + "transferred_source_record": "each transferred row is its own source record", + "wage_universe": wage_universe, + # Why the kernel's own ACS earnings-universe receipt counts no rows. + "kernel_wage_evidence_scope": ( + "the kernel resolves the ACS earnings universe on rows with the " + "'acs' support channel; this lane's ACS rows carry the late " + "spine's, so wage_universe applies the rule" + ), + } + if anchored is view: + return frame, receipt + id_column = US_SCHEMA.entity_id_column(_PERSON) + anchored_person = anchored.table(_PERSON) + if not np.array_equal( + anchored_person[id_column].to_numpy(), person[id_column].to_numpy() + ): + raise SourceRuntimeError( + "Local ESI premium anchor: the kernel reordered the person table." + ) + tables = { + entity: (person.copy(deep=False) if entity == _PERSON else frame.table(entity)) + for entity in frame.entities + } + tables.update({name: frame.link(name) for name in frame.links}) + for column in US_ESI_PREMIUMS_OUTPUT_COLUMNS: + tables[_PERSON][column] = anchored_person[column].to_numpy(dtype=np.float64) + result = Frame( + tables, + frame.schema, + {entity: frame.weights_for(entity) for entity in frame.weighted_entities}, + frame.strata, + mass_log=frame.mass_log, + metadata=frame.metadata, + ) + return result, receipt + + +def _gate_view(frame: Frame) -> Frame: + return _narrow_view( + frame, + person_columns=_GATE_PERSON_COLUMNS, + household_columns=_GATE_HOUSEHOLD_COLUMNS, + ) + + +def acs_local_esi_premium_signal_gate(frame: Frame) -> GateResult: + """The ESI premium signal gate on a lane frame, graded by row kind. + + The donor rows, which carry the raw ASEC fields, get the full MEPS-IC + recomputation, and the ACS rows are compared with them + (``allow_transferred_rows=True``; Route A's callers keep the default, + which refuses a transferred row). It runs on a narrow view; the verdict + is that of the full frame. + """ + + return us_esi_premiums_signal_gate(_gate_view(frame), allow_transferred_rows=True) + + +def acs_local_esi_premium_anchor_gate(frame: Frame, *, time_period: int) -> GateResult: + """The ESI premium anchor gate on a lane frame, graded by row kind. + + As :func:`acs_local_esi_premium_signal_gate`, for the anchor-universe + total against the anchor for ``time_period``. + """ + + return us_esi_premiums_anchor_gate( + _gate_view(frame), time_period=time_period, allow_transferred_rows=True + ) + + +def acs_local_esi_premium_gates( + frame: Frame, *, time_period: int +) -> tuple[GateResult, GateResult]: + """Both ESI premium gates on a lane frame: ``(signal, anchor)``. + + The gates grade a pooled frame by row kind: the donor rows, which carry + the raw ASEC fields, get the full MEPS-IC recomputation, and the ACS rows + are compared with them (``allow_transferred_rows=True``; Route A's callers + keep the default, which refuses a transferred row). Each gate runs on its + own narrow view of the frame, with the same columns; the verdicts are + those of the full frame. The staging build calls this pair; the ACS local + release calls the two gates one by one, each beside its entry of the gate + battery's shadow (microcosm#1585 item 11). + """ + + return ( + acs_local_esi_premium_signal_gate(frame), + acs_local_esi_premium_anchor_gate(frame, time_period=time_period), + ) + + +def _strict_json(value: Any) -> Any: + if isinstance(value, Mapping): + return {str(key): _strict_json(item) for key, item in value.items()} + if isinstance(value, (list, tuple)): + return [_strict_json(item) for item in value] + if isinstance(value, np.generic): + return _strict_json(value.item()) + if isinstance(value, float) and not math.isfinite(value): + return None + return value + + +def acs_local_esi_premium_gate_payload(gate: GateResult) -> dict[str, object]: + """One gate verdict for a lane summary or gate report. + + Failures are kept verbatim, so a diagnostic build that waived them still + records what was red. Non-finite detail values become ``null``: the + staging summary is written as strict JSON. + """ + + return { + "name": gate.name, + "passed": bool(gate.passed), + "failures": list(gate.failures), + "details": _strict_json(dict(gate.details)), + } diff --git a/packages/microcosm-build/src/microcosm/build/us_runtime/acs_local_immigration.py b/packages/microcosm-build/src/microcosm/build/us_runtime/acs_local_immigration.py index 8d586b6427..c7960fa51c 100644 --- a/packages/microcosm-build/src/microcosm/build/us_runtime/acs_local_immigration.py +++ b/packages/microcosm-build/src/microcosm/build/us_runtime/acs_local_immigration.py @@ -54,16 +54,15 @@ runs long, and can clear the five-year bar early, for anyone who adjusted status after arriving: a person who arrived in 2014 and obtained qualified status in 2023 gets 10 modeled years in 2024 but has one qualifying year -(policyengine-us#9658). That matters for the policyengine-us 2.2.1 tests -that read the clock. The Medicaid immigration-status test (CHIP follows it, -because CHIP excludes Medicaid-eligible children) and Washington TANF read -it against a five-year bar, so the long clock can clear the bar early. -Washington RCA reads it the other way, as a window that closes -(``years_since_us_entry < window_years``), so the long clock can wrongly -exclude a recently qualified person from RCA. Under the statute the SNAP -five-year bar also runs from entry with -qualified status, but the pinned engine's federal SNAP status test reads -the status, not this clock, so any SNAP effect is indirect. The receipt's +(policyengine-us#9658). That matters for the policyengine-us 2.145.3 tests +that read the clock. SNAP's qualified-alien waiting period, the federal +Medicaid and CHIP immigration-status tests (CHIP also excludes +Medicaid-eligible children), Medicare Part B for permanent residents, +Washington TANF, Missouri and New Hampshire SSP, Nevada LIHEAP and Utah HEAT +read it against a bar, five years for SNAP and Medicaid, so the long clock +can clear the bar early. Washington RCA reads it the other way, as a window +that closes (``years_since_us_entry < window_years``), so the long clock can +wrongly exclude a recently qualified person from RCA. The receipt's ``adjustment_lag_sensitivity`` block reports the size of the affected group under each lag in :data:`ADJUSTMENT_LAG_YEARS` (one to ten, 15 and 20 years): the ACS weight assigned a status the bar applies to @@ -301,25 +300,26 @@ "status, so for a person who adjusted status after arriving the " "proxy runs long and can clear the bar early (arrival in 2014, " "status in 2023: 10 modeled years in 2024, one qualifying year; " - "policyengine-us#9658). That affects the policyengine-us 2.2.1 " - "tests that read the clock: Medicaid (CHIP follows it) and " - "Washington TANF read it against a five-year bar, so the long " - "clock can clear the bar early; Washington RCA reads it as a " - "window that closes (years_since_us_entry < window_years), so " - "the long clock can wrongly exclude a recently qualified person " - "from RCA. Under the statute the SNAP five-year " - "bar also runs from entry with qualified status, but the pinned " - "engine's federal SNAP status test reads the status, not this " - "clock, so any SNAP effect is indirect. adjustment_lag_sensitivity " + "policyengine-us#9658). That affects the policyengine-us 2.145.3 " + "tests that read the clock. SNAP's qualified-alien waiting period, " + "the federal Medicaid and CHIP immigration-status tests, Medicare " + "Part B for permanent residents, Washington TANF, Missouri and New " + "Hampshire SSP, Nevada LIHEAP and Utah HEAT read it against a bar, " + "five years for SNAP and Medicaid, so the long clock can clear the " + "bar early; Washington RCA reads it as a window that closes " + "(years_since_us_entry < window_years), so the long clock can " + "wrongly exclude a recently qualified person from RCA. " + "adjustment_lag_sensitivity " "reports the size of the affected group under each lag; the " "real-data check is microcosm#1093." ), "engine_readers": ( - "policyengine-us 2.2.1 reads the clock in the Medicaid " - "immigration-status test (CHIP follows it, because CHIP excludes " - "Medicaid-eligible children) and in Washington TANF, as a " - "five-year bar, and in Washington RCA, as a closing window; its " - "federal SNAP status test reads the status alone" + "policyengine-us 2.145.3 reads the clock in SNAP's qualified-alien " + "waiting period, the federal Medicaid and CHIP immigration-status " + "tests (CHIP also excludes Medicaid-eligible children), Medicare " + "Part B for permanent residents, Missouri and New Hampshire SSP, " + "Nevada LIHEAP and Utah HEAT, each as a bar, in Washington TANF, as " + "a five-year bar, and in Washington RCA, as a closing window" ), } diff --git a/packages/microcosm-build/src/microcosm/build/us_runtime/acs_local_reviewed_fill_consumers.py b/packages/microcosm-build/src/microcosm/build/us_runtime/acs_local_reviewed_fill_consumers.py index e4421bdaa5..194ce388dc 100644 --- a/packages/microcosm-build/src/microcosm/build/us_runtime/acs_local_reviewed_fill_consumers.py +++ b/packages/microcosm-build/src/microcosm/build/us_runtime/acs_local_reviewed_fill_consumers.py @@ -30,9 +30,11 @@ - :func:`means_tested_consumers` is the dependency walk the register's ``consumers`` lists come from. It takes any index with ``consumer_receipts`` (the engine-tier test passes - ``PolicyEngineUSVariableMetadataIndex``) and follows consumers from the - column until nothing new is reached, recording the programs whose roots it - meets. A column that is itself a root reaches its own program. + ``PolicyEngineUSVariableMetadataIndex(follow_helpers=True)``, so a read + inside one of the engine's helper functions is its calling variable's) and + follows consumers from the column until nothing new is reached, recording + the programs whose roots it meets. A column that is itself a root reaches + its own program. The module reads no origin tag: the manifests carry per-spine counts, and the register's ``spines`` lists are compared with them as plain labels. diff --git a/packages/microcosm-build/src/microcosm/build/us_runtime/acs_local_reviewed_fill_consumers.yaml b/packages/microcosm-build/src/microcosm/build/us_runtime/acs_local_reviewed_fill_consumers.yaml index 678ee0c408..9348a5495f 100644 --- a/packages/microcosm-build/src/microcosm/build/us_runtime/acs_local_reviewed_fill_consumers.yaml +++ b/packages/microcosm-build/src/microcosm/build/us_runtime/acs_local_reviewed_fill_consumers.yaml @@ -19,11 +19,12 @@ # standalone outputs. State income tax credits are out of scope. # - consumers: every program with a root the column reaches in the static # dependency graph of the pinned engine -# (PolicyEngineUSVariableMetadataIndex.consumer_receipts, walked from the -# column to its consumers until nothing new is reached). A column that is a -# root reaches its own program. The engine-tier test -# test_us_acs_local_reviewed_fill_consumers.py recomputes the walk and fails -# when a list here differs from it. +# (PolicyEngineUSVariableMetadataIndex.consumer_receipts with follow_helpers, +# so a read inside one of the engine's helper functions is its calling +# variable's, walked from the column to its consumers until nothing new is +# reached). A column that is a root reaches its own program. The engine-tier +# test test_us_acs_local_reviewed_fill_consumers.py recomputes the walk and +# fails when a list here differs from it. # - notes: each consumer is covered by exactly one note. verdict is harmless # when the default does not change the program's result on the filled rows, # or changes it only negligibly, and the note says why (the default is the @@ -33,7 +34,7 @@ # than the true value would give), understates or mixed. via names the # programs whose results carry an inherited effect. # - couplings: a program that reads another program's result inherits its bias. -# Medicaid and CHIP eligibility bar the PTC (pays_aca_premium) and Medicaid +# Medicaid and CHIP eligibility bar the PTC (is_aca_marketplace_enrollee) and Medicaid # eligibility bars CHIP (is_chip_eligible_child), so a Medicaid bias moves them # the opposite way; SSI and TANF are SNAP unearned income, and TANF receipt # confers SNAP categorical eligibility; Medicaid, SNAP and TANF receipt confer @@ -54,7 +55,7 @@ schema_version: 1 issue: "microcosm#1022" reviewed_against: - policyengine_us: "2.2.1" + policyengine_us: "2.145.3" programs: aca_ptc: label: "ACA premium tax credit" @@ -119,8 +120,9 @@ entries: One of five American opportunity credit (AOTC) conditions, all False on ACS rows because the ACS asks none of them, so no ACS student claims the AOTC and qualified tuition goes to the lifetime learning credit instead. - consumers: [aca_ptc, chip, ctc, general_assistance, lifeline, medicaid, - state_benefits, wic] + consumers: [aca_ptc, chip, ctc, eitc, general_assistance, head_start, + housing_assistance, lifeline, medicaid, school_meals, snap, ssi, state_benefits, + tanf, wic] notes: - programs: [ctc] verdict: known_bias @@ -143,6 +145,33 @@ entries: everything past it do not change. County general assistance subtracts income tax or payroll withholding from earnings (Santa Clara, Marin, Los Angeles), but its applicants owe almost none. + - programs: [head_start, school_meals, snap] + verdict: harmless + note: >- + Reached only through the filer flag, which a change in tax liability cannot + flip: only a unit already required to file has tax liability for these + deductions and credits to change (see the Medicaid note). + - programs: [eitc, housing_assistance, tanf] + verdict: harmless + note: >- + Reached only through the 2020-only charitable deduction for non-itemizers + (charitable_contributions_ald), which is 0 before it reads anything in any + other year, and the behavioral responses (labor_supply_behavioral_response and + capital_gains_behavioral_response, which read household_net_income, and the + labor-supply elasticities they gate), which return 0 before reading anything + in an engine pass without a reform; inert. + - programs: [ssi] + verdict: harmless + note: >- + Reached only through the 2020-only charitable deduction for non-itemizers + (charitable_contributions_ald), which is 0 before it reads anything in any + other year, and/or the contributed COLA means test + (social_security_cola_means_test_withheld), which is False unless + gov.contrib.ssa.benefit_levers.cola.means_test.enabled, and the behavioral + responses (labor_supply_behavioral_response and + capital_gains_behavioral_response, which read household_net_income, and the + labor-supply elasticities they gate), which return 0 before reading anything + in an engine pass without a reform; inert. - entity: person column: cps_race fill_value: "0" @@ -158,7 +187,7 @@ entries: fill_value: "0" spines: [acs_2024_1yr] rows: "every ACS person" - summary: "No policyengine-us 2.2.1 variable reads it." + summary: "No policyengine-us 2.145.3 variable reads it." consumers: [] notes: [] - entity: person @@ -169,23 +198,49 @@ entries: summary: >- Scholarships, grants and other educational assistance received; no ACS item isolates it. SNAP does not count it. - consumers: [general_assistance, school_meals, state_benefits, wic] + consumers: [aca_ptc, chip, ctc, eitc, general_assistance, head_start, + housing_assistance, lifeline, medicaid, school_meals, snap, ssi, state_benefits, + tanf, wic] notes: - - programs: [school_meals, wic] + - programs: [wic] verdict: known_bias direction: overstates note: >- - Both count educational assistance as income - (gov.usda.school_meals.income.sources, gov.usda.wic.income.sources). At 0, - families with a student receiving aid look slightly poorer, so eligibility is - slightly overstated. - - programs: [general_assistance, state_benefits] + WIC counts educational assistance as income (gov.usda.wic.income.sources). At + 0, families with a student receiving aid look slightly poorer, so eligibility + is slightly overstated. + - programs: [school_meals] + verdict: harmless + note: >- + School meals no longer count educational assistance + (gov.usda.school_meals.income.sources leaves it out, citing 20 U.S.C. 1087uu). + The only remaining static path runs from WIC receipt through California CARE's + electricity discount into Illinois AABD's utility allowance, which no + household can take: CARE is defined for California and the AABD utility + allowance for Illinois. + - programs: [general_assistance] verdict: known_bias direction: overstates note: >- Orange County and San Bernardino County general relief count it as unearned - income; California's CVRP increased rebate reads the school-meal income ratio - and CARE reads WIC receipt, so they inherit the same small overstatement. + income, so a student with aid looks slightly poorer. + - programs: [state_benefits] + verdict: harmless + note: >- + Its only state-benefit routes are California's CVRP, whose income test counts + it (ca_cvrp_countable_income), and California CARE, through WIC receipt. Both + pay nothing on these files: CVRP's rebate needs a purchased-vehicle amount + (ca_cvrp_vehicle_rebate_amount) and CARE's discounts an electricity or gas + expense, which no stage writes. + - programs: [aca_ptc, chip, ctc, eitc, head_start, housing_assistance, lifeline, + medicaid, snap, ssi, tanf] + verdict: harmless + note: >- + Reached only through the behavioral responses + (labor_supply_behavioral_response and capital_gains_behavioral_response, which + read household_net_income, and the labor-supply elasticities they gate), which + return 0 before reading anything in an engine pass without a reform, as every + release pass is; inert. - entity: person column: employment_income_before_lsr fill_value: "0" @@ -206,6 +261,46 @@ entries: 0 is the source-consistent value: WAGP is not asked below age 15, and the certified ASEC frame also carries an explicit zero there (acs_income_universe). + - entity: person + column: federal_parent_plus_loan_balance + fill_value: "0" + spines: [acs_2024_1yr] + rows: "every ACS person" + summary: >- + Federal Parent PLUS loan balance, which the national build imputes from the SCF + (scf_education_debt, microcosm#1073); the ACS asks no debt item. Read only by + the Parent PLUS and combined standard repayment payments + (parent_plus_standard_repayment_payment, parent_plus_standard_amortized_payment, + combined_standard_repayment_payment, tiered_standard_repayment_payment), which + reach no means-tested program. At 0, ACS parents carry no Parent PLUS debt. + consumers: [] + notes: [] + - entity: person + column: federal_student_loan_balance + fill_value: "0" + spines: [acs_2024_1yr] + rows: "every ACS person" + summary: >- + Federal student loan balance, which the national build imputes from the SCF + (scf_education_debt, microcosm#1073); the ACS asks no debt item. Read only by the + federal repayment plans (standard, tiered, income-based, income-contingent, PAYE, + SAVE and RAP payments, and income-driven eligibility), which reach no means-tested + program. At 0, ACS borrowers carry no federal student debt and every repayment + payment is 0. + consumers: [] + notes: [] + - entity: person + column: federal_student_loan_graduate_share + fill_value: "0" + spines: [acs_2024_1yr] + rows: "every ACS person" + summary: >- + Graduate share of the federal student loan balance (scf_education_debt, + microcosm#1073). Read only by save_plan_payment, which reaches no means-tested + program; inert while federal_student_loan_balance is the reviewed default 0 on + the same rows. + consumers: [] + notes: [] - entity: person column: fsla_overtime_premium fill_value: "0" @@ -215,8 +310,9 @@ entries: FLSA overtime premium, which the ACS does not separate from WAGP. Read by the federal overtime deduction (tax years 2025-2028, P.L. 119-21) and Georgia's overtime exclusion. - consumers: [aca_ptc, chip, ctc, general_assistance, lifeline, medicaid, - state_benefits, wic] + consumers: [aca_ptc, chip, ctc, eitc, general_assistance, head_start, + housing_assistance, lifeline, medicaid, school_meals, snap, ssi, state_benefits, + tanf, wic] notes: - programs: [ctc] verdict: known_bias @@ -240,6 +336,33 @@ entries: County general assistance subtracts income tax or payroll withholding from earnings (Santa Clara, Marin, Los Angeles), but its applicants owe almost none. + - programs: [head_start, school_meals, snap] + verdict: harmless + note: >- + Reached only through the filer flag, which a change in tax liability cannot + flip: only a unit already required to file has tax liability for these + deductions and credits to change (see the Medicaid note). + - programs: [eitc, housing_assistance, tanf] + verdict: harmless + note: >- + Reached only through the 2020-only charitable deduction for non-itemizers + (charitable_contributions_ald), which is 0 before it reads anything in any + other year, and the behavioral responses (labor_supply_behavioral_response and + capital_gains_behavioral_response, which read household_net_income, and the + labor-supply elasticities they gate), which return 0 before reading anything + in an engine pass without a reform; inert. + - programs: [ssi] + verdict: harmless + note: >- + Reached only through the 2020-only charitable deduction for non-itemizers + (charitable_contributions_ald), which is 0 before it reads anything in any + other year, and/or the contributed COLA means test + (social_security_cola_means_test_withheld), which is False unless + gov.contrib.ssa.benefit_levers.cola.means_test.enabled, and the behavioral + responses (labor_supply_behavioral_response and + capital_gains_behavioral_response, which read household_net_income, and the + labor-supply elasticities they gate), which return 0 before reading anything + in an engine pass without a reform; inert. - entity: person column: has_american_opportunity_credit_1098_t_or_exception fill_value: "False" @@ -249,8 +372,9 @@ entries: One of five American opportunity credit (AOTC) conditions, all False on ACS rows because the ACS asks none of them, so no ACS student claims the AOTC and qualified tuition goes to the lifetime learning credit instead. - consumers: [aca_ptc, chip, ctc, general_assistance, lifeline, medicaid, - state_benefits, wic] + consumers: [aca_ptc, chip, ctc, eitc, general_assistance, head_start, + housing_assistance, lifeline, medicaid, school_meals, snap, ssi, state_benefits, + tanf, wic] notes: - programs: [ctc] verdict: known_bias @@ -273,6 +397,33 @@ entries: everything past it do not change. County general assistance subtracts income tax or payroll withholding from earnings (Santa Clara, Marin, Los Angeles), but its applicants owe almost none. + - programs: [head_start, school_meals, snap] + verdict: harmless + note: >- + Reached only through the filer flag, which a change in tax liability cannot + flip: only a unit already required to file has tax liability for these + deductions and credits to change (see the Medicaid note). + - programs: [eitc, housing_assistance, tanf] + verdict: harmless + note: >- + Reached only through the 2020-only charitable deduction for non-itemizers + (charitable_contributions_ald), which is 0 before it reads anything in any + other year, and the behavioral responses (labor_supply_behavioral_response and + capital_gains_behavioral_response, which read household_net_income, and the + labor-supply elasticities they gate), which return 0 before reading anything + in an engine pass without a reform; inert. + - programs: [ssi] + verdict: harmless + note: >- + Reached only through the 2020-only charitable deduction for non-itemizers + (charitable_contributions_ald), which is 0 before it reads anything in any + other year, and/or the contributed COLA means test + (social_security_cola_means_test_withheld), which is False unless + gov.contrib.ssa.benefit_levers.cola.means_test.enabled, and the behavioral + responses (labor_supply_behavioral_response and + capital_gains_behavioral_response, which read household_net_income, and the + labor-supply elasticities they gate), which return 0 before reading anything + in an engine pass without a reform; inert. - entity: person column: has_american_opportunity_credit_institution_ein fill_value: "False" @@ -282,8 +433,9 @@ entries: One of five American opportunity credit (AOTC) conditions, all False on ACS rows because the ACS asks none of them, so no ACS student claims the AOTC and qualified tuition goes to the lifetime learning credit instead. - consumers: [aca_ptc, chip, ctc, general_assistance, lifeline, medicaid, - state_benefits, wic] + consumers: [aca_ptc, chip, ctc, eitc, general_assistance, head_start, + housing_assistance, lifeline, medicaid, school_meals, snap, ssi, state_benefits, + tanf, wic] notes: - programs: [ctc] verdict: known_bias @@ -306,6 +458,33 @@ entries: everything past it do not change. County general assistance subtracts income tax or payroll withholding from earnings (Santa Clara, Marin, Los Angeles), but its applicants owe almost none. + - programs: [head_start, school_meals, snap] + verdict: harmless + note: >- + Reached only through the filer flag, which a change in tax liability cannot + flip: only a unit already required to file has tax liability for these + deductions and credits to change (see the Medicaid note). + - programs: [eitc, housing_assistance, tanf] + verdict: harmless + note: >- + Reached only through the 2020-only charitable deduction for non-itemizers + (charitable_contributions_ald), which is 0 before it reads anything in any + other year, and the behavioral responses (labor_supply_behavioral_response and + capital_gains_behavioral_response, which read household_net_income, and the + labor-supply elasticities they gate), which return 0 before reading anything + in an engine pass without a reform; inert. + - programs: [ssi] + verdict: harmless + note: >- + Reached only through the 2020-only charitable deduction for non-itemizers + (charitable_contributions_ald), which is 0 before it reads anything in any + other year, and/or the contributed COLA means test + (social_security_cola_means_test_withheld), which is False unless + gov.contrib.ssa.benefit_levers.cola.means_test.enabled, and the behavioral + responses (labor_supply_behavioral_response and + capital_gains_behavioral_response, which read household_net_income, and the + labor-supply elasticities they gate), which return 0 before reading anything + in an engine pass without a reform; inert. - entity: person column: has_never_worked fill_value: "False" @@ -326,12 +505,13 @@ entries: A direct premium override. The statutory medical-expense aggregate (medical_expense_health_insurance_premiums) reads 0 as not supplied and uses the transferred health_insurance_premiums_without_medicare_part_b plus the modeled - Part B premium instead. The self-employed health insurance deduction, Missouri's - child care subsidy, Orange County general relief and a few state income taxes read - it directly. + Part B premium instead, and so does + medicaid_eligibility_health_insurance_premiums, which Medicaid's spend-down tests + read. The self-employed health insurance deduction, Missouri's child care subsidy, + Orange County general relief and a few state income taxes read it directly. consumers: [aca_ptc, chip, ctc, eitc, general_assistance, head_start, - housing_assistance, lifeline, medicaid, school_meals, snap, state_benefits, tanf, - wic] + housing_assistance, lifeline, medicaid, school_meals, snap, ssi, state_benefits, + tanf, wic] notes: - programs: [eitc, medicaid] verdict: known_bias @@ -348,7 +528,7 @@ entries: note: >- The same too-high MAGI lowers the PTC and CHIP eligibility directly, but it also lifts some people above the Medicaid limit, and Medicaid eligibility bars - both the PTC (pays_aca_premium) and CHIP (is_chip_eligible_child), so those + both the PTC (is_aca_marketplace_enrollee) and CHIP (is_chip_eligible_child), so those people gain PTC or CHIP eligibility instead. - programs: [lifeline, wic] verdict: known_bias @@ -363,8 +543,7 @@ entries: note: >- Missouri's child care subsidy deducts only these premiums from gross income (mo_ccs_adjusted_income) and Orange County general relief deducts them from - countable income, so at 0 both see slightly too much income; California's CVRP - reads AGI (above). + countable income, so at 0 both see slightly too much income. - programs: [ctc, head_start, housing_assistance, school_meals, snap, tanf] verdict: harmless note: >- @@ -374,13 +553,26 @@ entries: Missouri's smaller child care subsidy leaves slightly larger out-of-pocket child care for the SNAP, HUD and Missouri TANF child-care deductions and the CDCC ahead of the CTC; the CTC phases out only above $200,000 of AGI; Head - Start and school meals follow SNAP and TANF receipt. + Start follows SNAP and TANF receipt; school meals also count SSI state + supplements, which this column moves only through a spouse's Medicaid + enrollment (Colorado OAP and AND-CS) and Illinois income tax withholding on + AGI (Illinois AABD). + - programs: [ssi] + verdict: harmless + note: >- + Reached only through the contributed COLA means test + (social_security_cola_means_test_withheld), which is False unless + gov.contrib.ssa.benefit_levers.cola.means_test.enabled, and the behavioral + responses (labor_supply_behavioral_response and + capital_gains_behavioral_response, which read household_net_income, and the + labor-supply elasticities they gate), which return 0 before reading anything + in an engine pass without a reform; inert. - entity: person column: hourly_wage fill_value: "0" spines: [acs_2024_1yr] rows: "every ACS person" - summary: "No policyengine-us 2.2.1 variable reads it." + summary: "No policyengine-us 2.145.3 variable reads it." consumers: [] notes: [] - entity: person @@ -403,8 +595,9 @@ entries: One of five American opportunity credit (AOTC) conditions, all False on ACS rows because the ACS asks none of them, so no ACS student claims the AOTC and qualified tuition goes to the lifetime learning credit instead. - consumers: [aca_ptc, chip, ctc, general_assistance, lifeline, medicaid, - state_benefits, wic] + consumers: [aca_ptc, chip, ctc, eitc, general_assistance, head_start, + housing_assistance, lifeline, medicaid, school_meals, snap, ssi, state_benefits, + tanf, wic] notes: - programs: [ctc] verdict: known_bias @@ -427,6 +620,33 @@ entries: everything past it do not change. County general assistance subtracts income tax or payroll withholding from earnings (Santa Clara, Marin, Los Angeles), but its applicants owe almost none. + - programs: [head_start, school_meals, snap] + verdict: harmless + note: >- + Reached only through the filer flag, which a change in tax liability cannot + flip: only a unit already required to file has tax liability for these + deductions and credits to change (see the Medicaid note). + - programs: [eitc, housing_assistance, tanf] + verdict: harmless + note: >- + Reached only through the 2020-only charitable deduction for non-itemizers + (charitable_contributions_ald), which is 0 before it reads anything in any + other year, and the behavioral responses (labor_supply_behavioral_response and + capital_gains_behavioral_response, which read household_net_income, and the + labor-supply elasticities they gate), which return 0 before reading anything + in an engine pass without a reform; inert. + - programs: [ssi] + verdict: harmless + note: >- + Reached only through the 2020-only charitable deduction for non-itemizers + (charitable_contributions_ald), which is 0 before it reads anything in any + other year, and/or the contributed COLA means test + (social_security_cola_means_test_withheld), which is False unless + gov.contrib.ssa.benefit_levers.cola.means_test.enabled, and the behavioral + responses (labor_supply_behavioral_response and + capital_gains_behavioral_response, which read household_net_income, and the + labor-supply elasticities they gate), which return 0 before reading anything + in an engine pass without a reform; inert. - entity: person column: is_executive_administrative_professional fill_value: "False" @@ -460,25 +680,125 @@ entries: consumers: [] notes: [] - entity: person - column: is_military + column: is_income_based_repayment_new_borrower fill_value: "False" spines: [acs_2024_1yr] rows: "every ACS person" summary: >- - Read only by the FLSA overtime occupation category and the 2021 recovery rebate - credit's armed-forces exception, neither of which reaches a means-tested program - (ACS MIL == 1 could fill it natively). + Whether the borrower is a new borrower under Income-Based Repayment + (scf_education_debt, microcosm#1073). Read only by income_based_repayment_payment, + which reaches no means-tested program; inert while federal_student_loan_balance is + the reviewed default 0 on the same rows. consumers: [] notes: [] + - entity: person + column: is_military + fill_value: "False" + spines: [acs_2024_1yr] + rows: "every ACS person" + summary: >- + Active-duty status; ACS MIL == 1 could fill it natively. SNAP's five-year bar + exempts a military-connected qualified alien, their spouse and their dependent + children (is_snap_alien_military_connected); Missouri SSP's immigrant waiver, the + 2020-2021 recovery rebate credits' armed-forces exception, the FLSA overtime + occupation category, Indiana EAP and Utah HEAT read it too. + consumers: [aca_ptc, chip, ctc, eitc, general_assistance, head_start, + housing_assistance, lifeline, medicaid, school_meals, snap, ssi, state_benefits, + tanf, wic] + notes: + - programs: [snap] + verdict: known_bias + direction: mixed + note: >- + ACS active-duty members inside the five-year bar, and their spouses and + dependent children, lose the military-connected exception (8 U.S.C. + 1612(a)(2)(C), is_snap_alien_military_connected), so the bar excludes them. A + unit whose members are all inside the bar loses SNAP; in a unit that keeps an + exempt member, such as a child under 18, the barred adults' income is prorated + (7 CFR 273.11(c)(2)), which can raise or lower its allotment. + - programs: [lifeline] + verdict: known_bias + direction: understates + via: [snap] + note: >- + Only through SNAP receipt, which only a unit whose members are all inside the + bar loses, and only where it is the unit's only route: Lifeline's own income + test is 135% of FPG (150% in Texas). + - programs: [state_benefits] + verdict: harmless + note: >- + California CARE (categorical through CalFresh), Los Angeles EZ-SAVE and + Missouri SSP pay nothing on these files: CARE and EZ-SAVE need an electricity + expense, and Missouri SSP a living arrangement, which no stage writes. Its + other state-benefit routes run only through Medicaid enrollment, which the + Medicaid note below rules nil. + - programs: [head_start, school_meals, wic] + verdict: harmless + note: >- + A unit with a child keeps SNAP receipt through the child, whom the five-year + bar exempts under 18, so Head Start and school-meal categorical eligibility do + not change; WIC's 185% income test passes for any SNAP-income-eligible unit. + Missouri SSP's immigrant waiver needs a living arrangement no stage produces. + - programs: [aca_ptc, chip, medicaid] + verdict: harmless + note: >- + Only through SNAP's community-engagement pass-through, which applies from 2027 + (gov.hhs.medicaid.eligibility.work_requirements.applies), and the 2020-2021 + recovery rebate credits, whose maximums are 0 from 2022. The SNAP change + removes receipt only from a unit whose members are all inside the five-year + bar, and Medicaid's own five-year bar already excludes them (no military + exemption is modeled). CHIP reads Medicaid eligibility only for children and + pregnant people, whom the work requirement exempts; the PTC follows Medicaid. + - programs: [ctc, general_assistance] + verdict: harmless + note: >- + Only through the armed-forces exception of the 2020 and 2021 recovery rebate + credits, whose maximums are 0 from 2022. + - programs: [eitc, housing_assistance, tanf] + verdict: harmless + note: >- + Reached only through the 2020-only charitable deduction for non-itemizers + (charitable_contributions_ald), which is 0 before it reads anything in any + other year, and the behavioral responses (labor_supply_behavioral_response and + capital_gains_behavioral_response, which read household_net_income, and the + labor-supply elasticities they gate), which return 0 before reading anything + in an engine pass without a reform; inert. + - programs: [ssi] + verdict: harmless + note: >- + Reached only through the 2020-only charitable deduction for non-itemizers + (charitable_contributions_ald), which is 0 before it reads anything in any + other year, and/or the contributed COLA means test + (social_security_cola_means_test_withheld), which is False unless + gov.contrib.ssa.benefit_levers.cola.means_test.enabled, and the behavioral + responses (labor_supply_behavioral_response and + capital_gains_behavioral_response, which read household_net_income, and the + labor-supply elasticities they gate), which return 0 before reading anything + in an engine pass without a reform; inert. - entity: person column: is_paid_hourly fill_value: "False" spines: [acs_2024_1yr] rows: "every ACS person" summary: >- - Read only by is_eligible_for_fsla_overtime, which reaches no means-tested program. - consumers: [] - notes: [] + Read by is_eligible_for_fsla_overtime, which reaches no means-tested program, and + by Georgia's overtime exclusion (ga_qualified_overtime_exclusion), which reaches + means-tested programs only through household_net_income and the behavioral + responses. + consumers: [aca_ptc, chip, ctc, eitc, general_assistance, head_start, + housing_assistance, lifeline, medicaid, school_meals, snap, ssi, state_benefits, + tanf, wic] + notes: + - programs: [aca_ptc, chip, ctc, eitc, general_assistance, head_start, + housing_assistance, lifeline, medicaid, school_meals, snap, ssi, + state_benefits, tanf, wic] + verdict: harmless + note: >- + Reached only through the behavioral responses + (labor_supply_behavioral_response and capital_gains_behavioral_response, which + read household_net_income, and the labor-supply elasticities they gate), which + return 0 before reading anything in an engine pass without a reform, as every + release pass is; inert. - entity: person column: is_pursuing_credential_for_american_opportunity_credit fill_value: "False" @@ -488,8 +808,9 @@ entries: One of five American opportunity credit (AOTC) conditions, all False on ACS rows because the ACS asks none of them, so no ACS student claims the AOTC and qualified tuition goes to the lifetime learning credit instead. - consumers: [aca_ptc, chip, ctc, general_assistance, lifeline, medicaid, - state_benefits, wic] + consumers: [aca_ptc, chip, ctc, eitc, general_assistance, head_start, + housing_assistance, lifeline, medicaid, school_meals, snap, ssi, state_benefits, + tanf, wic] notes: - programs: [ctc] verdict: known_bias @@ -512,19 +833,47 @@ entries: everything past it do not change. County general assistance subtracts income tax or payroll withholding from earnings (Santa Clara, Marin, Los Angeles), but its applicants owe almost none. + - programs: [head_start, school_meals, snap] + verdict: harmless + note: >- + Reached only through the filer flag, which a change in tax liability cannot + flip: only a unit already required to file has tax liability for these + deductions and credits to change (see the Medicaid note). + - programs: [eitc, housing_assistance, tanf] + verdict: harmless + note: >- + Reached only through the 2020-only charitable deduction for non-itemizers + (charitable_contributions_ald), which is 0 before it reads anything in any + other year, and the behavioral responses (labor_supply_behavioral_response and + capital_gains_behavioral_response, which read household_net_income, and the + labor-supply elasticities they gate), which return 0 before reading anything + in an engine pass without a reform; inert. + - programs: [ssi] + verdict: harmless + note: >- + Reached only through the 2020-only charitable deduction for non-itemizers + (charitable_contributions_ald), which is 0 before it reads anything in any + other year, and/or the contributed COLA means test + (social_security_cola_means_test_withheld), which is False unless + gov.contrib.ssa.benefit_levers.cola.means_test.enabled, and the behavioral + responses (labor_supply_behavioral_response and + capital_gains_behavioral_response, which read household_net_income, and the + labor-supply elasticities they gate), which return 0 before reading anything + in an engine pass without a reform; inert. - entity: person column: is_self_employed fill_value: "False" spines: [acs_2024_1yr] rows: "every ACS person" summary: >- - Read only as the defined_for condition of self_employed_health_insurance_premiums, - the input to the self-employed health insurance deduction. ACS COW 6/7 could fill - it natively, but the deduction also needs health_insurance_premiums, which is 0 on - ACS rows. + Read only as the defined_for condition of self_employed_health_insurance_premiums + and self_employed_long_term_care_premiums, the inputs to the self-employed health + insurance deduction. ACS COW 6/7 could fill it natively, but the deduction also + needs health_insurance_premiums, which is 0 on ACS rows, or long-term care + premiums, which no stage produces. consumers: [aca_ptc, chip, ctc, eitc, general_assistance, head_start, - housing_assistance, lifeline, medicaid, school_meals, snap, state_benefits, tanf, - wic] + housing_assistance, lifeline, medicaid, school_meals, snap, ssi, state_benefits, + tanf, wic] notes: - programs: [eitc, medicaid] verdict: known_bias @@ -541,7 +890,7 @@ entries: note: >- The same too-high MAGI lowers the PTC and CHIP eligibility directly, but it also lifts some people above the Medicaid limit, and Medicaid eligibility bars - both the PTC (pays_aca_premium) and CHIP (is_chip_eligible_child), so those + both the PTC (is_aca_marketplace_enrollee) and CHIP (is_chip_eligible_child), so those people gain PTC or CHIP eligibility instead. - programs: [lifeline, wic] verdict: known_bias @@ -553,7 +902,10 @@ entries: - programs: [state_benefits] verdict: known_bias direction: understates - note: "California's CVRP income test reads AGI (above)." + note: >- + State programs reached through AGI or MAGI see too much income for + self-employed people who buy their own coverage; which of those routes move a + benefit is not reviewed yet (microcosm#1720). - programs: [ctc, general_assistance, head_start, housing_assistance, school_meals, snap, tanf] verdict: harmless @@ -562,7 +914,21 @@ entries: through Medicare IRMAA (AGI two years prior, above $103,000 for a single filer in 2024, far above their limits), the 2020-only unemployment exclusion (taxable_uc_agi) and South Carolina TANF's count of taxable Social Security; - the CTC phases out only above $200,000 of AGI. All negligible. + the CTC phases out only above $200,000 of AGI. All negligible. School meals + also count SSI state supplements: Illinois AABD deducts Illinois income tax + withholding, which reads AGI, and Colorado OAP and AND-CS read a spouse's + Medicaid enrollment, which the MAGI above moves; DC TANF reads filing status, + which a dependent's gross income can move. All second-order. + - programs: [ssi] + verdict: harmless + note: >- + Reached only through the contributed COLA means test + (social_security_cola_means_test_withheld), which is False unless + gov.contrib.ssa.benefit_levers.cola.means_test.enabled, and the behavioral + responses (labor_supply_behavioral_response and + capital_gains_behavioral_response, which read household_net_income, and the + labor-supply elasticities they gate), which return 0 before reading anything + in an engine pass without a reform; inert. - entity: person column: is_separated fill_value: "False" @@ -586,7 +952,7 @@ entries: Mostly overstated: separated ACS filers without a qualifying child file single instead of separately, so the PTC's separate-filer bar (is_aca_ptc_eligible) never applies to them. The Medicaid changes below move the PTC the other way - for some units, because Medicaid eligibility bars it (pays_aca_premium). + for some units, because Medicaid eligibility bars it (is_aca_marketplace_enrollee). - programs: [chip, ctc, eitc, general_assistance, housing_assistance, medicaid, snap, ssi, tanf] verdict: known_bias @@ -602,8 +968,11 @@ entries: - programs: [head_start, lifeline, school_meals, state_benefits, wic] verdict: known_bias direction: mixed - via: [medicaid, snap, tanf] - note: "Only through Medicaid, SNAP and TANF results." + via: [medicaid, snap, ssi, tanf] + note: >- + Only through Medicaid, SNAP, SSI and TANF results; the state supplements in + household_state_benefits and in school-meal income also apply SSI's spousal + rules to the same tax-unit roles. - entity: person column: is_surviving_spouse fill_value: "False" @@ -616,8 +985,8 @@ entries: two prior years, which ACS MARHW (widowed in the past 12 months) only approximates. consumers: [aca_ptc, chip, ctc, eitc, general_assistance, head_start, - housing_assistance, lifeline, medicaid, school_meals, snap, state_benefits, tanf, - wic] + housing_assistance, lifeline, medicaid, school_meals, snap, ssi, state_benefits, + tanf, wic] notes: - programs: [aca_ptc, chip, ctc, eitc, general_assistance, head_start, housing_assistance, lifeline, medicaid, school_meals, snap, state_benefits, @@ -630,13 +999,27 @@ entries: thresholds (above $103,000 for a single filer in 2024) or California's CVRP income caps (above $135,000), and surviving spouse versus head of household moves none of them. The CTC sees only the tax-liability difference, for the - few recently widowed parents whose liability limits it; negligible. + few recently widowed parents whose liability limits it; negligible. The one + exception is the filing threshold: a surviving spouse's is the joint one, so + as head of household a unit counts as required to file at a lower income, + which moves the filer flag, and Medicaid's non-filer rules, only for a + recently widowed parent with no earnings and no refundable credit; negligible. + - programs: [ssi] + verdict: harmless + note: >- + Reached only through the contributed COLA means test + (social_security_cola_means_test_withheld), which is False unless + gov.contrib.ssa.benefit_levers.cola.means_test.enabled, and the behavioral + responses (labor_supply_behavioral_response and + capital_gains_behavioral_response, which read household_net_income, and the + labor-supply elasticities they gate), which return 0 before reading anything + in an engine pass without a reform; inert. - entity: person column: is_union_member_or_covered fill_value: "False" spines: [acs_2024_1yr] rows: "every ACS person" - summary: "No policyengine-us 2.2.1 variable reads it." + summary: "No policyengine-us 2.145.3 variable reads it." consumers: [] notes: [] - entity: person @@ -661,8 +1044,9 @@ entries: noninstitutional ones (emergency and transitional shelters, group homes, workers' quarters), whose residents can pay for their shelter; 0 is right only for those who pay nothing. - consumers: [aca_ptc, chip, ctc, general_assistance, head_start, housing_assistance, - lifeline, medicaid, school_meals, snap, state_benefits, tanf, wic] + consumers: [aca_ptc, chip, ctc, eitc, general_assistance, head_start, + housing_assistance, lifeline, medicaid, school_meals, snap, ssi, state_benefits, + tanf, wic] notes: - programs: [snap] verdict: known_bias @@ -687,10 +1071,11 @@ entries: verdict: known_bias direction: understates note: >- - Conditional on paid shelter: Los Angeles and Riverside general relief and - Nebraska AABD's standard of need read housing costs, so they are too low for a - group-quarters resident who pays for shelter. - - programs: [head_start, lifeline, school_meals, wic] + Conditional on paid shelter: Los Angeles and Riverside general relief, + Nebraska AABD's standard of need and Connecticut SSP's shelter allowance read + housing costs or rent, so they are too low for a group-quarters resident who + pays for shelter. + - programs: [head_start, lifeline, wic] verdict: known_bias direction: understates via: [snap, tanf] @@ -699,6 +1084,17 @@ entries: own housing-cost adjustment (head_start_countable_income) applies only when head_start_applies_housing_cost_adjustment is set, which it is not on these rows. + - programs: [school_meals] + verdict: known_bias + direction: mixed + via: [snap, state_benefits, tanf] + note: >- + Through SNAP and TANF categorical eligibility, understated as above; and + through the Connecticut SSP, Nebraska AABD and Illinois AABD payments that + school meals count as income (Illinois AABD directly, since it is outside + state benefits), whose shelter allowances read rent (ct_ssp_shelter_allowance, + il_aabd_shelter_allowance, ne_aabd_standard_of_need), so at 0 a recipient's + school-meal income is too low. Both only for a group-quarters unit that holds a K-12 student. - programs: [medicaid] verdict: known_bias direction: understates @@ -711,28 +1107,54 @@ entries: meet the work requirement. - programs: [aca_ptc] verdict: known_bias - direction: overstates + direction: mixed via: [medicaid] note: >- - No effect for 2024. From 2027, the rare adult the Medicaid path above leaves - Medicaid-ineligible no longer has Medicaid eligibility barring the PTC - (pays_aca_premium). + No effect for 2024, and none in practice from 2027: an adult the Medicaid path + above leaves without Medicaid fails only the work requirement, which bars the + Marketplace too (is_medicaid_ineligible_due_to_work_requirement in + gov.aca.ineligible_coverage). Kept known_bias because REVIEWED_FILL_COUPLINGS + requires it wherever Medicaid is. - programs: [chip, ctc, housing_assistance] verdict: harmless note: >- - HUD assistance attaches to housing units, not group quarters, so 0 HUD gross - rent is the right value here (the renter-test overstatement is noted on - spm_unit_tenure_type). CHIP reads Medicaid eligibility only for children and - pregnant people, whom the Medicaid work requirement exempts. The CTC sees only - the tax chain (TANF in the state sales-tax deduction); negligible. + HUD assistance attaches to housing units, not group quarters, so any payment + to these units comes from the renter test (noted on spm_unit_tenure_type): + with pre_subsidy_rent 0, hud_gross_rent is the HUD utility allowance alone, + encoded only for Los Angeles County, the Texas TDHCA area and four Kansas + PHAs, and a true rent would only enlarge that payment. CHIP reads Medicaid + eligibility only for children and pregnant people, whom the Medicaid work + requirement exempts. The CTC sees only the tax chain (TANF in the state + sales-tax deduction); negligible. + - programs: [eitc] + verdict: harmless + note: >- + Reached only through the 2020-only charitable deduction for non-itemizers + (charitable_contributions_ald), which is 0 before it reads anything in any + other year, and the behavioral responses (labor_supply_behavioral_response and + capital_gains_behavioral_response, which read household_net_income, and the + labor-supply elasticities they gate), which return 0 before reading anything + in an engine pass without a reform; inert. + - programs: [ssi] + verdict: harmless + note: >- + Reached only through the 2020-only charitable deduction for non-itemizers + (charitable_contributions_ald), which is 0 before it reads anything in any + other year, and/or the contributed COLA means test + (social_security_cola_means_test_withheld), which is False unless + gov.contrib.ssa.benefit_levers.cola.means_test.enabled, and the behavioral + responses (labor_supply_behavioral_response and + capital_gains_behavioral_response, which read household_net_income, and the + labor-supply elasticities they gate), which return 0 before reading anything + in an engine pass without a reform; inert. - entity: person column: previous_year_income_available fill_value: "False" spines: [acs_2024_1yr] rows: "every ACS person" summary: >- - No policyengine-us 2.2.1 variable reads it; it is a provenance flag the prior-year - income gate reads. + No policyengine-us 2.145.3 variable reads it; it is a provenance flag the + prior-year income gate reads. consumers: [] notes: [] - entity: person @@ -745,8 +1167,9 @@ entries: summary: >- Native TAXAMT on the reference person of owner-occupied units; TAXAMT is blank for every other household, whose members keep the default. - consumers: [aca_ptc, chip, ctc, general_assistance, head_start, housing_assistance, - lifeline, medicaid, school_meals, snap, state_benefits, tanf, wic] + consumers: [aca_ptc, chip, ctc, eitc, general_assistance, head_start, + housing_assistance, lifeline, medicaid, school_meals, snap, ssi, state_benefits, + tanf, wic] notes: - programs: [aca_ptc, chip, ctc, general_assistance, head_start, housing_assistance, lifeline, medicaid, school_meals, snap, state_benefits, @@ -755,8 +1178,30 @@ entries: note: >- The filled households own no home, so they pay no property tax directly and 0 is the right value for SNAP's shelter costs, the TANF shelter allowances, Head - Start and school-meal housing costs, state property-tax relief (which reads - rent for renters) and itemized deductions. + Start housing costs, the Illinois and Nebraska AABD shelter allowances that + school meals count, state property-tax relief (which reads rent for renters) + and itemized deductions. + - programs: [eitc] + verdict: harmless + note: >- + Reached only through the 2020-only charitable deduction for non-itemizers + (charitable_contributions_ald), which is 0 before it reads anything in any + other year, and the behavioral responses (labor_supply_behavioral_response and + capital_gains_behavioral_response, which read household_net_income, and the + labor-supply elasticities they gate), which return 0 before reading anything + in an engine pass without a reform; inert. + - programs: [ssi] + verdict: harmless + note: >- + Reached only through the 2020-only charitable deduction for non-itemizers + (charitable_contributions_ald), which is 0 before it reads anything in any + other year, and/or the contributed COLA means test + (social_security_cola_means_test_withheld), which is False unless + gov.contrib.ssa.benefit_levers.cola.means_test.enabled, and the behavioral + responses (labor_supply_behavioral_response and + capital_gains_behavioral_response, which read household_net_income, and the + labor-supply elasticities they gate), which return 0 before reading anything + in an engine pass without a reform; inert. - entity: person column: roth_401k_contributions_desired fill_value: "0" @@ -767,8 +1212,8 @@ entries: deferrals do not reduce AGI; they share the 402(g) scale with traditional deferrals (also 0 on ACS rows) and count for the saver's credit. consumers: [aca_ptc, chip, ctc, eitc, general_assistance, head_start, - housing_assistance, lifeline, medicaid, school_meals, snap, state_benefits, tanf, - wic] + housing_assistance, lifeline, medicaid, school_meals, snap, ssi, state_benefits, + tanf, wic] notes: - programs: [ctc] verdict: known_bias @@ -784,7 +1229,20 @@ entries: Roth deferrals do not reduce AGI or MAGI, and the 402(g) scale is inert while traditional deferrals are also 0 on ACS rows. The saver's credit reaches these programs only through the tax-liability chain, which cannot flip the filer - flag of a unit not already required to file. + flag of a unit not already required to file. Roth deferrals to an employer + plan also leave less room for a self-employed person's own plan deduction + (self_employed_pension_contribution_limit), which binds only for self-employed + savers contributing at the limit; negligible. + - programs: [ssi] + verdict: harmless + note: >- + Reached only through the contributed COLA means test + (social_security_cola_means_test_withheld), which is False unless + gov.contrib.ssa.benefit_levers.cola.means_test.enabled, and the behavioral + responses (labor_supply_behavioral_response and + capital_gains_behavioral_response, which read household_net_income, and the + labor-supply elasticities they gate), which return 0 before reading anything + in an engine pass without a reform; inert. - entity: person column: roth_ira_contributions_desired fill_value: "0" @@ -796,8 +1254,8 @@ entries: transferred traditional IRA contributions (ira_contribution_scale) and count for the saver's credit. consumers: [aca_ptc, chip, ctc, eitc, general_assistance, head_start, - housing_assistance, lifeline, medicaid, school_meals, snap, state_benefits, tanf, - wic] + housing_assistance, lifeline, medicaid, school_meals, snap, ssi, state_benefits, + tanf, wic] notes: - programs: [ctc] verdict: known_bias @@ -816,6 +1274,16 @@ entries: contributions exceed it ($7,000 in 2024), rare at these programs' incomes; the saver's credit reaches them only through the tax-liability chain, which cannot flip the filer flag of a unit not already required to file. + - programs: [ssi] + verdict: harmless + note: >- + Reached only through the contributed COLA means test + (social_security_cola_means_test_withheld), which is False unless + gov.contrib.ssa.benefit_levers.cola.means_test.enabled, and the behavioral + responses (labor_supply_behavioral_response and + capital_gains_behavioral_response, which read household_net_income, and the + labor-supply elasticities they gate), which return 0 before reading anything + in an engine pass without a reform; inert. - entity: person column: s_corp_income fill_value: "0" @@ -827,8 +1295,8 @@ entries: pass-through profit is missing on ACS rows. SNAP's income sources do not include it. consumers: [aca_ptc, chip, ctc, eitc, general_assistance, head_start, - housing_assistance, lifeline, medicaid, school_meals, snap, state_benefits, tanf, - wic] + housing_assistance, lifeline, medicaid, school_meals, snap, ssi, state_benefits, + tanf, wic] notes: - programs: [ctc, eitc, housing_assistance, lifeline, medicaid, state_benefits, tanf] @@ -837,10 +1305,9 @@ entries: note: >- It counts in MAGI, AGI (the EITC and CTC phase-outs), HUD unearned income, IRS gross income (Lifeline), South Carolina TANF unearned income and several state - benefits' income (California CARE and FERA, New Jersey, child care in - Massachusetts, Oklahoma and Wisconsin), so owners' incomes are understated and - eligibility overstated. S corporation owners are rarely in these programs' - income ranges. + benefits' income (New Jersey, child care in Massachusetts, Oklahoma and + Wisconsin), so owners' incomes are understated and eligibility overstated. S + corporation owners are rarely in these programs' income ranges. - programs: [aca_ptc, chip] verdict: known_bias direction: mixed @@ -848,7 +1315,7 @@ entries: note: >- Understated MAGI raises the PTC and CHIP eligibility directly, but it also brings some owners' households under the Medicaid limit, and Medicaid - eligibility bars both the PTC (pays_aca_premium) and CHIP + eligibility bars both the PTC (is_aca_marketplace_enrollee) and CHIP (is_chip_eligible_child), so those households lose PTC or CHIP eligibility instead. - programs: [snap] @@ -859,13 +1326,21 @@ entries: SNAP does not count S corporation income; only through South Carolina TANF (sc_tanf): more TANF cash is SNAP unearned income, and TANF receipt confers SNAP categorical eligibility. - - programs: [head_start, school_meals] + - programs: [head_start] verdict: known_bias direction: overstates via: [tanf] note: >- - They do not count S corporation income; only through South Carolina TANF + It does not count S corporation income; only through South Carolina TANF receipt, which confers categorical eligibility. + - programs: [school_meals] + verdict: known_bias + direction: overstates + note: >- + School meals count each person's S corporation income, a net loss as zero + (partnership_s_corp_income in gov.usda.school_meals.income.business_sources), + so owners' school-meal income is understated and eligibility overstated; S + corporation owners are rarely in these income ranges. - programs: [wic] verdict: known_bias direction: overstates @@ -879,6 +1354,16 @@ entries: It does not count S corporation income. Its static paths run through Medicare IRMAA, TANF and child-care subsidy results and income tax withholding; negligible. + - programs: [ssi] + verdict: harmless + note: >- + Reached only through the contributed COLA means test + (social_security_cola_means_test_withheld), which is False unless + gov.contrib.ssa.benefit_levers.cola.means_test.enabled, and the behavioral + responses (labor_supply_behavioral_response and + capital_gains_behavioral_response, which read household_net_income, and the + labor-supply elasticities they gate), which return 0 before reading anything + in an engine pass without a reform; inert. - entity: person column: self_employment_income_before_lsr fill_value: "0" @@ -916,10 +1401,50 @@ entries: ACS persons under 15 (outside the SSIP universe) and donor-spine persons without a reported amount summary: >- - Read only by applicable_ssi, which policyengine-us 2.2.1 documents as deprecated: - no program reads it, and programs count ssi directly (policyengine-us#9111). + Read only by applicable_ssi, which policyengine-us 2.145.3 documents as + deprecated: no program reads it, and programs count ssi directly + (policyengine-us#9111). consumers: [] notes: [] + - entity: person + column: strike_benefits + fill_value: "0" + spines: [acs_2024_1yr] + rows: "every ACS person" + summary: >- + Strike benefits (ASEC other-income code 12). The ACS asks no separate item: OIP is + one combined amount. Neither the shared plan nor the local income pass transfers + the column; the donor carries it only as a component of the OIP predictor analog + (ACS_LOCAL_OTHER_INCOME_DONOR_COMPONENTS). No respondent in the pinned public ASEC + person files reports code 12, so every donor-spine value is 0 too + (microcosm#922). + consumers: [aca_ptc, chip, ctc, eitc, general_assistance, head_start, + housing_assistance, lifeline, medicaid, school_meals, snap, ssi, state_benefits, + tanf, wic] + notes: + - programs: [aca_ptc, chip, ctc, eitc, general_assistance, head_start, + housing_assistance, lifeline, medicaid, school_meals, snap, state_benefits, + tanf, wic] + verdict: harmless + note: >- + 0 is the value the donor gives every person: no pinned ASEC respondent reports + strike benefits, so a QRF transfer from the donor would also draw 0 on these + rows. Federal tax counts them through taxable_strike_benefits (gross income, + AGI, EITC earned income, the filing requirement), and HUD unearned income, + school-meal and WIC income, Missouri and Texas TANF unearned income, Marin and + San Bernardino general relief and several state programs count them directly; + the fill differs from the true value only for ACS respondents whose OIP + includes strike pay, which no pinned ASEC year observes. + - programs: [ssi] + verdict: harmless + note: >- + Reached only through the contributed COLA means test + (social_security_cola_means_test_withheld), which is False unless + gov.contrib.ssa.benefit_levers.cola.means_test.enabled, and the behavioral + responses (labor_supply_behavioral_response and + capital_gains_behavioral_response, which read household_net_income, and the + labor-supply elasticities they gate), which return 0 before reading anything + in an engine pass without a reform; inert. - entity: person column: tip_income fill_value: "0" @@ -928,10 +1453,11 @@ entries: summary: >- Tips, which ACS WAGP already includes and does not separate. Read by the federal tip deduction (tax years 2025-2028, P.L. 119-21), Florida School Readiness income - (from October 2025), Georgia's cash tip exclusion and Washington's long-term care - wage base. - consumers: [aca_ptc, chip, ctc, general_assistance, head_start, housing_assistance, - lifeline, medicaid, school_meals, snap, state_benefits, tanf, wic] + (from October 2025), Georgia's cash tip exclusion, Hawaii's tip deduction and + Washington's long-term care wage base. + consumers: [aca_ptc, chip, ctc, eitc, general_assistance, head_start, + housing_assistance, lifeline, medicaid, school_meals, snap, ssi, state_benefits, + tanf, wic] notes: - programs: [ctc] verdict: known_bias @@ -956,6 +1482,27 @@ entries: County general assistance subtracts income tax or payroll withholding from earnings (Santa Clara, Marin, Los Angeles), but its applicants owe almost none. + - programs: [eitc] + verdict: harmless + note: >- + Reached only through the 2020-only charitable deduction for non-itemizers + (charitable_contributions_ald), which is 0 before it reads anything in any + other year, and the behavioral responses (labor_supply_behavioral_response and + capital_gains_behavioral_response, which read household_net_income, and the + labor-supply elasticities they gate), which return 0 before reading anything + in an engine pass without a reform; inert. + - programs: [ssi] + verdict: harmless + note: >- + Reached only through the 2020-only charitable deduction for non-itemizers + (charitable_contributions_ald), which is 0 before it reads anything in any + other year, and/or the contributed COLA means test + (social_security_cola_means_test_withheld), which is False unless + gov.contrib.ssa.benefit_levers.cola.means_test.enabled, and the behavioral + responses (labor_supply_behavioral_response and + capital_gains_behavioral_response, which read household_net_income, and the + labor-supply elasticities they gate), which return 0 before reading anything + in an engine pass without a reform; inert. - entity: person column: traditional_401k_contributions_desired fill_value: "0" @@ -966,17 +1513,18 @@ entries: and WAGP is gross of deferrals. At 0, irs_employment_income, AGI and MAGI include wages that savers defer. consumers: [aca_ptc, chip, ctc, eitc, general_assistance, head_start, - housing_assistance, lifeline, medicaid, school_meals, snap, state_benefits, tanf, - wic] + housing_assistance, lifeline, medicaid, school_meals, snap, ssi, state_benefits, + tanf, wic] notes: - programs: [eitc, lifeline, medicaid, state_benefits] verdict: known_bias direction: understates note: >- - MAGI (Medicaid), AGI (the EITC phase-out, California's CVRP) and IRS gross - income (Lifeline, Los Angeles EZ Save) are too high for workers who defer - wages, so their eligibility and amounts are understated. EITC earned income is - gross of deferrals, so only the phase-out moves. + MAGI (Medicaid), AGI (the EITC phase-out) and IRS gross income (Lifeline) are + too high for workers who defer wages, so their eligibility and amounts are + understated. EITC earned income is gross of deferrals, so only the phase-out + moves. State programs reached through those measures see the same; which of + their routes move a benefit is not reviewed yet (microcosm#1720). - programs: [aca_ptc, chip] verdict: known_bias direction: mixed @@ -984,7 +1532,7 @@ entries: note: >- Too-high MAGI lowers the PTC and CHIP eligibility directly, but it also lifts some workers' households above the Medicaid limit, and Medicaid eligibility - bars both the PTC (pays_aca_premium) and CHIP (is_chip_eligible_child), so + bars both the PTC (is_aca_marketplace_enrollee) and CHIP (is_chip_eligible_child), so those households gain PTC or CHIP eligibility instead. - programs: [ctc] verdict: known_bias @@ -1006,6 +1554,21 @@ entries: 2024), the 2020-only unemployment exclusion and South Carolina TANF's count of taxable Social Security; Los Angeles General Relief reads irs_employment_income, but its applicants rarely defer wages. All negligible. + School meals also count SSI state supplements: Illinois AABD deducts Illinois + income tax withholding, which reads AGI, and Colorado OAP and AND-CS read a + spouse's Medicaid enrollment, which Medicaid's filing test on + irs_employment_income moves; DC TANF reads filing status, which a dependent's + gross income can move. All second-order. + - programs: [ssi] + verdict: harmless + note: >- + Reached only through the contributed COLA means test + (social_security_cola_means_test_withheld), which is False unless + gov.contrib.ssa.benefit_levers.cola.means_test.enabled, and the behavioral + responses (labor_supply_behavioral_response and + capital_gains_behavioral_response, which read household_net_income, and the + labor-supply elasticities they gate), which return 0 before reading anything + in an engine pass without a reform; inert. - entity: person column: treasury_tipped_occupation_code fill_value: "0" @@ -1014,35 +1577,159 @@ entries: summary: >- Treasury tipped-occupation code for the tip deduction (tax years 2025-2028); ACS OCCP is not mapped to it. - consumers: [aca_ptc, chip, ctc, general_assistance, lifeline, medicaid, - state_benefits, wic] + consumers: [aca_ptc, chip, ctc, eitc, general_assistance, head_start, + housing_assistance, lifeline, medicaid, school_meals, snap, ssi, state_benefits, + tanf, wic] notes: - - programs: [aca_ptc, chip, ctc, general_assistance, lifeline, medicaid, - state_benefits, wic] + - programs: [aca_ptc, chip, ctc, general_assistance, head_start, lifeline, + medicaid, school_meals, snap, state_benefits, wic] verdict: harmless note: >- Inert while tip_income is the reviewed default 0 on the same rows: without - tips the tip deduction is zero whatever the occupation. Revisit if tip_income - is filled. + tips the federal tip deduction, Georgia's cash tip exclusion and Hawaii's tip + deduction are zero whatever the occupation. Revisit if tip_income is filled. + - programs: [eitc, housing_assistance, tanf] + verdict: harmless + note: >- + Reached only through the 2020-only charitable deduction for non-itemizers + (charitable_contributions_ald), which is 0 before it reads anything in any + other year, and the behavioral responses (labor_supply_behavioral_response and + capital_gains_behavioral_response, which read household_net_income, and the + labor-supply elasticities they gate), which return 0 before reading anything + in an engine pass without a reform; inert. + - programs: [ssi] + verdict: harmless + note: >- + Reached only through the 2020-only charitable deduction for non-itemizers + (charitable_contributions_ald), which is 0 before it reads anything in any + other year, and/or the contributed COLA means test + (social_security_cola_means_test_withheld), which is False unless + gov.contrib.ssa.benefit_levers.cola.means_test.enabled, and the behavioral + responses (labor_supply_behavioral_response and + capital_gains_behavioral_response, which read household_net_income, and the + labor-supply elasticities they gate), which return 0 before reading anything + in an engine pass without a reform; inert. - entity: person column: weeks_unemployed fill_value: "0" spines: [acs_2024_1yr] rows: "every ACS person" summary: >- - Read only by the Alabama, New York, Oklahoma and Pennsylvania unemployment benefit - calculators, which feed no means-tested program. SNAP's work-registration test - reads unemployment_compensation > 0, not weeks. - consumers: [] - notes: [] + Weeks of unemployment; the ACS asks none. They set the months of UC receipt + (unemployment_compensation_months, 12 when weeks are 0 and UC is positive), which + exempt a recipient from SNAP work registration and so from the ABAWD time limit, + and they feed the Alabama, New York, Oklahoma and Pennsylvania unemployment + benefit calculators, whose claim-wage inputs no stage produces. + consumers: [aca_ptc, chip, ctc, eitc, general_assistance, head_start, + housing_assistance, lifeline, medicaid, school_meals, snap, ssi, state_benefits, + tanf, wic] + notes: + - programs: [snap] + verdict: known_bias + direction: overstates + note: >- + With weeks 0 a UC recipient is exempt from SNAP work registration, and so from + the ABAWD time limit, in all 12 months; with true weeks only in the months of + receipt. In 2024 that frees ABAWD-age adults (18 to 52, 18 to 54 from October + 2024) with no household member under 18 (under 14 from 2025-07-04), working + under 20 hours a week, outside waived areas. + - programs: [medicaid] + verdict: known_bias + direction: understates + note: >- + No effect for 2024. From 2027 Medicaid's work requirement applies + (gov.hhs.medicaid.eligibility.work_requirements.applies), and its SNAP + community-engagement pass-through needs a SNAP recipient who is subject to a + SNAP work requirement. With weeks 0 a UC recipient is exempt from SNAP work + registration in every month, so loses the pass-through; the fill never adds + one. + - programs: [aca_ptc] + verdict: known_bias + direction: mixed + via: [medicaid] + note: >- + No effect for 2024, and none in practice from 2027: an adult the Medicaid path + above leaves without Medicaid fails only the work requirement, which bars the + Marketplace too (is_medicaid_ineligible_due_to_work_requirement in + gov.aca.ineligible_coverage), and the requirement binds only below its income + test, under the PTC's income floor. Kept known_bias because + REVIEWED_FILL_COUPLINGS requires it wherever Medicaid is. + - programs: [head_start, lifeline, school_meals, state_benefits, wic] + verdict: harmless + note: >- + The ABAWD time limit skips SNAP units with a member under 18 (14 from + 2025-07-04) or a pregnant member, so it never reaches the units Head Start and + WIC serve. Lifeline, California CARE (through CalFresh) and school meals read + SNAP receipt over the year, which the months of receipt keep. From 2027 the + Medicaid change reaches only SNAP recipients, who keep Lifeline through SNAP, + and adults outside WIC's categories; CVRP's increased rebate has its own + income test, and school meals read Medicaid enrollment only second-order, + through state supplements. + - programs: [chip] + verdict: harmless + note: >- + Only through Medicaid eligibility, for children and pregnant people, whom the + Medicaid work requirement exempts, and through the modeled state UI programs, + whose claim-wage inputs no stage produces. + - programs: [ctc, eitc, general_assistance, housing_assistance, ssi, tanf] + verdict: harmless + note: >- + Reached only through the modeled state UI programs + (gov.states.household.modeled_state_unemployment_compensation), whose monetary + eligibility needs base-period and quarterly wage inputs that default to 0 and + no stage produces (test_us_weeks_unemployed.py), so they pay nothing on ACS + rows; total_unemployment_compensation also prefers the reported amount. + - entity: person + column: weeks_worked + fill_value: "0" + spines: [acs_2024_1yr] + rows: "ACS persons under 16, outside the WKWN universe" + summary: >- + Weeks worked in the past 12 months. Staging maps ACS WKWN natively on every ACS + row (microcosm#1021) and leaves it blank, with WKHP, below age 16, where the ACS + does not ask it. policyengine-us 2.145.3 reads it as an input (its 2.2.1 + formula_2025 is gone, policyengine-us#9660): SNAP's work tests average usual hours + over the year with it, Wisconsin Works averages the W-2 parent's hours, Hawaii TDI + counts qualifying weeks and SPM work expenses count adults' weeks. 0 is the + engine's "not reported" value, which keeps usual hours unchanged. + consumers: [aca_ptc, chip, ctc, eitc, general_assistance, head_start, + housing_assistance, lifeline, medicaid, school_meals, snap, ssi, state_benefits, + tanf, wic] + notes: + - programs: [aca_ptc, chip, ctc, general_assistance, head_start, + housing_assistance, lifeline, medicaid, school_meals, snap, state_benefits, + tanf, wic] + verdict: harmless + note: >- + The filled rows are persons under 16. Below 15 their usual hours are the + modeled 0, so the averaged hours are 0 whatever the weeks. At 15 none of the + rules that read the average applies: SNAP's general work requirements exempt + persons under 16 and the ABAWD time limit starts at 18, Medicaid's work + requirement (from 2027) covers ages 19 to 64, and Wisconsin Works reads the + hours of the W-2 parent (a custodial parent or the tax-unit head or spouse who + claims the child), rarely a person under 16. Hawaii TDI reaches only the Marin + and Los Angeles general relief net incomes, through payroll withholding, a + route no household can take. The other consumers read these only through + those programs' results. + - programs: [eitc, ssi] + verdict: harmless + note: >- + Reached only through the behavioral responses (labor_supply_behavioral_response + and capital_gains_behavioral_response), which return 0 before reading anything + in an engine pass without a reform, as every release pass is, together with + the 2020-only charitable deduction for non-itemizers + (charitable_contributions_ald), which is 0 before it reads anything in any + other year, or, for SSI, the contributed COLA means test + (social_security_cola_means_test_withheld), which is False unless + gov.contrib.ssa.benefit_levers.cola.means_test.enabled; inert. - entity: household column: auto_loan_balance fill_value: "0" spines: [acs_2024_1yr] rows: "every ACS household" summary: >- - No policyengine-us 2.2.1 variable reads it; the auto loan interest deduction reads - qualified_passenger_vehicle_loan_interest. + No policyengine-us 2.145.3 variable reads it; the auto loan interest deduction + reads qualified_passenger_vehicle_loan_interest. consumers: [] notes: [] - entity: household @@ -1051,8 +1738,8 @@ entries: spines: [acs_2024_1yr] rows: "every ACS household" summary: >- - No policyengine-us 2.2.1 variable reads it; the auto loan interest deduction reads - qualified_passenger_vehicle_loan_interest. + No policyengine-us 2.145.3 variable reads it; the auto loan interest deduction + reads qualified_passenger_vehicle_loan_interest. consumers: [] notes: [] - entity: household @@ -1061,17 +1748,68 @@ entries: spines: [acs_2024_1yr] rows: "every ACS household" summary: >- - No policyengine-us 2.2.1 variable reads it. Donor-spine-only geography (reviewed - limitation mixed_sub_puma_column_coverage). - consumers: [] - notes: [] + Donor-spine-only geography (reviewed limitation mixed_sub_puma_column_coverage). + Read only by the local sales tax geography (sales_tax_location, behind + combined_sales_tax_rate and local_sales_tax_table), which uses the county's + population-weighted rate when block and place are blank, as on ACS rows. + consumers: [aca_ptc, chip, ctc, eitc, general_assistance, head_start, + housing_assistance, lifeline, medicaid, school_meals, snap, ssi, state_benefits, + tanf, wic] + notes: + - programs: [aca_ptc, chip, head_start, lifeline, medicaid, school_meals, snap, + state_benefits, wic] + verdict: harmless + note: >- + Reached only through the local sales tax rate (sales_tax_location reads block, + county and place). Block and place are blank on ACS rows, so + combined_sales_tax_rate is the county's population-weighted rate, and outside + New York, Virginia and the Streamlined Sales Tax states with local taxes the + local rate is 0 whatever the place. The tax reaches these programs only + through the itemized SALT deduction and the tax-liability chain into + tax_unit_is_filer; a change in itemized deductions moves tax only for a unit + already required to file, so the filer flag and everything past it do not + change. + - programs: [ctc] + verdict: harmless + note: >- + Only itemizers who deduct sales tax, in states whose local rates vary by + place, see the county's population-weighted rate instead of their own: tens of + dollars of deduction and a few dollars of tax, which reach the CTC only where + tax liability limits it; negligible. + - programs: [general_assistance] + verdict: harmless + note: >- + Marin general relief subtracts withholding estimated from income tax before + credits, and policyengine-us has no official California locality rates, so the + location cannot change local sales tax there. + - programs: [eitc, housing_assistance, tanf] + verdict: harmless + note: >- + Reached only through the 2020-only charitable deduction for non-itemizers + (charitable_contributions_ald), which is 0 before it reads anything in any + other year, and the behavioral responses (labor_supply_behavioral_response and + capital_gains_behavioral_response, which read household_net_income, and the + labor-supply elasticities they gate), which return 0 before reading anything + in an engine pass without a reform; inert. + - programs: [ssi] + verdict: harmless + note: >- + Reached only through the 2020-only charitable deduction for non-itemizers + (charitable_contributions_ald), which is 0 before it reads anything in any + other year, and/or the contributed COLA means test + (social_security_cola_means_test_withheld), which is False unless + gov.contrib.ssa.benefit_levers.cola.means_test.enabled, and the behavioral + responses (labor_supply_behavioral_response and + capital_gains_behavioral_response, which read household_net_income, and the + labor-supply elasticities they gate), which return 0 before reading anything + in an engine pass without a reform; inert. - entity: household column: cbsa_code fill_value: "''" spines: [acs_2024_1yr] rows: "every ACS household" summary: >- - No policyengine-us 2.2.1 variable reads it. Donor-spine-only geography (reviewed + No policyengine-us 2.145.3 variable reads it. Donor-spine-only geography (reviewed limitation mixed_sub_puma_column_coverage). consumers: [] notes: [] @@ -1088,8 +1826,9 @@ entries: count only scales exemptions of a zero value or averages it, except in the count-only rules of San Francisco CAAP, Los Angeles General Relief and lives_in_vehicle. - consumers: [aca_ptc, chip, ctc, general_assistance, head_start, housing_assistance, - lifeline, medicaid, school_meals, snap, state_benefits, tanf, wic] + consumers: [aca_ptc, chip, ctc, eitc, general_assistance, head_start, + housing_assistance, lifeline, medicaid, school_meals, snap, ssi, state_benefits, + tanf, wic] notes: - programs: [general_assistance] verdict: known_bias @@ -1110,11 +1849,32 @@ entries: note: >- Texas's broad-based categorical eligibility asset test for SNAP (meets_tanf_non_cash_asset_test) uses the count only to scale the per-vehicle - exclusions applied to vehicle value, and Montana - and Washington TANF (Washington RCA through it) and Illinois AABD (its + exclusions applied to vehicle value, and Montana and Washington TANF + (Washington RCA through it) and Illinois AABD (its own asset test and its Medicaid buy-in) use it only to average value across vehicles; with household_vehicles_value 0 on the same rows none of them moves. The other programs are reached only through those results. + - programs: [eitc] + verdict: harmless + note: >- + Reached only through the 2020-only charitable deduction for non-itemizers + (charitable_contributions_ald), which is 0 before it reads anything in any + other year, and the behavioral responses (labor_supply_behavioral_response and + capital_gains_behavioral_response, which read household_net_income, and the + labor-supply elasticities they gate), which return 0 before reading anything + in an engine pass without a reform; inert. + - programs: [ssi] + verdict: harmless + note: >- + Reached only through the 2020-only charitable deduction for non-itemizers + (charitable_contributions_ald), which is 0 before it reads anything in any + other year, and/or the contributed COLA means test + (social_security_cola_means_test_withheld), which is False unless + gov.contrib.ssa.benefit_levers.cola.means_test.enabled, and the behavioral + responses (labor_supply_behavioral_response and + capital_gains_behavioral_response, which read household_net_income, and the + labor-supply elasticities they gate), which return 0 before reading anything + in an engine pass without a reform; inert. - entity: household column: household_vehicles_value fill_value: "0" @@ -1124,8 +1884,9 @@ entries: The ACS asks how many vehicles a household keeps (VEH) but not their value (reviewed limitation acs_household_vehicle_value_default). SNAP's own asset test (snap_assets) reads no vehicle. - consumers: [aca_ptc, chip, ctc, general_assistance, head_start, housing_assistance, - lifeline, medicaid, school_meals, snap, state_benefits, tanf, wic] + consumers: [aca_ptc, chip, ctc, eitc, general_assistance, head_start, + housing_assistance, lifeline, medicaid, school_meals, snap, ssi, state_benefits, + tanf, wic] notes: - programs: [snap] verdict: known_bias @@ -1155,7 +1916,7 @@ entries: note: >- Medicaid eligibility bars the PTC: an Illinois worker with a disability whose zero vehicle value passes the HBWD asset test is modeled Medicaid-eligible - (is_medicaid_eligible), fails pays_aca_premium and loses the whole credit + (is_medicaid_eligible), fails is_aca_marketplace_enrollee and loses the whole credit (is_aca_ptc_eligible), even where the true vehicle value would leave an otherwise eligible 2024 Marketplace adult. Illinois only, but the full credit for each person it reaches. @@ -1176,23 +1937,53 @@ entries: eligibility (is_lifeline_eligible) and WIC adjunctive eligibility: the Illinois HBWD buy-in, Texas's SNAP asset test and the state TANF resource tests above. - - programs: [head_start, school_meals] + - programs: [head_start] verdict: known_bias direction: overstates via: [snap, tanf] note: "Only through TANF and SNAP categorical eligibility." + - programs: [school_meals] + verdict: known_bias + direction: mixed + via: [snap, tanf] + note: >- + Mostly overstated through TANF and SNAP categorical eligibility. School meals + also count Illinois AABD as income, and zero vehicle value passes AABD's asset + test (il_aabd_countable_vehicle_value), so the family of an Illinois AABD + recipient with vehicle equity sees too much school-meal income. - programs: [ctc, housing_assistance] verdict: harmless note: >- Second-order and negligible: TANF income in HUD income, and CalWORKs child care in the CDCC ahead of the CTC and in HUD's child-care deduction. + - programs: [eitc] + verdict: harmless + note: >- + Reached only through the 2020-only charitable deduction for non-itemizers + (charitable_contributions_ald), which is 0 before it reads anything in any + other year, and the behavioral responses (labor_supply_behavioral_response and + capital_gains_behavioral_response, which read household_net_income, and the + labor-supply elasticities they gate), which return 0 before reading anything + in an engine pass without a reform; inert. + - programs: [ssi] + verdict: harmless + note: >- + Reached only through the 2020-only charitable deduction for non-itemizers + (charitable_contributions_ald), which is 0 before it reads anything in any + other year, and/or the contributed COLA means test + (social_security_cola_means_test_withheld), which is False unless + gov.contrib.ssa.benefit_levers.cola.means_test.enabled, and the behavioral + responses (labor_supply_behavioral_response and + capital_gains_behavioral_response, which read household_net_income, and the + labor-supply elasticities they gate), which return 0 before reading anything + in an engine pass without a reform; inert. - entity: household column: net_worth fill_value: "0" spines: [acs_2024_1yr] rows: "every ACS household" summary: >- - No policyengine-us 2.2.1 variable reads it; SNAP's asset test reads snap_assets + No policyengine-us 2.145.3 variable reads it; SNAP's asset test reads snap_assets (bank, stock and bond holdings). consumers: [] notes: [] @@ -1202,10 +1993,63 @@ entries: spines: [acs_2024_1yr] rows: "every ACS household" summary: >- - No policyengine-us 2.2.1 variable reads it. Donor-spine-only geography (reviewed - limitation mixed_sub_puma_column_coverage). - consumers: [] - notes: [] + Donor-spine-only geography (reviewed limitation mixed_sub_puma_column_coverage). + Read by the local sales tax geography (sales_tax_location, behind + combined_sales_tax_rate and local_sales_tax_table), which uses the county's + population-weighted rate when block and place are blank, as on ACS rows, and by + Alaska's Heating Assistance Program (ak_hap), which reaches no means-tested + program. + consumers: [aca_ptc, chip, ctc, eitc, general_assistance, head_start, + housing_assistance, lifeline, medicaid, school_meals, snap, ssi, state_benefits, + tanf, wic] + notes: + - programs: [aca_ptc, chip, head_start, lifeline, medicaid, school_meals, snap, + state_benefits, wic] + verdict: harmless + note: >- + Reached only through the local sales tax rate (sales_tax_location reads block, + county and place). Block and place are blank on ACS rows, so + combined_sales_tax_rate is the county's population-weighted rate, and outside + New York, Virginia and the Streamlined Sales Tax states with local taxes the + local rate is 0 whatever the place. The tax reaches these programs only + through the itemized SALT deduction and the tax-liability chain into + tax_unit_is_filer; a change in itemized deductions moves tax only for a unit + already required to file, so the filer flag and everything past it do not + change. + - programs: [ctc] + verdict: harmless + note: >- + Only itemizers who deduct sales tax, in states whose local rates vary by + place, see the county's population-weighted rate instead of their own: tens of + dollars of deduction and a few dollars of tax, which reach the CTC only where + tax liability limits it; negligible. + - programs: [general_assistance] + verdict: harmless + note: >- + Marin general relief subtracts withholding estimated from income tax before + credits, and policyengine-us has no official California locality rates, so the + location cannot change local sales tax there. + - programs: [eitc, housing_assistance, tanf] + verdict: harmless + note: >- + Reached only through the 2020-only charitable deduction for non-itemizers + (charitable_contributions_ald), which is 0 before it reads anything in any + other year, and the behavioral responses (labor_supply_behavioral_response and + capital_gains_behavioral_response, which read household_net_income, and the + labor-supply elasticities they gate), which return 0 before reading anything + in an engine pass without a reform; inert. + - programs: [ssi] + verdict: harmless + note: >- + Reached only through the 2020-only charitable deduction for non-itemizers + (charitable_contributions_ald), which is 0 before it reads anything in any + other year, and/or the contributed COLA means test + (social_security_cola_means_test_withheld), which is False unless + gov.contrib.ssa.benefit_levers.cola.means_test.enabled, and the behavioral + responses (labor_supply_behavioral_response and + capital_gains_behavioral_response, which read household_net_income, and the + labor-supply elasticities they gate), which return 0 before reading anything + in an engine pass without a reform; inert. - entity: household column: qualified_passenger_vehicle_loan_interest fill_value: "0" @@ -1214,8 +2058,9 @@ entries: summary: >- Interest on a qualified passenger vehicle loan for the auto loan interest deduction (tax years 2025-2028, P.L. 119-21); the ACS has no item. - consumers: [aca_ptc, chip, ctc, general_assistance, lifeline, medicaid, - state_benefits, wic] + consumers: [aca_ptc, chip, ctc, eitc, general_assistance, head_start, + housing_assistance, lifeline, medicaid, school_meals, snap, ssi, state_benefits, + tanf, wic] notes: - programs: [ctc] verdict: known_bias @@ -1239,13 +2084,40 @@ entries: County general assistance subtracts income tax or payroll withholding from earnings (Santa Clara, Marin, Los Angeles), but its applicants owe almost none. + - programs: [head_start, school_meals, snap] + verdict: harmless + note: >- + Reached only through the filer flag, which a change in tax liability cannot + flip: only a unit already required to file has tax liability for these + deductions and credits to change (see the Medicaid note). + - programs: [eitc, housing_assistance, tanf] + verdict: harmless + note: >- + Reached only through the 2020-only charitable deduction for non-itemizers + (charitable_contributions_ald), which is 0 before it reads anything in any + other year, and the behavioral responses (labor_supply_behavioral_response and + capital_gains_behavioral_response, which read household_net_income, and the + labor-supply elasticities they gate), which return 0 before reading anything + in an engine pass without a reform; inert. + - programs: [ssi] + verdict: harmless + note: >- + Reached only through the 2020-only charitable deduction for non-itemizers + (charitable_contributions_ald), which is 0 before it reads anything in any + other year, and/or the contributed COLA means test + (social_security_cola_means_test_withheld), which is False unless + gov.contrib.ssa.benefit_levers.cola.means_test.enabled, and the behavioral + responses (labor_supply_behavioral_response and + capital_gains_behavioral_response, which read household_net_income, and the + labor-supply elasticities they gate), which return 0 before reading anything + in an engine pass without a reform; inert. - entity: household column: sldl fill_value: "''" spines: [acs_2024_1yr] rows: "every ACS household" summary: >- - No policyengine-us 2.2.1 variable reads it. Donor-spine-only geography (reviewed + No policyengine-us 2.145.3 variable reads it. Donor-spine-only geography (reviewed limitation mixed_sub_puma_column_coverage). consumers: [] notes: [] @@ -1255,7 +2127,7 @@ entries: spines: [acs_2024_1yr] rows: "every ACS household" summary: >- - No policyengine-us 2.2.1 variable reads it. Donor-spine-only geography (reviewed + No policyengine-us 2.145.3 variable reads it. Donor-spine-only geography (reviewed limitation mixed_sub_puma_column_coverage). consumers: [] notes: [] @@ -1265,17 +2137,41 @@ entries: spines: [acs_2024_1yr] rows: "ACS group-quarters households (TYPEHUGQ 2/3)" summary: >- - Native ACS TEN for housing units; group quarters have none. No policyengine-us - 2.2.1 variable reads it: programs read spm_unit_tenure_type. - consumers: [] - notes: [] + Native ACS TEN for housing units; group quarters have none. Read only by + Colorado's in-kind support and maintenance exemption for clients who own their + home (_ism_exempt); other programs read spm_unit_tenure_type. + consumers: [aca_ptc, chip, ctc, eitc, general_assistance, head_start, + housing_assistance, lifeline, medicaid, school_meals, snap, ssi, state_benefits, + tanf, wic] + notes: + - programs: [aca_ptc, chip, head_start, lifeline, medicaid, school_meals, snap, + state_benefits, wic] + verdict: harmless + note: >- + Read only by Colorado's in-kind support and maintenance exemption for a client + who owns their home (_ism_exempt in co_ssa_in_kind_support_and_maintenance), + which Colorado OAP and AND-CS count; SNAP and school meals count those grants, + and the other programs follow SNAP and Medicaid. NONE gives the same answer as + RENTED, and group-quarters residents do not own their quarters, so NONE is the + true value here. Colorado counts this ISM only for a client who receives + shelter from others (ssi_receives_shelter_from_others_in_household, + ssi_receives_outside_shelter_support), inputs no stage produces, and SSI + recipients are charged SSA's ISM, which reads no tenure. + - programs: [ctc, eitc, general_assistance, housing_assistance, ssi, tanf] + verdict: harmless + note: >- + Reached only through the behavioral responses + (labor_supply_behavioral_response and capital_gains_behavioral_response, which + read household_net_income, and the labor-supply elasticities they gate), which + return 0 before reading anything in an engine pass without a reform, as every + release pass is; inert. - entity: household column: tract_geoid fill_value: "''" spines: [acs_2024_1yr] rows: "every ACS household" summary: >- - No policyengine-us 2.2.1 variable reads it. Donor-spine-only geography (reviewed + No policyengine-us 2.145.3 variable reads it. Donor-spine-only geography (reviewed limitation mixed_sub_puma_column_coverage). consumers: [] notes: [] @@ -1285,65 +2181,103 @@ entries: spines: [acs_2024_1yr] rows: "every ACS tax unit" summary: "Second-home mortgage balance; the ACS has no item." - consumers: [aca_ptc, chip, ctc, general_assistance, lifeline, medicaid, - state_benefits, wic] + consumers: [aca_ptc, chip, ctc, eitc, general_assistance, head_start, + housing_assistance, lifeline, medicaid, school_meals, snap, ssi, state_benefits, + tanf, wic] notes: - - programs: [aca_ptc, chip, ctc, general_assistance, lifeline, medicaid, - state_benefits, wic] + - programs: [aca_ptc, chip, ctc, general_assistance, head_start, lifeline, + medicaid, school_meals, snap, state_benefits, wic] verdict: harmless note: >- - Inert while second_home_mortgage_interest is the reviewed default 0 on the - same rows; the balance prorates deductible mortgage interest only above the - $750,000 acquisition-debt cap. - - entity: tax_unit - column: second_home_mortgage_interest - fill_value: "0.0" - spines: [acs_2024_1yr] - rows: "every ACS tax unit" - summary: "Second-home mortgage interest; the ACS has no item." - consumers: [aca_ptc, chip, ctc, general_assistance, lifeline, medicaid, - state_benefits, wic] - notes: - - programs: [aca_ptc, chip, ctc, general_assistance, lifeline, medicaid, - state_benefits, wic] + 0 matches the donor: the base carries the second-home legs as all-zero columns + and consolidates the mortgage surface onto the first-home leaves the transfer + carries (acs_transfer.py, puf_tax_itemization), so the acquisition-debt caps + already see the household's whole balance. Second-residence interest is now + the person input second_residence_mortgage_interest + (PolicyEngine/policyengine-us#9605), which no stage produces. + - programs: [eitc, housing_assistance, tanf] verdict: harmless note: >- - It lowers tax only for itemizers with a second-home mortgage, few of whom have - a CTC limited by tax liability; negligible. Itemized deductions leave AGI and - MAGI unchanged. Reached only through the tax-liability chain: nonrefundable - credits ahead of the CTC, then refundable_ctc, eligible_for_refundable_credits - and tax_unit_is_filer, which Medicaid's non-filer rules and the PTC's filing - condition read, and programs that read Medicaid enrollment. A change in tax - liability moves the refundable CTC to or from zero only for a unit with - positive income tax, which is already required to file, so the filer flag and - everything past it do not change. County general assistance subtracts income - tax or payroll withholding from earnings (Santa Clara, Marin, Los Angeles), - but its applicants owe almost none. + Reached only through the 2020-only charitable deduction for non-itemizers + (charitable_contributions_ald), which is 0 before it reads anything in any + other year, and the behavioral responses (labor_supply_behavioral_response and + capital_gains_behavioral_response, which read household_net_income, and the + labor-supply elasticities they gate), which return 0 before reading anything + in an engine pass without a reform; inert. + - programs: [ssi] + verdict: harmless + note: >- + Reached only through the 2020-only charitable deduction for non-itemizers + (charitable_contributions_ald), which is 0 before it reads anything in any + other year, and/or the contributed COLA means test + (social_security_cola_means_test_withheld), which is False unless + gov.contrib.ssa.benefit_levers.cola.means_test.enabled, and the behavioral + responses (labor_supply_behavioral_response and + capital_gains_behavioral_response, which read household_net_income, and the + labor-supply elasticities they gate), which return 0 before reading anything + in an engine pass without a reform; inert. - entity: tax_unit column: second_home_mortgage_origination_year fill_value: "0" spines: [acs_2024_1yr] rows: "every ACS tax unit" summary: "Second-home mortgage origination year; the ACS has no item." - consumers: [aca_ptc, chip, ctc, general_assistance, lifeline, medicaid, - state_benefits, wic] + consumers: [aca_ptc, chip, ctc, eitc, general_assistance, head_start, + housing_assistance, lifeline, medicaid, school_meals, snap, ssi, state_benefits, + tanf, wic] notes: - - programs: [aca_ptc, chip, ctc, general_assistance, lifeline, medicaid, - state_benefits, wic] + - programs: [aca_ptc, chip, ctc, general_assistance, head_start, lifeline, + medicaid, school_meals, snap, state_benefits, wic] + verdict: harmless + note: >- + Inert while second_home_mortgage_balance is the reviewed default 0 on the same + rows: an unknown year (0) only classifies that balance as post-2017 debt. + - programs: [eitc, housing_assistance, tanf] + verdict: harmless + note: >- + Reached only through the 2020-only charitable deduction for non-itemizers + (charitable_contributions_ald), which is 0 before it reads anything in any + other year, and the behavioral responses (labor_supply_behavioral_response and + capital_gains_behavioral_response, which read household_net_income, and the + labor-supply elasticities they gate), which return 0 before reading anything + in an engine pass without a reform; inert. + - programs: [ssi] verdict: harmless note: >- - Inert while second_home_mortgage_interest is the reviewed default 0 on the - same rows; the year selects the acquisition-debt cap. + Reached only through the 2020-only charitable deduction for non-itemizers + (charitable_contributions_ald), which is 0 before it reads anything in any + other year, and/or the contributed COLA means test + (social_security_cola_means_test_withheld), which is False unless + gov.contrib.ssa.benefit_levers.cola.means_test.enabled, and the behavioral + responses (labor_supply_behavioral_response and + capital_gains_behavioral_response, which read household_net_income, and the + labor-supply elasticities they gate), which return 0 before reading anything + in an engine pass without a reform; inert. - entity: tax_unit column: selected_marketplace_plan_benchmark_ratio fill_value: "1.0" spines: [acs_2024_1yr] rows: "every ACS tax unit" summary: >- - Read only by selected_marketplace_plan_premium_proxy, a net-premium proxy; the - premium tax credit reads the benchmark (SLCSP) premium, not the selected plan. - consumers: [] - notes: [] + Read only by monthly_selected_marketplace_plan_premium_proxy, which + selected_marketplace_plan_premium_proxy sums, a net-premium proxy; the premium tax + credit reads the benchmark (SLCSP) premium, not the selected plan. The proxy + reaches the programs only through household health costs, household_net_income and + the behavioral responses. + consumers: [aca_ptc, chip, ctc, eitc, general_assistance, head_start, + housing_assistance, lifeline, medicaid, school_meals, snap, ssi, state_benefits, + tanf, wic] + notes: + - programs: [aca_ptc, chip, ctc, eitc, general_assistance, head_start, + housing_assistance, lifeline, medicaid, school_meals, snap, ssi, + state_benefits, tanf, wic] + verdict: harmless + note: >- + Reached only through the behavioral responses + (labor_supply_behavioral_response and capital_gains_behavioral_response, which + read household_net_income, and the labor-supply elasticities they gate), which + return 0 before reading anything in an engine pass without a reform, as every + release pass is; inert. - entity: tax_unit column: takes_up_aca_if_eligible fill_value: "True" @@ -1352,7 +2286,9 @@ entries: summary: >- Runtime-owned take-up flag, not seeded on ACS rows (reviewed limitation acs_take_up_engine_defaults). - consumers: [aca_ptc] + consumers: [aca_ptc, chip, ctc, eitc, general_assistance, head_start, + housing_assistance, lifeline, medicaid, school_meals, snap, ssi, state_benefits, + tanf, wic] notes: - programs: [aca_ptc] verdict: known_bias @@ -1360,49 +2296,15 @@ entries: note: >- Universal take-up: assigned_aca_ptc is the full credit for every eligible ACS unit, while donor rows carry the seeded draw. - - entity: tax_unit - column: takes_up_eitc - fill_value: "True" - spines: [acs_2024_1yr] - rows: "every ACS tax unit" - summary: >- - Runtime-owned take-up flag, not seeded on ACS rows (reviewed limitation - acs_take_up_engine_defaults). The EITC it gates also sets - eligible_for_refundable_credits, which feeds the filer flag. - consumers: [aca_ptc, chip, ctc, eitc, general_assistance, lifeline, medicaid, - state_benefits, wic] - notes: - - programs: [eitc] - verdict: known_bias - direction: overstates - note: "Universal take-up on ACS rows, while donor rows carry the seeded draw." - - programs: [aca_ptc] - verdict: known_bias - direction: mixed - via: [medicaid] - note: >- - Mostly overstated: every EITC-eligible unit counts as eligible for refundable - credits, so more ACS units file (tax_unit_is_filer) and meet the PTC's filing - condition. The Medicaid changes below (non-filer rules) move the PTC either - way for some units, because Medicaid eligibility bars it (pays_aca_premium). - - programs: [chip, medicaid] - verdict: known_bias - direction: mixed - note: >- - More ACS units count as filers, so Medicaid's non-filer household rules - (medicaid_uses_non_filer_rules) apply to fewer of them; the direction depends - on the household. - - programs: [lifeline, state_benefits, wic] - verdict: known_bias - direction: mixed - via: [medicaid] - note: "Only through Medicaid enrollment." - - programs: [ctc, general_assistance] + - programs: [chip, ctc, eitc, general_assistance, head_start, housing_assistance, + lifeline, medicaid, school_meals, snap, ssi, state_benefits, tanf, wic] verdict: harmless note: >- - The CTC reads the EITC only in the additional CTC's alternative phase-in for - three or more children (Social Security taxes minus the EITC); county general - assistance reads only income tax withholding. Negligible. + Reached only through the behavioral responses + (labor_supply_behavioral_response and capital_gains_behavioral_response, which + read household_net_income, and the labor-supply elasticities they gate), which + return 0 before reading anything in an engine pass without a reform, as every + release pass is; inert. - entity: tax_unit column: would_file_taxes_voluntarily fill_value: "False" @@ -1411,26 +2313,26 @@ entries: summary: >- Voluntary-filing propensity, which donor rows carry (voluntary_filing) and ACS rows do not. It feeds the filer flag and the EITC's filing condition. - consumers: [aca_ptc, chip, ctc, eitc, general_assistance, lifeline, medicaid, - state_benefits, wic] + consumers: [aca_ptc, chip, ctc, eitc, general_assistance, head_start, + housing_assistance, lifeline, medicaid, school_meals, snap, ssi, state_benefits, + tanf, wic] notes: - programs: [eitc] - verdict: known_bias - direction: understates + verdict: harmless note: >- - It requires a filed return. ACS units neither required to file nor filing for - refundable credits never file, so the few that would file anyway lose the - credit (small, since EITC-eligible units mostly file for credits). + The EITC's own filing test passes for every unit: + would_file_if_eligible_for_refundable_credit is the engine default True on + every row, so voluntary filing never decides the credit. - programs: [aca_ptc] verdict: known_bias direction: mixed via: [medicaid] note: >- - Mostly understated: the PTC requires a filed return, and ACS units neither - required to file nor filing for refundable credits never file, so the few that - would file anyway lose it. The Medicaid changes below (non-filer rules) move - the PTC the other way for some units, because Medicaid eligibility bars it - (pays_aca_premium). + No direct effect on ACS rows: files_return_for_aca_ptc counts a unit that + takes up a positive credit as filing for it, and takes_up_aca_if_eligible is + the reviewed default True on every ACS unit. Only through Medicaid's non-filer + rules below, which move the PTC either way because Medicaid eligibility keeps + a person off the Marketplace. - programs: [chip, medicaid] verdict: known_bias direction: mixed @@ -1448,6 +2350,37 @@ entries: The CTC reads the EITC only in the additional CTC's alternative phase-in for three or more children; county general assistance reads only income tax withholding. Negligible. + - programs: [head_start, school_meals, snap] + verdict: harmless + note: >- + Second-order and negligible: only through the Medicaid enrollment of a + Colorado OAP or AND-CS client's spouse (or, for AND-CS, parent), which can lift + the deeming and + so change the grant that SNAP counts as unearned income and school meals count + as income (Head Start follows SNAP receipt); the other state supplements that + read Medicaid enrollment need facility or certification inputs no stage + produces, and the California CARE route into Illinois AABD crosses states. + - programs: [housing_assistance, tanf] + verdict: harmless + note: >- + Reached only through the 2020-only charitable deduction for non-itemizers + (charitable_contributions_ald), which is 0 before it reads anything in any + other year, and the behavioral responses (labor_supply_behavioral_response and + capital_gains_behavioral_response, which read household_net_income, and the + labor-supply elasticities they gate), which return 0 before reading anything + in an engine pass without a reform; inert. + - programs: [ssi] + verdict: harmless + note: >- + Reached only through the 2020-only charitable deduction for non-itemizers + (charitable_contributions_ald), which is 0 before it reads anything in any + other year, and/or the contributed COLA means test + (social_security_cola_means_test_withheld), which is False unless + gov.contrib.ssa.benefit_levers.cola.means_test.enabled, and the behavioral + responses (labor_supply_behavioral_response and + capital_gains_behavioral_response, which read household_net_income, and the + labor-supply elasticities they gate), which return 0 before reading anything + in an engine pass without a reform; inert. - entity: spm_unit column: spm_unit_energy_subsidy fill_value: "0" @@ -1474,8 +2407,9 @@ entries: rows: "ACS group-quarters SPM units (TYPEHUGQ 2/3)" summary: >- Native ACS TEN for housing units; group quarters have none and read as renters. - consumers: [aca_ptc, chip, general_assistance, head_start, housing_assistance, - lifeline, medicaid, school_meals, snap, state_benefits, wic] + consumers: [aca_ptc, chip, ctc, eitc, general_assistance, head_start, + housing_assistance, lifeline, medicaid, school_meals, snap, ssi, state_benefits, + tanf, wic] notes: - programs: [housing_assistance] verdict: known_bias @@ -1487,10 +2421,32 @@ entries: Angeles County, the Texas TDHCA area and four Kansas PHAs, so a payment arises only there, and only where the transferred housing take-up flag is True (microcosm#975). - - programs: [aca_ptc, chip, general_assistance, head_start, lifeline, medicaid, - school_meals, snap, state_benefits, wic] + - programs: [aca_ptc, chip, ctc, general_assistance, head_start, lifeline, + medicaid, school_meals, snap, state_benefits, wic] verdict: harmless note: >- Reached only through housing_assistance into rent, which stays 0 for these units because their pre-subsidy rent is 0, and into California CARE and FERA - income (Los Angeles County group quarters only); negligible. + income (Los Angeles County group quarters only), which pay nothing on these + files; nil. + - programs: [eitc, tanf] + verdict: harmless + note: >- + Reached only through the 2020-only charitable deduction for non-itemizers + (charitable_contributions_ald), which is 0 before it reads anything in any + other year, and the behavioral responses (labor_supply_behavioral_response and + capital_gains_behavioral_response, which read household_net_income, and the + labor-supply elasticities they gate), which return 0 before reading anything + in an engine pass without a reform; inert. + - programs: [ssi] + verdict: harmless + note: >- + Reached only through the 2020-only charitable deduction for non-itemizers + (charitable_contributions_ald), which is 0 before it reads anything in any + other year, and/or the contributed COLA means test + (social_security_cola_means_test_withheld), which is False unless + gov.contrib.ssa.benefit_levers.cola.means_test.enabled, and the behavioral + responses (labor_supply_behavioral_response and + capital_gains_behavioral_response, which read household_net_income, and the + labor-supply elasticities they gate), which return 0 before reading anything + in an engine pass without a reform; inert. diff --git a/packages/microcosm-build/src/microcosm/build/us_runtime/acs_local_ssi_medicaid_take_up.py b/packages/microcosm-build/src/microcosm/build/us_runtime/acs_local_ssi_medicaid_take_up.py index e0799b5956..f321d6fee6 100755 --- a/packages/microcosm-build/src/microcosm/build/us_runtime/acs_local_ssi_medicaid_take_up.py +++ b/packages/microcosm-build/src/microcosm/build/us_runtime/acs_local_ssi_medicaid_take_up.py @@ -67,7 +67,7 @@ weight, on its own keyed draw; a record not kept is an ordinary non-anchor, which can still draw or be calibrated in. The state's excess is recorded. The treatment is state-level because the CMS counts are: - policyengine-us 2.2.1 gives CHIP its own ``takes_up_chip_if_eligible`` and + policyengine-us 2.145.3 gives CHIP its own ``takes_up_chip_if_eligible`` and makes CHIP eligibility exclusive of Medicaid eligibility, so HINS4 CHIP children already fall outside the measured (Medicaid-eligible) anchor mass, and the ledger has no child/adult split of the Medicaid counts to diff --git a/packages/microcosm-build/src/microcosm/build/us_runtime/acs_local_take_up.py b/packages/microcosm-build/src/microcosm/build/us_runtime/acs_local_take_up.py index d6bb15a806..ec8d0be7a9 100644 --- a/packages/microcosm-build/src/microcosm/build/us_runtime/acs_local_take_up.py +++ b/packages/microcosm-build/src/microcosm/build/us_runtime/acs_local_take_up.py @@ -27,6 +27,18 @@ ``receives_tanf``, the receipt cross-tabs the two on ACS units and reports the weighted share of TANF reporters that drew ``False`` (informational, never graded). +- EITC uses the same contract's seeded Bernoulli draw, on tax units, at the + National Taxpayer Advocate's rates by number of qualifying children + (counted from members' ages), also with no receipt anchor (microcosm#1675). + At the engine default every eligible ACS tax unit claimed the credit, and + the release's state SOI EITC targets then shrank the weights of eligible + ACS units instead of choosing claimants among them, the bias the SSI and + Medicaid stage avoids for Medicaid (microcosm#170). +- WIC take-up is not drawn here: staging draws the ACS rows' decisions with + the national generator + (:mod:`~microcosm.build.us_runtime.acs_local_wic_take_up`, microcosm#1154). + This stage refuses a frame where the column is incomplete, and the gate + grades it on both spines. Three more inputs reached the engine pass missing on every ACS row and took an engine default that biases SNAP (microcosm#1022). None needs the engine: @@ -83,8 +95,8 @@ SNAP household targets reweight instead. Other ``takes_up_*`` flags on ACS rows are not this stage's: SSI and Medicaid take-up are assigned after an engine pre-pass by -:mod:`~microcosm.build.us_runtime.acs_local_ssi_medicaid_take_up`, and EITC, -Early Head Start and the rest still ship at the engine default +:mod:`~microcosm.build.us_runtime.acs_local_ssi_medicaid_take_up`, and Early +Head Start, the ACA credit and the rest still ship at the engine default (microcosm#1022); the gate here does not grade them. """ @@ -107,6 +119,10 @@ head_start_fill, vehicles_available_summary, ) +from microcosm.build.us_runtime.acs_local_wic_take_up import ( + US_WIC_TAKE_UP_COLUMN, + require_complete_us_wic_take_up, +) from microcosm.build.us_runtime.acs_pums import ACS_2024_1YR_SPINE from microcosm.build.us_runtime.acs_transfer import ASEC_PUF_DONOR_SPINE from microcosm.build.us_runtime.base_pool import spine_column @@ -130,6 +146,7 @@ ) from microcosm.build.us_runtime.take_up import ( US_TAKE_UP_SHARE_BAND, + _eitc_child_count_by_tax_unit, _seed_program, _stable_unit_draws, _units_with_source_identity, @@ -142,11 +159,13 @@ from microcosm.frame.units import US_SCHEMA __all__ = [ + "ACS_LOCAL_EITC_TAKE_UP_ISSUE", "ACS_LOCAL_ENGINE_FREE_FILLS_ISSUE", "ACS_LOCAL_ENGINE_FREE_FILL_COLUMNS", "ACS_LOCAL_TAKE_UP_COLUMNS", "ACS_LOCAL_TAKE_UP_GATE_NAME", "ACS_VEHICLES_AVAILABLE_RECEIPT", + "US_EITC_TAKE_UP_OUTPUT_COLUMN", "US_HOUSING_ASSISTANCE_RECEIPT_COLUMN", "US_TANF_TAKE_UP_OUTPUT_COLUMN", "acs_local_take_up_signal_gate", @@ -155,6 +174,9 @@ US_TANF_TAKE_UP_OUTPUT_COLUMN = "takes_up_tanf_if_eligible" US_HOUSING_ASSISTANCE_RECEIPT_COLUMN = "receives_housing_assistance" +#: The tax-unit take-up flag this stage owns on ACS rows (microcosm#1675). +US_EITC_TAKE_UP_OUTPUT_COLUMN = "takes_up_eitc" +ACS_LOCAL_EITC_TAKE_UP_ISSUE = "microcosm#1675" #: The SPM-unit take-up flags this stage owns on ACS rows. ACS_LOCAL_TAKE_UP_COLUMNS: tuple[str, ...] = ( @@ -185,6 +207,7 @@ ACS_VEHICLES_AVAILABLE_RECEIPT = "vehicles_available" _ID_COLUMN = "spm_unit_id" +_TAX_UNIT_ID_COLUMN = "tax_unit_id" #: Reported SNAP receipt: the survey anchor (on ACS rows, native household #: FS from staging, microcosm#1022; the QRF transfer's before it). _REPORTED_SNAP_COLUMN = "receives_snap" @@ -196,6 +219,13 @@ US_SNAP_TAKE_UP_OUTPUT_COLUMN: _SNAP_TAKE_UP_SHARE_BAND, US_TANF_TAKE_UP_OUTPUT_COLUMN: US_TAKE_UP_SHARE_BAND[US_TANF_TAKE_UP_OUTPUT_COLUMN], } +#: The weighted ACS share band of the EITC take-up flag the gate grades beside +#: the SPM-unit flags: the contract's band. WIC take-up has none here: the +#: national generator draws it at its category rates and staging records the +#: shares (microcosm#1154). +_EITC_SHARE_BAND = US_TAKE_UP_SHARE_BAND[US_EITC_TAKE_UP_OUTPUT_COLUMN] +#: The contract's EITC rate bins by number of qualifying children. +_EITC_CHILD_BINS = ("0", "1", "2", "3+") _AGE_COLUMN = "age" _DISCRETIONARY_OPERATION = "derive_snap_abawd_discretionary_exemption" @@ -226,6 +256,8 @@ _HOUSING: "no one receives housing assistance", _MEDICARE: "every eligible person enrolls in Medicare", _HEAD_START: "every Head Start-eligible child aged 3-5 takes Head Start up", + US_EITC_TAKE_UP_OUTPUT_COLUMN: "every eligible tax unit claims the EITC", + US_WIC_TAKE_UP_COLUMN: "every eligible person takes WIC up", } @@ -278,13 +310,28 @@ def _covered_age(age: np.ndarray) -> np.ndarray: return (age >= low) & (age <= high) -def _tanf_program() -> TakeUpProgram: +def _contract_program(variable: str) -> TakeUpProgram: for program in seeded_take_up_programs(): - if program.variable == US_TANF_TAKE_UP_OUTPUT_COLUMN: + if program.variable == variable: return program - raise ValueError( - f"The take-up contract does not seed {US_TANF_TAKE_UP_OUTPUT_COLUMN!r}." + raise ValueError(f"The take-up contract does not seed {variable!r}.") + + +def _tanf_program() -> TakeUpProgram: + return _contract_program(US_TANF_TAKE_UP_OUTPUT_COLUMN) + + +def _eitc_program() -> TakeUpProgram: + return _contract_program(US_EITC_TAKE_UP_OUTPUT_COLUMN) + + +def _eitc_child_bins(frame: Frame) -> np.ndarray: + """Each tax unit's contract rate bin ("0", "1", "2", "3+"), in table order.""" + ids = frame.table("tax_unit")[_TAX_UNIT_ID_COLUMN] + counts = ( + _eitc_child_count_by_tax_unit(frame).reindex(ids).fillna(0).to_numpy(dtype=int) ) + return np.where(counts >= 3, "3+", counts.astype(str)) def _filled(values: pd.Series, missing: np.ndarray, assigned: np.ndarray) -> pd.Series: @@ -575,6 +622,8 @@ def _assignment_sha256( units: np.ndarray, person: pd.DataFrame, persons: np.ndarray, + tax_unit: pd.DataFrame, + tax_units: np.ndarray, ) -> str: """Digest of the ACS rows' ids and assigned cells, to prove two passes agree. ACS ``VEH`` is not in it: it reaches no engine input.""" @@ -597,6 +646,16 @@ def _assignment_sha256( }, } ), + pd.DataFrame( + { + _TAX_UNIT_ID_COLUMN: tax_unit.loc[ + tax_units, _TAX_UNIT_ID_COLUMN + ].to_numpy(), + US_EITC_TAKE_UP_OUTPUT_COLUMN: _flags( + tax_unit.loc[tax_units, US_EITC_TAKE_UP_OUTPUT_COLUMN] + )[0], + } + ), ) digest = hashlib.sha256() for table in selected: @@ -612,7 +671,10 @@ def with_acs_local_take_up_inputs( Args: frame: The local lane's multispine US frame. Its spm_unit and person - tables must carry complete origin tags; spm_unit both take-up + and tax_unit tables must carry complete origin tags; tax_unit + ``takes_up_eitc``; person a complete boolean + ``takes_up_wic_if_eligible``, which staging draws for ACS rows; + spm_unit both take-up columns, ``receives_snap``, ``receives_housing_assistance`` and the transferred ``takes_up_housing_assistance_if_eligible``; person ``is_snap_abawd_discretionary_exempt``, @@ -641,13 +703,16 @@ def with_acs_local_take_up_inputs( spm_unit = frame.table("spm_unit") person = frame.table("person") household = frame.table("household") + tax_unit = frame.table("tax_unit") tag = spine_column("spm_unit") person_tag = spine_column("person") household_tag = spine_column("household") + tax_tag = spine_column("tax_unit") for table, column in ( (spm_unit, tag), (person, person_tag), (household, household_tag), + (tax_unit, tax_tag), ): if column not in table or table[column].isna().any(): raise ValueError( @@ -663,6 +728,14 @@ def with_acs_local_take_up_inputs( f"ACS local take-up requires spm_unit column(s) {absent}; a missing " "donor column would reach the engine as universal take-up." ) + if US_EITC_TAKE_UP_OUTPUT_COLUMN not in tax_unit: + raise ValueError( + "ACS local take-up requires tax_unit column " + f"{US_EITC_TAKE_UP_OUTPUT_COLUMN!r}; a missing donor column would " + "reach the engine as universal take-up." + ) + # microcosm#1154: staging draws the ACS rows' WIC decisions; never filled. + require_complete_us_wic_take_up(person, what="ACS local take-up") absent = [ f"{entity}.{column}" for entity, columns in ( @@ -701,6 +774,7 @@ def with_acs_local_take_up_inputs( household[household_tag].eq(ACS_2024_1YR_SPINE).to_numpy(dtype=bool) ) donor_persons = person[person_tag].eq(ASEC_PUF_DONOR_SPINE).to_numpy(dtype=bool) + acs_tax_units = tax_unit[tax_tag].eq(ACS_2024_1YR_SPINE).to_numpy(dtype=bool) units = _units_with_source_identity(frame, "spm_unit") if not np.array_equal(units[_ID_COLUMN].to_numpy(), spm_unit[_ID_COLUMN]): raise ValueError("SPM-unit source identity does not align with the table.") @@ -743,6 +817,17 @@ def with_acs_local_take_up_inputs( tanf_assigned = np.asarray(seeded[US_TANF_TAKE_UP_OUTPUT_COLUMN], dtype=bool) tanf_missing = acs & ~_flags(spm_unit[US_TANF_TAKE_UP_OUTPUT_COLUMN])[1] + # EITC (microcosm#1675): the contract's seeded Bernoulli draw by number of + # qualifying children, no receipt anchor, as for TANF. + eitc_program = _eitc_program() + eitc_seeded, _ = _seed_program(frame, eitc_program, seed=int(seed)) + if not np.array_equal( + eitc_seeded[_TAX_UNIT_ID_COLUMN], tax_unit[_TAX_UNIT_ID_COLUMN].to_numpy() + ): + raise ValueError("Seeded EITC take-up does not align with the tax_unit table.") + eitc_assigned = np.asarray(eitc_seeded[US_EITC_TAKE_UP_OUTPUT_COLUMN], dtype=bool) + eitc_missing = acs_tax_units & ~_flags(tax_unit[US_EITC_TAKE_UP_OUTPUT_COLUMN])[1] + # microcosm#1022: the engine-free fills. discretionary_missing, discretionary_assigned, discretionary = _discretionary_fill( frame, acs_persons, seed=int(seed) @@ -792,6 +877,12 @@ def with_acs_local_take_up_inputs( ): updated[column] = _filled(person[column], missing, assigned) replaced["person"] = updated + if eitc_missing.any(): + updated = tax_unit.copy() + updated[US_EITC_TAKE_UP_OUTPUT_COLUMN] = _filled( + tax_unit[US_EITC_TAKE_UP_OUTPUT_COLUMN], eitc_missing, eitc_assigned + ) + replaced["tax_unit"] = updated if replaced: result = Frame( { @@ -806,7 +897,13 @@ def with_acs_local_take_up_inputs( ) final = result.table("spm_unit") final_person = result.table("person") + final_tax_unit = result.table("tax_unit") acs_weights = weights[acs] + tax_weights = np.asarray( + result.resolve_weights("tax_unit").values, dtype=np.float64 + ) + eitc_flags = _flags(final_tax_unit[US_EITC_TAKE_UP_OUTPUT_COLUMN])[0] + child_bins = _eitc_child_bins(result) person_weights = np.asarray( result.resolve_weights("person").values, dtype=np.float64 ) @@ -839,6 +936,7 @@ def with_acs_local_take_up_inputs( "seed": int(seed), "spine": ACS_2024_1YR_SPINE, "acs_spm_units": int(acs.sum()), + "acs_tax_units": int(acs_tax_units.sum()), "programs": { US_SNAP_TAKE_UP_OUTPUT_COLUMN: { "rate": rate, @@ -866,6 +964,31 @@ def with_acs_local_take_up_inputs( ), "receipt_crosstab": _tanf_receipt_crosstab(final.loc[acs], acs_weights), }, + US_EITC_TAKE_UP_OUTPUT_COLUMN: { + "issue": ACS_LOCAL_EITC_TAKE_UP_ISSUE, + "entity": "tax_unit", + "rates_by_num_children": eitc_program.rate.get( + "values_by_num_children" + ), + "rate_source": eitc_program.rate.get("source"), + "filled_rows": int(eitc_missing.sum()), + "preserved_rows": int((acs_tax_units & ~eitc_missing).sum()), + "weighted_take_up_share": _share( + tax_weights[acs_tax_units], eitc_flags[acs_tax_units] + ), + "by_num_children": { + label: { + "acs_tax_units": int( + (acs_tax_units & (child_bins == label)).sum() + ), + "weighted_take_up_share": _share( + tax_weights[acs_tax_units & (child_bins == label)], + eitc_flags[acs_tax_units & (child_bins == label)], + ), + } + for label in _EITC_CHILD_BINS + }, + }, }, "engine_free_fills": { "issue": ACS_LOCAL_ENGINE_FREE_FILLS_ISSUE, @@ -879,7 +1002,9 @@ def with_acs_local_take_up_inputs( }, ACS_VEHICLES_AVAILABLE_RECEIPT: vehicles_available, }, - "assigned_sha256": _assignment_sha256(final, acs, final_person, acs_persons), + "assigned_sha256": _assignment_sha256( + final, acs, final_person, acs_persons, final_tax_unit, acs_tax_units + ), } return result, receipt @@ -1125,6 +1250,53 @@ def _grade_medicare( return failures +def _grade_take_up_flag( + table: pd.DataFrame, + selected: np.ndarray, + column: str, + weights: np.ndarray, + band: tuple[float, float] | None, + *, + entity: str, + graded: bool, + columns: dict[str, object], +) -> list[str]: + """Grade one tax-unit or person take-up flag on one spine's rows. + + ``band`` is the ACS spine's weighted share band, or ``None`` for none. + """ + if column not in table: + return [f"missing {entity}.{column}."] + if not selected.any(): + return [f"no {entity} rows."] + flags, present = _flags(table.loc[selected, column]) + share = _share(weights[selected], flags) + unique = len(np.unique(flags[present])) + columns[column] = { + "entity": entity, + "missing_rows": int((~present).sum()), + "unique_values": unique, + "take_up_share": share, + "share_band": None if band is None else list(band), + } + failures: list[str] = [] + if not present.all(): + failures.append( + f"{column} has missing rows; an engine-default fill means " + f"{_ENGINE_DEFAULT_EFFECT[column]}." + ) + if unique < 2: + failures.append( + f"{column} is constant; universal take-up is the engine-default landmine." + ) + if graded and band is not None and not (band[0] <= share <= band[1]): + failures.append( + f"{column} take-up share {share:.3f} outside plausibility band " + f"[{band[0]}, {band[1]}]." + ) + return failures + + def acs_local_take_up_signal_gate(frame: Frame) -> GateResult: """Require complete, anchored, plausible ACS-lane runtime inputs per origin. @@ -1139,7 +1311,11 @@ def acs_local_take_up_signal_gate(frame: Frame) -> GateResult: (``False`` in group quarters), Medicare take-up equal to ``HINS3 == 1`` with a high share at 65+ (blank and invalid ``HINS3`` cells are counted in the ACS detail but not graded), and Head Start take-up only at ages - 3-5, at a share around the donor spine's. The owned vehicle count must be + 3-5, at a share around the donor spine's. EITC take-up (tax unit, + microcosm#1675) and WIC take-up (person, microcosm#1154) are held to the + same completeness and variation on both spines, and EITC take-up on the + ACS spine to the contract's band; WIC's category shares are staging's + receipt, drawn by the national generator. The owned vehicle count must be complete and vary on the donor spine and stay at the reviewed default on the ACS spine (missing, or 0 once filled): ACS ``VEH`` counts vehicles available, not owned, and is recorded beside it as information only @@ -1151,9 +1327,11 @@ def acs_local_take_up_signal_gate(frame: Frame) -> GateResult: spm_unit = frame.table("spm_unit") person = frame.table("person") household = frame.table("household") + tax_unit = frame.table("tax_unit") tag = spine_column("spm_unit") person_tag = spine_column("person") household_tag = spine_column("household") + tax_tag = spine_column("tax_unit") failures: list[str] = [] by_spine: dict[str, object] = {} if tag not in spm_unit or spm_unit[tag].isna().any(): @@ -1162,12 +1340,15 @@ def acs_local_take_up_signal_gate(frame: Frame) -> GateResult: failures.append(f"Missing person origin tags: {person_tag}.") elif household_tag not in household or household[household_tag].isna().any(): failures.append(f"Missing household origin tags: {household_tag}.") + elif tax_tag not in tax_unit or tax_unit[tax_tag].isna().any(): + failures.append(f"Missing tax-unit origin tags: {tax_tag}.") else: weights = np.asarray(frame.resolve_weights("spm_unit").values, dtype=float) person_weights = np.asarray(frame.resolve_weights("person").values, dtype=float) household_weights = np.asarray( frame.resolve_weights("household").values, dtype=float ) + tax_weights = np.asarray(frame.resolve_weights("tax_unit").values, dtype=float) head_start_share: float | None = None if _HEAD_START in person and _AGE_COLUMN in person: try: @@ -1253,11 +1434,43 @@ def acs_local_take_up_signal_gate(frame: Frame) -> GateResult: columns=columns, ) ] + for table, entity, selected_rows, entity_weights, column, band in ( + ( + tax_unit, + "tax_unit", + tax_unit[tax_tag].eq(spine).to_numpy(dtype=bool), + tax_weights, + US_EITC_TAKE_UP_OUTPUT_COLUMN, + _EITC_SHARE_BAND, + ), + ( + person, + "person", + person[person_tag].eq(spine).to_numpy(dtype=bool), + person_weights, + US_WIC_TAKE_UP_COLUMN, + None, + ), + ): + failures += [ + f"{spine}: {failure}" + for failure in _grade_take_up_flag( + table, + selected_rows, + column, + entity_weights, + band, + entity=entity, + graded=graded, + columns=columns, + ) + ] known = {ASEC_PUF_DONOR_SPINE, ACS_2024_1YR_SPINE} if ( set(spm_unit[tag].unique()) - known or set(person[person_tag].unique()) - known or set(household[household_tag].unique()) - known + or set(tax_unit[tax_tag].unique()) - known ): failures.append("Local take-up origin tags contain an unsupported spine.") return GateResult( diff --git a/packages/microcosm-build/src/microcosm/build/us_runtime/acs_local_wic_take_up.py b/packages/microcosm-build/src/microcosm/build/us_runtime/acs_local_wic_take_up.py new file mode 100644 index 0000000000..633f271e77 --- /dev/null +++ b/packages/microcosm-build/src/microcosm/build/us_runtime/acs_local_wic_take_up.py @@ -0,0 +1,155 @@ +"""WIC take-up for the ACS rows of the retained ACS local lane (microcosm#1154). + +The national draws ``takes_up_wic_if_eligible`` once per person in the +``wic_claim_input`` stage (:mod:`~microcosm.build.us_runtime.wic_claim`): a +stable seeded Bernoulli at USDA FNS's CY2022 coverage rate for the person's +WIC category. The ACS transfer does not carry the flag and no later stage drew +it for ACS rows, so the engine pass filled the engine default, ``True``, and +every eligible ACS person took WIC up (microcosm#1155). This module carries +PolicyEngine/microcosm#1156's repair onto the current lane: + +- :func:`with_acs_local_wic_take_up` runs the national generator, unchanged, + on the ACS-only frame after the transfer has completed the inputs it reads + (``is_pregnant`` and ``own_children_in_household``) and before the frame is + pooled with the donor. The loader's source identity (``source_year``, + ``source_household_id``, ``source_person_id``) still keys each person's draw + there. Categories, rates and draws stay the generator's. +- :func:`require_complete_us_wic_take_up` refuses an absent, partly missing or + non-boolean column. The pool builder holds the donor to it before it loads + any ACS record, since donor decisions are kept and never redrawn, and holds + the pooled frame to it after assembly. The release tool holds the staging + frame to it, refuses a null cell before any reviewed fill, and grades both + spines on the packaged bytes + (:func:`~microcosm.build.us_runtime.acs_local_take_up.acs_local_take_up_signal_gate`). + +The rates are shares of the eligible in each category, so the ACS rows draw at +the national's rates with no adjustment for the pooled record count. +""" + +from __future__ import annotations + +import numpy as np +import pandas as pd + +from microcosm.build.us_runtime.wic_claim import ( + _SOURCE_IDENTITY_COLUMNS, + US_WIC_CLAIM_OUTPUT_COLUMNS, + WIC_CLAIM_FNS_SOURCE_URL, + us_wic_claim_summary, + with_us_wic_claim_input, +) +from microcosm.frame import Frame +from microcosm.frame.units import US_SCHEMA + +__all__ = [ + "ACS_LOCAL_WIC_TAKE_UP_ISSUE", + "US_WIC_TAKE_UP_COLUMN", + "require_complete_us_wic_take_up", + "with_acs_local_wic_take_up", +] + +ACS_LOCAL_WIC_TAKE_UP_ISSUE = "microcosm#1154" +(US_WIC_TAKE_UP_COLUMN,) = US_WIC_CLAIM_OUTPUT_COLUMNS + + +def require_complete_us_wic_take_up(person: pd.DataFrame, *, what: str) -> None: + """Refuse an absent, partly missing or non-boolean WIC take-up column. + + Never fills: a missing decision would reach the engine as its default, + ``True``, universal WIC take-up. + + Raises: + ValueError: naming ``what`` (the frame being checked). + """ + + column = US_WIC_TAKE_UP_COLUMN + if column not in person: + raise ValueError( + f"{what}: WIC take-up requires person column {column!r} " + f"({ACS_LOCAL_WIC_TAKE_UP_ISSUE}); without it the engine default " + "makes every eligible person take WIC up." + ) + missing = int(person[column].isna().sum()) + if missing: + raise ValueError( + f"{what}: WIC take-up {column!r} is missing on {missing} of " + f"{len(person)} person rows ({ACS_LOCAL_WIC_TAKE_UP_ISSUE}); re-run " + "staging with the current builder, which draws the ACS rows' " + "decisions." + ) + if not pd.api.types.is_bool_dtype(person[column].dtype): + raise ValueError( + f"{what}: WIC take-up {column!r} must be boolean, not " + f"{person[column].dtype} ({ACS_LOCAL_WIC_TAKE_UP_ISSUE})." + ) + + +def with_acs_local_wic_take_up( + frame: Frame, *, seed: int, time_period: int +) -> tuple[Frame, dict[str, object]]: + """Draw WIC take-up for an ACS-only frame with the national's generator. + + Args: + frame: The transferred ACS frame, before it is pooled with the donor. + Every person must carry the loader's source identity, from + ``time_period``, and no WIC decision yet. + seed: The build seed, the one the transfer uses. + time_period: The ACS vintage, which is also every person's + ``source_year``. + + Returns: + The frame with a complete boolean ``takes_up_wic_if_eligible`` and a + JSON-ready receipt: the seed, the source, the weighted take-up share + overall and per WIC category, and the category counts. + + Raises: + ValueError: If the frame is not US-schema, already carries a decision, + lacks a complete source identity, or holds a person whose + ``source_year`` is not ``time_period`` (a donor row). + """ + + if frame.schema != US_SCHEMA: + raise ValueError("ACS WIC take-up requires the US schema.") + person = frame.table("person") + column = US_WIC_TAKE_UP_COLUMN + if column in person and person[column].notna().any(): + raise ValueError( + f"ACS WIC take-up: the ACS frame already carries {column!r}; the " + "transfer must not, and donor decisions are never redrawn." + ) + missing = [name for name in _SOURCE_IDENTITY_COLUMNS if name not in person] + if missing: + raise ValueError( + f"ACS WIC take-up requires the loader's source identity: {missing}." + ) + if person.loc[:, list(_SOURCE_IDENTITY_COLUMNS)].isna().any(axis=None): + raise ValueError( + "ACS WIC take-up requires a complete source identity on every person." + ) + years = pd.to_numeric(person["source_year"], errors="coerce").to_numpy() + if not np.all(years == int(time_period)): + raise ValueError( + f"ACS WIC take-up draws ACS rows only: every source_year must be " + f"{int(time_period)}." + ) + # The generator writes the whole column when any cell is missing, so an + # all-null column from the pooled schema is simply replaced. + result = with_us_wic_claim_input( + frame, seed=int(seed), time_period=int(time_period) + ) + require_complete_us_wic_take_up(result.table("person"), what="ACS WIC take-up") + summary = us_wic_claim_summary(result) + receipt: dict[str, object] = { + "issue": ACS_LOCAL_WIC_TAKE_UP_ISSUE, + "design": "microcosm#1156", + "seed": int(seed), + "source_year": int(time_period), + "person_rows": int(len(result.table("person"))), + "output_columns": list(US_WIC_CLAIM_OUTPUT_COLUMNS), + "category_rates_source": WIC_CLAIM_FNS_SOURCE_URL, + "category_rates": summary["category_rates"], + "weighted_take_up_share": summary["weighted_claim_share"], + "category_counts": summary["category_counts"], + "category_weighted_take_up_shares": summary["category_weighted_claim_shares"], + } + return result, receipt diff --git a/packages/microcosm-build/src/microcosm/build/us_runtime/acs_local_work_disability.py b/packages/microcosm-build/src/microcosm/build/us_runtime/acs_local_work_disability.py index 8852b34ecd..13a3e1310a 100644 --- a/packages/microcosm-build/src/microcosm/build/us_runtime/acs_local_work_disability.py +++ b/packages/microcosm-build/src/microcosm/build/us_runtime/acs_local_work_disability.py @@ -27,12 +27,11 @@ codes must be 1 or 2, and a code below the minimum age is refused. - **weeks_worked** is ``WKWN`` under the ``WKHP`` universe rules (:func:`~microcosm.build.us_runtime.acs_inputs.acs_weeks_worked_values`), - and must be blank exactly where ``WKHP`` is. It is carried on the staging - ACS spine only. Under the pinned policyengine-us, ``weeks_worked`` has a - ``formula_2025``, so the consumer export's ``project_input_only`` holds it - back as formula-owned. Exporting it needs policyengine-us#9660 (part A1 - deletes that formula) and a pin/ABI bump; until then staging records it - and this module's gate checks it, and nothing downstream reads it. + and must be blank exactly where ``WKHP`` is. On policyengine-us 2.145.3 it + is an input (policyengine-us#9660 part A1 deleted its ``formula_2025``), so + the consumer export carries it, and the reviewed fill gives its blank cells + the value 0, which the donor gives its own not-in-universe rows. Staging + grades it here. Not exported (see the receipt's ``not_exported``): @@ -84,7 +83,7 @@ "ACS_LOCAL_WORK_DISABILITY_ISSUE", "ACS_NATIVE_PROVENANCE", "WEEKS_WORKED_COLUMN", - "WEEKS_WORKED_EXPORT_BLOCKER", + "WEEKS_WORKED_INPUT_CHANGE", "AcsLocalWorkDisabilityResult", "acs_local_work_disability_signal_gate", "map_acs_local_work_disability_inputs", @@ -107,7 +106,9 @@ WEEKS_WORKED_COLUMN, ) #: What must land before ``weeks_worked`` can reach the consumer export. -WEEKS_WORKED_EXPORT_BLOCKER = "policyengine-us#9660" +#: The engine change that made ``weeks_worked`` an input: part A1 deleted +#: its ``formula_2025``, so the consumer export carries it. +WEEKS_WORKED_INPUT_CHANGE = "policyengine-us#9660" _AGE = "age" _USUAL_HOURS = "weekly_hours_worked_before_lsr" @@ -338,14 +339,14 @@ def map_acs_local_work_disability_inputs(frame: Frame) -> AcsLocalWorkDisability "hours_paired_rows", ) }, - "exported": False, - "export_blocker": WEEKS_WORKED_EXPORT_BLOCKER, + "exported": True, + "input_since": WEEKS_WORKED_INPUT_CHANGE, "export_note": ( - "Carried on the staging ACS spine only: the pinned " - "policyengine-us gives weeks_worked a formula_2025, so the " - "consumer export holds it back as formula-owned until " - f"{WEEKS_WORKED_EXPORT_BLOCKER} deletes that formula and the " - "pin and ABI lock are bumped. Under-16 rows stay missing." + "Exported: on policyengine-us 2.145.3 weeks_worked is an " + f"input ({WEEKS_WORKED_INPUT_CHANGE} deleted its formula_2025). " + "Its blank cells, under-16 rows among them, take the reviewed " + "fill 0, the value the donor gives its own not-in-universe " + "rows." ), }, "not_exported": {key: dict(value) for key, value in _NOT_EXPORTED.items()}, @@ -635,8 +636,9 @@ def acs_local_work_disability_signal_gate( a native source with zero transfer-imputed cells. With ``require_weeks_worked`` (staging), the ACS spine must also carry ``weeks_worked`` equal to its native ``WKWN`` mapping, non-constant, and - paired with usual hours. The finalize run passes ``False``: the consumer - export holds ``weeks_worked`` back until ``WEEKS_WORKED_EXPORT_BLOCKER``. + paired with usual hours. The finalize run passes ``False``: staging grades + ``weeks_worked`` where its blanks are the ACS universe's, and the packaged + file carries the reviewed fill in those cells. Details report, informationally, the ACS difficulty-only share (ACS DIS), the SSI increment and the ``is_disabled``/``is_blind`` shares by age band @@ -696,9 +698,9 @@ def acs_local_work_disability_signal_gate( details[WEEKS_WORKED_COLUMN] = { "evaluated": False, "reason": ( - "The consumer export holds weeks_worked back as formula-owned " - f"under the pinned policyengine-us until " - f"{WEEKS_WORKED_EXPORT_BLOCKER}; staging graded it." + "Staging graded weeks_worked where its blanks are the ACS " + "universe's; the packaged file carries the reviewed fill in " + f"those cells ({WEEKS_WORKED_INPUT_CHANGE} made it an input)." ), } if set(person[tag].unique()) - {ASEC_PUF_DONOR_SPINE, ACS_2024_1YR_SPINE}: diff --git a/packages/microcosm-build/src/microcosm/build/us_runtime/acs_multispine.py b/packages/microcosm-build/src/microcosm/build/us_runtime/acs_multispine.py index 5bae4819e1..6c3cb9059f 100644 --- a/packages/microcosm-build/src/microcosm/build/us_runtime/acs_multispine.py +++ b/packages/microcosm-build/src/microcosm/build/us_runtime/acs_multispine.py @@ -27,6 +27,10 @@ with_acs_spm_independence_role, without_acs_group_quarters_children, ) +from microcosm.build.us_runtime.acs_local_esi_premiums import ( + acs_local_esi_premium_transfer_target_families, + with_acs_local_esi_premium_anchor, +) from microcosm.build.us_runtime.acs_local_hours import ( acs_local_hours_transfer_target_families, complete_acs_local_under15_hours, @@ -45,6 +49,10 @@ require_acs_receipt_anchor_sources, with_acs_local_snap_receipt_anchor, ) +from microcosm.build.us_runtime.acs_local_wic_take_up import ( + require_complete_us_wic_take_up, + with_acs_local_wic_take_up, +) from microcosm.build.us_runtime.acs_local_work_disability import ( map_acs_local_work_disability_inputs, record_acs_local_work_disability_transfer, @@ -118,9 +126,12 @@ def build_optional_acs_multispine( hours_donor_factory: Callable[[Frame], tuple[Frame, Frame, dict[str, object]]] | None = None, hours_under15_policy: str | None = None, + esi_premium_donor_factory: Callable[[Frame], tuple[Frame, dict[str, object]]] + | None = None, work_disability_inputs: bool = False, income_transfer: bool = False, native_receipt_anchors: bool = False, + wic_take_up: bool = False, semp_covers_partnership_income: bool = False, donor_spine: str = ASEC_PUF_DONOR_SPINE, donor_channel: str | None = ACS_DONOR_CHANNEL_AUTO, @@ -165,13 +176,29 @@ def build_optional_acs_multispine( public-assistance counts it records against ``receives_tanf``) is ``provenance["acs_local_receipt_anchors"]``. The source is checked before any fit. + ``wic_take_up`` (the ACS local lane, microcosm#1154, the design of + microcosm#1156) draws the ACS rows' ``takes_up_wic_if_eligible`` with the + national generator after the shared transfer, which completes the + pregnancy and own-children inputs it reads, and before pooling, while the + loader's source identity keys each draw. The donor's decisions are kept: + they must be complete before the ACS spine is loaded, and the pooled frame + after assembly. Its receipt is ``provenance["wic_take_up"]``. ``semp_covers_partnership_income`` (the ACS local lane, microcosm#1387) tells the shared transfer that ACS ``SEMP`` already includes own-partnership income, so a ``partnership_income`` draw is kept at zero where the row's or its tax unit's SEMP accounts for it (see :func:`~microcosm.build.us_runtime.acs_transfer.keep_semp_covered_partnership_income`). - Only the shared call receives it; the hours and income passes do not - draw ``partnership_income``. + Only the shared call receives it; the hours, income and ESI passes do + not draw ``partnership_income``. + ``esi_premium_donor_factory`` (the ACS local lane, microcosm#454) + qualifies the base as the donor of the employer premium and returns its + ASEC observation role. The premium then reaches the ACS rows through its + own ASEC-only pass, after the income pass and immediately before the + shared transfer, so the hours and income passes see the frame they saw + without it. After pooling, the frame is held to the donor rows' premium + per unit of household mass + (:func:`~.acs_local_esi_premiums.with_acs_local_esi_premium_anchor`). Its + receipt is ``provenance["local_esi_premiums"]``. Large intermediate frames are released as soon as the next stage has materialized its own frame. This cannot make the final dense pool small, @@ -211,6 +238,10 @@ def build_optional_acs_multispine( donor_location_rule=donor_location_rule, ) + if wic_take_up: + # microcosm#1154: the donor's WIC decisions are kept, never redrawn, + # so they must be complete before any ACS record is loaded. + require_complete_us_wic_take_up(base.table("person"), what="ACS pool donor") raw_acs, loader_metadata = build_acs_pums_unit_frame( source, chunksize=chunksize, @@ -362,6 +393,32 @@ def build_optional_acs_multispine( ) income_receipt["resolved_donor_channel"] = income.resolved_donor_channel del income + esi_fit_records = () + esi_imputed_inputs = () + esi_donor_channel = None + esi_source = None + if esi_premium_donor_factory is not None: + # Local lane only (microcosm#454). The premium follows measured wages, + # so it fits on the ASEC observation role like usual hours, not on the + # PUF-detail role the tax details use: that role's wages are + # PUF-imputed. It runs last before the shared transfer, so the hours + # and income passes see exactly the frame they see without it. + esi_donor, esi_source = esi_premium_donor_factory(base) + esi_transfer = transfer_acs_inputs( + mapped_frame, + esi_donor, + target_families=acs_local_esi_premium_transfer_target_families(), + donor_spine=donor_spine, + donor_channel=BASE_ASEC_SUPPORT_CHANNEL, + seed=seed, + n_estimators=n_estimators, + max_targets_per_fit=max_targets_per_fit, + ) + mapped_frame = esi_transfer.frame + esi_fit_records = tuple(esi_transfer.fit_records) + esi_imputed_inputs = tuple(esi_transfer.imputed_inputs) + esi_donor_channel = esi_transfer.resolved_donor_channel + del esi_transfer, esi_donor transferred = transfer_acs_inputs( mapped_frame, base, @@ -380,10 +437,16 @@ def build_optional_acs_multispine( del mapped_frame adult_care_gate = _require_recipient_adult_care_structure(transferred.frame) fit_records = ( - hours_fit_records + income_fit_records + tuple(transferred.fit_records) + hours_fit_records + + income_fit_records + + esi_fit_records + + tuple(transferred.fit_records) ) imputed_provenance = _json_ready_sequence( - hours_imputed_inputs + income_imputed_inputs + tuple(transferred.imputed_inputs) + hours_imputed_inputs + + income_imputed_inputs + + esi_imputed_inputs + + tuple(transferred.imputed_inputs) ) deferred_inputs = tuple(transferred.deferred_inputs) if block_location: @@ -414,6 +477,15 @@ def build_optional_acs_multispine( transferred_frame, receipt_anchors = with_acs_local_snap_receipt_anchor( transferred_frame ) + # microcosm#1154 (the design of microcosm#1156): the transfer has completed + # the pregnancy and own-children inputs, and the frame still holds ACS + # rows only with the loader's source identity, so the national generator + # draws the ACS rows' WIC decisions here, before pooling. + wic_take_up_receipt = None + if wic_take_up: + transferred_frame, wic_take_up_receipt = with_acs_local_wic_take_up( + transferred_frame, seed=seed, time_period=source.vintage + ) pool_options: dict[str, Any] = {"acs_share": acs_share} if block_location: @@ -442,6 +514,13 @@ def build_optional_acs_multispine( ) pooled = with_optional_acs_spine(base, transferred_frame, **pool_options) del transferred_frame + esi_anchor = None + if esi_premium_donor_factory is not None: + # Pooling has set each spine's share of household mass; the anchor + # reads it from the live frame. + pooled, esi_anchor = with_acs_local_esi_premium_anchor(pooled) + if wic_take_up: + require_complete_us_wic_take_up(pooled.table("person"), what="ACS pool") provenance = { "enabled": True, @@ -465,11 +544,18 @@ def build_optional_acs_multispine( "max_targets_per_fit": max_targets_per_fit, }, } + if wic_take_up_receipt is not None: + provenance["wic_take_up"] = _json_ready(wic_take_up_receipt) if hours_donor is not None or hours_donor_factory is not None: provenance["fit_configuration"]["hours_donor_channel"] = hours_donor_channel provenance["local_hours_source"] = hours_source if modeled_hours is not None: provenance["hours_modeled_completion"] = modeled_hours + if esi_premium_donor_factory is not None: + provenance["fit_configuration"]["esi_premium_donor_channel"] = esi_donor_channel + provenance["local_esi_premiums"] = _json_ready_mapping( + {"source": esi_source, "anchor": esi_anchor} + ) if income_receipt is not None: provenance["fit_configuration"]["income_donor_channel"] = income_receipt[ "resolved_donor_channel" diff --git a/packages/microcosm-build/src/microcosm/build/us_runtime/battery_bindings.py b/packages/microcosm-build/src/microcosm/build/us_runtime/battery_bindings.py index 1ce949326f..bd687e4f08 100644 --- a/packages/microcosm-build/src/microcosm/build/us_runtime/battery_bindings.py +++ b/packages/microcosm-build/src/microcosm/build/us_runtime/battery_bindings.py @@ -1479,6 +1479,37 @@ def _us_local_specs() -> tuple[USGateSpec, ...]: arguments={"receipt": "receipt_anchors_receipt"}, pinned=_pins("acs_local_receipt_anchors", "ACS_SNAP_HOUSEHOLD_SHARE_BAND"), ), + # The lane's ESI premium gates grade the pooled frame by row kind + # (allow_transferred_rows=True), so they bind the lane's own callables, + # not the shared ESI checks, which keep the default and refuse an ACS + # row. Each pins the national entry's constants and the band the ACS + # rows are compared against. + USGateSpec( + check="esi_premiums_signal", + legacy_name="esi_premiums_signal", + gate="tool:acs_local_esi_premium_signal_gate", + positional=(FRAME,), + pinned=_pins( + "esi_premiums", + "_POSITIVE_SHARE_BAND", + "_RAW_MEAN_BAND", + "_TRANSFERRED_TO_SOURCE_BAND", + ), + ), + USGateSpec( + check="esi_premiums_anchor", + legacy_name="esi_premiums_anchor", + gate="tool:acs_local_esi_premium_anchor_gate", + positional=(FRAME,), + arguments={"time_period": "time_period"}, + pinned=_pins( + "esi_premiums", + "ANCHOR_RELATIVE_TOLERANCE", + "_EMPLOYED_SHARE_BAND", + "_RAW_MEAN_BAND", + "_TRANSFERRED_PER_MASS_BAND", + ), + ), USGateSpec( check="reviewed_fill_consumers", legacy_name="acs_local_reviewed_fill_consumers", diff --git a/packages/microcosm-build/src/microcosm/build/us_runtime/esi_premiums.py b/packages/microcosm-build/src/microcosm/build/us_runtime/esi_premiums.py index 86f612526c..a16dae5d13 100644 --- a/packages/microcosm-build/src/microcosm/build/us_runtime/esi_premiums.py +++ b/packages/microcosm-build/src/microcosm/build/us_runtime/esi_premiums.py @@ -75,6 +75,36 @@ the column matches within half a percent on the pinned pools. Neither is gated. +Frames that mix CPS and transferred rows +---------------------------------------- +A frame can hold CPS rows, which carry the raw ASEC columns, beside rows a +cross-source transfer filled, which carry none of them: the ACS local lane's +pooled frame is one. The summary and both gates take the keyword-only +``allow_transferred_rows``: + +* ``False``, the default (Route A's base builder and release, and the + idempotent branch of :func:`with_us_esi_premium_inputs`): every row must + carry every raw ASEC field, and a row without them is refused. ``PERIDNUM`` + is not read. +* ``True`` (the ACS local lane): a row is transferred only if it has none of + the raw fields and no CPS record id (``PERIDNUM``). A row with some of the + fields, a CPS record without them, a row with them but no id, and any + incomplete row in a frame without the id column are refused, so lost + coverage codes cannot pass as a transfer. The CPS rows are graded as on a + single-source frame, and the transferred rows are summarized against them. + +When every row is a CPS row, the summary computes every figure as it does for +a single-source frame, under either setting. + +Once the transfer has filled every other row, +:func:`with_us_esi_premium_pool_anchor` gives each support clone its source +record's draw, clears the premium where that record reports zero wages, and +scales the transferred premiums to the CPS rows' weighted total per unit of +household mass. A missing wage is refused, not read as zero. The transferred +rows have no policyholder flag, so the anchor-universe total a gate derives +for a mixed frame assumes employed policyholders carry the same share of it +there as on the CPS rows. + Not produced here ----------------- ``pre_tax_health_insurance_premiums``, the employee share paid by pre-tax @@ -110,6 +140,11 @@ SourceRuntimeError, run_source_stage, ) +from microcosm.build.us_runtime.acs_income_universe import ( + ACS_PUMS_EARNINGS_SOURCE_COLUMNS, + ACS_PUMS_EARNINGS_UNIVERSE_PERSON_INPUTS, + resolve_acs_pums_earnings_universe, +) from microcosm.frame import Frame from microcosm.frame.units import US_SCHEMA @@ -117,8 +152,11 @@ "US_ESI_EMPLOYER_PREMIUM_COLUMN", "US_ESI_PREMIUMS_NONCONSTANT_PERSON_COLUMNS", "US_ESI_PREMIUMS_OUTPUT_COLUMNS", + "US_ESI_PREMIUMS_CPS_RECORD_COLUMN", + "US_ESI_PREMIUMS_POOL_ANCHOR_PERSON_INPUTS", "US_ESI_PREMIUMS_REQUIRED_SOURCE_COLUMNS", "US_ESI_PREMIUMS_STAGE_NAME", + "US_ESI_PREMIUMS_WAGE_COLUMN", "derive_us_employer_esi_premiums_from_manifest", "load_meps_ic_esi_premium_cells", "meps_ic_private_active_employer_totals", @@ -129,6 +167,7 @@ "us_esi_premiums_stage_spec", "us_esi_premiums_summary", "with_us_esi_premium_inputs", + "with_us_esi_premium_pool_anchor", ] US_ESI_PREMIUMS_STAGE_NAME = "meps_esi_premiums" @@ -194,6 +233,59 @@ _PRIVATE_EMPLOYER_CODES = (4, 5, 6) _EMPLOYER_SECTOR_CODES = (_FEDERAL, _STATE_GOVERNMENT, _LOCAL_GOVERNMENT, 4, 5, 6) +#: Wages of a person without raw ASEC columns: the canonical input ACS maps +#: natively from ``WAGP`` (:mod:`.acs_inputs`). +US_ESI_PREMIUMS_WAGE_COLUMN = "employment_income_before_lsr" +#: The raw ASEC person columns whose presence marks a row the stage derived +#: itself. ``state_fips`` is on the household of every source. +_RAW_EVIDENCE_COLUMNS: tuple[str, ...] = tuple( + column + for column in US_ESI_PREMIUMS_REQUIRED_SOURCE_COLUMNS + if column != "state_fips" +) +#: The raw ASEC record id. A pool marks its CPS-source rows by it, so it +#: corroborates the row kind the raw coverage fields imply: a CPS record +#: always carries those fields, and a row without the id never had them. +US_ESI_PREMIUMS_CPS_RECORD_COLUMN = "PERIDNUM" +_CPS_EVIDENCE_COLUMN = US_ESI_PREMIUMS_CPS_RECORD_COLUMN +#: The raw ACS wage behind the mapped wage. A transferred person's wage must be +#: evidence: the raw field reported, or blank only below the ACS earnings age. +_RAW_ACS_WAGE_COLUMN = ACS_PUMS_EARNINGS_SOURCE_COLUMNS[US_ESI_PREMIUMS_WAGE_COLUMN] +_PERSON_SOURCE_ID_COLUMN = "person_source_id" +_PERSON_CLONE_INDEX_COLUMN = "person_support_clone_index" +#: Every assembled person column :func:`with_us_esi_premium_pool_anchor` reads +#: besides the stage output, with the provision that supplies it, for a +#: caller's input manifest. +US_ESI_PREMIUMS_POOL_ANCHOR_PERSON_INPUTS: Mapping[str, str] = MappingProxyType( + { + **dict.fromkeys( + (*_RAW_EVIDENCE_COLUMNS, _CPS_EVIDENCE_COLUMN), + "assembled_raw_asec_source_evidence", + ), + US_ESI_PREMIUMS_WAGE_COLUMN: "assembled_native_person_input", + _RAW_ACS_WAGE_COLUMN: "assembled_raw_acs_source_authority", + # The ACS earnings universe the wage evidence is resolved against: + # age, tax-unit membership and support provenance. + **ACS_PUMS_EARNINGS_UNIVERSE_PERSON_INPUTS, + _PERSON_SOURCE_ID_COLUMN: "assembly_support_source_identity", + _PERSON_CLONE_INDEX_COLUMN: "assembly_support_provenance", + } +) +#: Relative tolerance of a pool's weighted employer total around the +#: CPS-source total divided by its mass share, straight after +#: :func:`with_us_esi_premium_pool_anchor`. +_POOL_ANCHOR_RTOL = 1e-9 +#: Transferred rows against source-derived rows, for the weighted share with a +#: positive employer premium and its mean. The pool anchor holds the totals, +#: so these ratios are what show a transfer that put the premiums on the wrong +#: people. +_TRANSFERRED_TO_SOURCE_BAND = (0.5, 2.0) +#: Transferred rows' weighted employer premium per unit of household mass over +#: the source-derived rows'. The pool anchor sets it to 1; calibration and +#: sparse selection move it. Outside this band a mixed frame's anchor-universe +#: total no longer rests on comparable halves. +_TRANSFERRED_PER_MASS_BAND = (0.8, 1.25) + _CELLS_RESOURCE = "meps_ic_esi_premium_cells.json" _CELLS_SHA256 = "29a5502abbd921e70007d6bcec8ed1ae065b309cacfa80f49f9bc4dd9a28ec93" _PERSON_WEIGHT_COLUMN = "person_weight" @@ -860,10 +952,13 @@ def refuse_unassigned_us_esi_premiums(frame: Frame, *, consumer: str) -> None: """Refuse a frame whose ESI employer premium input is null on some rows. A lineage that pools rows the stage never ran on (ACS-spine rows beside an - ASEC donor that carries the column) leaves it null there. Filling those - with the engine default would ship a column that is zero on part of the - population yet looks populated, and no anchor gate runs on that lineage, so - the consumer refuses instead. + ASEC donor that carries the column) leaves it null there unless something + assigns it. Filling those with the engine default would ship a column that + is zero on part of the population yet looks populated. The ACS local lane + transfers the premium onto its ACS rows and grades it with both ESI gates + (``acs_local_esi_premiums``), so on that lineage a null means an older + staging frame or one a diagnostic build waived (``--allow-esi-premium-gaps``). + The consumer refuses it, as the backstop. """ person = frame.table("person") @@ -881,6 +976,436 @@ def refuse_unassigned_us_esi_premiums(frame: Frame, *, consumer: str) -> None: ) +def _cps_record_evidence(person: pd.DataFrame) -> np.ndarray | None: + """Rows that carry a CPS record id; ``None`` if the frame has no such column.""" + + if _CPS_EVIDENCE_COLUMN not in person.columns: + return None + evidence = person[_CPS_EVIDENCE_COLUMN] + available = evidence.notna() + if pd.api.types.is_string_dtype(evidence.dtype) or evidence.dtype == object: + available &= evidence.astype("string").str.strip().ne("").fillna(False) + return available.to_numpy(dtype=bool) + + +def _raw_evidence_mask( + person: pd.DataFrame, *, allow_transferred_rows: bool = False +) -> np.ndarray: + """Rows whose premiums the stage derived from measured ASEC fields. + + A single-source frame carries the raw fields on every row. Without + ``allow_transferred_rows`` that is the only frame accepted: a row that + lacks any raw field is refused, naming each field that is missing and on + how many rows, and the CPS record id is not read. + + With it, a frame may also hold rows a cross-source transfer filled, with + transferred premiums and nulls in all of the fields. A row with some of + the fields is neither, and is refused. Nulls alone do not make a row + transferred: a CPS record that lost its fields would look the same. The + CPS record id decides. A row with the id must carry every field, a row + with the fields must carry the id, and a frame without the id column + cannot hold transferred rows at all. + """ + + present = person[list(_RAW_EVIDENCE_COLUMNS)].notna().to_numpy(dtype=bool) + complete = present.all(axis=1) + if not allow_transferred_rows: + if not complete.all(): + gaps = [ + f"{column} has {int(count)} missing row(s)" + for column, count in zip( + _RAW_EVIDENCE_COLUMNS, (~present).sum(axis=0), strict=True + ) + if count + ] + not_restored = ( + "the Census column was not restored for every vintage " + "(asec_census_person_columns) and is never defaulted" + if len(gaps) == 1 + else "the Census columns were not restored for every vintage " + "(asec_census_person_columns) and are never defaulted" + ) + raise SourceRuntimeError( + f"US ESI premium stage: {int((~complete).sum())} row(s) lack some " + f"of the raw ASEC fields: {', '.join(gaps)}; {not_restored}. " + "Only a frame that holds transferred ACS rows needs " + "allow_transferred_rows=True; on any other frame, restore the " + "fields." + ) + return complete + partial = present.any(axis=1) & ~complete + if partial.any(): + raise SourceRuntimeError( + f"US ESI premium stage: {int(partial.sum())} row(s) carry only some " + f"of the raw ASEC fields {list(_RAW_EVIDENCE_COLUMNS)}; a row is " + "either source-derived (all present) or transferred (all null)." + ) + evidenced = _cps_record_evidence(person) + if evidenced is None: + if not complete.all(): + raise SourceRuntimeError( + f"US ESI premium stage: {int((~complete).sum())} row(s) carry " + "none of the raw ASEC fields and the frame has no " + f"{_CPS_EVIDENCE_COLUMN!r} column to show they are not CPS " + "records that lost them. Only a frame that marks its CPS " + "records can hold transferred rows." + ) + return complete + lost = evidenced & ~complete + if lost.any(): + raise SourceRuntimeError( + f"US ESI premium stage: {int(lost.sum())} CPS record(s) " + f"({_CPS_EVIDENCE_COLUMN!r} present) lack the raw ASEC fields. A CPS " + "record's premium is recomputed from those fields; it is never " + "graded as transferred." + ) + stray = complete & ~evidenced + if stray.any(): + raise SourceRuntimeError( + f"US ESI premium stage: {int(stray.sum())} row(s) carry the raw ASEC " + f"fields without a CPS record id ({_CPS_EVIDENCE_COLUMN!r})." + ) + return complete + + +def _household_masses( + frame: Frame, person_rows: np.ndarray | pd.Series +) -> tuple[float, float]: + """Household mass in the households of ``person_rows``, and in the others. + + Each side is summed on its own, so a side holds exactly its own weight at + any scale and a ratio of the two never loses a small side to rounding. A + household whose members fall on both sides is refused. + """ + + rows = np.asarray(person_rows, dtype=bool) + person = frame.table("person") + if rows.shape != (len(person),): + raise SourceRuntimeError( + "US ESI premium household mass share needs one flag per person." + ) + membership = person[frame.schema.membership_column("household")] + household_ids = frame.table("household")[frame.schema.entity_id_column("household")] + selected = household_ids.isin(membership[rows]).to_numpy(dtype=bool) + unselected = household_ids.isin(membership[~rows]).to_numpy(dtype=bool) + if (selected & unselected).any(): + raise SourceRuntimeError( + f"US ESI premium stage: {int((selected & unselected).sum())} " + "household(s) mix source-derived and transferred people." + ) + weights = np.asarray(frame.resolve_weights("household").values, dtype=np.float64) + if not (np.isfinite(weights).all() and (weights >= 0).all()): + raise SourceRuntimeError( + "US ESI premium stage requires finite nonnegative household weights." + ) + selected_mass = float(weights[selected].sum()) + unselected_mass = float(weights[unselected].sum()) + if not selected_mass + unselected_mass > 0: + raise SourceRuntimeError( + "US ESI premium stage requires household weights with positive mass." + ) + return selected_mass, unselected_mass + + +def _source_record_values(person: pd.DataFrame, values: np.ndarray) -> np.ndarray: + """Each row's value on its clone-0 source record, for every support clone. + + A support clone is the same surveyed person with another tax-detail + vector. Frames without clone provenance hold source records only, and + ``values`` is returned as it is. + """ + + if not {_PERSON_SOURCE_ID_COLUMN, _PERSON_CLONE_INDEX_COLUMN} <= set( + person.columns + ): + return values + native = ( + pd.to_numeric(person[_PERSON_CLONE_INDEX_COLUMN], errors="coerce") + .eq(0) + .to_numpy(dtype=bool) + ) + source_id = person[_PERSON_SOURCE_ID_COLUMN] + by_source = pd.Series(values[native], index=source_id[native].to_numpy()) + if not by_source.index.is_unique: + raise SourceRuntimeError( + "US ESI premium stage: source records repeat a " + f"{_PERSON_SOURCE_ID_COLUMN!r}." + ) + orphan = ~source_id.isin(by_source.index).to_numpy(dtype=bool) + if orphan.any(): + raise SourceRuntimeError( + f"US ESI premium stage: {int(orphan.sum())} support clone(s) have no " + "clone-0 source record." + ) + return source_id.map(by_source).to_numpy(dtype=np.float64, na_value=np.nan) + + +def _source_record_wages(person: pd.DataFrame) -> np.ndarray: + """Wages each person's source record reports, for every support clone. + + A clone takes the survey-side wages of its clone-0 record, as the + source-derived rows take one premium per source person. A wage that is + missing or not a number comes back as NaN; the caller decides what a + missing wage means, and it never means zero. + """ + + if US_ESI_PREMIUMS_WAGE_COLUMN not in person.columns: + raise SourceRuntimeError( + "US ESI premium stage: transferred rows need " + f"{US_ESI_PREMIUMS_WAGE_COLUMN!r} to place the premiums' structural " + "zeros." + ) + wages = pd.to_numeric( + person[US_ESI_PREMIUMS_WAGE_COLUMN], errors="coerce" + ).to_numpy(dtype=np.float64, na_value=np.nan) + return _source_record_values(person, wages) + + +def _transferred_wage_evidence( + frame: Frame, transferred: np.ndarray +) -> dict[str, object]: + """Refuse transferred people whose wage is not evidence, and receipt the rest. + + A transferred person's premium is cleared when the source record reports + zero wages, so that zero must be a measurement. The ACS earnings universe + (:func:`resolve_acs_pums_earnings_universe`) says when it is: the raw + ``WAGP`` field reported a value, or is blank below the age Census asks it + from and the mapped wage is the named universe zero. A blank raw field on + an eligible person is missing evidence however a producer filled the + mapped wage, and is refused. + """ + + try: + universe = resolve_acs_pums_earnings_universe( + frame, + columns=(US_ESI_PREMIUMS_WAGE_COLUMN,), + person_scope=transferred, + boundary="US ESI premium pool anchor wage evidence", + ) + except ValueError as error: + raise SourceRuntimeError(str(error)) from error + rule = dict(universe.receipt["rules"][US_ESI_PREMIUMS_WAGE_COLUMN]) + missing = int(rule["in_universe_null_rows"]) + int( + rule["raw_in_universe_null_rows"] + ) + if missing: + raise SourceRuntimeError( + "US ESI premium pool anchor: transferred people the ACS asks for " + f"wages lack them (in_universe_null_rows={rule['in_universe_null_rows']}, " + f"raw_in_universe_null_rows={rule['raw_in_universe_null_rows']} under " + f"{rule['rule_id']}). A missing wage is not a zero wage, even after a " + "producer filled the mapped column." + ) + return { + key: rule[key] + for key in ( + "rule_id", + "eligible_acs_person_rows", + "structurally_absent_person_rows", + "mapped_universe_zero_rows", + ) + } + + +def with_us_esi_premium_pool_anchor(frame: Frame) -> tuple[Frame, dict[str, object]]: + """Hold a mixed frame's transferred employer premiums to the stage's scale. + + Runs once every row carries the stage's outputs: the stage derived them on + the rows with raw ASEC fields, and a cross-source transfer filled the + rest. Rows are told apart as ``allow_transferred_rows=True`` grades them + (:func:`_raw_evidence_mask`). The source-derived rows are never + rewritten. On the transferred rows it + + 1. gives every support clone its clone-0 source record's draw, so a + person carries one premium however the pool ordered its transfer and + its clone; + 2. clears the outputs where that source record reports zero wages (the + stage's universe is people employed by an employer); and + 3. scales the employer premiums by one factor so those rows carry the same + weighted total per unit of household mass as the source-derived rows: + ``source total / source mass x transferred mass``, with each side's + household mass summed on its own. + + A transferred person's source record must report a wage. A missing wage + is refused: it is not evidence of no wages. + + The frame-wide weighted employer premium then equals ``source total / + share``, with ``share`` the source-derived rows' share of household mass, + and each side carries it in proportion to household mass, so reweighting + across sources downstream does not move the total. Transferred rows that + hold no household mass have nothing to scale to and keep the factor at + one. A frame with no transferred row is returned unchanged. Returns the + frame and a receipt. + """ + + if frame.schema != US_SCHEMA: + raise ValueError("US ESI premium pool anchor requires the US schema.") + person = frame.table("person") + missing = [ + column + for column in (*US_ESI_PREMIUMS_OUTPUT_COLUMNS, *_RAW_EVIDENCE_COLUMNS) + if column not in person.columns + ] + if missing: + raise SourceRuntimeError( + f"US ESI premium pool anchor: the person table lacks {missing}; it " + "needs the stage outputs on every row and the raw ASEC fields that " + "mark the source-derived rows." + ) + outputs = { + column: person[column].to_numpy(dtype=np.float64) + for column in US_ESI_PREMIUMS_OUTPUT_COLUMNS + } + for column, values in outputs.items(): + if not np.isfinite(values).all() or (values < 0).any(): + raise SourceRuntimeError( + f"US ESI premium pool anchor: {column} must be finite and " + "nonnegative on every row; the transfer left a gap." + ) + weights = np.asarray(frame.resolve_weights("person").values, dtype=np.float64) + if not np.isfinite(weights).all() or (weights < 0).any(): + raise SourceRuntimeError( + "US ESI premium pool anchor requires finite nonnegative weights." + ) + source = _raw_evidence_mask(person, allow_transferred_rows=True) + transferred = ~source + if not source.any(): + raise SourceRuntimeError( + "US ESI premium pool anchor: no row carries the raw ASEC fields." + ) + employer = outputs[US_ESI_EMPLOYER_PREMIUM_COLUMN] + source_mass, transferred_mass = _household_masses(frame, source) + share = source_mass / (source_mass + transferred_mass) + source_total = _weighted(weights, employer, source) + if not (source_mass > 0 and source_total > 0): + raise SourceRuntimeError( + "US ESI premium pool anchor: the source-derived rows hold no " + "employer premium mass." + ) + # Premium per unit of household mass on the source-derived rows, divided + # out first so every intermediate stays on the scale of the result: any + # finite weights whose correct totals are finite give finite targets. + intensity = source_total / source_mass + target = intensity * transferred_mass + pool_target = source_total + target + if not ( + np.isfinite(intensity) and np.isfinite(target) and np.isfinite(pool_target) + ): + raise SourceRuntimeError( + "US ESI premium pool anchor: the employer premium target is not " + "finite at these household weights." + ) + receipt: dict[str, object] = { + "source_household_mass_share": share, + "source_household_mass": source_mass, + "transferred_household_mass": transferred_mass, + "source_rows": int(source.sum()), + "transferred_rows": int(transferred.sum()), + "source_employer_premium_total": source_total, + "pool_employer_premium_target": pool_target, + "wage_column": US_ESI_PREMIUMS_WAGE_COLUMN, + } + if not transferred.any(): + return frame, receipt | { + "status": "no_transferred_rows", + "employer_premium_total": source_total, + } + + wage_evidence = _transferred_wage_evidence(frame, transferred) + wages = _source_record_wages(person) + unknown = transferred & ~np.isfinite(wages) + if unknown.any(): + raise SourceRuntimeError( + f"US ESI premium pool anchor: {int(unknown.sum())} transferred row(s) " + f"have no finite {US_ESI_PREMIUMS_WAGE_COLUMN!r} on their source " + "record. A missing wage is not a zero wage; map it, or zero it " + "under a named universe rule, before the anchor." + ) + # One premium per source person on the transferred side too. + drawn = { + column: np.where(transferred, _source_record_values(person, values), values) + for column, values in outputs.items() + } + reset = {column: drawn[column] != outputs[column] for column in outputs} + no_wages = transferred & ~(wages > 0) + cleared = {column: no_wages & (values > 0) for column, values in drawn.items()} + before = _weighted( + weights, drawn[US_ESI_EMPLOYER_PREMIUM_COLUMN], transferred & ~no_wages + ) + if target > 0 and not before > 0: + raise SourceRuntimeError( + "US ESI premium pool anchor: the transferred rows hold no employer " + "premium mass on people with wages, so there is nothing to scale." + ) + # Transferred rows without household mass have no total to be held to. + factor = target / before if before > 0 else 1.0 + if not (np.isfinite(factor) and factor >= 0): + raise SourceRuntimeError( + "US ESI premium pool anchor: the transferred rows' scale factor " + f"{factor!r} is not a finite nonnegative number." + ) + receipt |= { + "transferred_household_mass_share": transferred_mass + / (source_mass + transferred_mass), + "transferred_wage_evidence": wage_evidence, + "transferred_rows_reset_to_source_record": { + column: int(rows.sum()) for column, rows in reset.items() + }, + "transferred_rows_without_source_wages": int(no_wages.sum()), + "cleared_rows": {column: int(rows.sum()) for column, rows in cleared.items()}, + "cleared_weighted_total": { + column: _weighted(weights, drawn[column], rows) + for column, rows in cleared.items() + }, + "transferred_employer_premium_total_before": before, + "transferred_employer_premium_target": target, + "scale_factor": factor, + } + settled = ( + not any(rows.any() for rows in reset.values()) + and not any(rows.any() for rows in cleared.values()) + and np.isclose(factor, 1.0, rtol=1e-12, atol=0.0) + ) + if settled: + # Already on the stage's scale: rerunning must not move a byte. + return frame, receipt | { + "status": "already_on_anchor" if target > 0 else "no_transferred_mass", + "employer_premium_total": _weighted(weights, employer), + } + outputs = {column: values.copy() for column, values in drawn.items()} + for values in outputs.values(): + values[no_wages] = 0.0 + outputs[US_ESI_EMPLOYER_PREMIUM_COLUMN][transferred] *= factor + if not np.isfinite(outputs[US_ESI_EMPLOYER_PREMIUM_COLUMN]).all(): + raise SourceRuntimeError( + "US ESI premium pool anchor: scaling left a transferred employer " + "premium that is not finite." + ) + total = _weighted(weights, outputs[US_ESI_EMPLOYER_PREMIUM_COLUMN]) + # Matching infinities would pass isclose, so a total must be finite first. + if not ( + np.isfinite(total) + and np.isclose(total, pool_target, rtol=_POOL_ANCHOR_RTOL, atol=0.0) + ): + raise SourceRuntimeError( + f"US ESI premium pool anchor: the pool totals ${total / 1e9:,.6f}B " + f"after scaling, not ${pool_target / 1e9:,.6f}B." + ) + tables = {entity: frame.table(entity).copy() for entity in frame.entities} + tables.update({name: frame.link(name) for name in frame.links}) + for column, values in outputs.items(): + tables["person"][column] = values + result = Frame( + tables, + frame.schema, + {entity: frame.weights_for(entity) for entity in frame.weighted_entities}, + frame.strata, + mass_log=frame.mass_log, + metadata=frame.metadata, + ) + return result, receipt | {"status": "scaled", "employer_premium_total": total} + + def _weighted( weights: np.ndarray, values: np.ndarray, mask: np.ndarray | None = None ) -> float: @@ -889,11 +1414,17 @@ def _weighted( return float(weights[mask] @ values[mask]) -def _clone_disagreements(person: pd.DataFrame) -> int: +def _clone_disagreements(person: pd.DataFrame, rows: np.ndarray) -> int: + """Source persons among ``rows`` whose support clones disagree.""" + if not {"source_year", "source_household_id", "source_person_id"} <= set( person.columns ): return 0 + # A frame of source rows is read as it is, as a single-source frame is: + # only a mixed frame is subset. + if not rows.all(): + person = person.loc[rows] keys = _stable_person_keys(person) work = person[list(US_ESI_PREMIUMS_OUTPUT_COLUMNS)].copy() work["_key"] = keys.to_numpy() @@ -906,7 +1437,211 @@ def _clone_disagreements(person: pd.DataFrame) -> int: ) -def us_esi_premiums_summary(frame: Frame) -> dict[str, object]: +def _positive_share_and_mean( + weights: np.ndarray, values: np.ndarray, rows: np.ndarray +) -> tuple[float, float]: + """Weighted share of ``rows`` with a positive value, and its mean.""" + + mass = float(weights[rows].sum()) + positive = rows & (values > 0) + positive_mass = float(weights[positive].sum()) + return ( + positive_mass / mass if mass else 0.0, + _weighted(weights, values, positive) / positive_mass if positive_mass else 0.0, + ) + + +def _refuse_overflowing_mixed_aggregates(*terms: tuple[str, float]) -> None: + """Refuse a mixed frame whose weighted sums, or totals formed from them, + run past the largest float. + + Finite nonnegative weights can still sum to infinity. Positive infinity + passes a ``not x > 0`` check, and the shares formed from it come out zero + or NaN, so this names each infinite term instead. Both gates record the + refusal as red. + """ + + overflowing = [f"{label} ({value!r})" for label, value in terms if np.isinf(value)] + if overflowing: + raise SourceRuntimeError( + "US ESI premium stage: on this mixed frame " + f"{'; '.join(overflowing)} ran past the largest float, so the " + "shares and ratios formed from it have no value." + ) + + +def _transferred_row_summary( + frame: Frame, + person: pd.DataFrame, + weights: np.ndarray, + employer: np.ndarray, + source: np.ndarray, +) -> dict[str, object]: + """How the rows without raw ASEC columns compare with the rows that have them.""" + + transferred = ~source + source_mass, transferred_mass = _household_masses(frame, source) + # Each side's mass stays finite only up to the largest float, and their + # sum can overflow while both sides stay finite. + _refuse_overflowing_mixed_aggregates( + ("the source-derived rows' household mass", source_mass), + ("the transferred rows' household mass", transferred_mass), + ("the two sides' household mass together", source_mass + transferred_mass), + ) + share = source_mass / (source_mass + transferred_mass) + source_total = _weighted(weights, employer, source) + transferred_total = _weighted(weights, employer, transferred) + # The premium totals read the person weights, which can overflow while + # the household masses stay finite. + _refuse_overflowing_mixed_aggregates( + ("the source-derived rows' weighted employer premium", source_total), + ("the transferred rows' weighted employer premium", transferred_total), + ) + source_positive, source_mean = _positive_share_and_mean(weights, employer, source) + positive, mean = _positive_share_and_mean(weights, employer, transferred) + without_wages: int | None = None + missing_wages: int | None = None + if US_ESI_PREMIUMS_WAGE_COLUMN in person.columns: + records = transferred + if _PERSON_CLONE_INDEX_COLUMN in person.columns: + records = transferred & pd.to_numeric( + person[_PERSON_CLONE_INDEX_COLUMN], errors="coerce" + ).eq(0).to_numpy(dtype=bool) + wages = pd.to_numeric( + person[US_ESI_PREMIUMS_WAGE_COLUMN], errors="coerce" + ).to_numpy(dtype=np.float64, na_value=np.nan) + held = records & (employer > 0) + without_wages = int((held & np.isfinite(wages) & ~(wages > 0)).sum()) + missing_wages = int((held & ~np.isfinite(wages)).sum()) + clone_disagreements = 0 + if {_PERSON_SOURCE_ID_COLUMN, _PERSON_CLONE_INDEX_COLUMN} <= set(person.columns): + clone_disagreements = int( + pd.Series(employer[transferred]) + .groupby(person.loc[transferred, _PERSON_SOURCE_ID_COLUMN].to_numpy()) + .nunique() + .gt(1) + .sum() + ) + # Transferred rows that hold no household mass cannot be compared. + weighed = transferred_mass > 0 + # The source-derived rows' premium per unit of household mass. It rounds + # to zero when their premium holders carry far less weight than the rest + # of their side, and then, as when they hold no premium, there is no + # ratio to grade. + source_rate = source_total / source_mass if source_mass > 0 else 0.0 + return { + "source_rows": int(source.sum()), + "transferred_rows": int(transferred.sum()), + "source_household_mass_share": share, + "transferred_household_mass_share": transferred_mass + / (source_mass + transferred_mass), + # Absolute masses: a share can round to zero while its side holds mass, + # so whether the transferred side is weighed is read from these. + "source_household_mass": source_mass, + "transferred_household_mass": transferred_mass, + "transferred_clone_disagreement_source_records": clone_disagreements, + "source_employer_premium_total": source_total, + "transferred_employer_premium_total": transferred_total, + "source_employer_premium_positive_share": source_positive, + "transferred_employer_premium_positive_share": positive, + "source_employer_premium_mean_per_positive_person": source_mean, + "transferred_employer_premium_mean_per_positive_person": mean, + "transferred_to_source_positive_share_ratio": ( + positive / source_positive if weighed and source_positive else float("nan") + ), + "transferred_to_source_mean_ratio": ( + mean / source_mean if weighed and source_mean else float("nan") + ), + "transferred_to_source_band": list(_TRANSFERRED_TO_SOURCE_BAND), + "transferred_to_source_per_household_mass_ratio": ( + (transferred_total / transferred_mass) / source_rate + if source_rate and weighed + else float("nan") + ), + "transferred_per_household_mass_band": list(_TRANSFERRED_PER_MASS_BAND), + # Recorded, not gated: later stages may rewrite wages. The pool anchor + # enforces both when the pool is built. + "transferred_source_records_with_premium_and_no_wages": without_wages, + "transferred_source_records_with_premium_and_missing_wages": missing_wages, + } + + +def _refuse_unusable_source_anchor_evidence( + *, + source_household_mass: float, + raw_anchor_total: float, + raw_universe_total: float, + raw_positive_weight: float, + employed_share: float, +) -> None: + """Refuse a mixed frame whose source-derived rows cannot anchor the rest. + + A mixed frame's anchor-universe total prices the transferred rows' column + at the source-derived rows' employed share of the anchor universe, and + the raw mean divides by their weight. Both need source-derived rows that + hold household mass, policyholders among them with a weighted MEPS-IC + employer share, and employed ones with a positive part of it, large + enough that their share of the whole does not round to zero. Without + that weighted evidence there is no total to compare, so the frame is + refused here and both gates record the refusal as a red verdict. A total + that ran past the largest float would pass the checks below as positive + infinity, so this refuses it first, by name. + """ + + _refuse_overflowing_mixed_aggregates( + ( + "the source-derived rows' policyholders' weighted MEPS-IC employer share", + raw_anchor_total, + ), + ( + "their employed policyholders' weighted MEPS-IC employer share", + raw_universe_total, + ), + ( + "their employed policyholders' weight with a positive share", + raw_positive_weight, + ), + ) + gaps = [ + reason + for unusable, reason in ( + ( + not source_household_mass > 0, + f"hold no household mass ({source_household_mass!r})", + ), + ( + not raw_anchor_total > 0, + "give their policyholders no weighted MEPS-IC employer share " + f"({raw_anchor_total!r})", + ), + ( + not (raw_universe_total > 0 and raw_positive_weight > 0), + "give their employed policyholders no weighted MEPS-IC employer " + f"share ({raw_universe_total!r} over weight {raw_positive_weight!r})", + ), + ( + raw_anchor_total > 0 + and raw_universe_total > 0 + and not employed_share > 0, + "give their employed policyholders a part of the policyholders' " + "weighted MEPS-IC employer share that rounds to zero " + f"({raw_universe_total!r} of {raw_anchor_total!r})", + ), + ) + if unusable + ] + if gaps: + raise SourceRuntimeError( + "US ESI premium stage: the source-derived rows of this mixed frame " + f"{'; they '.join(gaps)}. Their weighted raw ASEC fields are what " + "the rows without them are priced against, so there is no " + "anchor-universe total to grade." + ) + + +def us_esi_premiums_summary( + frame: Frame, *, allow_transferred_rows: bool = False +) -> dict[str, object]: """Weighted ESI premium lineage and structure, for gates and manifests. It recomputes the raw MEPS-IC shares from the raw ASEC columns, so the @@ -914,6 +1649,25 @@ def us_esi_premiums_summary(frame: Frame) -> dict[str, object]: checked against the cells rather than trusted. A frame that lacks those columns gets the column totals only, with ``source_columns_missing`` naming what is absent; both gates fail on it. + + By default every row must carry the raw columns. With + ``allow_transferred_rows`` a frame may also hold rows a transfer filled + (:func:`_raw_evidence_mask`). The recomputation then covers the CPS rows, + the transferred rows are summarized against them, and + ``anchor_universe_employer_total`` adds the transferred column at the CPS + rows' employed share of the anchor universe: those rows have no + policyholder flag to price the other policyholders from. A mixed frame + whose CPS rows hold no household mass, or give their policyholders or + their employed policyholders no weighted MEPS-IC share (or the employed a + part of it that rounds to zero), has no such total and is refused + (``SourceRuntimeError``), which both gates record as red. So is a mixed + frame with a weighted sum that runs past the largest float: household + mass on either side or both together, the employer premium on either + side or both together, the anchor-universe total formed from it, or the + CPS rows' MEPS-IC share or the weight of their employed policyholders + with a positive share. + When every row is a CPS row, every figure is computed as for a + single-source frame. """ person = frame.table("person") @@ -923,6 +1677,16 @@ def us_esi_premiums_summary(frame: Frame) -> dict[str, object]: total_weight = float(weights.sum()) holders = float(weights[positive].sum()) person = _person_with_state(frame) + source_columns_missing = [ + column + for column in US_ESI_PREMIUMS_REQUIRED_SOURCE_COLUMNS + if column not in person.columns + ] + source = ( + np.ones(len(person), dtype=bool) + if source_columns_missing + else _raw_evidence_mask(person, allow_transferred_rows=allow_transferred_rows) + ) summary: dict[str, object] = { "employer_premium_total": _weighted(weights, employer), "employer_premium_positive_persons": holders, @@ -934,18 +1698,27 @@ def us_esi_premiums_summary(frame: Frame) -> dict[str, object]: else 0.0, "nonfinite_rows": int((~np.isfinite(employer)).sum()), "negative_rows": int((employer < 0).sum()), - "clone_disagreement_source_persons": _clone_disagreements(person), + "clone_disagreement_source_persons": _clone_disagreements(person, source), "anchor": dict(EMPLOYER_PREMIUM_ANCHOR), "cross_check": dict(EMPLOYER_PREMIUM_CROSS_CHECK), "cells_sha256": _CELLS_SHA256, - "source_columns_missing": [ - column - for column in US_ESI_PREMIUMS_REQUIRED_SOURCE_COLUMNS - if column not in person.columns - ], + "source_columns_missing": source_columns_missing, } - if summary["source_columns_missing"]: + if source_columns_missing: return summary + mixed = not source.all() + transferred_total = 0.0 + # Only a mixed frame is subset by ``source``; a frame of CPS rows keeps its + # own arrays, as a single-source frame does. No in-process test can see + # this part of the guard, because an all-True subset holds the same values + # in the same order: it holds by construction, not by a test. + if mixed: + summary |= _transferred_row_summary(frame, person, weights, employer, source) + transferred_total = float(summary["transferred_employer_premium_total"]) + # Everything below is over the source-derived rows. + person = person.loc[source].reset_index(drop=True) + weights, employer = weights[source], employer[source] + positive = employer > 0 codes, raw, premium, contribution = _person_raw_shares(person) universe = codes.universe holder = codes.policyholder @@ -953,11 +1726,48 @@ def us_esi_premiums_summary(frame: Frame) -> dict[str, object]: raw_positive = universe & (raw > 0) raw_universe_total = _weighted(weights, raw, universe) raw_anchor_total = _weighted(weights, raw) - scale = ( - summary["employer_premium_total"] / raw_universe_total - if raw_universe_total - else float("nan") + employed_share = ( + raw_universe_total / raw_anchor_total if raw_anchor_total else float("nan") ) + if mixed: + _refuse_unusable_source_anchor_evidence( + source_household_mass=float(summary["source_household_mass"]), + raw_anchor_total=raw_anchor_total, + raw_universe_total=raw_universe_total, + raw_positive_weight=float(weights[raw_positive].sum()), + employed_share=employed_share, + ) + scale = ( + _weighted(weights, employer) / raw_universe_total + if raw_universe_total + else float("nan") + ) + anchor_universe_total = scale * raw_anchor_total + ( + transferred_total / employed_share if transferred_total else 0.0 + ) + # Each side's premium total was refused above if it overflowed; their + # sum, and the anchor-universe total that divides it by the employed + # share, can still overflow while both stay finite. + _refuse_overflowing_mixed_aggregates( + ( + "the weighted employer premium of both kinds of row together", + float(summary["employer_premium_total"]), + ), + ("the anchor-universe employer total", anchor_universe_total), + ) + other_policyholder_total = anchor_universe_total - float( + summary["employer_premium_total"] + ) + else: + # Every row is a CPS row: a single-source frame's expressions, on the + # frame's own arrays. + scale = ( + summary["employer_premium_total"] / raw_universe_total + if raw_universe_total + else float("nan") + ) + anchor_universe_total = scale * raw_anchor_total + other_policyholder_total = scale * (raw_anchor_total - raw_universe_total) by_tier = { tier: _weighted(weights, employer, universe & (codes.tier == code)) for code, tier in _TIER_BY_CODE.items() @@ -1013,12 +1823,9 @@ def us_esi_premiums_summary(frame: Frame) -> dict[str, object]: "scale_factor_spread": ( float(np.nanmax(ratio) - np.nanmin(ratio)) if raw_positive.any() else 0.0 ), - "anchor_universe_employer_total": scale * raw_anchor_total, - "other_policyholder_employer_total": scale - * (raw_anchor_total - raw_universe_total), - "employed_share_of_anchor_universe": ( - raw_universe_total / raw_anchor_total if raw_anchor_total else float("nan") - ), + "anchor_universe_employer_total": anchor_universe_total, + "other_policyholder_employer_total": other_policyholder_total, + "employed_share_of_anchor_universe": employed_share, "employer_premium_by_tier": by_tier, "employer_premium_by_sector": by_sector, "employer_premium_outside_universe_rows": int((positive & ~universe).sum()), @@ -1043,13 +1850,20 @@ def _missing_source_failure(missing: list[str], consequence: str) -> str: ) -def us_esi_premiums_signal_gate(frame: Frame) -> GateResult: +def us_esi_premiums_signal_gate( + frame: Frame, *, allow_transferred_rows: bool = False +) -> GateResult: """Structure and scale-invariant signal of the ESI employer premium input. Holds on any frame size (smoke builds included). It proves every positive value sits in the employed-policyholder universe and equals one common multiple of its MEPS-IC cell. Those proofs read the raw ASEC columns, so a frame without them fails: it cannot be certified. + + ``allow_transferred_rows`` goes to :func:`us_esi_premiums_summary`. With + it, the proofs cover the CPS rows of a mixed frame, and the rows a + transfer filled must carry the premium too, with a weighted positive share + and mean within ``_TRANSFERRED_TO_SOURCE_BAND`` of the CPS rows'. """ person = frame.table("person") @@ -1066,7 +1880,9 @@ def us_esi_premiums_signal_gate(frame: Frame) -> GateResult: details={"missing": missing}, ) try: - summary = us_esi_premiums_summary(frame) + summary = us_esi_premiums_summary( + frame, allow_transferred_rows=allow_transferred_rows + ) except SourceRuntimeError as exc: return GateResult( name="esi_premiums_signal", @@ -1089,6 +1905,10 @@ def us_esi_premiums_signal_gate(frame: Frame) -> GateResult: ("nonfinite_rows", "non-finite value(s)"), ("negative_rows", "negative value(s)"), ("clone_disagreement_source_persons", "support-clone disagreement(s)"), + ( + "transferred_clone_disagreement_source_records", + "support-clone disagreement(s) on the rows without raw ASEC columns", + ), ( "employer_premium_outside_universe_rows", "employer premium(s) outside employed policyholders", @@ -1111,6 +1931,19 @@ def us_esi_premiums_signal_gate(frame: Frame) -> GateResult: failures.append( f"employer premium positive share {share:.4f} outside [{low}, {high}]." ) + if float(summary.get("transferred_household_mass", 0.0)) > 0: + low, high = _TRANSFERRED_TO_SOURCE_BAND + for key, label in ( + ("transferred_to_source_positive_share_ratio", "positive share"), + ("transferred_to_source_mean_ratio", "mean per positive person"), + ): + ratio = float(summary[key]) + if not low <= ratio <= high: + failures.append( + f"employer premium {label} on the rows without raw ASEC " + f"columns is {ratio:.3f} times the source-derived rows', " + f"outside [{low}, {high}]." + ) if "raw_employer_share_mean_per_positive_person" in summary: mean = float(summary["raw_employer_share_mean_per_positive_person"]) low, high = _RAW_MEAN_BAND @@ -1134,7 +1967,9 @@ def us_esi_premiums_signal_gate(frame: Frame) -> GateResult: ) -def us_esi_premiums_anchor_gate(frame: Frame, *, time_period: int) -> GateResult: +def us_esi_premiums_anchor_gate( + frame: Frame, *, time_period: int, allow_transferred_rows: bool = False +) -> GateResult: """Hold a release's weighted ESI employer premium total to its anchor. Runs on the calibrated export (dense and sparse). The anchor, BEA NIPA @@ -1148,6 +1983,19 @@ def us_esi_premiums_anchor_gate(frame: Frame, *, time_period: int) -> GateResult the employed share of it leaves its band. CMS NHE Table 24 and MEPS-IC's own private-sector enrollment total are recorded beside the verdict, not gated. + + ``allow_transferred_rows`` goes to :func:`us_esi_premiums_summary`. With + it, a mixed frame carries the raw columns on its CPS rows only. Its + anchor-universe total is theirs plus the transferred rows' column at the + CPS rows' employed share, and the gate also fails when the transferred + rows' column per unit of household mass leaves + ``_TRANSFERRED_PER_MASS_BAND`` of the CPS rows', because the total then + rests on halves that no longer compare. CPS rows without the weighted + evidence that total needs fail it as a refusal. The private-sector + cross-check is scaled by the CPS rows' share of household mass. When that + share rounds to zero, or the CPS rows' sector total or the scaled total is + not finite, it is recorded without a value and with an ``unavailable`` + reason that names which. """ person = frame.table("person") @@ -1164,7 +2012,9 @@ def us_esi_premiums_anchor_gate(frame: Frame, *, time_period: int) -> GateResult details={"missing": missing}, ) try: - summary = us_esi_premiums_summary(frame) + summary = us_esi_premiums_summary( + frame, allow_transferred_rows=allow_transferred_rows + ) except SourceRuntimeError as exc: return GateResult( name="esi_premiums_anchor", @@ -1238,17 +2088,83 @@ def us_esi_premiums_anchor_gate(frame: Frame, *, time_period: int) -> GateResult f"employed policyholders carry {employed_share:.4f} of the " f"anchor-universe employer total, outside [{low}, {high}]." ) + if "transferred_rows" in summary: + details |= { + key: summary[key] + for key in ( + "source_rows", + "transferred_rows", + "source_household_mass_share", + "transferred_household_mass_share", + "source_household_mass", + "transferred_household_mass", + "source_employer_premium_total", + "transferred_employer_premium_total", + "transferred_to_source_per_household_mass_ratio", + "transferred_per_household_mass_band", + ) + } + details["anchor_universe_assumption"] = ( + "rows without raw ASEC columns carry the source-derived rows' " + "employed share of the anchor universe" + ) + ratio = float(summary["transferred_to_source_per_household_mass_ratio"]) + low, high = _TRANSFERRED_PER_MASS_BAND + weighed = float(summary["transferred_household_mass"]) > 0 + if weighed and not low <= ratio <= high: + failures.append( + "rows without raw ASEC columns carry " + f"{ratio:.3f} times the source-derived rows' employer " + f"premium per unit of household mass, outside [{low}, {high}]." + ) nhe = EMPLOYER_PREMIUM_CROSS_CHECK["values"].get(year) if nhe is not None and np.isfinite(universe_total): details["cross_check_ratio"] = universe_total / float(nhe) active = dict(summary["meps_ic_private_active_employer_total"]) if year in active: private = float(dict(summary["employer_premium_by_sector"])["private"]) - details["private_active_cross_check"] = { + unavailable: str | None = None + if "transferred_rows" in summary: + # The sector split reads the raw columns, so in a mixed frame it + # covers the source-derived rows; their share of household mass + # scales it to the population. That share can round to zero + # while those rows hold mass, and then scales nothing. The + # cross-check is recorded, not gated, so when the scaled total + # has no finite value it goes without one, naming the term at + # fault, rather than divide by zero. + share = float(summary["source_household_mass_share"]) + causes = [] + if not np.isfinite(private): + causes.append( + "the source-derived rows' private-sector employer total " + f"({private!r}) is not finite" + ) + if not share > 0: + causes.append( + "the source-derived rows' share of household mass " + f"({share!r}) is not a positive number, so it scales " + "nothing" + ) + if not causes: + scaled = private / share + if not np.isfinite(scaled): + causes.append( + "the source-derived rows' private-sector employer " + f"total ({private!r}) over their share of household " + f"mass ({share!r}) is not finite" + ) + private = scaled + if causes: + private = float("nan") + unavailable = "; ".join(causes) + cross_check: dict[str, object] = { "meps_ic_private_active_employer_total": active[year], "employer_premium_private_sector": private, "ratio": private / active[year], } + if unavailable is not None: + cross_check["unavailable"] = unavailable + details["private_active_cross_check"] = cross_check return GateResult( name="esi_premiums_anchor", passed=not failures, diff --git a/packages/microcosm-build/tests/engine_contract/us/test_us_acs_local_release_tool.py b/packages/microcosm-build/tests/engine_contract/us/test_us_acs_local_release_tool.py new file mode 100644 index 0000000000..f9488bd362 --- /dev/null +++ b/packages/microcosm-build/tests/engine_contract/us/test_us_acs_local_release_tool.py @@ -0,0 +1,110 @@ +"""The ACS local release tool's engine pass on a lane frame (microcosm #454). + +``fill_reviewed_nulls`` applies the nullable-artifact contract with the +installed engine's input names and defaults. It refuses a frame whose ESI +employer premium is null on some rows, which is what an ACS spine pooled +beside a donor used to carry. The lane now transfers and anchors the column +at staging, so the engine pass must run on its frame. +""" + +from __future__ import annotations + +import json + +import numpy as np +import pytest + +from microcosm.build.source_runtime import SourceRuntimeError +from microcosm.frame import Frame +from test_support.microcosm_build.us_acs_local_esi_premiums import ( + EMPLOYER, + build_lane, + dense_donor, + donor_rows, + raw_acs, +) +from test_support.microcosm_build.us_acs_local_release_tool import ( + load_staging_builder_module, + load_tool_module, +) + +#: An input the donor release carries and no transfer in this fixture gives +#: the ACS rows: the kind of reviewed null the engine pass exists to fill. +_REVIEWED_NULL = "pre_subsidy_rent" + + +def _with_person(frame: Frame, person) -> Frame: + return Frame( + { + entity: person if entity == "person" else frame.table(entity) + for entity in frame.entities + }, + frame.schema, + {"household": frame.weights_for("household")}, + frame.strata, + ) + + +@pytest.fixture(scope="module") +def staged() -> Frame: + """A staged lane frame with one reviewed engine-input null on ACS rows.""" + + frame = build_lane(dense_donor(120), raw_acs(100), n_estimators=5).frame + person = frame.table("person").copy() + person[_REVIEWED_NULL] = np.where(donor_rows(frame), 9_600.0, np.nan) + return _with_person(frame, person) + + +def _summary(tmp_path, frame: Frame): + """The staging summary's null register, as the staging tool audits it.""" + + audit = load_staging_builder_module()._legacy._engine_input_null_audit(frame) + path = tmp_path / "acs_multispine_staging.summary.json" + path.write_text(json.dumps({"reviewed_engine_input_nulls": audit})) + return path, audit + + +def test_the_engine_pass_runs_on_the_lane_frame_and_leaves_the_premium( + tmp_path, staged +) -> None: + tool = load_tool_module() + summary_path, audit = _summary(tmp_path, staged) + # Every row carries the premium, so the staging audit registers no null + # for it: there is nothing for the engine pass to fill or to refuse. + assert EMPLOYER not in {entry["column"] for entry in audit} + assert {entry["column"] for entry in audit} == {_REVIEWED_NULL} + before = staged.table("person")[EMPLOYER].to_numpy(copy=True) + + projected, _dropped = tool.project_input_only(staged) + fills, drift = tool.fill_reviewed_nulls(projected, summary_path) + + person = projected.table("person") + assert [fill["column"] for fill in fills] == [_REVIEWED_NULL] + assert fills[0]["filled_rows"] == 100 + assert fills[0]["missing_rows_by_spine"] == {"acs_2024_1yr": 100} + assert drift == [] + assert person[_REVIEWED_NULL].notna().all() + # The engine knows the premium as an input and the pass did not touch it. + assert EMPLOYER in person.columns + np.testing.assert_array_equal(person[EMPLOYER].to_numpy(), before) + assert (person.loc[~donor_rows(staged), EMPLOYER] > 0).any() + + +def test_the_engine_pass_still_refuses_an_untransferred_acs_spine( + tmp_path, staged +) -> None: + # A staging H5 built before the lane transferred the column: null on ACS + # rows, and registered as a reviewed null by that build's audit. + tool = load_tool_module() + person = staged.table("person").copy() + person.loc[~donor_rows(staged), EMPLOYER] = np.nan + stale = _with_person(staged, person) + summary_path, audit = _summary(tmp_path, stale) + assert EMPLOYER in {entry["column"] for entry in audit} + + with pytest.raises(SourceRuntimeError, match="never filled") as error: + tool.fill_reviewed_nulls(stale, summary_path) + + assert f"'{EMPLOYER}': 100" in str(error.value) + # Refused before any fill: the registered null was not defaulted to zero. + assert stale.table("person")[EMPLOYER].isna().sum() == 100 diff --git a/packages/microcosm-build/tests/engine_contract/us/test_us_acs_local_reviewed_fill_consumers.py b/packages/microcosm-build/tests/engine_contract/us/test_us_acs_local_reviewed_fill_consumers.py index 72eeb5e318..e011c371e4 100644 --- a/packages/microcosm-build/tests/engine_contract/us/test_us_acs_local_reviewed_fill_consumers.py +++ b/packages/microcosm-build/tests/engine_contract/us/test_us_acs_local_reviewed_fill_consumers.py @@ -3,8 +3,10 @@ Each register entry declares the means-tested programs its column reaches. This test recomputes them with the engine's static dependency graph -(``PolicyEngineUSVariableMetadataIndex.consumer_receipts``, walked by -:func:`means_tested_consumers`) and fails when an entry misses a program the +(``PolicyEngineUSVariableMetadataIndex.consumer_receipts`` with +``follow_helpers``, so a read inside one of the engine's helper functions is +its calling variable's, walked by :func:`means_tested_consumers`; +microcosm#1675) and fails when an entry misses a program the walk reaches, or lists one it no longer reaches, so a policyengine-us bump cannot silently add a consumer the notes never reviewed. It also checks that the program roots are engine variables covering the engine's own CBO @@ -17,8 +19,8 @@ The walk tests hold only for the engine the register was reviewed against. On any other engine the ACS local release gate refuses the release (fail closed), so they skip until the register is re-reviewed, and one test checks -that the gate refuses the installed engine meanwhile (policyengine-us 2.145.3: -microcosm#1675). +that the gate refuses any other engine meanwhile. The register was re-reviewed +against policyengine-us 2.145.3 in microcosm#1675. """ from __future__ import annotations @@ -67,7 +69,7 @@ @pytest.fixture(scope="module") def index() -> PolicyEngineUSVariableMetadataIndex: - return PolicyEngineUSVariableMetadataIndex() + return PolicyEngineUSVariableMetadataIndex(follow_helpers=True) @pytest.fixture(scope="module") @@ -173,9 +175,12 @@ def test_each_program_coupling_is_an_engine_edge(index) -> None: def consumers(name): return {receipt.consumer for receipt in index.consumer_receipts(name)} - # The bars: Medicaid and CHIP eligibility gate the PTC. - assert "pays_aca_premium" in consumers("is_medicaid_eligible") - assert "pays_aca_premium" in consumers("is_chip_eligible") + # The bars: Medicaid and CHIP eligibility keep a person off the Marketplace + # (gov.aca.ineligible_coverage); only an enrollee pays an age-rated premium, + # which the PTC requires (policyengine-us 2.145.3). + for upstream in ("is_medicaid_eligible", "is_chip_eligible"): + assert "is_aca_marketplace_enrollee" in consumers(upstream), upstream + assert "pays_aca_premium" in consumers("is_aca_marketplace_enrollee") assert "is_aca_ptc_eligible" in consumers("pays_aca_premium") # SSI and TANF reach SNAP categorical eligibility. assert "meets_snap_categorical_eligibility" in consumers("ssi") @@ -205,14 +210,37 @@ def test_the_key_snap_paths(index) -> None: def reach(column): return means_tested_consumers(column, index, _PROGRAMS) + def consumers(name): + return {receipt.consumer for receipt in index.consumer_receipts(name)} + vehicles = reach("household_vehicles_value") assert "meets_tanf_non_cash_asset_test" in vehicles["snap"] # SNAP's utility allowance does not read the energy subsidy; the subsidy is # the LIHEAP program's own value. assert reach("spm_unit_energy_subsidy") == {"liheap": ("spm_unit_energy_subsidy",)} # No program reads these at all. - for column in ("weeks_unemployed", "net_worth", "tenure_type", "ssi_reported"): + for column in ("net_worth", "ssi_reported"): assert reach(column) == {}, column + # Weeks unemployed set the months of UC receipt, which exempt a recipient from + # SNAP work registration and so from the ABAWD time limit (policyengine-us + # 2.145.3); the modeled UI programs need claim-wage inputs no stage produces + # (test_us_weeks_unemployed.py). + assert "unemployment_compensation_months" in consumers("weeks_unemployed") + assert "is_receiving_unemployment_compensation" in consumers( + "unemployment_compensation_months" + ) + assert "is_snap_work_registration_exempt_non_age" in consumers( + "is_receiving_unemployment_compensation" + ) + assert "is_snap_abawd_exempt" in consumers( + "is_snap_work_registration_exempt_non_age" + ) + assert "snap" in reach("weeks_unemployed") + # The household tenure is read only by Colorado's in-kind support and + # maintenance exemption for a client who owns their home (_ism_exempt), which + # Colorado OAP and AND-CS count, and SNAP counts those grants. + assert "co_ssa_in_kind_support_and_maintenance" in consumers("tenure_type") + assert "snap" in reach("tenure_type") # SNAP's medical deduction reads the medical-expense aggregate, which # treats a zero direct premium as not supplied. premiums = reach("health_insurance_premiums")["snap"] @@ -223,9 +251,6 @@ def reach(column): # SNAP's shelter deduction reads rent through housing_cost (the shortest # path from the rent runs through Arizona TANF, so check the edges). - def consumers(name): - return {receipt.consumer for receipt in index.consumer_receipts(name)} - assert "rent" in consumers("pre_subsidy_rent") assert "housing_cost" in consumers("rent") assert "snap_excess_shelter_expense_deduction" in consumers("housing_cost") diff --git a/packages/microcosm-build/tests/engine_free/us/test_us_acs_block_location.py b/packages/microcosm-build/tests/engine_free/us/test_us_acs_block_location.py index 901a878f31..44d7e5c46d 100644 --- a/packages/microcosm-build/tests/engine_free/us/test_us_acs_block_location.py +++ b/packages/microcosm-build/tests/engine_free/us/test_us_acs_block_location.py @@ -854,9 +854,9 @@ def fake_write(frame, path, **kwargs): monkeypatch.setattr(builder, "_load_base_frame", lambda path: base) # The donor checks and local-input stages main gained since September # (SPM role, immigration, income, SIPP SSI disability, work experience, - # receipt anchors, self-employment identity) pass through: these tests - # exercise the location wiring, and test_us_acs_multispine_legacy_builder - # covers those stages. + # receipt anchors, self-employment identity, ESI employer premium) pass + # through: these tests exercise the location wiring, and + # test_us_acs_multispine_legacy_builder covers those stages. for name in ( "_require_donor_spm_independence_role", "_require_immigration_donor", @@ -864,8 +864,13 @@ def fake_write(frame, path, **kwargs): "_require_ssi_disability_donor", "_require_donor_work_experience", "_require_pooled_spm_independence_role", + "_qualify_esi_premium_donor", ): monkeypatch.setattr(builder, name, lambda *a, **k: None) + monkeypatch.setattr( + builder, "acs_local_esi_premium_transfer_target_families", lambda: {} + ) + monkeypatch.setattr(builder, "_local_esi_premium_evidence", lambda result, **k: {}) monkeypatch.setattr( builder, "_load_ssi_disability_donor", lambda *a, **k: (None, {}) ) @@ -985,12 +990,14 @@ def test__legacy_tool__block_v1_main_records_rule_seed_gate_and_attributes( "work_disability_inputs": True, "income_transfer": True, "native_receipt_anchors": True, + "wic_take_up": True, "drop_group_quarters_children": False, "location_rule": "block_v1", "location_seed": 5, "location_clones": 1, "donor_location_rule": "block_v1", "semp_covers_partnership_income": True, + "esi_premium_donor_factory": builder.prepare_acs_local_esi_premium_donor, } location = summary["household_location"] diff --git a/packages/microcosm-build/tests/engine_free/us/test_us_acs_county_agi_support.py b/packages/microcosm-build/tests/engine_free/us/test_us_acs_county_agi_support.py new file mode 100644 index 0000000000..9295d4f13c --- /dev/null +++ b/packages/microcosm-build/tests/engine_free/us/test_us_acs_county_agi_support.py @@ -0,0 +1,462 @@ +"""The pre-R2 check for counties whose SOI AGI row would be empty (microcosm#922). + +``tools/check_us_acs_county_agi_support.py`` lists counties that have +households but none with a nonzero AGI: R2's ``attach_surface`` refuses such +a county after the engine pass. These tests stub the engine pass (the +household AGI), so no country engine is imported; the engine-tier test +``engine_workflow/us/test_us_acs_county_agi_support_engine.py`` runs it. +""" + +from __future__ import annotations + +import importlib.util +import json +import sys +from dataclasses import dataclass +from pathlib import Path +from types import SimpleNamespace + +import numpy as np +import pandas as pd +import pytest + +from microcosm.frame import US_SCHEMA, Frame, WeightKind, Weights +from test_support.paths import paths_for + +_TEST_PATHS = paths_for("microcosm-build") + + +@pytest.fixture(scope="module") +def check(): + path = _TEST_PATHS.repository / "tools" / "check_us_acs_county_agi_support.py" + spec = importlib.util.spec_from_file_location("check_us_county_agi", path) + module = importlib.util.module_from_spec(spec) + assert spec.loader is not None + sys.modules[spec.name] = module + spec.loader.exec_module(module) + return module + + +def _frame(person_columns: dict[str, list] | None = None) -> Frame: + """Six households in three counties of state 01, one person each. + + 01001 and 01003 hold two donor households each; 01005 holds two ACS + households, the second a group-quarters record. + """ + + n = 6 + ids = np.arange(1, n + 1) + person = pd.DataFrame( + { + "person_id": ids, + **{f"person_{entity}_id": ids for entity in US_SCHEMA.group_entities}, + "age": np.full(n, 40.0), + **(person_columns or {}), + } + ) + tables = {"person": person} + for entity in US_SCHEMA.group_entities: + tables[entity] = pd.DataFrame({f"{entity}_id": ids}) + household = tables["household"] + household["state_fips"] = np.full(n, 1) + household["county_fips"] = [1001, 1001, 1003, 1003, 1005, 1005] + household["county_fips_2023"] = household["county_fips"] + household["household_spine"] = pd.Series( + ["asec_puf"] * 4 + ["acs_2024_1yr"] * 2, dtype=object + ) + household["TYPEHUGQ"] = [np.nan] * 4 + [1.0, 3.0] + return Frame( + tables, + US_SCHEMA, + {"household": Weights(np.ones(n), WeightKind.CALIBRATED)}, + ) + + +def test_report_lists_counties_with_households_but_no_nonzero_agi(check) -> None: + households = _frame().table("household") + nonzero = np.asarray([True, True, False, False, False, True]) + + report = check.county_agi_report( + households, + nonzero, + county_column="county_fips_2023", + county_populations={1001: 10.0, 1003: 5.0, 1005: 5.0, 1007: 3.0}, + ) + + assert report["at_risk"] == ["01003"] + assert report["at_risk_detail"]["01003"] == { + "households": 2, + "supporting_households": 2, + "households_with_agi_income": 0, + } + # 1007 has ladder population but no household after the minimum-support + # moves (the report's input), so R2's check_support refuses it. + assert report["no_household"] == ["01007"] + assert report["unsupported_counties"] == ["01007"] + # A group-quarters record counts for AGI but not for support. + assert report["by_county"]["01005"]["supporting_households"] == 1 + assert report["fewer_than_min_support_with_agi_income"] == ["01001", "01005"] + assert report["counties_outside_ladder"] == [] + assert check.exit_status(report) == check.EXIT_R2_REFUSES + + +def test_report_lists_the_counties_r2_refuses_before_its_engine_pass(check) -> None: + households = _frame().table("household").copy() + # 01005 keeps only its group-quarters record, and one household names + # 01009, a county outside the ladder. + households["county_fips_2023"] = [1001, 1001, 1003, 1009, 1003, 1005] + nonzero = np.ones(len(households), dtype=bool) + + report = check.county_agi_report( + households, + nonzero, + county_column="county_fips_2023", + county_populations={1001: 10.0, 1003: 5.0, 1005: 5.0}, + ) + + assert report["at_risk"] == [] + assert report["no_household"] == [] + assert report["counties_outside_ladder"] == ["01009"] + assert report["unsupported_counties"] == ["01005"] + assert check.exit_status(report) == check.EXIT_R2_REFUSES + # Without the ladder neither list is checked. + unladdered = check.county_agi_report( + households, nonzero, county_column="county_fips_2023" + ) + assert unladdered["counties_outside_ladder"] is None + assert unladdered["unsupported_counties"] is None + assert check.exit_status(unladdered) == 0 + + +def test_exit_status_3_takes_precedence_over_2(check) -> None: + at_risk = {"at_risk": ["01003"], "counties_outside_ladder": []} + assert check.exit_status({**at_risk, "unsupported_counties": []}) == 2 + assert check.exit_status({**at_risk, "unsupported_counties": ["01005"]}) == 3 + assert ( + check.exit_status( + { + **at_risk, + "counties_outside_ladder": ["01009"], + "unsupported_counties": [], + } + ) + == 3 + ) + assert check.exit_status({"at_risk": [], "unsupported_counties": None}) == 0 + + +def test_ladder_support_moves_no_household_when_a_county_is_outside_the_ladder( + check, monkeypatch: pytest.MonkeyPatch +) -> None: + import microcosm.build.us_runtime.puma_ladder as puma_ladder + + households = _frame().table("household") + surface = check.county_surface + planned = [] + monkeypatch.setattr(puma_ladder, "load_us_puma_ladder", lambda path: "ladder") + monkeypatch.setattr(surface, "county_puma_overlaps", lambda path, column: {}) + + def plan( + households, populations, overlaps, *, county_column, per_county, household_agi + ): + planned.append(sorted(populations)) + return [], {"rewritten_columns": [county_column], "moves": []} + + monkeypatch.setattr(surface, "plan_minimum_support", plan) + for populations, expected in ( + # 01005 is outside this ladder: R2 refuses the run before any move. + ({1001: 10.0, 1003: 5.0, 1007: 3.0}, []), + # Every county is in the ladder and 01007 has no household: R2 plans + # its moves. + ({1001: 10.0, 1003: 5.0, 1005: 5.0, 1007: 3.0}, [[1001, 1003, 1005, 1007]]), + ): + planned.clear() + monkeypatch.setattr( + surface, + "with_county_populations", + lambda ladder, known, geographies, *, county_column, _p=populations: { + "county": _p + }, + ) + + _moved, ladder_populations, support = check.ladder_support( + households, + Path("ladder.npz"), + county_column="county_fips_2023", + county_min_support=3, + ) + + assert ladder_populations == populations + assert planned == expected + assert (support is None) is (not expected) + + +_NEVER_DEFAULT = frozenset( + { + ("person", "takes_up_ssi_if_eligible"), + ("person", "is_blind"), + ("spm_unit", "takes_up_snap_if_eligible"), + } +) + + +#: The columns of ``_NEVER_DEFAULT`` that an R2 stage fills on ACS rows; +#: ``is_blind`` stands in for one that staging must fill. +_STAGE_FILLED = frozenset( + { + ("person", "takes_up_ssi_if_eligible"), + ("spm_unit", "takes_up_snap_if_eligible"), + } +) +#: One person per household: persons 5 and 6 are ACS rows. +_PERSON_SPINE = ["asec_puf"] * 4 + ["acs_2024_1yr"] * 2 + + +def _hold_back(check, frame, agi_inputs): + return check.hold_back_null_runtime_columns( + frame, + never_default_filled=_NEVER_DEFAULT, + stage_filled=_STAGE_FILLED, + agi_inputs=agi_inputs, + ) + + +def test_null_stage_filled_columns_on_acs_rows_outside_the_agi_are_held_back( + check, +) -> None: + frame = _frame( + { + "person_spine": _PERSON_SPINE, + "takes_up_ssi_if_eligible": [True, True, True, True, np.nan, True], + "is_blind": [False] * 6, + } + ) + + held_frame, held = _hold_back(check, frame, {"is_blind", "age"}) + + assert held == {"person": ["takes_up_ssi_if_eligible"]} + assert "takes_up_ssi_if_eligible" not in held_frame.table("person").columns + assert "is_blind" in held_frame.table("person").columns + assert held_frame.n("household") == frame.n("household") + + +@pytest.mark.parametrize( + ("columns", "agi_inputs", "message"), + [ + # An R2 stage fills it on the ACS rows, but the AGI reads it. + ( + {"takes_up_ssi_if_eligible": [True] * 4 + [np.nan, True]}, + {"takes_up_ssi_if_eligible"}, + r"person\.takes_up_ssi_if_eligible: the AGI reads it", + ), + # R2's stages fill the ACS rows only; this null is on a donor row. + ( + {"takes_up_ssi_if_eligible": [np.nan] + [True] * 4 + [np.nan]}, + {"age"}, + r"person\.takes_up_ssi_if_eligible: null on 1 non-ACS row", + ), + # No R2 stage fills it, so staging must, on any spine. + ( + {"is_blind": [False] * 4 + [np.nan, False]}, + {"age"}, + r"person\.is_blind: no R2 stage fills it", + ), + ], + ids=["agi-input", "donor-row", "staging-filled"], +) +def test_never_default_nulls_r2_refuses_are_refused( + check, columns, agi_inputs, message +) -> None: + frame = _frame({"person_spine": _PERSON_SPINE, **columns}) + + with pytest.raises(SystemExit, match=message): + _hold_back(check, frame, agi_inputs) + + +def test_a_null_stage_filled_column_without_a_spine_tag_is_refused(check) -> None: + frame = _frame({"takes_up_ssi_if_eligible": [True] * 4 + [np.nan, True]}) + + with pytest.raises(SystemExit, match="no person_spine column"): + _hold_back(check, frame, {"age"}) + + +def test_a_frame_without_null_runtime_columns_is_returned_as_is(check) -> None: + frame = _frame({"takes_up_ssi_if_eligible": [True] * 6}) + + held_frame, held = _hold_back(check, frame, {"age"}) + + assert held == {} + assert held_frame is frame + + +@dataclass(frozen=True) +class _Closure: + input_leaves: tuple[str, ...] + + +def test_agi_engine_inputs_are_the_static_closure_of_agi(check) -> None: + class _Index: + def variable_dependency_closure(self, name): + assert name == "adjusted_gross_income" + return _Closure(("age", "employment_income_before_lsr")) + + assert check.agi_engine_inputs(_Index()) == {"age", "employment_income_before_lsr"} + + +@dataclass(frozen=True) +class _EdgeClosure: + input_leaves: tuple[str, ...] + edges: tuple[tuple[str, str], ...] + + +def test_agi_engine_inputs_stop_at_a_deduction_the_year_does_not_list(check) -> None: + """Past an unread deduction the walk reads nothing; a leaf it reaches by + another path stays.""" + + class _Index: + def variable_dependency_closure(self, name): + assert name == "adjusted_gross_income" + return _EdgeClosure( + input_leaves=("age", "employment_income_before_lsr", "takes_up_x"), + edges=( + ("adjusted_gross_income", "irs_gross_income"), + ("adjusted_gross_income", "charitable_contributions_ald"), + ("irs_gross_income", "employment_income_before_lsr"), + ("charitable_contributions_ald", "tax_unit_itemizes"), + ("tax_unit_itemizes", "takes_up_x"), + ("tax_unit_itemizes", "age"), + ("irs_gross_income", "age"), + ), + ) + + unread = ("charitable_contributions_ald",) + assert check.agi_engine_inputs(_Index(), unread=unread) == { + "age", + "employment_income_before_lsr", + } + assert check.agi_engine_inputs(_Index()) == { + "age", + "employment_income_before_lsr", + "takes_up_x", + } + + +def _stub_release(frame: Frame) -> SimpleNamespace: + return SimpleNamespace(_load_staging_frame=lambda path: frame) + + +def test_command_exits_2_and_reports_an_at_risk_county( + check, tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + staging = tmp_path / "staging.h5" + staging.write_bytes(b"") + (tmp_path / "staging.summary.json").write_text("{}") + out = tmp_path / "report.json" + monkeypatch.setattr(check, "_release_tool", lambda: _stub_release(_frame())) + calls = [] + + def agi(frame, summary_path, *, release, hh_chunk): + calls.append((summary_path, hh_chunk)) + # 01003's households have an AGI of 0; a negative AGI is stored. + return np.asarray([100.0, 0.0, 0.0, 0.0, -5.0, 0.0]), {"stub": True} + + monkeypatch.setattr(check, "household_agi", agi) + + status = check.main(["--h5", str(staging), "--out", str(out)]) + + report = json.loads(out.read_text()) + assert status == check.EXIT_AT_RISK + assert report["exit_status"] == check.EXIT_AT_RISK + assert report["at_risk"] == ["01003"] + # Without --puma-ladder, R2's support refusals are not checked. + assert report["unsupported_counties"] is None + assert report["households_with_agi_income"] == 2 + assert report["agi_engine"] == {"stub": True} + assert report["minimum_support"] is None + # The summary path defaults as R2's does: the H5 with .summary.json. + assert calls == [(tmp_path / "staging.summary.json", check.DEFAULT_HH_CHUNK)] + + def healthy(frame, summary_path, *, release, hh_chunk): + return np.asarray([1.0, 0.0, 0.0, 2.0, 0.0, 3.0]), {} + + monkeypatch.setattr(check, "household_agi", healthy) + assert check.main(["--h5", str(staging), "--county-column", "county_fips"]) == 0 + + +def test_command_exits_3_when_r2_refuses_before_its_engine_pass( + check, tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + staging = tmp_path / "staging.h5" + staging.write_bytes(b"") + (tmp_path / "staging.summary.json").write_text("{}") + out = tmp_path / "report.json" + monkeypatch.setattr(check, "_release_tool", lambda: _stub_release(_frame())) + # 01003's households have an AGI of 0, so it is also at risk. + monkeypatch.setattr( + check, + "household_agi", + lambda frame, path, *, release, hh_chunk: ( + np.asarray([1.0, 1.0, 0.0, 0.0, 1.0, 1.0]), + {}, + ), + ) + calls = [] + + def ladder(households, path, *, county_column, county_min_support, household_agi): + calls.append((path, county_column, county_min_support)) + # 01005 is not in this ladder. + return households, {1001: 10.0, 1003: 5.0}, None + + monkeypatch.setattr(check, "ladder_support", ladder) + ladder_path = tmp_path / "ladder.npz" + + status = check.main( + ["--h5", str(staging), "--puma-ladder", str(ladder_path), "--out", str(out)] + ) + + report = json.loads(out.read_text()) + assert status == check.EXIT_R2_REFUSES + assert report["exit_status"] == check.EXIT_R2_REFUSES + assert report["at_risk"] == ["01003"] + assert report["counties_outside_ladder"] == ["01005"] + assert report["unsupported_counties"] == [] + assert calls == [ + ( + ladder_path, + check.county_surface.COUNTY_COLUMN_2023, + check.county_surface.DEFAULT_COUNTY_MIN_SUPPORT, + ) + ] + + +def test_an_agi_below_float32_resolution_is_stored_as_zero( + check, tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + staging = tmp_path / "staging.h5" + staging.write_bytes(b"") + summary = tmp_path / "other.summary.json" + summary.write_text("{}") + monkeypatch.setattr(check, "_release_tool", lambda: _stub_release(_frame())) + monkeypatch.setattr( + check, + "household_agi", + lambda frame, path, *, release, hh_chunk: ( + np.asarray([1.0, 0.0, 1e-50, 0.0, 1.0, 0.0]), + {}, + ), + ) + + status = check.main(["--h5", str(staging), "--staging-summary", str(summary)]) + + assert status == check.EXIT_AT_RISK + + +def test_command_refuses_without_a_staging_summary( + check, tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + staging = tmp_path / "staging.h5" + staging.write_bytes(b"") + monkeypatch.setattr(check, "_release_tool", lambda: _stub_release(_frame())) + + with pytest.raises(SystemExit, match="Staging summary not found"): + check.main(["--h5", str(staging)]) diff --git a/packages/microcosm-build/tests/engine_free/us/test_us_acs_local_county_production.py b/packages/microcosm-build/tests/engine_free/us/test_us_acs_local_county_production.py index fae1b8362f..484df36f24 100644 --- a/packages/microcosm-build/tests/engine_free/us/test_us_acs_local_county_production.py +++ b/packages/microcosm-build/tests/engine_free/us/test_us_acs_local_county_production.py @@ -1094,6 +1094,214 @@ def test_recorded_moves_reapply_to_a_fresh_frame_and_refuse_a_changed_plan( county.apply_support_moves(stale, moves) +# --- SOI support (microcosm#1661) ----------------------------------------------- + + +def _soi_support_fixture(): + """01001 (eight households, AGI on the ACS ones) beside 01003, whose four + households all store an AGI of 0, in one PUMA.""" + cells = [(100001, 1001)] * 8 + [(100001, 1003)] * 4 + households = _support_households(cells) + agi = np.where( + (households["county_fips"] == "01001") + & (households["household_spine"] == "acs_2024_1yr"), + 25_000.0, + 0.0, + ) + populations = {1001: 80.0, 1003: 40.0} + overlaps = _county().puma_overlaps([100001, 100001], [1001, 1003], [80.0, 40.0]) + return households, agi, populations, overlaps + + +def test_soi_support_moves_households_with_agi_into_a_county_without_it() -> None: + county = _county() + households, agi, populations, overlaps = _soi_support_fixture() + assert county.counties_without_agi(households, agi, populations) == [1003] + + moves, receipt = county.plan_minimum_support( + households, populations, overlaps, per_county=1, household_agi=agi + ) + + soi = receipt["soi_support"] + assert soi["needed"] == ["01003"] + assert soi["counties"]["01003"]["status"] == "moved" + assert soi["still_without_agi"] == [] + assert len(moves) == 1 + (move,) = moves + assert move["reason"] == "soi_support" + assert (move["from_county"], move["to_county"]) == ("01001", "01003") + position = households.index[households["household_id"] == move["household_id"]] + assert agi[position[0]] > 0 + # The recorded moves replay as the first pass's do. + applied = county.apply_support_moves(households, moves) + assert county.counties_without_agi(applied, agi, populations) == [] + assert receipt["moved_counties"] == ["01003"] + + +def test_soi_support_keeps_each_donor_county_an_agi_household() -> None: + county = _county() + households, agi, populations, overlaps = _soi_support_fixture() + # 01001 keeps one household with an AGI: moving it would leave 01001 + # without one, so nothing moves and 01003 is named. + only = households.index[ + (households["county_fips"] == "01001") + & (households["household_spine"] == "acs_2024_1yr") + ][0] + agi = np.where(np.arange(len(agi)) == only, agi, 0.0) + + moves, receipt = county.plan_minimum_support( + households, populations, overlaps, per_county=1, household_agi=agi + ) + + assert moves == [] + soi = receipt["soi_support"] + assert soi["counties"]["01003"]["status"] == "insufficient_eligible_donors" + assert soi["still_without_agi"] == ["01003"] + + +def _first_pass_fixture(county): + """01001's twelve eligible households in the one PUMA it shares with the + unsupported 01003, and their order in 01003's rank.""" + households = _support_households([(100001, 1001)] * 12) + populations = {1001: 90.0, 1003: 10.0} + overlaps = county.puma_overlaps([100001, 100001], [1001, 1003], [90.0, 10.0]) + ranked = sorted( + households["household_id"].tolist(), + key=lambda household_id: county.support_rank( + county.COUNTY_MIN_SUPPORT_KEY, 1003, household_id + ), + ) + return households, populations, overlaps, ranked + + +def _agi_on(households, household_ids): + return np.where(households["household_id"].isin(household_ids), 1_000.0, 0.0) + + +def test_first_pass_keeps_the_rank_when_a_pick_has_agi() -> None: + county = _county() + households, populations, overlaps, ranked = _first_pass_fixture(county) + agi = _agi_on(households, [ranked[0], ranked[5]]) + + without, plain = county.plan_minimum_support( + households, populations, overlaps, per_county=3 + ) + moves, receipt = county.plan_minimum_support( + households, populations, overlaps, per_county=3, household_agi=agi + ) + + # The AGI changes nothing when one of the rank's picks has one. + assert [move["household_id"] for move in without] == ranked[:3] + assert moves == without + assert "soi_support" not in plain + first = receipt["soi_support"]["first_pass"] + assert first["swapped_counties"] == [] + assert (first["movers"], first["movers_with_positive_agi"]) == (3, 1) + assert first["mover_share_with_positive_agi"] == pytest.approx(1 / 3, abs=1e-6) + assert first["puma_share_with_positive_agi"] == pytest.approx(2 / 12, abs=1e-6) + assert receipt["soi_support"]["needed"] == [] + + +def test_first_pass_swaps_its_last_pick_for_one_with_agi() -> None: + county = _county() + households, populations, overlaps, ranked = _first_pass_fixture(county) + agi = _agi_on(households, [ranked[5], ranked[8]]) + + moves, receipt = county.plan_minimum_support( + households, populations, overlaps, per_county=3, household_agi=agi + ) + + # None of the rank's three picks has an AGI: the first two stay, and the + # third gives way to the next household in rank order that has one. + assert [move["household_id"] for move in moves] == [ + ranked[0], + ranked[1], + ranked[5], + ] + assert [move.get("reason") for move in moves] == [None, None, "positive_agi"] + soi = receipt["soi_support"] + first = soi["first_pass"] + assert first["swapped_counties"] == ["01003"] + assert (first["movers"], first["movers_with_positive_agi"]) == (3, 1) + assert first["puma_share_with_positive_agi"] == pytest.approx(2 / 12, abs=1e-6) + # The county has its AGI support, so the second pass has nothing to do. + assert soi["needed"] == [] and soi["still_without_agi"] == [] + assert receipt["moved_counties"] == ["01003"] + + +def test_first_pass_keeps_its_picks_when_no_household_with_agi_can_move() -> None: + county = _county() + households, populations, overlaps, ranked = _first_pass_fixture(county) + # 01001's only household with an AGI: moving it would leave 01001 without + # one, so neither pass can move it. + agi = _agi_on(households, [ranked[5]]) + + without, _ = county.plan_minimum_support( + households, populations, overlaps, per_county=3 + ) + moves, receipt = county.plan_minimum_support( + households, populations, overlaps, per_county=3, household_agi=agi + ) + + assert moves == without + soi = receipt["soi_support"] + assert soi["first_pass"]["swapped_counties"] == [] + assert soi["first_pass"]["movers_with_positive_agi"] == 0 + assert soi["needed"] == ["01003"] + assert soi["counties"]["01003"]["status"] == "insufficient_eligible_donors" + assert soi["still_without_agi"] == ["01003"] + + +def test_check_support_refuses_a_county_without_agi_before_the_engine_pass( + monkeypatch, tmp_path +) -> None: + from microcosm.frame import US_SCHEMA, Frame, WeightKind, Weights + + county = _county() + households, agi, populations, overlaps = _soi_support_fixture() + agi = np.zeros(len(households)) + ids = households["household_id"].to_numpy() + tables = { + "household": households, + "person": pd.DataFrame( + { + "person_id": ids, + "person_household_id": ids, + **{f"person_{group}_id": ids for group in US_SCHEMA.group_entities}, + } + ), + } + for group in US_SCHEMA.group_entities: + tables.setdefault(group, pd.DataFrame({f"{group}_id": ids})) + frame = Frame( + tables, + US_SCHEMA, + {"household": Weights(np.ones(len(ids)), WeightKind.DESIGN)}, + ) + monkeypatch.setattr( + county, "county_puma_overlaps", lambda _path, _column="county_fips": overlaps + ) + args = SimpleNamespace( + county_column="county_fips", + county_min_support=1, + ladder=tmp_path / "ladder.npz", + checkpoint_dir=tmp_path, + allow_partial_geography=False, + sample_fraction=1.0, + ) + + with pytest.raises(SystemExit, match="none with a nonzero AGI"): + county.check_support(frame, {"county": populations}, args, household_agi=agi) + report = json.loads((tmp_path / county.SUPPORT_FILENAME).read_text()) + assert report["minimum_support"]["soi_support"]["still_without_agi"] == [ + "01001", + "01003", + ] + # Without the AGI the same frame passes this check (R2 then refuses the + # empty AGI rows after its engine pass). + county.check_support(frame, {"county": populations}, args) + + def test_check_support_applies_minimum_support_before_refusing( monkeypatch, tmp_path ) -> None: diff --git a/packages/microcosm-build/tests/engine_free/us/test_us_acs_local_county_surface.py b/packages/microcosm-build/tests/engine_free/us/test_us_acs_local_county_surface.py index f1d6f553ad..bdb57bae6e 100644 --- a/packages/microcosm-build/tests/engine_free/us/test_us_acs_local_county_surface.py +++ b/packages/microcosm-build/tests/engine_free/us/test_us_acs_local_county_surface.py @@ -956,6 +956,16 @@ def _materialize_county_fixture( monkeypatch.setattr(module, "_require_local_income_transfer", lambda *_a: None) monkeypatch.setattr(module, "_require_local_ssi_disability", lambda *_a: None) monkeypatch.setattr(module, "_require_local_receipt_anchors", lambda *_a: None) + # Nor the engine it ran on; this test checks county hooks only. + monkeypatch.setattr(module, "_require_staging_engine", lambda *_a, **_k: None) + # microcosm#1661: on a county SOI surface materialize computes each + # household's AGI with the engine before minimum support; every household + # here has one, so no county needs SOI support. + monkeypatch.setattr( + module, + "_household_agi", + lambda current, *_a, **_k: np.ones(current.n("household")), + ) # microcosm#1022: the ACS SSI/Medicaid take-up stage compiles SSA and CMS # counts from the ledger feed and runs an engine pre-pass this fixture # cannot support; this test checks county hooks only. diff --git a/packages/microcosm-build/tests/engine_free/us/test_us_acs_local_esi_premiums.py b/packages/microcosm-build/tests/engine_free/us/test_us_acs_local_esi_premiums.py new file mode 100644 index 0000000000..ed27d5c708 --- /dev/null +++ b/packages/microcosm-build/tests/engine_free/us/test_us_acs_local_esi_premiums.py @@ -0,0 +1,1516 @@ +"""ESI employer premiums on the ACS local lane's ACS spine (microcosm #454). + +The lane pools a dense ASEC-by-PUF donor release with the ACS spine +(``with_optional_acs_spine``): the donor keeps ``1 - acs_share`` of its +household mass and ACS takes the rest. The donor carries the premium from the +``meps_esi_premiums`` stage; the lane transfers it onto the ACS rows from the +donor's ASEC observation role and anchors the pooled frame. + +Invariants of :func:`with_acs_local_esi_premium_anchor`, for every lane frame: + +* **Conservation**: the lane-wide weighted employer premium equals the donor + rows' total divided by their share of household mass. Pooling multiplies + every donor household weight by that share, so this is the donor release's + own weighted column. +* **Equal intensity**: both spines carry the same weighted premium per unit of + household mass. +* **Donor rows are immutable**: no donor cell changes by a byte. +* **Structural zeros**: an ACS person who reports zero wages carries no + premium, and neither does one below age 15, whose wage ACS leaves blank. +* **No invented zeros**: a blank wage at age 15 or older is refused, and the + frame's own blanks are never overwritten. +* **Proportionality**: every other ACS premium is one common multiple of the + value the transfer drew. +* **Idempotence**: an anchored frame is returned unchanged. +* **Identity independence**: ACS ids that repeat the donor's change nothing. + +And of the orchestration (:func:`~.acs_multispine.build_optional_acs_multispine`): + +* **Pass order**: the ESI pass runs after the hours and income passes and + immediately before the shared transfer, and moves no value but the + premium on any row of any table: those passes and the shared transfer draw + exactly what they draw without it. +""" + +from __future__ import annotations + +import importlib.util +import json +from functools import cache +from pathlib import Path + +import numpy as np +import pandas as pd +import pytest +from hypothesis import HealthCheck, assume, given, settings +from hypothesis import strategies as st + +from microcosm.build.source_runtime import SourceRuntimeError +from microcosm.build.us_runtime import acs_multispine +from microcosm.build.us_runtime import esi_premiums as esi +from microcosm.build.us_runtime.acs_inputs import map_acs_native_inputs +from microcosm.build.us_runtime.acs_local_esi_premiums import ( + ACS_LOCAL_ESI_PREMIUM_FAMILY, + acs_local_esi_premium_gate_payload, + acs_local_esi_premium_gates, + acs_local_esi_premium_transfer_target_families, + prepare_acs_local_esi_premium_donor, + with_acs_local_esi_premium_anchor, +) +from microcosm.build.us_runtime.acs_local_hours import ( + acs_local_hours_transfer_target_families, + acs_local_transfer_target_families, +) +from microcosm.build.us_runtime.acs_local_income import ( + ACS_LOCAL_INCOME_DONOR_CHANNEL, + ACS_LOCAL_INCOME_TRANSFER_COLUMNS, + acs_local_income_transfer_target_families, +) +from microcosm.build.us_runtime.acs_multispine import AcsMultispineResult +from microcosm.build.us_runtime.acs_pums import AcsPumsSource +from microcosm.build.us_runtime.acs_transfer import ( + ACS_DONOR_CHANNEL_AUTO, + declared_acs_transfer_target_families, + transfer_acs_inputs, +) +from microcosm.build.us_runtime.esi_premiums import ( + US_ESI_PREMIUMS_OUTPUT_COLUMNS, + refuse_unassigned_us_esi_premiums, + us_esi_premiums_anchor_gate, + us_esi_premiums_signal_gate, + with_us_esi_premium_pool_anchor, +) +from microcosm.build.us_runtime.h5_io import ( + LEGACY_NULLABLE_STAGING_ARTIFACT_KIND, + load_legacy_calibrated_us_h5, + write_nullable_us_h5, +) +from microcosm.build.us_runtime.multispine_pool import pool_transfer_target_families +from microcosm.frame import US_SCHEMA, Frame, WeightKind, Weights +from test_support.microcosm_build.us_acs_local_esi_premiums import ( + ACS, + ASEC_PUF, + EMPLOYER, + USUAL_HOURS, + WAGES, + build_lane, + dense_donor, + donor_rows, + employer_total, + household_mass_share, + income_donor, + person_weights, + pooled, + raw_acs, + reweighted, + transferred_acs, + with_person_values, +) + +#: The stage's scale anchor for CY2024, read from the stage, not restated. +ANCHOR = float(esi.EMPLOYER_PREMIUM_ANCHOR["values"]["2024"]) +RAW = tuple( + column + for column in esi.US_ESI_PREMIUMS_REQUIRED_SOURCE_COLUMNS + if column != "state_fips" +) +#: Above every donor id, so ACS ids do not repeat the donor's. +_DISJOINT_FIRST_ID = 5_000_000 + +requires_pytables = pytest.mark.skipif( + importlib.util.find_spec("tables") is None, + reason="requires pytables (the build environment)", +) + + +def _column(frame: Frame, column: str) -> np.ndarray: + return frame.table("person")[column].to_numpy(dtype=float) + + +def _replace_person(frame: Frame, person: pd.DataFrame) -> Frame: + return Frame( + { + entity: person if entity == "person" else frame.table(entity) + for entity in frame.entities + }, + frame.schema, + {"household": frame.weights_for("household")}, + frame.strata, + ) + + +# --- The lane's plan leaves the shared plans alone ---------------------------- + + +def test_the_lane_plan_names_the_premium_and_changes_no_shared_plan() -> None: + declared_before = declared_acs_transfer_target_families() + pool_before = pool_transfer_target_families() + + local = acs_local_esi_premium_transfer_target_families() + + assert local == {"person": {ACS_LOCAL_ESI_PREMIUM_FAMILY: (EMPLOYER,)}} + assert local["person"][ACS_LOCAL_ESI_PREMIUM_FAMILY] == ( + US_ESI_PREMIUMS_OUTPUT_COLUMNS + ) + assert declared_acs_transfer_target_families() == declared_before + assert pool_transfer_target_families() == pool_before + + # Neither the declared plan nor the shared pool plan names the column: + # the shared pool has no ESI family, so the lane plan is the only plan + # that transfers the premium. + def targets(plan) -> set[str]: + return { + target + for families in plan.values() + for family_targets in families.values() + for target in family_targets + } + + assert EMPLOYER not in targets(declared_before) + assert EMPLOYER not in targets(pool_before) + assert ACS_LOCAL_ESI_PREMIUM_FAMILY not in pool_before.get("person", {}) + # The hours plan the staging tool composes with is untouched too. + assert EMPLOYER not in { + target + for families in acs_local_transfer_target_families().values() + for targets in families.values() + for target in targets + } + + +# --- Donor qualification ------------------------------------------------------ + + +def test_the_donor_is_its_asec_observation_role_with_measured_wages() -> None: + donor = dense_donor() + before = {entity: donor.table(entity).copy() for entity in donor.entities} + + selected, receipt = prepare_acs_local_esi_premium_donor(donor) + + person = selected.table("person") + assert len(person) == 320 + assert set(person["person_support_channel"]) == {"asec"} + assert set(person["person_support_clone_index"]) == {0} + # Measured wages: a premium only where the person has wages. + assert not ((person[EMPLOYER] > 0) & ~(person[WAGES] > 0)).any() + assert receipt["donor_channel"] == "asec" + assert receipt["donor_rows"] == 640 + assert receipt["asec_observation_rows"] == 320 + assert receipt["asec_observation_premium_share_without_wages"] == 0.0 + assert receipt["donor_employer_premium_total"] == pytest.approx( + employer_total(donor), rel=1e-12 + ) + assert receipt["donor_signal_gate"] == {"passed": True, "failures": []} + for entity in donor.entities: + pd.testing.assert_frame_equal(donor.table(entity), before[entity]) + + +def _donor_without(*columns: str) -> Frame: + donor = dense_donor(80) + return _replace_person(donor, donor.table("person").drop(columns=list(columns))) + + +@pytest.mark.parametrize("column", [EMPLOYER, "NOW_OWNGRP", "PEIO1COW"]) +def test_a_donor_built_without_the_stage_is_refused(column: str) -> None: + with pytest.raises(ValueError, match="meps_esi_premiums stage") as error: + prepare_acs_local_esi_premium_donor(_donor_without(column)) + assert column in str(error.value) + assert "never defaults" in str(error.value) + + +def test_a_donor_without_the_cps_record_id_is_refused() -> None: + with pytest.raises(ValueError, match="lacks 'PERIDNUM'"): + prepare_acs_local_esi_premium_donor(_donor_without("PERIDNUM")) + + +def test_a_donor_row_with_raw_fields_and_no_record_id_is_refused() -> None: + # The record id and the raw fields must agree on every row. + donor = dense_donor(80) + person = donor.table("person").copy() + person["PERIDNUM"] = person["PERIDNUM"].astype(object) + person.loc[person.index[3], "PERIDNUM"] = None + with pytest.raises(ValueError, match="without a CPS record id"): + prepare_acs_local_esi_premium_donor(_replace_person(donor, person)) + + +def test_a_donor_row_that_lost_its_raw_fields_and_record_id_is_refused() -> None: + # Both kinds of evidence lost together, on a source record and its PUF + # clone, whose households hold no weight. Graded by row kind, the pair is + # two transferred rows without mass, so the signal gate passes it, and + # the observation role would still hand the source record to the fit. + donor = dense_donor(80) + person = donor.table("person").copy() + first = person.loc[person["person_support_clone_index"].eq(0), "person_source_id"] + pair = person["person_source_id"].eq(first.iloc[0]).to_numpy() + assert pair.sum() == 2 + for column in RAW: + person[column] = person[column].astype(np.float64) + person["PERIDNUM"] = person["PERIDNUM"].astype(object) + person.loc[pair, list(RAW)] = np.nan + person.loc[pair, "PERIDNUM"] = None + household = donor.table("household") + weights = np.asarray(donor.weights_for("household").values, dtype=float).copy() + weights[ + household["household_id"] + .isin(person.loc[pair, "person_household_id"]) + .to_numpy() + ] = 0.0 + damaged = Frame( + { + entity: person if entity == "person" else donor.table(entity) + for entity in donor.entities + }, + donor.schema, + {"household": Weights(weights, WeightKind.CALIBRATED)}, + donor.strata, + ) + + with pytest.raises( + ValueError, + match=( + r"2 row\(s\) without every raw ASEC field and 2 row\(s\) without a " + r"CPS record id" + ), + ): + prepare_acs_local_esi_premium_donor(damaged) + + +def test_a_donor_without_wages_is_refused() -> None: + with pytest.raises(ValueError, match="conditions the premium on"): + prepare_acs_local_esi_premium_donor(_donor_without(WAGES)) + + +def test_a_donor_whose_observation_role_has_missing_wages_is_refused() -> None: + donor = dense_donor(80) + person = donor.table("person").copy() + person.loc[person["person_support_clone_index"].eq(0).idxmax(), WAGES] = np.nan + with pytest.raises(ValueError, match="never treats a missing wage as zero"): + prepare_acs_local_esi_premium_donor(_replace_person(donor, person)) + + +def test_a_donor_without_support_roles_is_refused() -> None: + donor = dense_donor(80) + tables = { + entity: donor.table(entity).drop( + columns=[ + f"{entity}_source_id", + f"{entity}_support_channel", + f"{entity}_support_clone_index", + ] + ) + for entity in donor.entities + } + unclassified = Frame( + tables, US_SCHEMA, {"household": donor.weights_for("household")} + ) + with pytest.raises(ValueError, match="explicit legacy ASEC observation roles"): + prepare_acs_local_esi_premium_donor(unclassified) + + +def test_an_assembled_multispine_donor_is_refused() -> None: + donor = dense_donor(80) + person = donor.table("person").copy() + person["person_spine_source_id"] = person["person_source_id"] + with pytest.raises(ValueError, match="multispine records need their own"): + prepare_acs_local_esi_premium_donor(_replace_person(donor, person)) + + +def test_a_donor_failing_the_stage_signal_gate_is_refused() -> None: + # A premium outside its MEPS-IC cell: no longer one common multiple. + donor = dense_donor(80) + person = donor.table("person").copy() + positive = person[EMPLOYER] > 0 + person.loc[positive.idxmax(), EMPLOYER] *= 3.0 + with pytest.raises(ValueError, match="fails the meps_esi_premiums signal gate"): + prepare_acs_local_esi_premium_donor(_replace_person(donor, person)) + + +# --- The anchor on every lane frame ------------------------------------------- + +_amount = st.one_of( + st.just(0.0), + st.floats(min_value=1.0, max_value=40_000.0, allow_nan=False), +) +_weight = st.floats(min_value=0.5, max_value=5_000.0, allow_nan=False) + + +@cache +def _small_donor() -> Frame: + return dense_donor(40) + + +@st.composite +def _lane_cases(draw) -> dict[str, object]: + """Any donor weights, any share, and any ACS households and draws. + + The donor's household weights are rescaled one by one, so the donor rows + do not share one weight profile; ACS households hold one to several + people. + """ + + people = draw(st.integers(min_value=2, max_value=10)) + premiums = np.asarray(draw(st.lists(_amount, min_size=people, max_size=people))) + wages = np.asarray(draw(st.lists(_amount, min_size=people, max_size=people))) + # Some ACS people are children: PUMS leaves their wage blank. + child = np.asarray(draw(st.lists(st.booleans(), min_size=people, max_size=people))) + wages = np.where(child, np.nan, wages) + ages = np.where(child, 9.0, 30.0 + np.arange(people)) + joins = draw(st.lists(st.booleans(), min_size=people - 1, max_size=people - 1)) + households = np.concatenate([[0], np.cumsum(~np.asarray(joins, dtype=bool))]) + count = int(households.max()) + 1 + weights = np.asarray(draw(st.lists(_weight, min_size=count, max_size=count))) + assume(((premiums > 0) & (wages > 0)).any()) + donor = _small_donor() + factors = np.asarray( + draw( + st.lists( + st.floats(min_value=0.05, max_value=20.0), + min_size=donor.n("household"), + max_size=donor.n("household"), + ) + ) + ) + scale = draw(st.floats(min_value=0.01, max_value=100.0)) + return { + "premiums": premiums, + "wages": wages, + "ages": ages, + "weights": weights, + "households": households, + "acs_share": draw(st.floats(min_value=0.05, max_value=0.95)), + "donor": reweighted(donor, factors * scale), + } + + +def _lane_frame(case: dict[str, object], *, first_id: int = 1) -> Frame: + acs = transferred_acs( + case["premiums"], + case["wages"], + case["weights"], + households=case["households"], + ages=case["ages"], + first_id=first_id, + ) + return pooled(case["donor"], acs, acs_share=case["acs_share"]) + + +_SETTINGS = settings( + max_examples=60, + deadline=None, + suppress_health_check=[HealthCheck.too_slow, HealthCheck.filter_too_much], +) + + +@given(_lane_cases()) +@_SETTINGS +def test_lane_total_is_the_donor_rows_total_over_their_mass_share(case) -> None: + frame = _lane_frame(case) + donor = donor_rows(frame) + share = household_mass_share(frame, donor) + + anchored, receipt = with_acs_local_esi_premium_anchor(frame) + + # Pooling leaves the donor spine 1 - acs_share of the household mass. + assert share == pytest.approx(1.0 - case["acs_share"], rel=1e-9) + assert receipt["source_household_mass_share"] == pytest.approx(share, rel=1e-12) + expected = employer_total(frame, donor) / share + assert employer_total(anchored) == pytest.approx(expected, rel=1e-9) + assert receipt["employer_premium_total"] == pytest.approx(expected, rel=1e-9) + # Differential: that is the donor release's column at its own weights. + assert employer_total(anchored) == pytest.approx( + employer_total(case["donor"]), rel=1e-9 + ) + + +@given(_lane_cases()) +@_SETTINGS +def test_both_spines_carry_the_same_premium_per_unit_of_household_mass(case) -> None: + frame = _lane_frame(case) + donor = donor_rows(frame) + share = household_mass_share(frame, donor) + + anchored, _receipt = with_acs_local_esi_premium_anchor(frame) + + assert employer_total(anchored, ~donor) / (1.0 - share) == pytest.approx( + employer_total(anchored, donor) / share, rel=1e-9 + ) + + +@given(_lane_cases()) +@_SETTINGS +def test_donor_rows_and_every_other_column_are_untouched(case) -> None: + frame = _lane_frame(case) + donor = donor_rows(frame) + + anchored, _receipt = with_acs_local_esi_premium_anchor(frame) + + before, after = frame.table("person"), anchored.table("person") + assert list(after.columns) == list(before.columns) + pd.testing.assert_frame_equal(after.loc[donor], before.loc[donor]) + untouched = [column for column in before.columns if column != EMPLOYER] + pd.testing.assert_frame_equal(after[untouched], before[untouched]) + for entity in frame.entities: + if entity != "person": + pd.testing.assert_frame_equal(anchored.table(entity), frame.table(entity)) + np.testing.assert_array_equal(person_weights(anchored), person_weights(frame)) + assert anchored.weights_for("household").kind is WeightKind.IMPORTANCE + assert list(anchored.strata) == list(frame.strata) + assert anchored.mass_log == frame.mass_log + + +@given(_lane_cases()) +@_SETTINGS +def test_acs_people_without_wages_carry_nothing_and_the_rest_one_multiple( + case, +) -> None: + frame = _lane_frame(case) + donor = donor_rows(frame) + workers = _column(frame, WAGES) > 0 + + anchored, receipt = with_acs_local_esi_premium_anchor(frame) + + cleared = ~donor & ~workers + assert not _column(anchored, EMPLOYER)[cleared].any() + assert receipt["cleared_rows"][EMPLOYER] == int( + (cleared & (_column(frame, EMPLOYER) > 0)).sum() + ) + scaled = ~donor & workers + np.testing.assert_allclose( + _column(anchored, EMPLOYER)[scaled], + _column(frame, EMPLOYER)[scaled] * receipt["scale_factor"], + rtol=1e-12, + ) + values = _column(anchored, EMPLOYER) + assert np.isfinite(values).all() and (values >= 0).all() + # Every row carries the premium: nothing for a null fill to refuse. + refuse_unassigned_us_esi_premiums(anchored, consumer="lane property") + + +@given(_lane_cases()) +@_SETTINGS +def test_an_anchored_lane_frame_is_returned_unchanged(case) -> None: + anchored, first = with_acs_local_esi_premium_anchor(_lane_frame(case)) + + again, second = with_acs_local_esi_premium_anchor(anchored) + + assert first["status"] in {"scaled", "already_on_anchor"} + assert again is anchored + assert second["status"] == "already_on_anchor" + assert second["employer_premium_total"] == pytest.approx( + first["employer_premium_total"], rel=1e-12 + ) + + +@given(_lane_cases()) +@_SETTINGS +def test_acs_ids_that_repeat_the_donors_change_nothing(case) -> None: + # The pool kernel finds a clone's wages by person_source_id across the + # whole frame, and refuses a frame where source records repeat one. In + # this lane ACS rows keep their pre-remap ids as source ids. + colliding = _lane_frame(case, first_id=1) + disjoint = _lane_frame(case, first_id=_DISJOINT_FIRST_ID) + acs = ~donor_rows(colliding) + assert set(colliding.table("person").loc[acs, "person_source_id"]) & set( + colliding.table("person").loc[~acs, "person_source_id"] + ) + with pytest.raises(SourceRuntimeError, match="repeat a 'person_source_id'"): + with_us_esi_premium_pool_anchor(colliding) + + anchored, receipt = with_acs_local_esi_premium_anchor(colliding) + reference, reference_receipt = with_acs_local_esi_premium_anchor(disjoint) + + np.testing.assert_array_equal( + _column(anchored, EMPLOYER), _column(reference, EMPLOYER) + ) + assert receipt["scale_factor"] == reference_receipt["scale_factor"] + if np.isnan(case["wages"]).any(): + # The kernel alone has no universe rule for a blank ACS wage. + with pytest.raises(SourceRuntimeError, match="missing wage is not a zero"): + with_us_esi_premium_pool_anchor(disjoint) + return + # Differential: where the ids are unique the kernel runs on the whole + # frame, and the lane's narrow view gives the same bytes. + whole, whole_receipt = with_us_esi_premium_pool_anchor(disjoint) + np.testing.assert_array_equal( + _column(reference, EMPLOYER), _column(whole, EMPLOYER) + ) + assert reference_receipt["scale_factor"] == whole_receipt["scale_factor"] + assert reference_receipt["cleared_rows"] == whole_receipt["cleared_rows"] + + +def test_the_worked_lane_frame() -> None: + # Donor release: 40 one-person households cloned once. ACS: three people, + # one without wages. acs_share 0.25 leaves the donor 0.75 of the mass. + donor = _small_donor() + release_total = employer_total(donor) + acs = transferred_acs( + np.asarray([10_000.0, 5_000.0, 8_000.0]), + np.asarray([50_000.0, 0.0, 20_000.0]), + np.asarray([1.0, 1.0, 2.0]), + ) + frame = pooled(donor, acs, acs_share=0.25) + rows = donor_rows(frame) + + anchored, receipt = with_acs_local_esi_premium_anchor(frame) + + assert receipt["source_household_mass_share"] == pytest.approx(0.75, rel=1e-12) + assert employer_total(frame, rows) == pytest.approx(0.75 * release_total, rel=1e-9) + assert receipt["transferred_employer_premium_target"] == pytest.approx( + 0.25 * release_total, rel=1e-9 + ) + assert receipt["cleared_rows"] == {EMPLOYER: 1} + assert employer_total(anchored) == pytest.approx(release_total, rel=1e-9) + premiums = _column(anchored, EMPLOYER)[~rows] + # One factor on the two workers: 10,000 and 8,000 keep their ratio. + assert premiums[1] == 0.0 + assert premiums[0] / premiums[2] == pytest.approx(10_000.0 / 8_000.0, rel=1e-12) + + +def test_a_transferred_support_clone_is_refused() -> None: + frame = pooled( + _small_donor(), + transferred_acs(np.asarray([9_000.0]), np.asarray([30_000.0]), np.ones(1)), + ) + person = frame.table("person").copy() + person.loc[~donor_rows(frame), "person_support_clone_index"] = 1 + with pytest.raises(SourceRuntimeError, match="not clone-0 source records"): + with_acs_local_esi_premium_anchor(_replace_person(frame, person)) + + +@pytest.mark.parametrize( + "column", + [EMPLOYER, "NOW_HIPAID", "PERIDNUM", WAGES, "WAGP", "person_support_clone_index"], +) +def test_a_lane_frame_missing_an_anchor_input_is_refused(column: str) -> None: + frame = pooled( + _small_donor(), + transferred_acs(np.asarray([9_000.0]), np.asarray([30_000.0]), np.ones(1)), + ) + person = frame.table("person").drop(columns=[column]) + with pytest.raises(SourceRuntimeError, match="the person table lacks") as error: + with_acs_local_esi_premium_anchor(_replace_person(frame, person)) + assert column in str(error.value) + + +def test_acs_rows_with_no_premium_on_any_worker_are_refused() -> None: + # Nothing to scale: the anchor cannot put the ACS half on the donor's + # scale, so staging fails rather than shipping half the column. + frame = pooled( + _small_donor(), + transferred_acs( + np.asarray([0.0, 7_000.0]), np.asarray([30_000.0, 0.0]), np.ones(2) + ), + ) + with pytest.raises(SourceRuntimeError, match="nothing to scale"): + with_acs_local_esi_premium_anchor(frame) + + +def test_a_multi_person_household_scales_as_one_unit_of_mass() -> None: + # Three ACS people in one household and one alone: the household's mass + # counts once, and its non-worker is cleared. + donor = _small_donor() + acs = transferred_acs( + np.asarray([6_000.0, 4_000.0, 5_000.0, 3_000.0]), + np.asarray([40_000.0, 25_000.0, 0.0, 30_000.0]), + np.asarray([3.0, 1.0]), + households=np.asarray([0, 0, 0, 1]), + ) + frame = pooled(donor, acs, acs_share=0.4) + rows = donor_rows(frame) + + anchored, receipt = with_acs_local_esi_premium_anchor(frame) + + assert household_mass_share(frame, rows) == pytest.approx(0.6, rel=1e-12) + assert receipt["cleared_rows"] == {EMPLOYER: 1} + assert employer_total(anchored) == pytest.approx(employer_total(donor), rel=1e-9) + premiums = _column(anchored, EMPLOYER)[~rows] + assert premiums[2] == 0.0 + np.testing.assert_allclose( + premiums[[0, 1, 3]] / receipt["scale_factor"], [6_000.0, 4_000.0, 3_000.0] + ) + + +def _lane_with_a_child(**changes) -> Frame: + """Two ACS adults and one nine-year-old whose wage PUMS left blank.""" + + columns = { + "premiums": np.asarray([8_000.0, 5_000.0, 6_000.0]), + "wages": np.asarray([40_000.0, np.nan, 30_000.0]), + "ages": np.asarray([41.0, 9.0, 52.0]), + } | changes + acs = transferred_acs( + columns["premiums"], columns["wages"], np.ones(3), ages=columns["ages"] + ) + return pooled(_small_donor(), acs) + + +def test_a_blank_acs_wage_below_fifteen_is_a_zero_wage_in_the_anchor_only() -> None: + frame = _lane_with_a_child() + acs = ~donor_rows(frame) + + anchored, receipt = with_acs_local_esi_premium_anchor(frame) + + premiums = _column(anchored, EMPLOYER)[acs] + assert premiums[1] == 0.0 and (premiums[[0, 2]] > 0).all() + assert receipt["cleared_rows"] == {EMPLOYER: 1} + assert receipt["wage_universe"] == { + "rule_id": "acs_2024_pums_wagp_age_15_plus", + "minimum_age": 15, + "raw_source_column": "WAGP", + "eligible_transferred_rows": 2, + "transferred_rows_below_minimum_age": 1, + "transferred_rows_with_blank_wage": 1, + "transferred_rows_outside_universe_read_as_zero": 1, + "frame_cells_written": 0, + } + # The kernel's own earnings universe scopes on the "acs" support channel, + # which this lane's rows do not carry; the lane applied the rule. + assert receipt["transferred_wage_evidence"]["eligible_acs_person_rows"] == 0 + assert receipt["transferred_wage_evidence"]["structurally_absent_person_rows"] == 0 + # The staging frame keeps the source's blank: no zero is written to it. + np.testing.assert_array_equal( + _column(anchored, WAGES)[acs], [40_000.0, np.nan, 30_000.0] + ) + assert employer_total(anchored) == pytest.approx( + employer_total(_small_donor()), rel=1e-9 + ) + + +@pytest.mark.parametrize("age", [15.0, 40.0, np.nan]) +def test_a_blank_wage_at_fifteen_or_older_is_refused(age: float) -> None: + # Fifteen is inside the PUMS earnings universe, and an unknown age is not + # evidence of being outside it. + frame = _lane_with_a_child(ages=np.asarray([41.0, age, 52.0])) + with pytest.raises(SourceRuntimeError, match="missing wage is not a zero wage"): + with_acs_local_esi_premium_anchor(frame) + + +def test_a_child_whose_raw_wage_is_not_blank_is_not_read_as_zero() -> None: + # The mapped wage is null but PUMS reported one: that is a mapping fault, + # not the universe rule. + frame = _lane_with_a_child() + person = frame.table("person").copy() + acs = ~donor_rows(frame) + person["WAGP"] = np.where(acs, 1_200.0, np.nan) + with pytest.raises(SourceRuntimeError, match="mapping fault"): + with_acs_local_esi_premium_anchor(_replace_person(frame, person)) + + +@pytest.mark.parametrize("mapped", [0.0, 25_000.0]) +def test_an_adult_whose_blank_raw_wage_was_filled_is_refused(mapped: float) -> None: + # PUMS asks WAGP of everyone 15 or older, so a blank there is missing + # evidence: a producer that filled the mapped wage, with zero or anything + # else, does not make it a measurement. + frame = _lane_with_a_child() + person = frame.table("person").copy() + adult = np.flatnonzero(~donor_rows(frame))[0] + person.loc[person.index[adult], ["WAGP", WAGES]] = [np.nan, mapped] + with pytest.raises(SourceRuntimeError, match="missing wage is not a zero wage"): + with_acs_local_esi_premium_anchor(_replace_person(frame, person)) + + +def test_a_child_with_a_nonzero_mapped_wage_is_refused() -> None: + frame = _lane_with_a_child() + person = frame.table("person").copy() + child = np.flatnonzero(~donor_rows(frame))[1] + person.loc[person.index[child], WAGES] = 500.0 + with pytest.raises(SourceRuntimeError, match="mapping fault"): + with_acs_local_esi_premium_anchor(_replace_person(frame, person)) + + +def test_a_child_with_the_named_zero_already_mapped_passes() -> None: + # A producer that wrote the universe zero itself leaves nothing to read. + frame = _lane_with_a_child() + person = frame.table("person").copy() + child = np.flatnonzero(~donor_rows(frame))[1] + person.loc[person.index[child], WAGES] = 0.0 + + anchored, receipt = with_acs_local_esi_premium_anchor( + _replace_person(frame, person) + ) + + assert ( + receipt["wage_universe"]["transferred_rows_outside_universe_read_as_zero"] == 0 + ) + assert _column(anchored, EMPLOYER)[~donor_rows(frame)][1] == 0.0 + + +def test_a_blank_raw_wage_below_fifteen_corroborates_the_universe_rule() -> None: + frame = _lane_with_a_child() + person = frame.table("person").copy() + acs = ~donor_rows(frame) + person["WAGP"] = np.nan + person.loc[acs, "WAGP"] = [40_000.0, np.nan, 30_000.0] + + _anchored, receipt = with_acs_local_esi_premium_anchor( + _replace_person(frame, person) + ) + + assert ( + receipt["wage_universe"]["transferred_rows_outside_universe_read_as_zero"] == 1 + ) + + +def test_an_untransferred_acs_spine_is_refused_by_the_anchor() -> None: + # A lane frame whose ACS rows never got the premium: null, never zero. + frame = pooled( + _small_donor(), + transferred_acs(np.asarray([np.nan]), np.asarray([30_000.0]), np.ones(1)), + ) + with pytest.raises(SourceRuntimeError, match="the transfer left a gap"): + with_acs_local_esi_premium_anchor(frame) + with pytest.raises(SourceRuntimeError, match="never filled"): + refuse_unassigned_us_esi_premiums(frame, consumer="ACS local release") + + +# --- The staging orchestration, with the real transfer ------------------------ + + +@pytest.fixture(scope="module") +def lane() -> dict[str, object]: + donor = dense_donor() + result = build_lane(donor, raw_acs()) + return {"donor": donor, "result": result, "frame": result.frame} + + +def test_every_lane_row_carries_the_premium(lane) -> None: + frame = lane["frame"] + person = frame.table("person") + acs = person["person_spine"].eq(ACS).to_numpy() + + assert acs.sum() == 280 and (~acs).sum() == 640 + np.testing.assert_array_equal(acs, ~donor_rows(frame)) + assert set(person.loc[~acs, "person_spine"]) == {ASEC_PUF} + values = person[EMPLOYER].to_numpy(dtype=float) + assert np.isfinite(values).all() and (values >= 0).all() + assert (values[acs] > 0).any() and np.unique(values[acs]).size > 2 + # The raw ASEC fields stay null on the ACS rows: they mark the row kind. + assert person.loc[acs, list(RAW)].isna().all().all() + assert person.loc[~acs, list(RAW)].notna().all().all() + # fill_reviewed_nulls' refusal has nothing to refuse. + refuse_unassigned_us_esi_premiums( + frame, consumer="ACS local release (fill_reviewed_nulls)" + ) + + +def test_the_lane_total_is_the_donor_releases_total(lane) -> None: + frame, donor = lane["frame"], lane["donor"] + rows = donor_rows(frame) + anchor = lane["result"].provenance["local_esi_premiums"]["anchor"] + + assert household_mass_share(frame, rows) == pytest.approx(0.5, rel=1e-12) + assert employer_total(frame) == pytest.approx(employer_total(donor), rel=1e-9) + assert employer_total(frame, rows) == pytest.approx( + 0.5 * employer_total(donor), rel=1e-9 + ) + assert employer_total(frame, ~rows) == pytest.approx( + 0.5 * employer_total(donor), rel=1e-9 + ) + assert anchor["status"] == "scaled" + assert anchor["kernel"] == "with_us_esi_premium_pool_anchor" + assert anchor["source_household_mass_share"] == pytest.approx(0.5, rel=1e-12) + assert anchor["employer_premium_total"] == pytest.approx( + employer_total(donor), rel=1e-9 + ) + + +def test_the_donor_spine_is_the_release_byte_for_byte(lane) -> None: + frame, donor = lane["frame"], lane["donor"] + person = frame.table("person") + rows = donor_rows(frame) + + np.testing.assert_array_equal( + person.loc[rows, EMPLOYER].to_numpy(), _column(donor, EMPLOYER) + ) + np.testing.assert_array_equal( + person.loc[rows, WAGES].to_numpy(), _column(donor, WAGES) + ) + + +def test_acs_people_without_wages_carry_no_premium(lane) -> None: + person = lane["frame"].table("person") + acs = ~donor_rows(lane["frame"]) + workers = (person[WAGES] > 0).to_numpy() + anchor = lane["result"].provenance["local_esi_premiums"]["anchor"] + + assert (acs & ~workers).sum() == 112 + assert not person.loc[acs & ~workers, EMPLOYER].any() + assert (person.loc[acs & workers, EMPLOYER] > 0).any() + # The fit saw measured wages, so no draw needed clearing. + assert anchor["transferred_rows_without_source_wages"] == 112 + assert anchor["cleared_rows"] == {EMPLOYER: 0} + assert 0.5 <= anchor["scale_factor"] <= 2.0 + + +def test_the_premium_transfers_from_asec_observations_in_its_own_pass(lane) -> None: + provenance = lane["result"].provenance + entries = [ + item for item in provenance["imputed_inputs"] if item["column"] == EMPLOYER + ] + + assert provenance["fit_configuration"]["esi_premium_donor_channel"] == "asec" + assert provenance["local_esi_premiums"]["source"]["donor_channel"] == "asec" + assert len(entries) == 1 + assert entries[0]["family"] == ACS_LOCAL_ESI_PREMIUM_FAMILY + assert entries[0]["donor_channel"] == "asec" + assert entries[0]["imputed_recipient_rows"] == 280 + assert entries[0]["unmodeled_recipient_rows"] == 0 + assert "__acs_transfer_employment_income" in entries[0]["predictors"] + json.dumps(provenance, allow_nan=False) + + +def test_the_tax_detail_transfer_keeps_its_puf_donor() -> None: + # The lane's other families still fit on the PUF-detail role. + donor = dense_donor(120) + person = donor.table("person").copy() + puf = person["person_support_clone_index"].eq(1).to_numpy() + person["taxable_interest_income"] = np.where(puf, 500.0, 5.0) + np.arange( + len(person) + ) + result = build_lane( + _replace_person(donor, person), + raw_acs(60), + n_estimators=5, + target_families={"person": {"tax_detail": ("taxable_interest_income",)}}, + ) + + configuration = result.provenance["fit_configuration"] + assert configuration["resolved_donor_channel"] == "puf_tax_detail" + assert configuration["esi_premium_donor_channel"] == "asec" + channels = { + item["column"]: item["donor_channel"] + for item in result.provenance["imputed_inputs"] + } + assert channels == { + EMPLOYER: "asec", + "taxable_interest_income": "puf_tax_detail", + } + acs = ~donor_rows(result.frame) + assert ( + result.frame.table("person").loc[acs, "taxable_interest_income"] >= 500 + ).all() + + +def test_acs_children_get_no_premium_and_keep_their_blank_wage() -> None: + # The real orchestration on an ACS spine with children: PUMS leaves their + # WAGP blank, the native mapping keeps the blank, and the anchor reads it + # as zero wages without writing a zero into the staging frame. + donor = dense_donor(120) + result = build_lane(donor, raw_acs(100, children=20), n_estimators=5) + person = result.frame.table("person") + acs = ~donor_rows(result.frame) + child = acs & (person["age"] < 15).to_numpy() + anchor = result.provenance["local_esi_premiums"]["anchor"] + + assert child.sum() == 20 + assert person.loc[child, WAGES].isna().all() + assert person.loc[child, "WAGP"].isna().all() + assert not person.loc[child, EMPLOYER].any() + assert anchor["wage_universe"]["transferred_rows_with_blank_wage"] == 20 + assert ( + anchor["wage_universe"]["transferred_rows_outside_universe_read_as_zero"] == 20 + ) + assert employer_total(result.frame) == pytest.approx( + employer_total(donor), rel=1e-9 + ) + signal, anchor_gate = acs_local_esi_premium_gates(result.frame, time_period=2024) + assert signal.passed, signal.failures + assert anchor_gate.passed, anchor_gate.failures + refuse_unassigned_us_esi_premiums(result.frame, consumer="ACS local release") + + +def test_no_factory_leaves_the_orchestration_as_it_was() -> None: + # A caller that does not ask for the premium gets none: no pass, no anchor. + donor = dense_donor(80) + with pytest.MonkeyPatch.context() as patch: + patch.setattr( + acs_multispine, + "build_acs_pums_unit_frame", + lambda *a, **k: (raw_acs(40), {}), + ) + result = acs_multispine.build_optional_acs_multispine( + donor, + AcsPumsSource(Path("unused-hus.zip"), Path("unused-pus.zip")), + target_families={}, + ) + + assert "local_esi_premiums" not in result.provenance + assert "esi_premium_donor_channel" not in result.provenance["fit_configuration"] + acs = ~donor_rows(result.frame) + assert result.frame.table("person").loc[acs, EMPLOYER].isna().all() + + +# --- Pass order: the ESI pass moves nothing but the premium ------------------- + +#: A shared-transfer plan for the pass-order tests: a chained numeric family +#: and a boolean family on the person, and tax-unit and SPM-unit families as +#: the declared plan has, fit on the PUF-detail role (the default channel) as +#: the lane's shared transfer is. Without a plan the shared transfer fits +#: nothing, and a differential over it would hold trivially. +_SHARED_PLAN = { + "person": { + "pass_order_numeric": ( + "bank_account_assets", + "stock_assets", + "health_insurance_premiums_without_medicare_part_b", + ), + "pass_order_boolean": ("has_esi", "is_full_time_college_student"), + }, + "tax_unit": { + "pass_order_tax_unit": ( + "domestic_production_ald", + "health_savings_account_ald", + ), + }, + "spm_unit": { + "pass_order_spm_numeric": ("spm_unit_pre_subsidy_childcare_expenses",), + "pass_order_spm_boolean": ("receives_snap",), + }, +} +_SHARED_TARGETS = tuple( + target + for families in _SHARED_PLAN.values() + for targets in families.values() + for target in targets +) +#: The real transfer, captured before any test wraps it in a recorder. +_REAL_TRANSFER = acs_multispine.transfer_acs_inputs + + +def _with_shared_plan_columns(donor: Frame) -> Frame: + """The donor with the shared plan's targets, distinct on the PUF role.""" + + index = np.arange(donor.n("person")) + puf = donor.table("person")["person_support_clone_index"].eq(1).to_numpy() + frame = with_person_values( + donor, + { + "bank_account_assets": np.where(puf, 40_000.0, 900.0) + 13.0 * (index % 37), + "stock_assets": np.where(index % 3 == 0, 25_000.0 + 7.0 * index, 0.0), + "health_insurance_premiums_without_medicare_part_b": 150.0 * (index % 9), + "has_esi": index % 4 < 2, + "is_full_time_college_student": index % 7 == 0, + }, + ) + tables = {entity: frame.table(entity) for entity in frame.entities} + tax_unit = tables["tax_unit"].copy() + units = np.arange(len(tax_unit)) + tax_unit["domestic_production_ald"] = np.where( + units % 5 == 0, 1_000.0 + 3.0 * units, 0.0 + ) + tax_unit["health_savings_account_ald"] = 50.0 * (units % 11) + spm_unit = tables["spm_unit"].copy() + units = np.arange(len(spm_unit)) + spm_unit["spm_unit_pre_subsidy_childcare_expenses"] = np.where( + units % 6 == 0, 4_000.0 + units, 0.0 + ) + spm_unit["receives_snap"] = units % 7 == 0 + tables.update(tax_unit=tax_unit, spm_unit=spm_unit) + return Frame( + tables, + frame.schema, + {"household": frame.weights_for("household")}, + frame.strata, + ) + + +def _assert_identical(left: pd.Series, right: pd.Series, label: str) -> None: + """Exactly equal: values, missing cells, dtype and index; numbers by bytes.""" + + pd.testing.assert_series_equal(left, right, check_exact=True, obj=label) + if left.dtype.kind in "biufcmM": + assert left.to_numpy().tobytes() == right.to_numpy().tobytes(), label + + +def _assert_tables_identical( + left: pd.DataFrame, right: pd.DataFrame, label: str +) -> None: + assert list(left.columns) == list(right.columns), label + pd.testing.assert_index_equal(left.index, right.index, exact=True) + for column in left.columns: + _assert_identical(left[column], right[column], f"{label}.{column}") + + +def _without_premium(table: pd.DataFrame) -> pd.DataFrame: + return table.drop(columns=[EMPLOYER], errors="ignore") + + +@pytest.fixture(scope="module") +def pass_order() -> dict[str, AcsMultispineResult]: + donor = _with_shared_plan_columns(dense_donor()) + acs = raw_acs() + return { + "with": build_lane(donor, acs, target_families=_SHARED_PLAN), + "without": build_lane( + donor, acs, target_families=_SHARED_PLAN, esi_premiums=False + ), + } + + +def test_the_shared_transfer_draws_every_target_with_and_without_the_pass( + pass_order, +) -> None: + # The differential below is not vacuous: in both runs the shared transfer + # drew every target of its plan, person, tax-unit and SPM-unit, on all + # 280 ACS rows (one person, tax unit and SPM unit per ACS household). + for result in pass_order.values(): + drawn = { + item["column"]: item + for item in result.provenance["imputed_inputs"] + if item["column"] != EMPLOYER + } + assert set(drawn) == set(_SHARED_TARGETS) + for item in drawn.values(): + assert item["donor_channel"] == "puf_tax_detail" + assert item["imputed_recipient_rows"] == 280 + assert item["unmodeled_recipient_rows"] == 0 + for entity, families in _SHARED_PLAN.items(): + targets = [target for group in families.values() for target in group] + assert result.frame.table(entity)[targets].notna().all().all(), entity + + +def test_the_esi_pass_moves_no_other_value_on_any_row(pass_order) -> None: + # Every column but the premium is byte-equal on every row of every table, + # with the same weights, strata, mass log and metadata. + left, right = pass_order["with"].frame, pass_order["without"].frame + + assert left.entities == right.entities + for entity in left.entities: + _assert_tables_identical( + _without_premium(left.table(entity)), + _without_premium(right.table(entity)), + entity, + ) + assert left.links == right.links + for name in left.links: + _assert_tables_identical(left.link(name), right.link(name), name) + assert left.weighted_entities == right.weighted_entities + for entity in left.weighted_entities: + ours, theirs = left.weights_for(entity), right.weights_for(entity) + assert ours.kind is theirs.kind + assert ( + np.asarray(ours.values, dtype=np.float64).tobytes() + == np.asarray(theirs.values, dtype=np.float64).tobytes() + ) + _assert_identical(left.strata, right.strata, "strata") + assert left.mass_log == right.mass_log + assert dict(left.metadata) == dict(right.metadata) + # The premium itself: the donor rows' bytes are the release's either way; + # the ACS rows carry it only with the pass. + rows = donor_rows(left) + np.testing.assert_array_equal(donor_rows(right), rows) + ours, theirs = _column(left, EMPLOYER), _column(right, EMPLOYER) + assert ours[rows].tobytes() == theirs[rows].tobytes() + assert np.isnan(theirs[~rows]).all() + assert np.isfinite(ours[~rows]).all() + + +def test_the_esi_pass_leaves_every_other_receipt_alone(pass_order) -> None: + ours, theirs = pass_order["with"], pass_order["without"] + + def shared_inputs(result: AcsMultispineResult) -> list[dict]: + return [ + item + for item in result.provenance["imputed_inputs"] + if item["column"] != EMPLOYER + ] + + # Seeds, predictors, patterns and row counts of the shared transfer. + assert shared_inputs(ours) == shared_inputs(theirs) + # The ESI pass's fit records come before the shared transfer's, which are + # the ones the run without the pass records. + our_fits = ours.provenance["fit_records"] + their_fits = theirs.provenance["fit_records"] + assert len(our_fits) > len(their_fits) + assert our_fits[-len(their_fits) :] == their_fits + assert len(ours.fit_records) == len(our_fits) + + def rest(result: AcsMultispineResult) -> str: + provenance = dict(result.provenance) + for key in ("imputed_inputs", "fit_records", "local_esi_premiums"): + provenance.pop(key, None) + configuration = dict(provenance["fit_configuration"]) + configuration.pop("esi_premium_donor_channel", None) + provenance["fit_configuration"] = configuration + return json.dumps(provenance, sort_keys=True, allow_nan=False) + + assert rest(ours) == rest(theirs) + assert "local_esi_premiums" not in theirs.provenance + + +@pytest.fixture(scope="module") +def beside_income() -> dict[str, dict[str, object]]: + """The lane with its hours and income passes, every transfer call recorded. + + Run twice, with and without the ESI donor factory. Each record keeps the + call's keywords, the person table it was handed and the one it returned. + """ + + donor = _with_shared_plan_columns(income_donor(120)) + acs = raw_acs(60, income_sources=True) + runs: dict[str, dict[str, object]] = {} + for arm, esi_premiums in (("with", True), ("without", False)): + calls: list[dict[str, object]] = [] + + def recorded(recipient, donor, calls=calls, **kwargs): + result = _REAL_TRANSFER(recipient, donor, **kwargs) + calls.append( + { + "kwargs": kwargs, + "recipient": recipient.table("person").copy(), + "drawn": result.frame.table("person").copy(), + } + ) + return result + + with pytest.MonkeyPatch.context() as patch: + patch.setattr(acs_multispine, "transfer_acs_inputs", recorded) + result = build_lane( + donor, + acs, + n_estimators=5, + seed=5, + target_families=_SHARED_PLAN, + esi_premiums=esi_premiums, + hours_donor=donor, + income_transfer=True, + ) + runs[arm] = {"result": result, "calls": calls} + return runs + + +def test_the_passes_run_hours_income_esi_then_the_shared_transfer( + beside_income, +) -> None: + ours = beside_income["with"]["calls"] + theirs = beside_income["without"]["calls"] + hours = acs_local_hours_transfer_target_families() + income = acs_local_income_transfer_target_families() + esi_plan = acs_local_esi_premium_transfer_target_families() + + assert [call["kwargs"]["target_families"] for call in ours] == [ + hours, + income, + esi_plan, + _SHARED_PLAN, + ] + assert [call["kwargs"]["donor_channel"] for call in ours] == [ + "asec", + ACS_LOCAL_INCOME_DONOR_CHANNEL, + "asec", + ACS_DONOR_CHANNEL_AUTO, + ] + assert [call["kwargs"]["target_families"] for call in theirs] == [ + hours, + income, + _SHARED_PLAN, + ] + # The premium is absent where hours and income fit, drawn on every ACS row + # by its own pass, and present where the shared transfer fits. + for call in ours[:3]: + assert EMPLOYER not in call["recipient"] + assert ours[2]["drawn"][EMPLOYER].notna().all() + assert ours[3]["recipient"][EMPLOYER].notna().all() + for call in theirs: + assert EMPLOYER not in call["recipient"] + # The receipts list the passes in the same order. + provenance = beside_income["with"]["result"].provenance + columns = [item["column"] for item in provenance["imputed_inputs"]] + width = len(ACS_LOCAL_INCOME_TRANSFER_COLUMNS) + assert columns[0] == USUAL_HOURS + assert set(columns[1 : 1 + width]) == set(ACS_LOCAL_INCOME_TRANSFER_COLUMNS) + assert columns[1 + width] == EMPLOYER + assert set(columns[2 + width :]) == set(_SHARED_TARGETS) + assert len(columns) == 2 + width + len(_SHARED_TARGETS) + assert provenance["fit_configuration"]["esi_premium_donor_channel"] == "asec" + assert provenance["fit_configuration"]["income_donor_channel"] == ( + ACS_LOCAL_INCOME_DONOR_CHANNEL + ) + assert provenance["fit_configuration"]["hours_donor_channel"] == "asec" + + +def test_the_esi_pass_changes_no_call_or_draw_of_the_other_passes( + beside_income, +) -> None: + ours = beside_income["with"]["calls"] + theirs = beside_income["without"]["calls"] + + # Hours and income: the same call on the same frame, the same draws. + for position, name in ((0, "hours"), (1, "income")): + assert ours[position]["kwargs"] == theirs[position]["kwargs"], name + _assert_tables_identical( + ours[position]["recipient"], theirs[position]["recipient"], name + ) + _assert_tables_identical( + ours[position]["drawn"], theirs[position]["drawn"], name + ) + # The ESI pass is handed exactly the frame the shared transfer is handed + # without it, and returns it with the premium added. + _assert_tables_identical(ours[2]["recipient"], theirs[2]["recipient"], "esi") + _assert_tables_identical( + _without_premium(ours[2]["drawn"]), theirs[2]["recipient"], "esi drawn" + ) + # The shared transfer: the same call, on a frame that differs by the + # premium alone, and the same draws. + assert ours[3]["kwargs"] == theirs[2]["kwargs"] + _assert_tables_identical( + _without_premium(ours[3]["recipient"]), theirs[2]["recipient"], "shared" + ) + _assert_tables_identical( + _without_premium(ours[3]["drawn"]), theirs[2]["drawn"], "shared drawn" + ) + # And the lane frames: every other column of every table byte-equal, the + # income leaves on the ACS rows included. + left = beside_income["with"]["result"].frame + right = beside_income["without"]["result"].frame + for entity in left.entities: + _assert_tables_identical( + _without_premium(left.table(entity)), + _without_premium(right.table(entity)), + entity, + ) + acs = ~donor_rows(left) + assert ( + left.table("person") + .loc[acs, list(ACS_LOCAL_INCOME_TRANSFER_COLUMNS)] + .notna() + .all() + .all() + ) + signal, anchor = acs_local_esi_premium_gates(left, time_period=2024) + assert signal.passed, signal.failures + assert anchor.passed, anchor.failures + + +# --- Which donor role, and what it does to the structural zero ---------------- + + +def _acs_draws(donor: Frame, channel: str) -> tuple[pd.Series, pd.Series]: + mapped = map_acs_native_inputs(raw_acs()).frame + person = transfer_acs_inputs( + mapped, + donor, + target_families=acs_local_esi_premium_transfer_target_families(), + donor_channel=channel, + seed=0, + n_estimators=20, + ).frame.table("person") + return person[EMPLOYER], person[WAGES] + + +def test_the_puf_detail_role_would_put_premiums_on_people_without_wages() -> None: + # On PUF-detail rows the premium is a copy of the source person's and the + # wages are PUF-imputed, so wages no longer say who holds a job. + donor = dense_donor() + donor_person = donor.table("person") + puf = donor_person["person_support_clone_index"].eq(1).to_numpy() + premium, wages = _column(donor, EMPLOYER), _column(donor, WAGES) + assert not ((premium > 0) & ~(wages > 0))[~puf].any() + assert ((premium > 0) & ~(wages > 0))[puf].any() + + asec_premium, asec_wages = _acs_draws(donor, "asec") + puf_premium, puf_wages = _acs_draws(donor, "puf_tax_detail") + + def share_without_wages_drawing_a_premium(drawn, measured) -> float: + idle = ~(measured > 0) + return float((drawn[idle] > 0).mean()) + + def share_of_workers_drawing_a_premium(drawn, measured) -> float: + return float((drawn[measured > 0] > 0).mean()) + + # ASEC observations: the fit learns the structural zero from measured wages. + assert share_without_wages_drawing_a_premium(asec_premium, asec_wages) == 0.0 + # PUF-detail role: people without wages draw premiums, and workers draw + # fewer, because the fit cannot tell the two apart. + assert share_without_wages_drawing_a_premium(puf_premium, puf_wages) > 0.1 + assert share_of_workers_drawing_a_premium( + puf_premium, puf_wages + ) < share_of_workers_drawing_a_premium(asec_premium, asec_wages) + + +# --- Both gates on the lane frame --------------------------------------------- + + +def test_both_gates_pass_on_the_lane_frame(lane) -> None: + frame, donor = lane["frame"], lane["donor"] + + signal, anchor = acs_local_esi_premium_gates(frame, time_period=2024) + + assert signal.passed, signal.failures + assert anchor.passed, anchor.failures + assert signal.details["source_rows"] == 640 + assert signal.details["transferred_rows"] == 280 + assert signal.details["employer_premium_outside_universe_rows"] == 0 + assert signal.details["clone_disagreement_source_persons"] == 0 + assert signal.details["transferred_source_records_with_premium_and_no_wages"] == 0 + # The donor ran the stage at the whole anchor, and the lane keeps its + # anchor-universe total and its scale factor. + alone = us_esi_premiums_anchor_gate(donor, time_period=2024) + assert alone.passed, alone.failures + assert anchor.details["anchor_universe_employer_total"] == pytest.approx( + ANCHOR, rel=1e-9 + ) + assert anchor.details["relative_error"] == pytest.approx( + alone.details["relative_error"], abs=1e-9 + ) + assert anchor.details["scale_factor"] == pytest.approx( + alone.details["scale_factor"], rel=1e-9 + ) + assert anchor.details["source_household_mass_share"] == pytest.approx( + 0.5, rel=1e-12 + ) + assert anchor.details[ + "transferred_to_source_per_household_mass_ratio" + ] == pytest.approx(1.0, rel=1e-9) + assert "employed share" in anchor.details["anchor_universe_assumption"] + + +def test_the_narrow_gate_view_gives_the_whole_frame_verdicts(lane) -> None: + # Differential: the gates read a few columns but copy every table, so the + # lane hands them a narrow view. It must not change a verdict or a detail. + frame = lane["frame"] + + signal, anchor = acs_local_esi_premium_gates(frame, time_period=2024) + whole_signal = us_esi_premiums_signal_gate(frame, allow_transferred_rows=True) + whole_anchor = us_esi_premiums_anchor_gate( + frame, time_period=2024, allow_transferred_rows=True + ) + + for narrow, whole in ((signal, whole_signal), (anchor, whole_anchor)): + assert narrow.name == whole.name + assert narrow.passed is whole.passed + assert narrow.failures == whole.failures + assert json.dumps(dict(narrow.details), sort_keys=True, default=str) == ( + json.dumps(dict(whole.details), sort_keys=True, default=str) + ) + + +def test_the_lane_frame_is_red_under_route_as_default_rule(lane) -> None: + # The lane's gate calls pass allow_transferred_rows=True. Route A's + # callers keep the default, under which a row without the raw ASEC fields + # is refused: the lane frame's 280 ACS rows turn both gates red there. + frame = lane["frame"] + + signal = us_esi_premiums_signal_gate(frame) + anchor = us_esi_premiums_anchor_gate(frame, time_period=2024) + + for gate in (signal, anchor): + assert not gate.passed + assert any( + "280 row(s) lack some of the raw ASEC fields" in failure + for failure in gate.failures + ), gate.failures + + +def _with_acs_premium(frame: Frame, transform) -> Frame: + person = frame.table("person").copy() + acs = ~donor_rows(frame) + person.loc[acs, EMPLOYER] = transform(person.loc[acs, EMPLOYER]) + return _replace_person(frame, person) + + +def test_an_acs_spine_without_the_premium_fails_the_signal_gate(lane) -> None: + zeroed = _with_acs_premium(lane["frame"], lambda values: values * 0.0) + + signal, _anchor = acs_local_esi_premium_gates(zeroed, time_period=2024) + + assert not signal.passed + assert any( + "rows without raw ASEC columns" in failure for failure in signal.failures + ) + + +@pytest.mark.parametrize("factor", [0.7, 1.4]) +def test_an_acs_spine_off_the_donor_rows_scale_fails_the_anchor_gate( + lane, factor: float +) -> None: + scaled = _with_acs_premium(lane["frame"], lambda values: values * factor) + + _signal, anchor = acs_local_esi_premium_gates(scaled, time_period=2024) + + assert not anchor.passed + assert any("per unit of household mass" in failure for failure in anchor.failures) + assert anchor.details[ + "transferred_to_source_per_household_mass_ratio" + ] == pytest.approx(factor, rel=1e-9) + + +def test_a_lane_frame_from_a_donor_without_the_stage_fails_both_gates() -> None: + # A waived diagnostic build: no row carries the column at all. + acs = transferred_acs(np.asarray([9_000.0]), np.asarray([30_000.0]), np.ones(1)) + frame = pooled( + _donor_without(EMPLOYER), + _replace_person(acs, acs.table("person").drop(columns=[EMPLOYER])), + ) + assert EMPLOYER not in frame.table("person") + + signal, anchor = acs_local_esi_premium_gates(frame, time_period=2024) + + assert not signal.passed and not anchor.passed + assert signal.failures == (f"person column missing: {EMPLOYER}.",) + assert anchor.failures == (f"person column missing: {EMPLOYER}.",) + + +def test_moving_mass_between_spines_moves_neither_the_total_nor_the_ratio( + lane, +) -> None: + # Calibration moves mass between spines. Both carry the same premium per + # unit of household mass, so a shift that conserves the frame's mass + # leaves the lane total where it was. + frame = lane["frame"] + household = frame.table("household") + acs_household = household["household_spine"].eq(ACS).to_numpy() + weights = np.asarray(frame.weights_for("household").values, dtype=float).copy() + weights[acs_household] *= 1.3 + weights *= frame.weights_for("household").total / weights.sum() + moved = Frame( + {entity: frame.table(entity) for entity in frame.entities}, + frame.schema, + {"household": Weights(weights, WeightKind.CALIBRATED)}, + frame.strata, + ) + + signal, anchor = acs_local_esi_premium_gates(moved, time_period=2024) + + assert signal.passed, signal.failures + assert anchor.passed, anchor.failures + assert anchor.details[ + "transferred_to_source_per_household_mass_ratio" + ] == pytest.approx(1.0, rel=1e-9) + assert employer_total(moved) == pytest.approx(employer_total(frame), rel=1e-9) + + +def test_a_gate_payload_is_strict_json_and_keeps_failures_verbatim(lane) -> None: + signal, anchor = acs_local_esi_premium_gates( + _with_acs_premium(lane["frame"], lambda values: values * 0.0), + time_period=2024, + ) + + payload = acs_local_esi_premium_gate_payload(signal) + + assert payload["name"] == "esi_premiums_signal" + assert payload["passed"] is False + assert payload["failures"] == list(signal.failures) + json.dumps(payload, allow_nan=False) + json.dumps(acs_local_esi_premium_gate_payload(anchor), allow_nan=False) + + +@requires_pytables +def test_the_staging_h5_round_trip_keeps_the_verdicts(lane, tmp_path) -> None: + # Finalize grades the calibrated H5 the lane wrote, not the frame in memory. + frame = lane["frame"] + path = tmp_path / "acs_multispine_staging.h5" + + write_nullable_us_h5( + frame, path, period=2024, artifact_kind=LEGACY_NULLABLE_STAGING_ARTIFACT_KIND + ) + loaded = load_legacy_calibrated_us_h5(path) + + signal, anchor = acs_local_esi_premium_gates(loaded, time_period=2024) + assert signal.passed, signal.failures + assert anchor.passed, anchor.failures + assert employer_total(loaded) == pytest.approx(employer_total(frame), rel=1e-12) + np.testing.assert_array_equal(donor_rows(loaded), donor_rows(frame)) + refuse_unassigned_us_esi_premiums(loaded, consumer="ACS local release") + again, receipt = with_acs_local_esi_premium_anchor(loaded) + assert again is loaded and receipt["status"] == "already_on_anchor" diff --git a/packages/microcosm-build/tests/engine_free/us/test_us_acs_local_gate_shadow.py b/packages/microcosm-build/tests/engine_free/us/test_us_acs_local_gate_shadow.py index b109c55ab4..7c9896b135 100644 --- a/packages/microcosm-build/tests/engine_free/us/test_us_acs_local_gate_shadow.py +++ b/packages/microcosm-build/tests/engine_free/us/test_us_acs_local_gate_shadow.py @@ -9,6 +9,7 @@ from __future__ import annotations +import hashlib import json from types import SimpleNamespace @@ -58,6 +59,8 @@ def _tool_shadows_on(monkeypatch) -> None: "us_local_ssi_disability", "us_local_ssi_medicaid_take_up_finalize", "us_local_receipt_anchors", + "us_local_esi_premiums_signal", + "us_local_esi_premiums_anchor", "us_local_reviewed_fill_consumers_finalize", "us_local_district_ess_collapse", ), @@ -85,7 +88,10 @@ def _args(tmp_path): ) -def _run_stage(acs, args, stage, *, legacy=None): +def _run_stage(acs, args, stage, *, legacy=None, report=None): + """Run ``stage``'s stand-in gates; finalize also writes ``report``, if + given, to ``args.gate_report`` with the call ``do_finalize`` makes.""" + with acs._local_gate_shadow_stage(args, stage): observe_entries("us_local", acs, STAGE_ENTRIES[stage], legacy=legacy) if stage == "finalize": @@ -93,6 +99,8 @@ def _run_stage(acs, args, stage, *, legacy=None): "us_local_block_location", "the staging used the legacy location rule; no block ladder", ) + if report is not None: + acs._write_gate_report(args, report) def _comparison(args): @@ -129,6 +137,382 @@ def test_separate_stage_processes_add_up_to_one_finished_run( assert (acs_directory(args) / f"{stage}.observations.json").is_file() +def test_the_esi_premium_waiver_is_recorded_on_its_two_entries( + tmp_path, monkeypatch, acs +) -> None: + args = _args(tmp_path) + assert acs._local_gate_waivers(args) == {} + args.allow_esi_premium_gaps = True + waived = { + "us_local_esi_premiums_signal": ["--allow-esi-premium-gaps"], + "us_local_esi_premiums_anchor": ["--allow-esi-premium-gaps"], + } + assert acs._local_gate_waivers(args) == waived + stand_in_gates(monkeypatch, "us_local", acs) + for stage in STAGE_ENTRIES: + _run_stage(acs, args, stage) + payload = _comparison(args) + assert payload["run_completed"] is True + assert payload["verdict_difference"] is False + assert payload["waivers"] == waived + + +@pytest.mark.parametrize( + ("finalize_waived", "package_waived"), [(False, True), (True, False)] +) +def test_an_esi_entry_keeps_the_waiver_finalize_ran_with( + tmp_path, monkeypatch, acs, finalize_waived, package_waived +) -> None: + # The stages may run as separate processes with different flags. The ESI + # entries are evaluated at finalize, so the comparison the package stage + # rebuilds records finalize's waiver on them, never the package stage's. + args = _args(tmp_path) + stand_in_gates(monkeypatch, "us_local", acs) + for stage in STAGE_ENTRIES: + args.allow_esi_premium_gaps = ( + package_waived if stage == "package" else finalize_waived + ) + _run_stage(acs, args, stage) + + payload = _comparison(args) + flags = ["--allow-esi-premium-gaps"] if finalize_waived else [] + waived_by = {row["id"]: row["waived_by"] for row in payload["entries"]} + assert payload["run_completed"] is True + assert waived_by["us_local_esi_premiums_signal"] == flags + assert waived_by["us_local_esi_premiums_anchor"] == flags + assert payload["waivers"] == ( + { + "us_local_esi_premiums_signal": flags, + "us_local_esi_premiums_anchor": flags, + } + if finalize_waived + else {} + ) + # Rerunning an earlier stage discards finalize's record with its + # observations. + record = acs_directory(args) / "finalize.waivers.json" + assert record.is_file() + _run_stage(acs, args, "calibrate") + assert not record.exists() + + +def test_a_finalize_checkpoint_without_a_waiver_record_marks_the_waiver_unknown( + tmp_path, monkeypatch, acs +) -> None: + # A finalize checkpoint saved before finalize kept a waiver record has + # its observations and no record. Package cannot tell which waiver that + # finalize ran with, so the ESI entries record it as unknown, not as + # none, and the comparison is still rebuilt. + args = _args(tmp_path) + stand_in_gates(monkeypatch, "us_local", acs) + for stage in ("materialize", "calibrate", "qa", "finalize"): + _run_stage(acs, args, stage) + (acs_directory(args) / "finalize.waivers.json").unlink() + assert (acs_directory(args) / "finalize.observations.json").is_file() + _run_stage(acs, args, "package") + + payload = _comparison(args) + unknown = ["unknown: the finalize stage saved no waiver record"] + esi = {"us_local_esi_premiums_signal", "us_local_esi_premiums_anchor"} + waived_by = {row["id"]: row["waived_by"] for row in payload["entries"]} + assert payload["run_completed"] is True + assert {entry_id: waived_by[entry_id] for entry_id in esi} == dict.fromkeys( + esi, unknown + ) + assert all( + flags == [] for entry_id, flags in waived_by.items() if entry_id not in esi + ) + assert payload["waivers"] == dict.fromkeys(esi, unknown) + + +#: The entries finalize evaluates that --allow-esi-premium-gaps waives. +ESI = ("us_local_esi_premiums_signal", "us_local_esi_premiums_anchor") +WAIVED = ["--allow-esi-premium-gaps"] + + +def _sha256(path) -> str: + return hashlib.sha256(path.read_bytes()).hexdigest() + + +def _esi_waived_by(args) -> dict[str, list[str]]: + waived_by = {row["id"]: row["waived_by"] for row in _comparison(args)["entries"]} + return {entry_id: waived_by[entry_id] for entry_id in ESI} + + +def _finalize_record(args) -> dict: + return json.loads((acs_directory(args) / "finalize.waivers.json").read_text()) + + +def test_package_shows_a_finalize_waiver_only_on_the_gate_report_that_run_wrote( + tmp_path, monkeypatch, acs +) -> None: + # Finalize a.json without the waiver, then b.json with it, on one + # checkpoint. Package a.json ships a report that enforced the ESI gates, + # so its shadow must not show b's waiver: the record b left names b.json. + args = _args(tmp_path) + stand_in_gates(monkeypatch, "us_local", acs) + for stage in ("materialize", "calibrate", "qa"): + _run_stage(acs, args, stage) + a, b = tmp_path / "a.json", tmp_path / "b.json" + args.gate_report, args.allow_esi_premium_gaps = a, False + _run_stage(acs, args, "finalize", report={"run": "a", "enforced": True}) + args.gate_report, args.allow_esi_premium_gaps = b, True + _run_stage(acs, args, "finalize", report={"run": "b", "enforced": False}) + + args.gate_report, args.allow_esi_premium_gaps = a, False + _run_stage(acs, args, "package") + mismatch = [ + "unknown: the finalize stage's waiver record belongs to gate report " + f"{_sha256(b)}, not to the selected gate report {_sha256(a)}" + ] + assert _comparison(args)["run_completed"] is True + assert _esi_waived_by(args) == dict.fromkeys(ESI, mismatch) + assert _comparison(args)["waivers"] == dict.fromkeys(ESI, mismatch) + + # On the report that run wrote, its waiver, whatever package's flag says. + args.gate_report = b + _run_stage(acs, args, "package") + assert _esi_waived_by(args) == dict.fromkeys(ESI, WAIVED) + assert _finalize_record(args) == { + "gate_report_sha256": _sha256(b), + "waivers": dict.fromkeys(ESI, WAIVED), + } + + +def test_a_finalize_run_that_wrote_no_gate_report_names_none( + tmp_path, monkeypatch, acs +) -> None: + # A finalize run stopped before it wrote its report leaves the previous + # run's report in place. Its waiver record names no report, so package on + # that earlier report does not show the stopped run's waiver. + args = _args(tmp_path) + args.gate_report = tmp_path / "gate_summary.json" + stand_in_gates(monkeypatch, "us_local", acs) + for stage in ("materialize", "calibrate", "qa"): + _run_stage(acs, args, stage) + args.allow_esi_premium_gaps = False + _run_stage(acs, args, "finalize", report={"run": "first"}) + earlier = _sha256(args.gate_report) + args.allow_esi_premium_gaps = True + with pytest.raises(SystemExit, match="stopped"): + with acs._local_gate_shadow_stage(args, "finalize"): + observe_entries("us_local", acs, STAGE_ENTRIES["finalize"]) + raise SystemExit("finalize stopped before it wrote its gate report") + assert _sha256(args.gate_report) == earlier + + args.allow_esi_premium_gaps = False + _run_stage(acs, args, "package") + expected = [ + "unknown: the finalize stage's waiver record belongs to gate report " + "none (that run wrote no gate report, or its report could not be read), " + f"not to the selected gate report {earlier}" + ] + assert _esi_waived_by(args) == dict.fromkeys(ESI, expected) + assert _finalize_record(args) == { + "gate_report_sha256": None, + "waivers": dict.fromkeys(ESI, WAIVED), + } + + +def test_package_matches_the_waiver_to_the_gate_report_bytes_it_read( + tmp_path, monkeypatch, acs +) -> None: + # Finalize a.json without the waiver, then b.json with it, on one + # checkpoint. Package reads a.json, and the file at that path is then + # replaced by b's bytes before the stage ends. The release carries a's + # gates, so the shadow must match finalize's record to the bytes package + # read, not to the file at the path when it rebuilds the comparison. + args = _args(tmp_path) + stand_in_gates(monkeypatch, "us_local", acs) + for stage in ("materialize", "calibrate", "qa"): + _run_stage(acs, args, stage) + a, b = tmp_path / "a.json", tmp_path / "b.json" + args.gate_report, args.allow_esi_premium_gaps = a, False + _run_stage(acs, args, "finalize", report={"run": "a", "enforced": True}) + args.gate_report, args.allow_esi_premium_gaps = b, True + _run_stage(acs, args, "finalize", report={"run": "b", "enforced": False}) + read = _sha256(a) + + args.gate_report, args.allow_esi_premium_gaps = a, False + with acs._local_gate_shadow_stage(args, "package"): + observe_entries("us_local", acs, STAGE_ENTRIES["package"]) + assert acs._load_gate_report(args) == {"run": "a", "enforced": True} + a.write_bytes(b.read_bytes()) + + assert _sha256(a) == _sha256(b) + mismatch = [ + "unknown: the finalize stage's waiver record belongs to gate report " + f"{_sha256(b)}, not to the selected gate report {read}" + ] + assert _comparison(args)["run_completed"] is True + assert _esi_waived_by(args) == dict.fromkeys(ESI, mismatch) + + +def test_finalize_names_the_gate_report_bytes_it_wrote( + tmp_path, monkeypatch, acs +) -> None: + # Finalize writes its report, and another process replaces the file + # before the stage saves its waiver record. The record names the bytes + # finalize wrote, so package on the replacement does not take its waiver. + args = _args(tmp_path) + args.gate_report = tmp_path / "gate_summary.json" + args.allow_esi_premium_gaps = True + stand_in_gates(monkeypatch, "us_local", acs) + for stage in ("materialize", "calibrate", "qa"): + _run_stage(acs, args, stage) + with acs._local_gate_shadow_stage(args, "finalize"): + observe_entries("us_local", acs, STAGE_ENTRIES["finalize"]) + acs._write_gate_report(args, {"run": "finalize", "enforced": False}) + written = _sha256(args.gate_report) + args.gate_report.write_text(json.dumps({"run": "replaced"})) + + assert _finalize_record(args) == { + "gate_report_sha256": written, + "waivers": dict.fromkeys(ESI, WAIVED), + } + args.allow_esi_premium_gaps = False + _run_stage(acs, args, "package") + mismatch = [ + "unknown: the finalize stage's waiver record belongs to gate report " + f"{written}, not to the selected gate report {_sha256(args.gate_report)}" + ] + assert _esi_waived_by(args) == dict.fromkeys(ESI, mismatch) + + +@pytest.mark.parametrize("flags", [None, WAIVED], ids=["unwaived", "waived"]) +def test_a_finalize_waiver_record_without_a_gate_report_digest_is_unknown( + tmp_path, monkeypatch, acs, flags +) -> None: + # A record saved before records named their gate report holds the waivers + # alone, by entry id, as 24a417c11d wrote them. Nothing ties it to the + # report package selects, so the shadow records its waiver as unknown. + args = _args(tmp_path) + args.gate_report = tmp_path / "gate_summary.json" + stand_in_gates(monkeypatch, "us_local", acs) + for stage in ("materialize", "calibrate", "qa"): + _run_stage(acs, args, stage) + _run_stage(acs, args, "finalize", report={"run": "only"}) + (acs_directory(args) / "finalize.waivers.json").write_text( + json.dumps(dict.fromkeys(ESI, flags) if flags else {}) + ) + + _run_stage(acs, args, "package") + + expected = [ + "unknown: the finalize stage's waiver record names no gate report, so it " + f"cannot be matched to the selected gate report {_sha256(args.gate_report)}" + ] + assert _comparison(args)["run_completed"] is True + assert _esi_waived_by(args) == dict.fromkeys(ESI, expected) + + +@pytest.mark.parametrize( + ("text", "error"), + [ + # Truncated. + ("{", "JSONDecodeError: Expecting property name"), + # Wrong shape. + ("[]", "the record is a list, not a mapping"), + ('{"waivers": [], "gate_report_sha256": null}', "not lists of flags"), + # Wrong types. + ( + '{"waivers": {"us_local_esi_premiums_signal": [1]}, ' + '"gate_report_sha256": null}', + "not lists of flags", + ), + ('{"waivers": {}, "gate_report_sha256": 7}', "is not a SHA-256 hex digest"), + # An entry finalize does not waive, which the battery would accept. + ( + '{"us_local_take_up": ["--allow-esi-premium-gaps"]}', + "names entries the finalize stage does not waive: ['us_local_take_up']", + ), + # Nested past the JSON decoder's depth, before any shape check. + ("[" * 1_000_000 + "]" * 1_000_000, "RecursionError: "), + ], + ids=[ + "truncated", + "list", + "waivers_list", + "flag_type", + "digest_type", + "foreign", + "deeply_nested", + ], +) +def test_an_unreadable_waiver_record_is_unknown_and_the_comparison_is_rebuilt( + tmp_path, monkeypatch, acs, capsys, text, error +) -> None: + # A waiver record the shadow cannot read costs its own entries' waiver, + # which becomes unknown and names the file and the error. The shadow + # still rebuilds the comparison from every stage's observations, with + # its differences. + args = _args(tmp_path) + stand_in_gates(monkeypatch, "us_local", acs, failing={"local_hours_signal"}) + 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") + } + for stage in ("materialize", "calibrate", "qa"): + _run_stage(acs, args, stage) + _run_stage(acs, args, "finalize", legacy=legacy) + (acs_directory(args) / "finalize.waivers.json").write_text(text) + + _run_stage(acs, args, "package", legacy=legacy) + + payload = _comparison(args) + assert payload["run_completed"] is True + assert {row["id"] for row in payload["entries"]} == { + entry.id for entry in us_scoped_gate_manifest("us_local").gates + } + differing = [row["id"] for row in payload["differences"]] + assert differing and all(entry.startswith("us_local_hours") for entry in differing) + waived_by = {row["id"]: row["waived_by"] for row in payload["entries"]} + for entry_id in ESI: + (marker,) = waived_by[entry_id] + assert marker.startswith( + "unknown: finalize.waivers.json could not be read as a waiver record (" + ) + assert error in marker + assert all( + flags == [] for entry_id, flags in waived_by.items() if entry_id not in ESI + ) + assert "finalize.waivers.json could not be read" in capsys.readouterr().out + + +@pytest.mark.parametrize( + ("cause", "error"), + [("directory", "(IsADirectoryError: "), ("symlink_loop", "(OSError: ")], +) +def test_a_waiver_record_the_shadow_cannot_open_is_unknown_and_named( + tmp_path, monkeypatch, acs, cause, error +) -> None: + # A record path that holds something the shadow cannot open is named with + # the error, not read as a stage that saved no record. ``Path.is_file`` + # is False for a directory and for a path whose stat fails, here on a + # symbolic link loop. + args = _args(tmp_path) + stand_in_gates(monkeypatch, "us_local", acs) + for stage in ("materialize", "calibrate", "qa", "finalize"): + _run_stage(acs, args, stage) + record = acs_directory(args) / "finalize.waivers.json" + record.unlink() + if cause == "directory": + record.mkdir() + else: + record.symlink_to(record.name) + assert not record.is_file() + + _run_stage(acs, args, "package") + + assert _comparison(args)["run_completed"] is True + for (marker,) in _esi_waived_by(args).values(): + assert marker.startswith( + "unknown: finalize.waivers.json could not be read as a waiver record " + ) + assert error in marker + + def test_with_the_switch_off_a_stage_touches_no_shadow_file( tmp_path, monkeypatch, acs ) -> None: diff --git a/packages/microcosm-build/tests/engine_free/us/test_us_acs_local_immigration.py b/packages/microcosm-build/tests/engine_free/us/test_us_acs_local_immigration.py index 2eb95df032..fd34039c9d 100644 --- a/packages/microcosm-build/tests/engine_free/us/test_us_acs_local_immigration.py +++ b/packages/microcosm-build/tests/engine_free/us/test_us_acs_local_immigration.py @@ -793,13 +793,12 @@ def test_entry_clock_is_an_arrival_proxy_with_a_lag_sensitivity() -> None: for text in ( "neither the ACS nor the ASEC donor records the date qualified status", "the clock runs from arrival", - "the policyengine-us 2.2.1 tests that read the clock", - "Medicaid (CHIP follows it) and Washington TANF read it against a " - "five-year bar", + "the policyengine-us 2.145.3 tests that read the clock", + "SNAP's qualified-alien waiting period, the federal Medicaid and CHIP " + "immigration-status tests", + "read it against a bar, five years for SNAP and Medicaid", "Washington RCA reads it as a window that closes", "wrongly exclude a recently qualified person from RCA", - "federal SNAP status test reads the status, not this clock", - "any SNAP effect is indirect", "microcosm#1093", ): assert text in clock["caveat"] diff --git a/packages/microcosm-build/tests/engine_free/us/test_us_acs_local_release_lineage_order.py b/packages/microcosm-build/tests/engine_free/us/test_us_acs_local_release_lineage_order.py new file mode 100644 index 0000000000..acbc8c87c6 --- /dev/null +++ b/packages/microcosm-build/tests/engine_free/us/test_us_acs_local_release_lineage_order.py @@ -0,0 +1,46 @@ +"""Where the release tool requires the donor's reviewed lineage (microcosm#1661). + +A national donor of another lineage than Build O needs its +``REVIEWED_DONOR_LINEAGES`` entry before calibrate starts: calibrate fixes the +commit that package accepts, and finalize writes the inherited limitations the +entry decides. Materialize writes nothing the entry decides, so it may run +while the new donor's evidence is reviewed. +""" + +from __future__ import annotations + +import importlib.util +import inspect + +from test_support.paths import paths_for + +_TEST_PATHS = paths_for("microcosm-build") + + +def _load_tool_module(): + path = _TEST_PATHS.repository / "tools" / "build_us_acs_local_release.py" + spec = importlib.util.spec_from_file_location( + "build_us_acs_local_release_lineage_order", path + ) + module = importlib.util.module_from_spec(spec) + assert spec.loader is not None + spec.loader.exec_module(module) + return module + + +_TOOL = _load_tool_module() +_CHECK = "_require_reviewed_donor_lineage(" + + +def test_materialize_does_not_require_the_donor_lineage() -> None: + assert _CHECK not in inspect.getsource(_TOOL.do_materialize) + + +def test_calibrate_requires_it_before_loading_or_solving() -> None: + source = inspect.getsource(_TOOL.do_calibrate) + assert _CHECK in source + assert source.index(_CHECK) < source.index("load_checkpoint_surface(") + + +def test_finalize_requires_it_again() -> None: + assert _CHECK in inspect.getsource(_TOOL.do_finalize) 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 6060c8881f..c689873af6 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 @@ -34,6 +34,10 @@ ) from microcosm.data import stored_inputs from microcosm.data.build_folder_manifests import publication_commands +from test_support.microcosm_build.us_acs_local_release_tool import ( + load_staging_builder_module, + load_tool_module, +) from test_support.paths import paths_for _TEST_PATHS = paths_for("microcosm-build") @@ -53,10 +57,10 @@ #: fixture below replaces them, for the tests that pin the contract itself. _REAL_REQUIRE_H5_STORED_INPUTS = stored_inputs.require_h5_stored_inputs #: A policyengine-us stand-in for the package stage's stored-input contract. -#: Until the reviewed-fill register's re-review (microcosm#1675), the lane's -#: tests model a release on the register's reviewed engine, policyengine-us -#: 2.2.1 (``_REVIEWED_ENGINE`` below), so the stand-in keeps that label. The -#: stored-input register follows the locked engine, 2.145.3, which defines +#: The package-stage tests model a release built with policyengine-us 2.2.1, +#: the label their release fixtures record too: a fixed stand-in, not the +#: register's reviewed engine (``_REVIEWED_ENGINE`` below). The stored-input +#: register follows the locked engine, 2.145.3, which defines #: tax_unit_role_input as an input (policyengine-us#9617), so the stand-in #: defines it too. _PACKAGE_ENGINE = stored_inputs.CertifiedEngine( @@ -185,30 +189,47 @@ def _writer_code(module) -> dict: _STARTED_CODE = {"sha": "a" * 9, "commit": "a" * 40, "dirty": False, "branch": "main"} -def _load_tool_module(): - root = _TEST_PATHS.repository - path = root / "tools" / "build_us_acs_local_release.py" - spec = importlib.util.spec_from_file_location( - "build_us_acs_local_release", - path, - ) - module = importlib.util.module_from_spec(spec) - assert spec.loader is not None - spec.loader.exec_module(module) - return module +# The engine-contract test of this tool loads it through the same helpers. +_load_tool_module = load_tool_module +_load_staging_builder_module = load_staging_builder_module -def _load_staging_builder_module(): - root = _TEST_PATHS.repository - path = root / "tools" / "build_us_acs_multispine_base.py" - spec = importlib.util.spec_from_file_location( - "build_us_acs_multispine_base", - path, +def _passing_esi_premium_gates(artifact_sha: str) -> dict[str, dict]: + """The finalize report's ESI premium entries (microcosm#454), green and + bound to ``artifact_sha``: what the package stage requires before it + reaches the checks the other package tests are about.""" + + return { + name: { + "passed": True, + "failures": [], + "detail": {}, + "artifact_sha256": artifact_sha, + "enforced": True, + } + for name in ("esi_premiums_signal", "esi_premiums_anchor") + } + + +def _stub_esi_premium_gates( + module, monkeypatch, *, signal: tuple = (), anchor: tuple = () +) -> None: + """Fix the lane's ESI premium verdict; its own tests cover the grading.""" + + monkeypatch.setattr( + module, + "acs_local_esi_premium_signal_gate", + lambda frame: GateResult( + name="esi_premiums_signal", passed=not signal, failures=signal + ), + ) + monkeypatch.setattr( + module, + "acs_local_esi_premium_anchor_gate", + lambda frame, *, time_period: GateResult( + name="esi_premiums_anchor", passed=not anchor, failures=anchor + ), ) - module = importlib.util.module_from_spec(spec) - assert spec.loader is not None - spec.loader.exec_module(module) - return module def test_household_chunks_refuse_population_aggregates(monkeypatch, tmp_path) -> None: @@ -646,7 +667,9 @@ def test_finalize_reviewed_limitations_carries_staging_and_dedupes() -> None: for fragment in ("PEDIS*", "SERIALNO:SPORDER", "acs_local_ssi_medicaid_take_up"): assert fragment in ssi["reason"] defaults = by_id["acs_take_up_engine_defaults"]["reason"] - assert "EITC, ACA, Early Head Start" in defaults + assert "(ACA, Early Head Start and the rest)" in defaults + assert "EITC take-up is the take-up contract's seeded draw" in defaults + assert "WIC take-up the national generator's draw" in defaults assert "Medicare take-up is native ACS HINS3" in defaults assert "Head Start take-up a keyed draw" in defaults assert "acs_local_ssi_medicaid_take_up" in defaults @@ -713,9 +736,9 @@ def test_finalize_reviewed_limitations_carries_staging_and_dedupes() -> None: register_entries = load_reviewed_fill_consumer_register()["entries"] for fragment in ( f"{len(register_entries)} entries", - "policyengine-us 2.2.1", + f"policyengine-us {_REVIEWED_ENGINE}", "spm_unit.spm_unit_energy_subsidy (liheap)", - "tax_unit.takes_up_eitc (", + "tax_unit.takes_up_aca_if_eligible (aca_ptc)", ): assert fragment in register["reason"], fragment assert "acs_local_reviewed_fill_consumers" in register["treatment"] @@ -808,6 +831,70 @@ def by_id(): assert "social_security_cps_reporters_erased_inherited" not in by_id() +def test_a_national_donor_outside_the_build_o_lineage_needs_its_review( + monkeypatch, +) -> None: + """A US national build in a build folder is not of the Build O lineage + the inherited limitations describe: staging from one is refused until a + review lists the limitations that hold for it, and only those stay + (microcosm#1661).""" + + module = _load_tool_module() + build = "populace-us-2024-20261121T010000Z-d596fcb60" + staging_summary = { + "base": { + "donor_release": { + "repo_id": "policyengine/populace-us", + "release": "microcosm-us-2024-national", + "build": build, + } + }, + "reviewed_limitations": [], + } + diagnostics = {"effective_sample_size": 1.0, "ess_fraction": 0.5} + with pytest.raises(SystemExit, match="REVIEWED_DONOR_LINEAGES"): + module._require_reviewed_donor_lineage(staging_summary) + + monkeypatch.setattr( + module, + "REVIEWED_DONOR_LINEAGES", + {build: frozenset({"miscellaneous_income_loss_side_donor_defect"})}, + ) + module._require_reviewed_donor_lineage(staging_summary) + ids = { + item["id"] + for item in module.finalize_reviewed_limitations( + staging_summary, diagnostics, {} + ) + } + assert ids & set(module.BUILD_O_LINEAGE_LIMITATIONS) == { + "miscellaneous_income_loss_side_donor_defect" + } + + +def test_a_build_o_lineage_donor_keeps_every_inherited_limitation() -> None: + module = _load_tool_module() + assert module.REVIEWED_DONOR_LINEAGES == {} + staging_summary = { + "base": { + "donor_release": { + "repo_id": "policyengine/populace-us", + "release": "microcosm-us-2024-receipt-donor", + "build": "populace-us-2024-spm-receipts-20261201", + } + }, + "reviewed_limitations": [], + } + module._require_reviewed_donor_lineage(staging_summary) + ids = { + item["id"] + for item in module.finalize_reviewed_limitations( + staging_summary, {"effective_sample_size": 1.0, "ess_fraction": 0.5}, {} + ) + } + assert set(module.BUILD_O_LINEAGE_LIMITATIONS) <= ids + + def test_the_acs_wic_assumption_is_disclosed_exactly_when_it_was_applied() -> None: """microcosm#1263: the limitation follows the consumer export's receipt.""" @@ -1877,7 +1964,8 @@ def test_disability_inputs_are_never_default_filled() -> None: module = _load_tool_module() for column in ("is_disabled", "is_blind"): assert ("person", column) in module.NEVER_DEFAULT_FILLED - # weeks_worked is held back from the export, never filled (#9660). + # weeks_worked is an input since policyengine-us#9660 and takes its + # reviewed fill in its blank cells, so it is not never-default. assert ("person", "weeks_worked") not in module.NEVER_DEFAULT_FILLED @@ -2363,6 +2451,34 @@ def test_receipt_anchor_consumers_accept_a_current_staging_run() -> None: ) +@pytest.mark.parametrize( + "summary", + [ + {}, + {"engine_versions": None}, + {"engine_versions": {"policyengine_us": None}}, + {"engine_versions": {"policyengine_us": "0.0.1"}}, + ], + ids=["no-record", "null-record", "not-installed", "another-engine"], +) +def test_materialize_refuses_a_staging_run_on_another_engine(summary) -> None: + """Staging audits the nulls of its own engine's inputs, so R2 refuses + another engine's staging before it loads the file, and a staging that + records none.""" + + module = _load_tool_module() + with pytest.raises(SystemExit, match=r"re-run staging on this engine"): + module._require_staging_engine(summary) + + +def test_materialize_accepts_a_staging_run_on_its_own_engine() -> None: + module = _load_tool_module() + installed = module._installed_engine_version() + module._require_staging_engine( + {"engine_versions": {"policyengine_us": installed, "policyengine_core": "x"}} + ) + + def test_materialize_refuses_a_pre_anchor_staging_before_hashing_it( tmp_path, monkeypatch ) -> None: @@ -2590,6 +2706,9 @@ def test_materialize_resolves_the_take_up_counts_before_hashing_the_staging_h5( { "reviewed_engine_input_nulls": [{"entity": "person"}], **_staging_receipt_anchor_summary(), + "engine_versions": { + "policyengine_us": module._installed_engine_version() + }, } ) ) @@ -3091,6 +3210,7 @@ def _package_evidence_args(module, tmp_path: Path, monkeypatch, *, hours_report) "detail": {}, "artifact_sha256": artifact_sha, }, + **_passing_esi_premium_gates(artifact_sha), } if hours_report is not None: gates["acs_local_hours_signal"] = hours_report @@ -4012,8 +4132,13 @@ def gate(frame, *, receipt): monkeypatch.setattr(module, "acs_local_receipt_anchor_signal_gate", gate) -def _patch_finalize_collaborators(module, monkeypatch, frame=None, *, identity=True): - """Stub the ladder gate and composition; ``frame=None`` loads real bytes.""" +def _patch_finalize_collaborators( + module, monkeypatch, frame=None, *, identity=True, esi_premiums=True +): + """Stub the ladder gate and composition; ``frame=None`` loads real bytes. + + ``esi_premiums=False`` leaves the real ESI premium gates in place. + """ import microcosm.build.us_runtime.puma_ladder as puma from microcosm.build.gates import GateResult @@ -4035,6 +4160,8 @@ def _patch_finalize_collaborators(module, monkeypatch, frame=None, *, identity=T _stub_local_ssi_disability_gate(module, monkeypatch) _stub_local_ssi_medicaid_take_up_gate(module, monkeypatch) _stub_local_receipt_anchor_gate(module, monkeypatch) + if esi_premiums: + _stub_esi_premium_gates(module, monkeypatch) if frame is not None: monkeypatch.setattr(module, "_load_staging_frame", lambda *a, **k: frame) if identity: @@ -4045,8 +4172,8 @@ def _patch_finalize_collaborators(module, monkeypatch, frame=None, *, identity=T ) -def _run_finalize(module, monkeypatch, args, frame=None): - _patch_finalize_collaborators(module, monkeypatch, frame) +def _run_finalize(module, monkeypatch, args, frame=None, *, esi_premiums=True): + _patch_finalize_collaborators(module, monkeypatch, frame, esi_premiums=esi_premiums) with pytest.raises(SystemExit) as exc: module.do_finalize(args) report = ( @@ -4209,6 +4336,15 @@ def _take_up_gate_frame(*, spm_columns=(), person_columns=()): **dict(person_columns), } ) + # microcosm#1675: the ACS tax units' EITC draw, inside the contract's + # band; microcosm#1154: WIC decisions on both spines, which staging draws. + tax_unit = frame.table("tax_unit").assign( + **{ + spine_column("tax_unit"): spines, + "takes_up_eitc": [True, False, True, True, True, True, True, False], + } + ) + person = person.assign(takes_up_wic_if_eligible=[False, False, False, True] * 2) household = frame.table("household").assign( **{ spine_column("household"): spines, @@ -4218,7 +4354,12 @@ def _take_up_gate_frame(*, spm_columns=(), person_columns=()): "household_vehicles_owned": [1, 2, 0, 1, 0, 0, 0, 0], } ) - replaced = {"spm_unit": spm_unit, "person": person, "household": household} + replaced = { + "spm_unit": spm_unit, + "person": person, + "household": household, + "tax_unit": tax_unit, + } return Frame( { entity: replaced.get(entity, frame.table(entity)) @@ -5360,6 +5501,8 @@ def _package_args_with_hours( fill_gate["artifact_sha256"] = "0" * 64 if gates and reviewed_fill_state != "missing": gates["acs_local_reviewed_fill_consumers"] = fill_gate + # microcosm#454: package checks the ESI premium verdict before these gates. + gates = {**_passing_esi_premium_gates(artifact_sha), **gates} args.gate_report.write_text(json.dumps({"gates": gates})) args.out_summary.write_text(json.dumps({"simulation_ready": True})) evidence = { @@ -6463,9 +6606,35 @@ def _reviewed_fill(entity, column, fill_value="0", spine="acs_2024_1yr") -> dict } +#: Reviewed fills added since release 767312d60, each with its register entry. +#: strike_benefits: the OIP predictor extension (d5aa4e25c) makes every donor +#: carry it, and nothing transfers it, so every ACS person is filled +#: (microcosm#922). +_REVIEWED_FILLS_ADDED_SINCE_767312D60 = { + ("person", "strike_benefits"), + # microcosm#1675: columns the next national donor stores that ACS rows lack + # (the four SCF student-debt inputs) or that 2.145.3 reads as an input + # (weeks_worked, blank under 16). + ("person", "federal_parent_plus_loan_balance"), + ("person", "federal_student_loan_balance"), + ("person", "federal_student_loan_graduate_share"), + ("person", "is_income_based_repayment_new_borrower"), + ("person", "weeks_worked"), +} +#: Reviewed fills of release 767312d60 whose column the reviewed engine no longer +#: defines, so their entries left the register: policyengine-us 2.145.3 removed +#: second_home_mortgage_interest (PolicyEngine/policyengine-us#9605; +#: microcosm#1675). +_REVIEWED_FILLS_RETIRED_SINCE_767312D60 = { + ("tax_unit", "second_home_mortgage_interest") +} + + def test_the_register_covers_every_remaining_reviewed_fill() -> None: """Release 767312d60 default-filled 79 columns; the stack now fills 20 of - them (NEVER_DEFAULT_FILLED), and every other one has a register entry.""" + them (NEVER_DEFAULT_FILLED), and every other one has a register entry, + except one the reviewed engine no longer defines, as does each reviewed + fill added since.""" module = _load_tool_module() document = load_reviewed_fill_consumer_register() @@ -6483,11 +6652,17 @@ def test_the_register_covers_every_remaining_reviewed_fill() -> None: assert len(released) == 79 now_filled = released & set(module.NEVER_DEFAULT_FILLED) registered = {(entry["entity"], entry["column"]) for entry in document["entries"]} - # 20 are filled natively and 59 are registered. The ACS vehicle count - # returned to a reviewed fill after the microcosm#1064 review (VEH counts - # vehicles available, not owned): it left NEVER_DEFAULT_FILLED and gained - # an entry together, so this still holds. - assert registered == released - now_filled + # 20 are filled natively, 1 is retired and 58 are registered. The ACS + # vehicle count returned to a reviewed fill after the microcosm#1064 review + # (VEH counts vehicles available, not owned): it left NEVER_DEFAULT_FILLED + # and gained an entry together, so this still holds. + assert _REVIEWED_FILLS_RETIRED_SINCE_767312D60 <= released - now_filled + assert ( + registered + == (released - now_filled - _REVIEWED_FILLS_RETIRED_SINCE_767312D60) + | _REVIEWED_FILLS_ADDED_SINCE_767312D60 + ) + assert not released & _REVIEWED_FILLS_ADDED_SINCE_767312D60 def test_do_finalize_hard_fails_on_an_unregistered_reviewed_fill( @@ -6573,7 +6748,14 @@ def test_do_finalize_grades_the_registered_fills_of_both_engine_passes( assert detail["known_bias"]["household.household_vehicles_value"]["snap"] == ( "mixed" ) - assert "person.weeks_unemployed" not in detail["known_bias"] + # policyengine-us 2.145.3 reads the weeks: they set the months of UC receipt, + # which SNAP's ABAWD time limit and, from 2027, Medicaid's SNAP pass-through + # read (microcosm#1675). + assert detail["known_bias"]["person.weeks_unemployed"] == { + "aca_ptc": "mixed", + "medicaid": "understates", + "snap": "overstates", + } entries = load_reviewed_fill_consumer_register()["entries"] assert len(detail["unused_entries"]) == len(entries) - 2 summary = json.loads(args.out_summary.read_text()) @@ -6685,7 +6867,9 @@ def test_package_regrades_the_packaged_fill_manifests(tmp_path, monkeypatch): def test_package_ships_the_register_and_records_its_digest(tmp_path, monkeypatch): module = _load_tool_module() args = _package_args_with_hours(module, tmp_path, monkeypatch, gate_state="passed") - fills = [_reviewed_fill("tax_unit", "takes_up_eitc", "True")] + # microcosm#1675: EITC take-up is drawn on ACS rows and never default-filled; + # ACA take-up still ships at the default with its reviewed known bias. + fills = [_reviewed_fill("tax_unit", "takes_up_aca_if_eligible", "True")] (args.checkpoint_dir / "consumer_reviewed_null_fills.json").write_text( json.dumps({"columns_filled": 1, "fills": fills}) ) @@ -6704,16 +6888,8 @@ def test_package_ships_the_register_and_records_its_digest(tmp_path, monkeypatch ] assert record["sha256"] == reviewed_fill_register_sha256(document) assert record["entries"] == len(document["entries"]) - assert record["reviewed_against"] == {"policyengine_us": "2.2.1"} - assert record["known_bias"]["tax_unit.takes_up_eitc"] == [ - "aca_ptc", - "chip", - "eitc", - "lifeline", - "medicaid", - "state_benefits", - "wic", - ] + assert record["reviewed_against"] == {"policyengine_us": _REVIEWED_ENGINE} + assert record["known_bias"]["tax_unit.takes_up_aca_if_eligible"] == ["aca_ptc"] gate = json.loads((release_dir / "gate_summary.json").read_text())["gates"][ "acs_local_reviewed_fill_consumers" ] @@ -6722,16 +6898,7 @@ def test_package_ships_the_register_and_records_its_digest(tmp_path, monkeypatch assert gate["artifact_sha256"] == result["root_artifact"]["sha256"] assert gate["detail"]["register_sha256"] == record["sha256"] assert gate["detail"]["known_bias"] == { - "tax_unit.takes_up_eitc": { - # microcosm#1071 review: the Medicaid changes move it both ways. - "aca_ptc": "mixed", - "chip": "mixed", - "eitc": "overstates", - "lifeline": "mixed", - "medicaid": "mixed", - "state_benefits": "mixed", - "wic": "mixed", - } + "tax_unit.takes_up_aca_if_eligible": {"aca_ptc": "overstates"} } @@ -8028,3 +8195,480 @@ def test_finalize_refuses_a_block_v1_run_whose_targets_ladder_is_not_the_staged_ for key in ("location_rule", "location_seed", "location_clones"): legacy["orchestration"].pop(key, None) module.require_block_v1_targets_ladder(legacy, "e" * 64) + + +# --- microcosm#454: the lane's own verdict on the ESI employer premium -------- + + +@pytest.fixture(scope="module") +def esi_lane_frame(): + """A staged lane frame: the real ESI transfer, pooling and anchor.""" + + from test_support.microcosm_build.us_acs_local_esi_premiums import ( + build_lane, + dense_donor, + raw_acs, + ) + + return build_lane(dense_donor(), raw_acs()).frame + + +def _with_acs_premium_scaled(frame, factor: float): + """The lane frame with every ACS row's premium multiplied by ``factor``.""" + + from microcosm.frame import Frame + + person = frame.table("person").copy() + acs = person["person_spine"].eq("acs_2024_1yr") + person.loc[acs, "employer_sponsored_insurance_premiums"] *= factor + return Frame( + { + entity: person if entity == "person" else frame.table(entity) + for entity in frame.entities + }, + frame.schema, + {"household": frame.weights_for("household")}, + frame.strata, + ) + + +def _patch_esi_finalize(module, monkeypatch, args, frame) -> None: + """Finalize's collaborators with the real ESI premium gates, ``frame`` + served only as the calibrated artifact: loading any other path fails.""" + + _patch_finalize_collaborators(module, monkeypatch, esi_premiums=False) + + def calibrated_artifact_only(path, *_args, **_kwargs): + assert Path(path) == Path(args.out_h5), ( + f"finalize loaded {path}, not the calibrated artifact {args.out_h5}" + ) + return frame + + monkeypatch.setattr(module, "_load_staging_frame", calibrated_artifact_only) + + +def _run_esi_finalize(module, monkeypatch, args, frame): + _patch_esi_finalize(module, monkeypatch, args, frame) + with pytest.raises(SystemExit) as exc: + module.do_finalize(args) + return str(exc.value), json.loads(args.gate_report.read_text()) + + +def test_finalize_grades_the_esi_premium_on_the_calibrated_artifact( + tmp_path, monkeypatch, esi_lane_frame +) -> None: + """Both gates run on the artifact and their verdict replaces the + hard-coded input-coverage pass.""" + + module = _load_tool_module() + args = _finalize_args(module, tmp_path) + artifact_sha = module._sha256(args.out_h5) + + message, report = _run_esi_finalize(module, monkeypatch, args, esi_lane_frame) + + gates = report["gates"] + for name in module.ESI_PREMIUM_GATE_NAMES: + assert gates[name]["passed"] is True, gates[name]["failures"] + assert gates[name]["failures"] == [] + assert gates[name]["artifact_sha256"] == artifact_sha + assert gates[name]["enforced"] is True + assert name not in message + signal, anchor = (gates[name]["detail"] for name in module.ESI_PREMIUM_GATE_NAMES) + assert signal["source_rows"] == 640 and signal["transferred_rows"] == 280 + assert anchor["time_period"] == module.PERIOD + assert anchor["source_household_mass_share"] == pytest.approx(0.5, rel=1e-12) + assert anchor["transferred_to_source_per_household_mass_ratio"] == pytest.approx( + 1.0, rel=1e-9 + ) + assert abs(anchor["relative_error"]) < 1e-9 + assert gates["input_coverage"]["passed"] is True + assert gates["input_coverage"]["binds"] == "donor_certified_release" + assert gates["input_coverage"]["graded_on_artifact"] == list( + module.ESI_PREMIUM_GATE_NAMES + ) + # The report is strict JSON even where a detail is not finite. + json.loads(args.gate_report.read_text(), parse_constant=pytest.fail) + + +@pytest.mark.parametrize("factor", [0.0, 1.4]) +def test_finalize_hard_fails_on_a_red_esi_premium_gate( + tmp_path, monkeypatch, esi_lane_frame, factor +) -> None: + module = _load_tool_module() + args = _finalize_args(module, tmp_path) + frame = _with_acs_premium_scaled(esi_lane_frame, factor) + + message, report = _run_esi_finalize(module, monkeypatch, args, frame) + + red = "esi_premiums_signal" if factor == 0.0 else "esi_premiums_anchor" + assert red in message + assert report["gates"][red]["passed"] is False + assert report["gates"][red]["failures"] + assert report["gates"][red]["enforced"] is True + # The input-coverage entry no longer reads green on its own authority. + assert report["gates"]["input_coverage"]["passed"] is False + + +def test_finalize_records_a_waived_esi_premium_gate_without_failing_on_it( + tmp_path, monkeypatch, esi_lane_frame +) -> None: + module = _load_tool_module() + args = _finalize_args(module, tmp_path) + args.allow_esi_premium_gaps = True + frame = _with_acs_premium_scaled(esi_lane_frame, 1.4) + + message, report = _run_esi_finalize(module, monkeypatch, args, frame) + + # Finalize still fails here on the fixture's other evidence, not on this. + assert "esi_premiums" not in message + anchor = report["gates"]["esi_premiums_anchor"] + assert anchor["passed"] is False + assert anchor["enforced"] is False + assert any( + "per unit of household mass" in failure for failure in anchor["failures"] + ) + assert report["gates"]["input_coverage"]["passed"] is False + + +@pytest.mark.parametrize("factor", [1.0, 0.0, 1.4]) +def test_the_gate_battery_grades_the_esi_premium_as_finalize_does( + esi_lane_frame, factor +) -> None: + """The us_local ESI entries bind the lane's own gates, which grade by row + kind, so the shadow's verdict (microcosm#1585 item 11) is finalize's on a + lane frame: green on the fixture and red on the same lines when the ACS + premium is zeroed or scaled. The shared ESI checks, at their default, + refuse the lane frame, so binding them would be a verdict difference on + every local build.""" + + from microcosm.build.gate_battery import EvidenceContext + from microcosm.build.us_runtime.battery_bindings import us_gate_registry + from microcosm.build.us_runtime.esi_premiums import ( + us_esi_premiums_anchor_gate, + us_esi_premiums_signal_gate, + ) + from microcosm.build.us_runtime.gate_scopes import us_scoped_gate_manifest + + module = _load_tool_module() + frame = _with_acs_premium_scaled(esi_lane_frame, factor) + binding = us_gate_registry("us_local", tool=vars(module))["stage_health"] + entries = {entry.id: entry for entry in us_scoped_gate_manifest("us_local").gates} + today = { + "us_local_esi_premiums_signal": module.acs_local_esi_premium_signal_gate(frame), + "us_local_esi_premiums_anchor": module.acs_local_esi_premium_anchor_gate( + frame, time_period=module.PERIOD + ), + } + context = EvidenceContext(frame=frame, artifacts={"time_period": module.PERIOD}) + for entry_id, legacy in today.items(): + battery = binding.evaluate(context, entries[entry_id].parameters) + assert battery.passed is legacy.passed, (entry_id, battery.failures) + assert tuple(battery.failures) == tuple(legacy.failures), entry_id + if factor != 1.0: + red = "signal" if factor == 0.0 else "anchor" + assert today[f"us_local_esi_premiums_{red}"].passed is False + else: + assert all(gate.passed for gate in today.values()) + assert not us_esi_premiums_signal_gate(frame).passed + assert not us_esi_premiums_anchor_gate(frame, time_period=module.PERIOD).passed + + +@pytest.mark.parametrize("factor", [1.0, 0.0, 1.4]) +def test_finalize_with_the_shadow_armed_records_the_esi_verdicts_it_enforces( + tmp_path, monkeypatch, esi_lane_frame, factor +) -> None: + """A real build arms the gate battery's shadow (microcosm#1585 item 11), + which the test suite turns off. Armed, finalize still enforces the ESI + verdicts, and the shadow's us_local comparison records each ESI entry as + a match: the battery, given each site's evidence, grades as finalize + does, line for line.""" + + import hashlib + + from microcosm.build.us_runtime.gate_shadow import shadow_file_paths + from test_support.microcosm_build.us_gate_shadow import arm_us_tool_gate_shadows + + arm_us_tool_gate_shadows(monkeypatch) + module = _load_tool_module() + assert module.tool_gate_shadows_enabled() + args = _finalize_args(module, tmp_path) + _patch_esi_finalize( + module, monkeypatch, args, _with_acs_premium_scaled(esi_lane_frame, factor) + ) + + with pytest.raises(SystemExit) as exc: + with module._local_gate_shadow_stage(args, "finalize"): + module.do_finalize(args) + + message = str(exc.value) + gates = json.loads(args.gate_report.read_text())["gates"] + if factor == 1.0: + # Finalize fails on the fixture's other evidence, not on the premium. + assert "esi_premiums" not in message + assert all(gates[name]["passed"] for name in module.ESI_PREMIUM_GATE_NAMES) + else: + red = "esi_premiums_signal" if factor == 0.0 else "esi_premiums_anchor" + assert red in message + assert gates[red]["passed"] is False + assert gates[red]["enforced"] is True + assert gates["input_coverage"]["passed"] is False + _, comparison_path = shadow_file_paths( + module._local_gate_shadow_directory(args), "us_local" + ) + entries = { + entry["id"]: entry + for entry in json.loads(comparison_path.read_text())["entries"] + } + for name in module.ESI_PREMIUM_GATE_NAMES: + entry = entries["us_local_" + name] + today = gates[name] + status = "passed" if today["passed"] else "failed" + assert entry["match"] is True, entry["difference"] + assert entry["legacy"]["status"] == status + assert entry["legacy"]["failures"] == today["failures"] + assert entry["battery"]["status"] == status, entry["battery"] + assert entry["battery"]["failures"] == today["failures"] + # Finalize's waiver record names the report this run wrote, so package + # attaches it only to that report. + record = json.loads( + ( + module._local_gate_shadow_directory(args) / "finalize.waivers.json" + ).read_text() + ) + assert record == { + "gate_report_sha256": hashlib.sha256(args.gate_report.read_bytes()).hexdigest(), + "waivers": {}, + } + + +def test_finalize_on_an_artifact_without_the_premium_is_red_on_both_gates( + tmp_path, monkeypatch +) -> None: + """A staging H5 from a donor that predates the stage carries no column.""" + + module = _load_tool_module() + args = _finalize_args(module, tmp_path) + + message, report = _run_esi_finalize( + module, monkeypatch, args, _plausible_hours_frame() + ) + + for name in module.ESI_PREMIUM_GATE_NAMES: + assert name in message + assert report["gates"][name]["failures"] == [ + "person column missing: employer_sponsored_insurance_premiums." + ] + + +def _rewrite_package_gates(args, edit) -> None: + report = json.loads(args.gate_report.read_text()) + edit(report["gates"]) + args.gate_report.write_text(json.dumps(report)) + + +def _sibling_refusal(name: str) -> str: + """The text every other bound finalize gate refuses with.""" + + return f"Packaging requires a present, passing {name} gate bound to the packaged H5" + + +@pytest.mark.parametrize( + ("state", "allow_gaps", "match"), + [ + # Without the waiver the gates are held as every other finalize gate is. + ("missing", False, _sibling_refusal("esi_premiums_signal")), + ("truthy", False, _sibling_refusal("esi_premiums_anchor")), + ("unbound", False, _sibling_refusal("esi_premiums_anchor")), + ("stale", False, _sibling_refusal("esi_premiums_signal")), + ("failed", False, _sibling_refusal("esi_premiums_anchor")), + # The waiver admits a red verdict, never a missing or unbound one. + ("missing", True, "carries no esi_premiums_signal verdict"), + ("truthy", True, "carries no esi_premiums_anchor verdict"), + ("unbound", True, "esi_premiums_anchor gate is missing its artifact binding"), + ("stale", True, "esi_premiums_signal gate is missing its artifact binding"), + # Nor a red verdict finalize enforced (``enforced: true``): only the + # waiver finalize itself recorded ships. + ( + "failed", + True, + "esi_premiums_anchor gate is red and finalize did not record a waiver", + ), + # Only ``enforced: false`` is that record: not an absent key, a null, + # or a zero, which a truthiness or equality test would read as false. + *( + ( + state, + True, + "esi_premiums_anchor gate is red and finalize did not record a waiver", + ) + for state in ( + "failed_enforced_absent", + "failed_enforced_null", + "failed_enforced_zero", + ) + ), + ], +) +def test_package_requires_the_esi_premium_verdict_bound_to_the_packaged_bytes( + tmp_path: Path, monkeypatch, state, allow_gaps, match +) -> None: + module = _load_tool_module() + args = _package_evidence_args( + module, + tmp_path, + monkeypatch, + hours_report={"passed": True, "failures": [], "detail": {}}, + ) + args.allow_esi_premium_gaps = allow_gaps + + def edit(gates) -> None: + if state == "missing": + # A report finalized before the gates existed. + del gates["esi_premiums_signal"], gates["esi_premiums_anchor"] + elif state == "truthy": + gates["esi_premiums_anchor"]["passed"] = "true" + elif state == "unbound": + del gates["esi_premiums_anchor"]["artifact_sha256"] + elif state == "stale": + gates["esi_premiums_signal"]["artifact_sha256"] = "0" * 64 + else: + gates["esi_premiums_anchor"].update( + passed=False, failures=["invented: off the anchor"] + ) + if state == "failed_enforced_absent": + del gates["esi_premiums_anchor"]["enforced"] + elif state == "failed_enforced_null": + gates["esi_premiums_anchor"]["enforced"] = None + elif state == "failed_enforced_zero": + gates["esi_premiums_anchor"]["enforced"] = 0 + + _rewrite_package_gates(args, edit) + + with pytest.raises(SystemExit, match=match): + module.do_package(args) + + # Refused before any release directory exists. + assert not (args.out / "releases").exists() + assert not (args.out / "package_result.json").exists() + + +def test_package_ships_a_red_esi_premium_gate_only_as_a_recorded_waiver( + tmp_path: Path, monkeypatch +) -> None: + module = _load_tool_module() + args = _package_evidence_args( + module, + tmp_path, + monkeypatch, + hours_report={"passed": True, "failures": [], "detail": {}}, + ) + _rewrite_package_gates( + args, + lambda gates: gates["esi_premiums_signal"].update( + passed=False, + failures=["person column missing: employer_sponsored_insurance_premiums."], + enforced=False, + ), + ) + with pytest.raises(SystemExit, match=_sibling_refusal("esi_premiums_signal")): + module.do_package(args) + + args.allow_esi_premium_gaps = True + result = module.do_package(args) + + shipped = json.loads( + (Path(result["release_dir"]) / "gate_summary.json").read_text() + )["gates"] + assert shipped["esi_premiums_signal"]["passed"] is False + assert shipped["esi_premiums_signal"]["enforced"] is False + assert shipped["esi_premiums_signal"]["failures"] == [ + "person column missing: employer_sponsored_insurance_premiums." + ] + assert shipped["esi_premiums_anchor"]["passed"] is True + + +def test_package_with_the_shadow_armed_matches_the_waiver_to_the_report_it_read( + tmp_path: Path, monkeypatch +) -> None: + """Package reads the gate report once, and the shadow matches finalize's + waiver record to the bytes package read. Here another finalize run's + report, whose record carries the waiver, replaces the file after package + reads it: the release ships the report package read, so the shadow + records the ESI waiver as unknown, not as taken.""" + + import hashlib + + from microcosm.build.us_runtime.gate_shadow import shadow_file_paths + from test_support.microcosm_build.us_gate_shadow import arm_us_tool_gate_shadows + + arm_us_tool_gate_shadows(monkeypatch) + module = _load_tool_module() + args = _package_evidence_args( + module, + tmp_path, + monkeypatch, + hours_report={"passed": True, "failures": [], "detail": {}}, + ) + read = args.gate_report.read_bytes() + replacement = json.dumps({**json.loads(read), "run": "replacement"}).encode() + args.allow_esi_premium_gaps = True + module._save_local_stage_waivers( + args, + "finalize", + gate_report_sha256=hashlib.sha256(replacement).hexdigest(), + ) + args.allow_esi_premium_gaps = False + verify_run_identity = module._verify_run_identity + + def replaced_after_the_read(args): + args.gate_report.write_bytes(replacement) + return verify_run_identity(args) + + monkeypatch.setattr(module, "_verify_run_identity", replaced_after_the_read) + + with module._local_gate_shadow_stage(args, "package"): + result = module.do_package(args) + + assert args.gate_report.read_bytes() == replacement + shipped = json.loads( + (Path(result["release_dir"]) / "gate_summary.json").read_text() + ) + assert "run" not in shipped + _, comparison_path = shadow_file_paths( + module._local_gate_shadow_directory(args), "us_local" + ) + mismatch = [ + "unknown: the finalize stage's waiver record belongs to gate report " + f"{hashlib.sha256(replacement).hexdigest()}, not to the selected gate " + f"report {hashlib.sha256(read).hexdigest()}" + ] + assert json.loads(comparison_path.read_text())["waivers"] == { + "us_local_esi_premiums_signal": mismatch, + "us_local_esi_premiums_anchor": mismatch, + } + + +def test_the_esi_premium_waiver_is_off_by_default(tmp_path: Path) -> None: + module = _load_tool_module() + + assert _finalize_args(module, tmp_path).allow_esi_premium_gaps is False + assert "--allow-esi-premium-gaps" not in module.LEGACY_STAGING_REFRESH_RECIPE + + +def test_the_staged_lane_frame_passes_the_null_refusal(esi_lane_frame) -> None: + """Every row of the staged lane frame carries the premium, so the + refusal ``fill_reviewed_nulls`` runs first + (``refuse_unassigned_us_esi_premiums``) passes it. This calls the refusal + alone; ``fill_reviewed_nulls`` itself needs the engine, and the + engine-contract test of this tool runs it on a lane frame.""" + + from microcosm.build.us_runtime.esi_premiums import ( + refuse_unassigned_us_esi_premiums, + ) + + person = esi_lane_frame.table("person") + assert set(person["person_spine"]) == {"asec_puf", "acs_2024_1yr"} + assert person["employer_sponsored_insurance_premiums"].notna().all() + refuse_unassigned_us_esi_premiums( + esi_lane_frame, consumer="ACS local release (fill_reviewed_nulls)" + ) diff --git a/packages/microcosm-build/tests/engine_free/us/test_us_acs_local_reviewed_fill_consumers.py b/packages/microcosm-build/tests/engine_free/us/test_us_acs_local_reviewed_fill_consumers.py index 76de792202..c058d0a8db 100644 --- a/packages/microcosm-build/tests/engine_free/us/test_us_acs_local_reviewed_fill_consumers.py +++ b/packages/microcosm-build/tests/engine_free/us/test_us_acs_local_reviewed_fill_consumers.py @@ -619,12 +619,14 @@ def test_the_committed_register_is_sound() -> None: # The release tool's test pins the columns against release 767312d60 and # NEVER_DEFAULT_FILLED (test_the_register_covers_every_remaining_reviewed_fill). assert len(columns) == len(set(columns)) - assert document["reviewed_against"] == {"policyengine_us": "2.2.1"} + assert document["reviewed_against"] == {"policyengine_us": "2.145.3"} def test_the_committed_register_carries_the_triage_verdicts_for_snap() -> None: """microcosm#1022's triage: these defaults are harmless for SNAP (SNAP is - no consumer, or its note says harmless), and the vehicle value is not.""" + no consumer, or its note says harmless), and the vehicle value is not. On + policyengine-us 2.145.3 weeks unemployed are not harmless either + (microcosm#1675).""" document = load_reviewed_fill_consumer_register() entries = {entry["column"]: entry for entry in document["entries"]} @@ -637,7 +639,6 @@ def snap_verdict(column): return "not a consumer" for column in ( - "weeks_unemployed", "spm_unit_energy_subsidy", "net_worth", "health_insurance_premiums", @@ -647,6 +648,9 @@ def snap_verdict(column): ): assert snap_verdict(column) in {"harmless", "not a consumer"}, column assert snap_verdict("household_vehicles_value") == "known_bias" + # The weeks set the months of UC receipt, which exempt a recipient from the + # ABAWD time limit only in those months (policyengine-us 2.145.3). + assert snap_verdict("weeks_unemployed") == "known_bias" # microcosm#1071 review: residents of noninstitutional group quarters who # pay for shelter lose the shelter deduction at 0 rent. assert snap_verdict("pre_subsidy_rent") == "known_bias" @@ -692,7 +696,7 @@ def test_the_committed_register_carries_the_ptc_through_illinois_hbwd() -> None: ("medicaid", "snap", "tanf"), ) text = " ".join(note["note"] for note in entry["notes"]) - for fragment in ("HBWD", "pays_aca_premium", "is_aca_ptc_eligible"): + for fragment in ("HBWD", "is_aca_marketplace_enrollee", "is_aca_ptc_eligible"): assert fragment in text, fragment diff --git a/packages/microcosm-build/tests/engine_free/us/test_us_acs_local_reviewed_fills_check.py b/packages/microcosm-build/tests/engine_free/us/test_us_acs_local_reviewed_fills_check.py new file mode 100644 index 0000000000..425393ba47 --- /dev/null +++ b/packages/microcosm-build/tests/engine_free/us/test_us_acs_local_reviewed_fills_check.py @@ -0,0 +1,265 @@ +"""The post-staging pre-check of R2's reviewed-fill rules (microcosm#922). + +``tools/check_us_acs_local_reviewed_fills.py`` grades a staging summary's +reviewed nulls with R2's own fill constants and finalize gate. These tests +use synthetic summaries and a stand-in engine, so no country engine is +imported. +""" + +from __future__ import annotations + +import importlib.util +import json +import sys +from pathlib import Path +from types import SimpleNamespace + +import pytest + +from microcosm.build.us_runtime.acs_local_reviewed_fill_consumers import ( + load_reviewed_fill_consumer_register, +) +from microcosm.build.us_runtime.esi_premiums import US_ESI_EMPLOYER_PREMIUM_COLUMN +from test_support.paths import paths_for + +_TEST_PATHS = paths_for("microcosm-build") +_ACS = "acs_2024_1yr" +#: The pre-check grades fills against the packaged register, whose gate +#: passes only on the engine it was reviewed against. +_REVIEWED = load_reviewed_fill_consumer_register()["reviewed_against"][ + "policyengine_us" +] +#: An engine the register is never reviewed against. +_OTHER_ENGINE = "2.3.0" + + +@pytest.fixture(scope="module") +def check(): + path = _TEST_PATHS.repository / "tools" / "check_us_acs_local_reviewed_fills.py" + spec = importlib.util.spec_from_file_location("check_us_acs_fills", path) + module = importlib.util.module_from_spec(spec) + assert spec.loader is not None + sys.modules[spec.name] = module + spec.loader.exec_module(module) + return module + + +@pytest.fixture(scope="module") +def release(check): + return check._release_tool() + + +def _null(column, spines, *, entity="person"): + return { + "entity": entity, + "column": column, + "dtype": "float", + "missing_rows": sum(spines.values()), + "rows": 100, + "missing_rows_by_spine": spines, + } + + +def _resolve(column): + return 0, "int" + + +def test_stage_filled_columns_are_the_never_default_columns_r2_stages_fill( + check, release +) -> None: + filled = check.stage_filled_never_default(release) + + assert filled < set(release.NEVER_DEFAULT_FILLED) + # R2's own reasons agree: a stage-filled column's reason says to run an + # R2 stage first; every other one says to re-run staging. + for key, reason in release._NEVER_DEFAULT_FILLED_REASONS.items(): + assert ("stage first" in reason) is (key in filled), key + assert ("re-run staging" in reason) is (key not in filled), key + + +def test_staged_nulls_split_as_r2_fill_step_treats_them(check, release) -> None: + stage_filled = check.stage_filled_never_default(release) + stage_entity, stage_column = sorted(stage_filled)[0] + staging_entity, staging_column = sorted( + set(release.NEVER_DEFAULT_FILLED) - stage_filled + )[0] + nulls = [ + _null("strike_benefits", {_ACS: 7}), + _null(stage_column, {_ACS: 3}, entity=stage_entity), + _null(stage_column, {"asec_puf": 2}, entity=stage_entity), + # An R2 stage never fills this column: staging must. + _null(staging_column, {_ACS: 5}, entity=staging_entity), + _null(US_ESI_EMPLOYER_PREMIUM_COLUMN, {_ACS: 4}), + ] + + split = check.expected_fills( + nulls, + never_default_filled=release.NEVER_DEFAULT_FILLED, + stage_filled=stage_filled, + resolve_default=_resolve, + ) + + assert [fill["column"] for fill in split["fills"]] == ["strike_benefits"] + assert split["fills"][0]["fill_value"] == "0" + assert split["fills"][0]["missing_rows_by_spine"] == {_ACS: 7} + assert [item["column"] for item in split["natively_filled"]] == [ + f"{stage_entity}.{stage_column}" + ] + assert [item["missing_rows_by_spine"] for item in split["natively_filled"]] == [ + {_ACS: 3} + ] + assert [ + (item["missing_rows_by_spine"], item["r2_stage_fills"]) + for item in split["denied"] + ] == [({"asec_puf": 2}, True), ({_ACS: 5}, False)] + assert [item["column"] for item in split["esi"]] == [ + f"person.{US_ESI_EMPLOYER_PREMIUM_COLUMN}" + ] + + +@pytest.mark.parametrize( + ("nulls", "version", "passed", "message"), + [ + ([_null("strike_benefits", {_ACS: 7})], _REVIEWED, True, None), + ( + [_null("not_a_registered_input", {_ACS: 7})], + _REVIEWED, + False, + "person.not_a_registered_input", + ), + ( + [_null("strike_benefits", {_ACS: 7, "asec_puf": 1})], + _REVIEWED, + False, + "person.strike_benefits", + ), + ([_null("strike_benefits", {_ACS: 7})], _OTHER_ENGINE, False, _OTHER_ENGINE), + ], +) +def test_r2_gate_grades_the_expected_fills( + check, release, nulls, version, passed, message +) -> None: + split = check.expected_fills( + nulls, + never_default_filled=release.NEVER_DEFAULT_FILLED, + stage_filled=check.stage_filled_never_default(release), + resolve_default=_resolve, + ) + + report = check.grade( + split, + manifest_names=release.REVIEWED_FILL_MANIFESTS, + never_default_filled=release.NEVER_DEFAULT_FILLED, + installed_engine_version=version, + ) + + assert report["passed"] is passed + if message is not None: + assert any(message in refusal for refusal in report["refusals"]) + + +def test_an_acs_only_null_that_staging_should_have_filled_is_refused( + check, release +) -> None: + stage_filled = check.stage_filled_never_default(release) + staging_filled = sorted(set(release.NEVER_DEFAULT_FILLED) - stage_filled) + assert staging_filled + for entity, column in staging_filled: + split = check.expected_fills( + [_null(column, {_ACS: 3}, entity=entity)], + never_default_filled=release.NEVER_DEFAULT_FILLED, + stage_filled=stage_filled, + resolve_default=_resolve, + ) + + report = check.grade( + split, + manifest_names=release.REVIEWED_FILL_MANIFESTS, + never_default_filled=release.NEVER_DEFAULT_FILLED, + installed_engine_version=_REVIEWED, + ) + + assert report["passed"] is False + assert report["natively_filled"] == [] + assert any( + refusal.startswith(f"{entity}.{column}: null on ['{_ACS}']") + and "re-run staging" in refusal + for refusal in report["refusals"] + ), (entity, column) + + +def test_command_exits_2_on_an_unregistered_fill( + check, tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + variables = { + "strike_benefits": SimpleNamespace(default_value=0), + "not_a_registered_input": SimpleNamespace(default_value=0.0), + } + monkeypatch.setattr( + check, "_tax_benefit_system", lambda: SimpleNamespace(variables=variables) + ) + monkeypatch.setattr(check, "_engine_version", lambda _release: _REVIEWED) + summary = tmp_path / "staging.summary.json" + out = tmp_path / "report.json" + engine = {"policyengine_us": _REVIEWED, "policyengine_core": "3.32.5"} + summary.write_text( + json.dumps( + { + "engine_versions": engine, + "reviewed_engine_input_nulls": [_null("strike_benefits", {_ACS: 7})], + } + ) + ) + + assert check.main(["--staging-summary", str(summary), "--out", str(out)]) == 0 + assert json.loads(out.read_text())["expected_fills"] == 1 + + summary.write_text( + json.dumps( + { + "engine_versions": engine, + "reviewed_engine_input_nulls": [ + _null("strike_benefits", {_ACS: 7}), + _null("not_a_registered_input", {_ACS: 2}), + ], + } + ) + ) + assert check.main(["--staging-summary", str(summary), "--out", str(out)]) == 2 + refusals = json.loads(out.read_text())["refusals"] + assert any("not_a_registered_input" in refusal for refusal in refusals) + + +@pytest.mark.parametrize( + "engine", + [None, {"policyengine_us": _OTHER_ENGINE, "policyengine_core": "3.36.1"}], + ids=["no-record", "another-engine"], +) +def test_command_exits_2_on_a_staging_run_on_another_engine( + check, tmp_path: Path, monkeypatch: pytest.MonkeyPatch, engine +) -> None: + """Materialize refuses a staging run whose engine is not the installed + one before it loads the file, so the pre-check does too.""" + + monkeypatch.setattr( + check, + "_tax_benefit_system", + lambda: SimpleNamespace( + variables={"strike_benefits": SimpleNamespace(default_value=0)} + ), + ) + monkeypatch.setattr(check, "_engine_version", lambda _release: _REVIEWED) + summary = tmp_path / "staging.summary.json" + out = tmp_path / "report.json" + payload = {"reviewed_engine_input_nulls": [_null("strike_benefits", {_ACS: 7})]} + if engine is not None: + payload["engine_versions"] = engine + summary.write_text(json.dumps(payload)) + + assert check.main(["--staging-summary", str(summary), "--out", str(out)]) == 2 + report = json.loads(out.read_text()) + assert report["staging_engine_versions"] == engine + assert any( + refusal.startswith("staging:") and "re-run staging on this engine" in refusal + for refusal in report["refusals"] + ) diff --git a/packages/microcosm-build/tests/engine_free/us/test_us_acs_local_take_up.py b/packages/microcosm-build/tests/engine_free/us/test_us_acs_local_take_up.py index aa93bccff6..f222c6863a 100644 --- a/packages/microcosm-build/tests/engine_free/us/test_us_acs_local_take_up.py +++ b/packages/microcosm-build/tests/engine_free/us/test_us_acs_local_take_up.py @@ -1,7 +1,8 @@ """ACS-row SNAP/TANF take-up (microcosm#1019), the engine-free discretionary-exemption, housing-receipt, Medicare and Head Start fills -(microcosm#1022) and the ACS VEH vehicle-availability receipt (the #1064 -review) for the retained ACS local lane.""" +(microcosm#1022), the ACS VEH vehicle-availability receipt (the #1064 +review), EITC take-up (microcosm#1675) and the WIC take-up check +(microcosm#1154) for the retained ACS local lane.""" from __future__ import annotations @@ -11,6 +12,7 @@ from microcosm.build.us_runtime.acs_local_take_up import ( ACS_LOCAL_TAKE_UP_GATE_NAME, + US_EITC_TAKE_UP_OUTPUT_COLUMN, US_TANF_TAKE_UP_OUTPUT_COLUMN, acs_local_take_up_signal_gate, with_acs_local_take_up_inputs, @@ -26,13 +28,16 @@ US_SNAP_TAKE_UP_OUTPUT_COLUMN, us_snap_take_up_stage_spec, ) -from microcosm.build.us_runtime.take_up import _seed_program +from microcosm.build.us_runtime.take_up import US_TAKE_UP_SHARE_BAND, _seed_program from microcosm.build.us_runtime.take_up_contract import seeded_take_up_programs from microcosm.frame import US_SCHEMA, Frame, WeightKind, Weights SNAP = US_SNAP_TAKE_UP_OUTPUT_COLUMN TANF = US_TANF_TAKE_UP_OUTPUT_COLUMN +EITC = US_EITC_TAKE_UP_OUTPUT_COLUMN +WIC = "takes_up_wic_if_eligible" TAG = spine_column("spm_unit") +TAX_TAG = spine_column("tax_unit") PERSON_TAG = spine_column("person") DISCRETIONARY = "is_snap_abawd_discretionary_exempt" HOUSING = "receives_housing_assistance" @@ -65,7 +70,9 @@ def _frame( quarters), ACS persons ``SPORDER`` 1 and a native ``HINS3``; the housing take-up flag is transferred on both spines. Donor households carry a vehicle count, and donor positions 100-129 are children aged 3-5, a few - of them taking up Head Start. + of them taking up Head Start. Tax units carry donor EITC flags and NaN on + ACS rows; persons carry WIC decisions on both spines, since staging + draws the ACS rows' (microcosm#1154). """ n = n_asec + n_acs @@ -115,6 +122,12 @@ def _frame( asec, np.nan ) person[PERSON_TAG] = spm_unit[TAG].to_numpy() + tax_unit = tables["tax_unit"] + tax_unit[TAX_TAG] = spm_unit[TAG].to_numpy() + tax_unit[EITC] = pd.Series( + np.where(position < int(0.7 * n_asec), True, False), dtype=object + ).where(asec, np.nan) + person[WIC] = position % 30 == 0 age = rng.integers(0, 91, n).astype(float) children = asec & (position >= 100) & (position < 130) age[children] = np.resize([3.0, 4.0, 5.0], int(children.sum())) @@ -290,7 +303,7 @@ def test_a_filled_frame_passes_through_unchanged() -> None: assert again_receipt["assigned_sha256"] == receipt["assigned_sha256"] -@pytest.mark.parametrize("column", [SNAP, TANF, "receives_snap", TAG]) +@pytest.mark.parametrize("column", [SNAP, TANF, "receives_snap", TAG, EITC, TAX_TAG]) def test_missing_inputs_are_refused(column: str) -> None: with pytest.raises(ValueError, match="ACS local take-up requires"): with_acs_local_take_up_inputs(_frame(drop=(column,)), seed=0) @@ -304,7 +317,6 @@ def test_gate_passes_on_the_seeded_surface_and_ignores_other_flags() -> None: frame = _filled() # Other take-up flags remain engine defaults on ACS rows (microcosm#1022). tables = {entity: frame.table(entity) for entity in frame.entities} - tables["tax_unit"] = tables["tax_unit"].assign(takes_up_eitc=True) tables["person"] = tables["person"].assign(takes_up_ssi_if_eligible=True) frame = Frame(tables, frame.schema, {"household": frame.weights_for("household")}) gate = acs_local_take_up_signal_gate(frame) @@ -320,7 +332,11 @@ def test_gate_passes_on_the_seeded_surface_and_ignores_other_flags() -> None: MEDICARE, VEHICLES, HEAD_START, + EITC, + WIC, } + assert acs[EITC]["entity"] == "tax_unit" + assert acs[WIC]["entity"] == "person" assert acs[VEHICLES]["not_default_rows"] == 0 assert acs[VEHICLES]["vehicles_available"]["housing_units_without_veh"] == 0 assert acs[HEAD_START]["take_up_outside_ages"] == 0 @@ -1033,3 +1049,144 @@ def test_gate_reports_but_does_not_grade_donor_vehicles_or_head_start() -> None: assert donor_columns[HEAD_START]["take_up_outside_ages"] == 1 assert "vehicles_available" not in donor_columns[VEHICLES] assert "not_default_rows" not in donor_columns[VEHICLES] + + +# --------------------------------------------------------------------------- +# EITC take-up (microcosm#1675) and the WIC take-up check (microcosm#1154) +# --------------------------------------------------------------------------- + + +def _acs_tax_units(frame: Frame) -> np.ndarray: + return frame.table("tax_unit")[TAX_TAG].eq(ACS_2024_1YR_SPINE).to_numpy(dtype=bool) + + +def _eitc_program(): + return next(p for p in seeded_take_up_programs() if p.variable == EITC) + + +def test_eitc_take_up_is_the_contracts_draw_on_acs_tax_units() -> None: + frame = _frame() + result, receipt = with_acs_local_take_up_inputs(frame, seed=3) + seeded, _ = _seed_program(frame, _eitc_program(), seed=3) + acs = _acs_tax_units(frame) + tax_unit = result.table("tax_unit") + np.testing.assert_array_equal( + tax_unit.loc[acs, EITC].to_numpy(dtype=bool), + np.asarray(seeded[EITC], dtype=bool)[acs], + ) + assert ( + tax_unit.loc[~acs, EITC].tolist() + == frame.table("tax_unit").loc[~acs, EITC].tolist() + ) + entry = receipt["programs"][EITC] + assert entry["entity"] == "tax_unit" + assert entry["filled_rows"] == int(acs.sum()) + assert entry["preserved_rows"] == 0 + assert ( + entry["rates_by_num_children"] + == (_eitc_program().rate["values_by_num_children"]) + ) + low, high = US_TAKE_UP_SHARE_BAND[EITC] + assert low <= entry["weighted_take_up_share"] <= high + assert set(entry["by_num_children"]) == {"0", "1", "2", "3+"} + assert receipt["acs_tax_units"] == int(acs.sum()) + + +def test_a_stored_acs_eitc_cell_is_kept_and_enters_the_digest() -> None: + frame = _frame() + plain, plain_receipt = with_acs_local_take_up_inputs(frame, seed=3) + acs = _acs_tax_units(frame) + first = int(np.flatnonzero(acs)[0]) + drawn = bool(plain.table("tax_unit")[EITC].iloc[first]) + tax_unit = frame.table("tax_unit").copy() + tax_unit[EITC] = tax_unit[EITC].astype(object) + tax_unit.loc[tax_unit.index[first], EITC] = not drawn + stored = Frame( + { + entity: tax_unit if entity == "tax_unit" else frame.table(entity) + for entity in frame.entities + }, + frame.schema, + {"household": frame.weights_for("household")}, + ) + result, receipt = with_acs_local_take_up_inputs(stored, seed=3) + assert bool(result.table("tax_unit")[EITC].iloc[first]) is (not drawn) + assert receipt["programs"][EITC]["preserved_rows"] == 1 + assert receipt["programs"][EITC]["filled_rows"] == int(acs.sum()) - 1 + assert receipt["assigned_sha256"] != plain_receipt["assigned_sha256"] + + +@pytest.mark.parametrize("change", ["drop", "missing", "object"]) +def test_the_stage_refuses_an_incomplete_wic_column(change: str) -> None: + frame = _frame() + person = frame.table("person").copy() + if change == "drop": + person = person.drop(columns=WIC) + elif change == "missing": + person[WIC] = person[WIC].astype(object) + person.loc[person.index[-1], WIC] = np.nan + else: + person[WIC] = person[WIC].astype(object) + incomplete = Frame( + { + entity: person if entity == "person" else frame.table(entity) + for entity in frame.entities + }, + frame.schema, + {"household": frame.weights_for("household")}, + ) + with pytest.raises(ValueError, match="WIC take-up"): + with_acs_local_take_up_inputs(incomplete, seed=0) + + +def _with_entity(frame: Frame, entity: str, table: pd.DataFrame) -> Frame: + return Frame( + { + name: table if name == entity else frame.table(name) + for name in frame.entities + }, + frame.schema, + {"household": frame.weights_for("household")}, + ) + + +def test_gate_fails_on_universal_eitc_take_up_on_acs_rows() -> None: + frame = _filled() + acs = _acs_tax_units(frame) + tax_unit = frame.table("tax_unit").copy() + tax_unit[EITC] = tax_unit[EITC].where(~acs, True) + failures = _gate_failures(_with_entity(frame, "tax_unit", tax_unit)) + assert f"{ACS_2024_1YR_SPINE}: {EITC} is constant" in failures + assert "outside plausibility band" in failures + + +def test_gate_fails_on_a_missing_eitc_cell() -> None: + frame = _filled() + tax_unit = frame.table("tax_unit").copy() + tax_unit[EITC] = tax_unit[EITC].astype(object) + tax_unit.loc[tax_unit.index[-1], EITC] = np.nan + failures = _gate_failures(_with_entity(frame, "tax_unit", tax_unit)) + assert f"{ACS_2024_1YR_SPINE}: {EITC} has missing rows" in failures + assert "every eligible tax unit claims the EITC" in failures + + +@pytest.mark.parametrize("spine", [ASEC_PUF_DONOR_SPINE, ACS_2024_1YR_SPINE]) +def test_gate_fails_on_missing_or_constant_wic_take_up(spine: str) -> None: + frame = _filled() + person = frame.table("person").copy() + rows = person[PERSON_TAG].eq(spine).to_numpy(dtype=bool) + constant = person.assign(**{WIC: person[WIC].where(~rows, True)}) + failures = _gate_failures(_with_entity(frame, "person", constant)) + assert f"{spine}: {WIC} is constant" in failures + missing = person.copy() + missing[WIC] = missing[WIC].astype(object) + missing.loc[missing.index[np.flatnonzero(rows)[0]], WIC] = np.nan + failures = _gate_failures(_with_entity(frame, "person", missing)) + assert f"{spine}: {WIC} has missing rows" in failures + + +def test_gate_requires_tax_unit_origin_tags() -> None: + frame = _filled() + tax_unit = frame.table("tax_unit").drop(columns=TAX_TAG) + failures = _gate_failures(_with_entity(frame, "tax_unit", tax_unit)) + assert f"Missing tax-unit origin tags: {TAX_TAG}." in failures diff --git a/packages/microcosm-build/tests/engine_free/us/test_us_acs_local_wic_take_up.py b/packages/microcosm-build/tests/engine_free/us/test_us_acs_local_wic_take_up.py new file mode 100644 index 0000000000..16cfaac922 --- /dev/null +++ b/packages/microcosm-build/tests/engine_free/us/test_us_acs_local_wic_take_up.py @@ -0,0 +1,118 @@ +"""ACS local WIC take-up (microcosm#1154, the design of microcosm#1156).""" + +from __future__ import annotations + +import numpy as np +import pandas as pd +import pytest + +from microcosm.build.us_runtime.acs_local_wic_take_up import ( + ACS_LOCAL_WIC_TAKE_UP_ISSUE, + US_WIC_TAKE_UP_COLUMN, + require_complete_us_wic_take_up, + with_acs_local_wic_take_up, +) +from microcosm.build.us_runtime.wic_claim import ( + WIC_CLAIM_FNS_SOURCE_URL, + with_us_wic_claim_input, +) +from test_support.microcosm_build.us_wic_claim import ( + _frame, + _plausible_rows, + _replace_person, +) + +WIC = US_WIC_TAKE_UP_COLUMN + + +def _acs_frame(): + return _frame(_plausible_rows()) + + +def test_the_acs_rows_draw_with_the_national_generator() -> None: + frame = _acs_frame() + drawn, receipt = with_acs_local_wic_take_up(frame, seed=7, time_period=2024) + expected = with_us_wic_claim_input(frame, seed=7, time_period=2024) + person = drawn.table("person") + assert person[WIC].dtype == bool + pd.testing.assert_series_equal(person[WIC], expected.table("person")[WIC]) + assert receipt["issue"] == ACS_LOCAL_WIC_TAKE_UP_ISSUE + assert receipt["design"] == "microcosm#1156" + assert (receipt["seed"], receipt["source_year"]) == (7, 2024) + assert receipt["person_rows"] == len(person) + assert receipt["output_columns"] == [WIC] + assert receipt["category_rates_source"] == WIC_CLAIM_FNS_SOURCE_URL + assert set(receipt["category_weighted_take_up_shares"]) == set( + receipt["category_counts"] + ) + again, _ = with_acs_local_wic_take_up(frame, seed=7, time_period=2024) + pd.testing.assert_series_equal(again.table("person")[WIC], person[WIC]) + + +def test_an_all_null_column_from_the_pooled_schema_is_drawn() -> None: + frame = _acs_frame() + nulls = _replace_person(frame, frame.table("person").assign(**{WIC: np.nan})) + drawn, _ = with_acs_local_wic_take_up(nulls, seed=0, time_period=2024) + require_complete_us_wic_take_up(drawn.table("person"), what="test") + + +def test_existing_decisions_are_never_redrawn() -> None: + frame = _acs_frame() + stored = _replace_person(frame, frame.table("person").assign(**{WIC: True})) + with pytest.raises(ValueError, match="already carries"): + with_acs_local_wic_take_up(stored, seed=0, time_period=2024) + + +@pytest.mark.parametrize( + "column", ["source_year", "source_household_id", "source_person_id"] +) +def test_the_draw_needs_the_loaders_source_identity(column: str) -> None: + frame = _acs_frame() + person = frame.table("person").drop(columns=column) + with pytest.raises(ValueError, match="source identity"): + with_acs_local_wic_take_up( + _replace_person(frame, person), seed=0, time_period=2024 + ) + + +def test_a_partial_source_identity_is_refused() -> None: + frame = _acs_frame() + person = frame.table("person").copy() + person["source_person_id"] = person["source_person_id"].astype(float) + person.loc[person.index[0], "source_person_id"] = np.nan + with pytest.raises(ValueError, match="complete source identity"): + with_acs_local_wic_take_up( + _replace_person(frame, person), seed=0, time_period=2024 + ) + + +def test_donor_rows_are_refused() -> None: + frame = _acs_frame() + person = frame.table("person").copy() + person.loc[person.index[0], "source_year"] = 2023 + with pytest.raises(ValueError, match="ACS rows only"): + with_acs_local_wic_take_up( + _replace_person(frame, person), seed=0, time_period=2024 + ) + + +@pytest.mark.parametrize( + ("values", "match"), + [ + (None, "requires person column"), + ([True, np.nan], "missing on 1 of 2 person rows"), + (pd.Series([True, False], dtype=object), "must be boolean"), + ], +) +def test_an_incomplete_column_is_refused(values, match: str) -> None: + person = pd.DataFrame({"person_id": [1, 2]}) + if values is not None: + person[WIC] = values + with pytest.raises(ValueError, match=match): + require_complete_us_wic_take_up(person, what="test") + + +def test_a_complete_boolean_column_passes() -> None: + require_complete_us_wic_take_up( + pd.DataFrame({"person_id": [1, 2], WIC: [True, False]}), what="test" + ) diff --git a/packages/microcosm-build/tests/engine_free/us/test_us_acs_local_work_disability.py b/packages/microcosm-build/tests/engine_free/us/test_us_acs_local_work_disability.py index 659b1d1d95..c6216e27ad 100644 --- a/packages/microcosm-build/tests/engine_free/us/test_us_acs_local_work_disability.py +++ b/packages/microcosm-build/tests/engine_free/us/test_us_acs_local_work_disability.py @@ -15,7 +15,7 @@ ACS_DISABILITY_ITEMS, ACS_LOCAL_WORK_DISABILITY_GATE_NAME, ACS_NATIVE_PROVENANCE, - WEEKS_WORKED_EXPORT_BLOCKER, + WEEKS_WORKED_INPUT_CHANGE, acs_local_work_disability_signal_gate, map_acs_local_work_disability_inputs, record_acs_local_work_disability_transfer, @@ -341,8 +341,9 @@ def test_weeks_worked_follows_the_hours_universe_and_is_staging_only() -> None: assert receipt["source_universe_unavailable_rows"] == 2 assert receipt["source_unresolved_rows"] == 0 assert receipt["hours_paired_rows"] == 3 - assert receipt["exported"] is False - assert receipt["export_blocker"] == WEEKS_WORKED_EXPORT_BLOCKER + assert receipt["exported"] is True + assert receipt["input_since"] == WEEKS_WORKED_INPUT_CHANGE + assert "2.145.3" in receipt["export_note"] assert result.native_inputs["weeks_worked"]["missing_rows"] == 2 @@ -536,7 +537,7 @@ def test_gate_requires_native_paired_weeks_at_staging_only(staged) -> None: ) assert finalize.passed, finalize.failures assert finalize.details["weeks_worked"]["evaluated"] is False - assert WEEKS_WORKED_EXPORT_BLOCKER in finalize.details["weeks_worked"]["reason"] + assert WEEKS_WORKED_INPUT_CHANGE in finalize.details["weeks_worked"]["reason"] changed = list(_EXPECTED_WEEKS) changed[1] = 30.0 diff --git a/packages/microcosm-build/tests/engine_free/us/test_us_acs_multispine.py b/packages/microcosm-build/tests/engine_free/us/test_us_acs_multispine.py index caeb1c53d6..073340caad 100644 --- a/packages/microcosm-build/tests/engine_free/us/test_us_acs_multispine.py +++ b/packages/microcosm-build/tests/engine_free/us/test_us_acs_multispine.py @@ -825,3 +825,118 @@ def _raw_acs_frame() -> Frame: {"household": Weights(np.asarray([50.0]), WeightKind.DESIGN)}, pd.Series("acs_2024_1yr", index=person.index, dtype=object), ) + + +def test__given_wic_take_up__then_acs_decisions_are_drawn_before_pooling( + monkeypatch, + tmp_path, +) -> None: + """microcosm#1154 (the design of microcosm#1156): the donor's decisions are + checked before the ACS spine is loaded, the ACS rows' are drawn on the + ACS-only frame after the shared transfer, and the pooled frame is checked + after assembly.""" + + events: list[tuple[Any, ...]] = [] + raw_acs = object() + mapped_acs = object() + transferred_acs = SimpleNamespace(table=lambda entity: pd.DataFrame()) + drawn_acs = object() + pooled = SimpleNamespace(table=lambda entity: pd.DataFrame()) + base = SimpleNamespace(table=lambda entity: pd.DataFrame()) + receipt = {"issue": "microcosm#1154", "weighted_take_up_share": np.float64(0.03)} + source = AcsPumsSource(tmp_path / "csv_hus.zip", tmp_path / "csv_pus.zip") + + def fake_load(source, *, chunksize): + events.append(("load",)) + return raw_acs, {"spine": "acs_2024_1yr"} + + def fake_require(person, *, what): + events.append(("require", what)) + + def fake_map(frame): + events.append(("map", frame)) + return SimpleNamespace(frame=mapped_acs, native_inputs={}) + + def fake_transfer(recipient, donor, **kwargs): + events.append(("transfer", recipient)) + return SimpleNamespace( + frame=transferred_acs, + imputed_inputs=(), + fit_records=(), + deferred_inputs=(), + resolved_donor_channel="puf_support", + ) + + def fake_draw(frame, *, seed, time_period): + events.append(("wic", frame, seed, time_period)) + return drawn_acs, receipt + + def fake_pool(actual_base, actual_acs, **kwargs): + events.append(("pool", actual_base, actual_acs)) + return pooled + + monkeypatch.setattr(acs_multispine, "build_acs_pums_unit_frame", fake_load) + monkeypatch.setattr(acs_multispine, "require_complete_us_wic_take_up", fake_require) + monkeypatch.setattr(acs_multispine, "map_acs_native_inputs", fake_map) + monkeypatch.setattr(acs_multispine, "transfer_acs_inputs", fake_transfer) + monkeypatch.setattr(acs_multispine, "with_acs_local_wic_take_up", fake_draw) + monkeypatch.setattr(acs_multispine, "with_optional_acs_spine", fake_pool) + + result = acs_multispine.build_optional_acs_multispine( + cast(Frame, base), source, wic_take_up=True, seed=5 + ) + + assert events == [ + ("require", "ACS pool donor"), + ("load",), + ("map", raw_acs), + ("transfer", mapped_acs), + ("wic", transferred_acs, 5, source.vintage), + ("pool", base, drawn_acs), + ("require", "ACS pool"), + ] + assert result.provenance["wic_take_up"] == { + "issue": "microcosm#1154", + "weighted_take_up_share": 0.03, + } + json.dumps(result.provenance, allow_nan=False) + + +def test__given_no_wic_take_up__then_no_wic_step_runs(monkeypatch, tmp_path) -> None: + """The flag is the ACS local lane's; without it the pool builder is unchanged.""" + + monkeypatch.setattr( + acs_multispine, + "build_acs_pums_unit_frame", + lambda source, *, chunksize: (object(), {"spine": "acs_2024_1yr"}), + ) + monkeypatch.setattr( + acs_multispine, "require_complete_us_wic_take_up", _must_not_run + ) + monkeypatch.setattr(acs_multispine, "with_acs_local_wic_take_up", _must_not_run) + monkeypatch.setattr( + acs_multispine, + "map_acs_native_inputs", + lambda frame: SimpleNamespace(frame=object(), native_inputs={}), + ) + monkeypatch.setattr( + acs_multispine, + "transfer_acs_inputs", + lambda recipient, donor, **kwargs: SimpleNamespace( + frame=SimpleNamespace(table=lambda entity: pd.DataFrame()), + imputed_inputs=(), + fit_records=(), + deferred_inputs=(), + resolved_donor_channel="puf_support", + ), + ) + monkeypatch.setattr( + acs_multispine, "with_optional_acs_spine", lambda *args, **kwargs: object() + ) + + result = acs_multispine.build_optional_acs_multispine( + cast(Frame, SimpleNamespace(table=lambda entity: pd.DataFrame())), + AcsPumsSource(tmp_path / "csv_hus.zip", tmp_path / "csv_pus.zip"), + ) + + assert "wic_take_up" not in result.provenance diff --git a/packages/microcosm-build/tests/engine_free/us/test_us_acs_multispine_legacy_builder.py b/packages/microcosm-build/tests/engine_free/us/test_us_acs_multispine_legacy_builder.py index 2cab37a3ca..c479b42107 100644 --- a/packages/microcosm-build/tests/engine_free/us/test_us_acs_multispine_legacy_builder.py +++ b/packages/microcosm-build/tests/engine_free/us/test_us_acs_multispine_legacy_builder.py @@ -18,7 +18,17 @@ from microcosm.build.us_runtime.base_pool import spine_column from microcosm.build.us_runtime.puf_support import support_channel_column from microcosm.build.us_runtime.spm_role_source import NATIVE_SPM_ROLE -from microcosm.data.build_folder_manifests import ReferencedBuild, referenced_build +from microcosm.data.build_folder_manifests import ( + ReferencedBuild, + referenced_build, + rewrite_release_dir, +) +from microcosm.data.contract import ( + US_EVIDENCE_RELEASE_ID, + US_NATIONAL_RELEASE_ID, + US_RELEASE_DATASET_FILES, + _check_local_area_donor_reference, +) from microcosm.frame import US_SCHEMA, Frame, WeightKind, Weights from test_support.paths import paths_for @@ -156,6 +166,15 @@ def test_parser_exposes_production_defaults_and_transfer_controls() -> None: assert args.donor_channel == builder.ACS_DONOR_CHANNEL_AUTO # microcosm#1022: the SIPP donor resolves through the canonical cache. assert args.sipp_donor is None + # microcosm#454: a release build qualifies the ESI premium donor and + # enforces both ESI gates; only a diagnostic build waives them. + assert args.allow_esi_premium_gaps is False + assert ( + builder._parse_args( + ["--base-h5", "d.h5", "--out-h5", "c.h5", "--allow-esi-premium-gaps"] + ).allow_esi_premium_gaps + is True + ) custom = builder._parse_args( [ @@ -195,13 +214,28 @@ def test_parser_exposes_production_defaults_and_transfer_controls() -> None: assert local.sipp_donor == Path("pu2023.csv") -@pytest.mark.parametrize("staging_hours_pass", [True, False]) +@pytest.mark.parametrize( + ("staging_hours_pass", "esi_premiums"), + [(True, "green"), (False, "green"), (True, "red"), (True, "waived")], + ids=["green", "hours_red", "esi_red", "esi_waived"], +) def test_main_wires_verified_sources_transfer_audit_export_and_summary( monkeypatch: pytest.MonkeyPatch, tmp_path: Path, staging_hours_pass: bool, + esi_premiums: str, ) -> None: + """``esi_premiums``: ``"red"`` has a red ESI anchor gate stop the build + before the H5 is written; ``"waived"`` is a diagnostic build + (``--allow-esi-premium-gaps``) whose donor the ESI qualifier refuses, so + the lane neither transfers nor owes the premium (microcosm#454).""" + builder = _load_builder_module() + waived = esi_premiums == "waived" + waived_refusal = ( + "Local ESI premium donor was built without the meps_esi_premiums stage " + "(invented)." + ) manifest = _manifest() base = _frame() combined = _frame(spines=("asec_puf", "acs_2024_1yr")) @@ -225,6 +259,13 @@ def test_main_wires_verified_sources_transfer_audit_export_and_summary( combined.table("person")["passive_partnership_s_corp_income"] = [0.0, 0.0] combined.table("person")["person_tax_unit_id"] = [1, 2] combined.table("person")["tax_unit_role_input"] = ["HEAD", "HEAD"] + # microcosm#454: the lane transferred the ESI employer premium onto the + # ACS row, so the coverage check finds it complete there. A waived build + # transferred nothing, so its ACS row carries no premium. + combined.table("person")["employer_sponsored_insurance_premiums"] = [ + 9_000.0, + np.nan if waived else 0.0, + ] # What the ACS local immigration stage returns (microcosm#1020): the # null audit, hours gate and export must all see this frame, not the # unlabelled pool. @@ -353,7 +394,20 @@ def fake_build(actual_base, actual_source, **kwargs): "column": "takes_up_snap_if_eligible", "family": "benefit_participation", "unmodeled_recipient_rows": 0, - } + }, + # The lane owes the ACS spine the employer premium too, + # unless a diagnostic build waived its donor. + *( + [] + if waived + else [ + { + "column": "employer_sponsored_insurance_premiums", + "family": "source_operator_esi_premiums", + "unmodeled_recipient_rows": 0, + } + ] + ), ], "acs_local_work_disability": work_disability_receipt, "acs_local_income_transfer": income_receipt, @@ -364,6 +418,7 @@ def fake_build(actual_base, actual_source, **kwargs): def fake_write(frame, path, *, period): captured["write"] = (frame, path, period) + order.append("write") path.write_bytes(b"combined-output") def fake_load_puma_ladder(path): @@ -470,6 +525,16 @@ def staging_hours_gate(frame, *, source_null_audit): } monkeypatch.setattr(builder, "_load_base_frame", lambda path: base) + # A block_v1 donor under the legacy rule: the summary records the rule its + # base recorded, and the engine the staging ran on. + base_location = { + "location_rule": "block_v1", + "recorded": True, + "attributes": {"populace_location_rule": "block_v1"}, + } + monkeypatch.setattr(builder, "_base_location_rule", lambda path: base_location) + engine_versions = {"policyengine_us": "9.9.9", "policyengine_core": "8.8.8"} + monkeypatch.setattr(builder, "_engine_versions", lambda: engine_versions) monkeypatch.setattr( builder, "prepare_acs_local_hours_donor", @@ -554,6 +619,52 @@ def staging_hours_gate(frame, *, source_null_audit): ) monkeypatch.setattr(builder, "acs_local_ssi_disability_signal_gate", fake_ssi_gate) + # microcosm#454: the ESI employer premium's donor qualifier and gates. + def qualify_esi_premium_donor(frame): + captured.setdefault("esi_premium_donors", []).append(frame) + order.append("esi_premium_donor") + if waived: + raise ValueError(waived_refusal) + return frame, {"donor_channel": "asec"} + + signal_failures = ("invented: no ACS row carries the premium",) if waived else () + anchor_failures = ( + () if esi_premiums == "green" else ("invented: +20.0% from the anchor",) + ) + + def staging_esi_premium_gates(frame, *, time_period): + captured["staging_esi_premium_gates"] = (frame, time_period) + order.append("esi_premium_gates") + return ( + GateResult( + name="esi_premiums_signal", + passed=not signal_failures, + failures=signal_failures, + ), + GateResult( + name="esi_premiums_anchor", + passed=not anchor_failures, + failures=anchor_failures, + details={"relative_error": 0.0, "cross_check_ratio": float("nan")}, + ), + ) + + real_coverage = builder._require_default_transfer_coverage + + def recorded_coverage(result, donor, *, target_families=None): + captured["coverage_plan"] = target_families + return real_coverage(result, donor, target_families=target_families) + + monkeypatch.setattr( + builder, "prepare_acs_local_esi_premium_donor", qualify_esi_premium_donor + ) + monkeypatch.setattr( + builder, "acs_local_esi_premium_gates", staging_esi_premium_gates + ) + monkeypatch.setattr( + builder, "_require_default_transfer_coverage", recorded_coverage + ) + arguments = [ "--base-h5", str(base_h5), @@ -578,12 +689,34 @@ def staging_hours_gate(frame, *, source_null_audit): "--geography-seed", "19", ] + if waived: + arguments.append("--allow-esi-premium-gaps") if not staging_hours_pass: with pytest.raises( SystemExit, match="Local staging hours gate failed.*asec_puf" ): builder.main(arguments) assert captured["staging_hours_gate"] is True + # The ESI gates grade the frame after the hours gate passes. + assert "staging_esi_premium_gates" not in captured + assert "write" not in captured + assert not output_h5.exists() + assert not summary_path.exists() + return + if esi_premiums == "red": + # microcosm#454: a red ESI gate stops the build before the staging H5 + # (or its summary) is written. + with pytest.raises( + SystemExit, + match=( + "Local staging ESI employer premium gates failed: " + "esi_premiums_anchor: invented: \\+20.0% from the anchor" + ), + ): + builder.main(arguments) + assert captured["staging_esi_premium_gates"][0] is ssi_filled + assert order[-1] == "esi_premium_gates" + assert "write" not in order assert "write" not in captured assert not output_h5.exists() assert not summary_path.exists() @@ -600,6 +733,25 @@ def staging_hours_gate(frame, *, source_null_audit): assert build_options.pop("puma_ladder") is puma_ladder assert callable(build_options.pop("hours_donor_factory")) assert build_options.pop("drop_group_quarters_children") is True + # microcosm#454: the donor is qualified before the SIPP donor load and the + # ACS fetch, and the same qualifier selects its rows when the transfer + # runs. The gates grade the frame the H5 is written from: the one the SSI + # disability stage returned, the last stage that replaces the frame. A + # waived donor refusal leaves the transfer without the factory, and the + # coverage check does not owe the premium. + assert build_options.pop("esi_premium_donor_factory") is ( + None if waived else qualify_esi_premium_donor + ) + coverage_families = { + family for families in captured["coverage_plan"].values() for family in families + } + assert ("source_operator_esi_premiums" in coverage_families) is not waived + assert "benefit_participation" in coverage_families + assert len(captured["esi_premium_donors"]) == 1 + assert captured["esi_premium_donors"][0] is base + gated_frame, gated_period = captured["staging_esi_premium_gates"] + assert gated_frame is ssi_filled + assert gated_period == 2024 assert build_options == { "chunksize": 2000, "acs_share": 0.4, @@ -608,6 +760,7 @@ def staging_hours_gate(frame, *, source_null_audit): "work_disability_inputs": True, "income_transfer": True, "native_receipt_anchors": True, + "wic_take_up": True, "semp_covers_partnership_income": True, "donor_channel": builder.ACS_DONOR_CHANNEL_AUTO, "seed": 11, @@ -624,8 +777,11 @@ def staging_hours_gate(frame, *, source_null_audit): # the SIPP donor is verified before the ACS fetch, and the SSI disability # stage runs after the income gate and before the input-null audit. # microcosm#1022: the native FS receipt anchor's gate grades the pooled - # frame first, before any stage that replaces the frame. + # frame first, before any stage that replaces the frame. microcosm#454: + # the ESI premium donor is qualified first, and its gates run last, + # before the H5 is written. assert order == [ + "esi_premium_donor", "sipp_load", "acs_fetch", "receipt_anchor_gate", @@ -635,10 +791,14 @@ def staging_hours_gate(frame, *, source_null_audit): "ssi_disability", "ssi_disability_gate", "null_audit", + "esi_premium_gates", + "write", ] summary = json.loads(summary_path.read_text(encoding="utf-8")) assert summary["artifact_kind"] == "nullable_precalibration_staging_h5" + assert summary["base"]["location"] == base_location + assert summary["engine_versions"] == engine_versions assert summary["calibration_applied"] is False assert summary["simulation_ready"] is False assert summary["simulation_ready_except_calibration"] is True @@ -708,6 +868,27 @@ def staging_hours_gate(frame, *, source_null_audit): assert self_employment["details"]["partnership_on_spouse_rows"] == 0 assert self_employment["details"]["partnership_on_blank_semp_rows"] == 0 assert self_employment["details"]["passive_without_line_32_rows"] == 0 + # A waived build records its red verdicts and the refusal it waived. + assert summary["local_esi_premiums"] == { + "enforced": not waived, + "transferred": not waived, + "donor_qualification_waived": waived_refusal if waived else None, + "provenance": None, + "signal_gate": { + "name": "esi_premiums_signal", + "passed": not waived, + "failures": list(signal_failures), + "details": {}, + }, + "anchor_gate": { + "name": "esi_premiums_anchor", + "passed": not waived, + "failures": list(anchor_failures), + # Strict JSON: a non-finite detail is written as null. + "details": {"relative_error": 0.0, "cross_check_ratio": None}, + }, + } + assert summary["orchestration"]["allow_esi_premium_gaps"] is waived assert "pending_engine_input_nulls" not in summary assert summary["staging_export_peak_estimate_bytes"] == 123_456 assert summary["geography_ladder"] == { @@ -766,6 +947,165 @@ def staging_hours_gate(frame, *, source_null_audit): assert summary["output"]["sha256"] == hashlib.sha256(b"combined-output").hexdigest() +def test_esi_premium_donor_is_qualified_before_fetch( + monkeypatch: pytest.MonkeyPatch, +) -> None: + """microcosm#454: a donor without the stage's premium stops the build + before the SIPP donor load and the ACS fetch.""" + + builder = _load_builder_module() + monkeypatch.setattr( + builder.acs_sources, "load_acs_source_manifest", lambda path: _manifest() + ) + monkeypatch.setattr(builder, "_load_base_frame", lambda path: _frame()) + monkeypatch.setattr(builder, "_sha256", lambda path: "0" * 64) + monkeypatch.setattr( + builder, "_require_dense_donor_coverage", lambda frame, **kwargs: None + ) + # microcosm#1020/#1022: this donor carries no immigration columns, ASEC + # observation role or SSI disability criteria; this test checks the ESI + # premium qualification only. + monkeypatch.setattr(builder, "_require_immigration_donor", lambda *_a, **_k: None) + monkeypatch.setattr(builder, "_require_income_donor", lambda *_a: None) + monkeypatch.setattr(builder, "_require_ssi_disability_donor", lambda *_a: None) + + def must_not_load_sipp(*_args, **_kwargs): + pytest.fail("the SIPP donor must not load for an unqualified ESI donor") + + def must_not_fetch(*_args, **_kwargs): + pytest.fail("source fetch must not run for an unqualified ESI donor") + + monkeypatch.setattr(builder, "_load_ssi_disability_donor", must_not_load_sipp) + monkeypatch.setattr(builder.acs_sources, "fetch_acs_pums_sources", must_not_fetch) + + with pytest.raises(SystemExit) as exc: + builder.main(["--base-h5", "prestage.h5", "--out-h5", "combined.h5"]) + + message = str(exc.value) + assert "failed the ESI employer premium qualification" in message + assert "employer_sponsored_insurance_premiums" in message + assert "meps_esi_premiums stage" in message + assert "--allow-esi-premium-gaps" in message + + +def test_esi_premium_donor_refusal_is_a_recorded_waiver_for_a_diagnostic_build() -> ( + None +): + builder = _load_builder_module() + + waiver = builder._qualify_esi_premium_donor(_frame(), allow_gaps=True) + + assert waiver is not None + assert "built without the meps_esi_premiums stage" in waiver + + +def test_local_coverage_plan_owes_the_premium_only_when_it_was_transferred() -> None: + builder = _load_builder_module() + hours_only = builder.acs_local_transfer_target_families() + + with_premium = builder._local_coverage_plan(esi_premiums=True) + without_premium = builder._local_coverage_plan(esi_premiums=False) + + assert with_premium["person"]["source_operator_esi_premiums"] == ( + "employer_sponsored_insurance_premiums", + ) + assert without_premium == hours_only + assert { + family: targets + for family, targets in with_premium["person"].items() + if family != "source_operator_esi_premiums" + } == dict(hours_only["person"]) + # The composition copies: the shared plans are not edited in place. + assert builder.acs_local_transfer_target_families() == hours_only + assert ( + "source_operator_esi_premiums" + not in (builder.declared_acs_transfer_target_families()["person"]) + ) + + +def _esi_premium_gates(*, signal: tuple[str, ...] = (), anchor: tuple[str, ...] = ()): + return lambda frame, *, time_period: ( + GateResult(name="esi_premiums_signal", passed=not signal, failures=signal), + GateResult(name="esi_premiums_anchor", passed=not anchor, failures=anchor), + ) + + +def test_red_staging_esi_premium_gates_abort_before_export( + monkeypatch: pytest.MonkeyPatch, +) -> None: + builder = _load_builder_module() + result = builder.AcsMultispineResult(frame=_frame(), provenance={}) + monkeypatch.setattr( + builder, + "acs_local_esi_premium_gates", + _esi_premium_gates(anchor=("off the anchor",)), + ) + + with pytest.raises(SystemExit) as exc: + builder._local_esi_premium_evidence( + result, period=2024, waiver=None, allow_gaps=False + ) + + assert "Local staging ESI employer premium gates failed" in str(exc.value) + assert "esi_premiums_anchor: off the anchor" in str(exc.value) + + +def test_waived_staging_esi_premium_gates_are_recorded_red( + monkeypatch: pytest.MonkeyPatch, +) -> None: + builder = _load_builder_module() + result = builder.AcsMultispineResult(frame=_frame(), provenance={}) + missing = ("person column missing: employer_sponsored_insurance_premiums.",) + monkeypatch.setattr( + builder, + "acs_local_esi_premium_gates", + _esi_premium_gates(signal=missing, anchor=missing), + ) + + evidence = builder._local_esi_premium_evidence( + result, + period=2024, + waiver="Local ESI premium donor lacks the column.", + allow_gaps=True, + ) + + assert evidence["enforced"] is False + assert evidence["transferred"] is False + assert evidence["donor_qualification_waived"] == ( + "Local ESI premium donor lacks the column." + ) + assert evidence["signal_gate"]["passed"] is False + assert evidence["signal_gate"]["failures"] == list(missing) + assert evidence["anchor_gate"]["failures"] == list(missing) + json.dumps(evidence, allow_nan=False) + + +def test_staging_esi_premium_evidence_on_a_real_lane_is_strict_json() -> None: + """The real gates on the real lane orchestration's result: green, and + written to the strict-JSON staging summary as is, the transfer and anchor + receipts included (the summary also records the whole provenance).""" + + from test_support.microcosm_build.us_acs_local_esi_premiums import ( + build_lane, + dense_donor, + raw_acs, + ) + + builder = _load_builder_module() + result = build_lane(dense_donor(), raw_acs()) + + evidence = builder._local_esi_premium_evidence( + result, period=2024, waiver=None, allow_gaps=False + ) + + assert evidence["signal_gate"]["passed"] is True + assert evidence["anchor_gate"]["passed"] is True + assert evidence["provenance"] is result.provenance["local_esi_premiums"] + assert set(evidence["provenance"]) == {"source", "anchor"} + json.dumps(evidence, sort_keys=True, allow_nan=False) + json.dumps(result.provenance, sort_keys=True, allow_nan=False) + + def test_immigration_stage_failures_abort_staging(monkeypatch) -> None: """microcosm#1020: a failed stage or gate never reaches the null audit.""" @@ -1821,6 +2161,79 @@ def test_donor_release_identity_verifies_sha_and_pins_provenance( assert module._donor_release_identity(None, sha) is None +@pytest.mark.parametrize( + ("release", "build"), + [ + (US_NATIONAL_RELEASE_ID, "populace-us-2024-20261121T010000Z-d596fcb60"), + ( + US_EVIDENCE_RELEASE_ID, + "populace-us-2024-evidence-20261121T010000Z-d596fcb60", + ), + ], + ids=["certified", "evidence"], +) +def test_a_certified_national_build_is_a_donor_staging_can_name( + tmp_path: Path, release: str, build: str +) -> None: + """Certification writes the national build's manifests in the tagged + shape and rewrites them into its tier's build folder (microcosm#1570, + #1585 item 11). The rewritten release manifest is one staging accepts as + --donor-release-manifest, and the reference it records is one the + local-area release contract accepts, at either tier.""" + + module = _load_builder_module() + sha = "a" * 64 + dataset = US_RELEASE_DATASET_FILES[release] + release_dir = tmp_path / "releases" / release + release_dir.mkdir(parents=True) + + def entry(path: str, digest: str, kind: str) -> dict[str, str]: + # The national release tool's _artifact_entry. + return { + "kind": kind, + "path": path, + "repo_id": "policyengine/populace-us", + "revision": build, + "sha256": digest, + } + + (release_dir / "release_manifest.json").write_text( + json.dumps( + { + "schema_version": 1, + "dataset_role": "national_default", + "is_default": False, + "build": {"build_id": build, "built_at": "2026-11-21T01:00:00Z"}, + "artifacts": { + Path(dataset).stem: entry(dataset, sha, "microdata"), + "calibration": entry("calibration.npz", "b" * 64, "calibration"), + "us_source_coverage": entry( + "us_source_coverage.json", "c" * 64, "diagnostics" + ), + }, + } + ) + ) + rewrite_release_dir(release_dir, build=build) + + identity = module._donor_release_identity( + release_dir / "release_manifest.json", sha + ) + + assert identity["release"] == release + assert identity["build"] == build + assert identity["artifact"] == Path(dataset).stem + assert "revision" not in identity + assert referenced_build(identity) == ReferencedBuild( + repo_id="policyengine/populace-us", + revision="main", + folder=f"releases/{release}/{build}", + ) + failures: list[str] = [] + _check_local_area_donor_reference(identity, failures) + assert failures == [] + + def _build_folder_donor_manifest(sha: str) -> dict: """A donor's release manifest in the build-folder layout.""" return { diff --git a/packages/microcosm-build/tests/engine_free/us/test_us_base_pool.py b/packages/microcosm-build/tests/engine_free/us/test_us_base_pool.py index 9b0700128e..1c06d30c29 100644 --- a/packages/microcosm-build/tests/engine_free/us/test_us_base_pool.py +++ b/packages/microcosm-build/tests/engine_free/us/test_us_base_pool.py @@ -370,6 +370,54 @@ def test__given_donor_assigned_geography__then_pool_preserves_it_and_derives_pum assert acs_row["county_fips"].tolist() == ["01001"] +def test__given_a_block_v1_donor__then_the_legacy_pool_keeps_its_block_geography() -> ( + None +): + # Given: a block_v1 base's donors carry a block and the geography derived + # from it beside the assigned triple. The County Files staging may run + # the legacy rule on such a base, so the legacy pool must keep each + # donor's own location rather than draw one. + tracts = ["01001000100", "01001000100"] + base = _assigned_geography_base_frame( + tracts=tracts, congressional_districts=[101, 102], counties=["01001", "01001"] + ) + tables = {entity: base.table(entity).copy() for entity in base.entities} + blocks = ["010010001001000", "010010001002001"] + tables["household"]["block_geoid"] = blocks + tables["household"]["cbsa_code"] = ["33860", "33860"] + base = Frame( + tables, + US_SCHEMA, + {entity: base.weights_for(entity) for entity in base.weighted_entities}, + base.strata, + ) + + # When + result = with_optional_acs_spine( + base, + _acs_frame(), + puma_ladder=_test_puma_ladder(), + geography_seed=17, + expected_congressional_district_vintage="119th_congress", + ) + + # Then: the donors keep their block, its tract, district and county, and + # their 2023 county follows the tract; ACS rows get no block. + household = result.table("household") + donor = household[household[spine_column("household")].eq(ASEC_PUF_SPINE)] + assert donor["block_geoid"].tolist() == blocks + assert donor["cbsa_code"].tolist() == ["33860", "33860"] + assert donor["tract_geoid"].tolist() == tracts + assert donor["congressional_district_geoid"].tolist() == [101, 102] + assert donor["county_fips"].tolist() == ["01001", "01001"] + np.testing.assert_array_equal( + donor[COUNTY_FIPS_2023_COLUMN], county_fips_2023_from_tracts(tracts) + ) + acs = household[household[spine_column("household")].eq(ACS_2024_1YR_SPINE)] + assert acs["block_geoid"].isna().all() + assert acs["county_fips"].tolist() == ["01001"] + + def _single_puma_ladder( puma: str, tracts: list[str], counties: list[str], district: int ) -> UsPumaLadder: diff --git a/packages/microcosm-build/tests/engine_free/us/test_us_battery_bindings.py b/packages/microcosm-build/tests/engine_free/us/test_us_battery_bindings.py index 365bd0a665..8c76d4622a 100644 --- a/packages/microcosm-build/tests/engine_free/us/test_us_battery_bindings.py +++ b/packages/microcosm-build/tests/engine_free/us/test_us_battery_bindings.py @@ -96,15 +96,16 @@ }, "us_local": { # Moved by the entries that pin the thresholds they compare against - # (review of #1635, rounds 1 and 2). + # (review of #1635, rounds 1 and 2), then by the lane's two ESI + # premium entries (microcosm#454, d2283 PR 0). "gates_manifest_sha256": ( - "e436bc1fc2ce141270e49684e43e2546881ba93969f42e0ae7092857d509ed0f" + "016410cb9f1b7b6f9ec977ef9cd1edb40abeea2f1877ee3c958d95e7c4c05374" ), "policy_sha256": ( - "8c0a58ddee2fd707ba2e45d285c197b689c11723281e7f925965ff33d65ace21" + "fb38b4ceb7bc719ecaab8f6e9c013a78f8aef40490d00656bc4cd0c94a51b9cc" ), "spec_fingerprint": ( - "6b329c7dd72713c127dcd917e62aaa875e6b87f2b072c76db3724e8dace0bc08" + "c3774138d171c169b3a61d8dcb5bd15fdf65a65f5da13ecdd0a1792ffcfc5023" ), }, } diff --git a/packages/microcosm-build/tests/engine_free/us/test_us_esi_premiums_pool_anchor.py b/packages/microcosm-build/tests/engine_free/us/test_us_esi_premiums_pool_anchor.py new file mode 100644 index 0000000000..ecbe408688 --- /dev/null +++ b/packages/microcosm-build/tests/engine_free/us/test_us_esi_premiums_pool_anchor.py @@ -0,0 +1,1571 @@ +"""The ESI pool anchor and the row rule for mixed frames (microcosm #454). + +A mixed frame holds CPS rows, which carry the raw ASEC fields the stage +reads, beside rows a cross-source transfer filled, which carry none of them +(the ACS local lane's pooled frame is one). Taken from microcosm#1199 +(e730a951a, ``test_us_esi_premiums_pool.py``) without its stacked-pool +wiring, for d2283 PR 0. + +Invariants of :func:`with_us_esi_premium_pool_anchor`, for every valid frame: + +* **Conservation**: the frame-wide weighted employer premium equals the + source-derived rows' total divided by their share of household mass. +* **Equal intensity**: source-derived and transferred rows carry the same + weighted employer premium per unit of household mass. +* **Source rows are immutable**: no source-derived cell changes by a byte. +* **One premium per person**: every support clone of a transferred person + carries its clone-0 source record's draw, whether the transfer ran before + or after the clone. +* **Structural zeros**: a transferred person whose source record reports zero + wages carries no premium, on every support clone. A missing wage is + refused, never read as zero. +* **Proportionality**: every other transferred employer premium is one common + multiple of the value the transfer drew for the source record. +* **Idempotence**: a frame already on the stage's scale is returned unchanged. +* **Weight homogeneity**: rescaling every household weight leaves each value + where it was. + +The gates grade such a frame only when the caller passes +``allow_transferred_rows=True``; the default keeps the single-source rule +every Route A caller uses. +""" + +from __future__ import annotations + +import numpy as np +import pandas as pd +import pytest +from hypothesis import HealthCheck, assume, given, settings +from hypothesis import strategies as st + +from microcosm.build.source_runtime import SourceRuntimeError +from microcosm.build.us_runtime import esi_premiums as esi +from microcosm.build.us_runtime.esi_premiums import ( + US_ESI_EMPLOYER_PREMIUM_COLUMN, + US_ESI_PREMIUMS_OUTPUT_COLUMNS, + US_ESI_PREMIUMS_WAGE_COLUMN, + us_esi_premiums_anchor_gate, + us_esi_premiums_signal_gate, + us_esi_premiums_summary, + with_us_esi_premium_pool_anchor, +) +from microcosm.frame import US_SCHEMA, Frame, WeightKind, Weights +from test_support.microcosm_build.us_esi_premiums_frames import ( + ANCHOR, + YEAR, + asec_arm, + cps_rows, + households_of, + mixed_frame, + reweighted, + staged, + with_person_cells, + with_scaled_premiums, +) + +EMPLOYER = US_ESI_EMPLOYER_PREMIUM_COLUMN +WAGES = US_ESI_PREMIUMS_WAGE_COLUMN +RAW = esi._RAW_EVIDENCE_COLUMNS +CPS_ID = esi.US_ESI_PREMIUMS_CPS_RECORD_COLUMN +RAW_WAGE = esi._RAW_ACS_WAGE_COLUMN + +_GROUPS = ("tax_unit", "spm_unit", "family", "marital_unit") + + +def _pool( + households: list[dict], + *, + clone_of: dict[int, int] | None = None, + clone_index: dict[int, int] | None = None, +) -> Frame: + """A pool frame from household records. + + Each record has ``source`` (whether its people carry raw ASEC fields), + ``weight`` and ``people``: a list of ``(employer premium, wages)``. Every + other stage output takes half the employer premium. ``clone_of`` maps a + household position to the position of the household it is a support clone + of; clones then share ``person_source_id`` with their source person. + ``clone_index`` gives a clone's support index (1 by default; 2 is the + capital-gains tail descendant). + """ + + clone_of = clone_of or {} + clone_index = clone_index or {} + records = [] + for position, household in enumerate(households): + origin = clone_of.get(position, position) + for member, (premium, wages) in enumerate(household["people"]): + record = { + "person_household_id": position + 1, + "person_source_id": (origin + 1) * 100 + member, + "person_support_clone_index": ( + clone_index.get(position, 1) if position in clone_of else 0 + ), + WAGES: float(wages), + } + record |= { + column: float(premium) * (1.0 if column == EMPLOYER else 0.5) + for column in US_ESI_PREMIUMS_OUTPUT_COLUMNS + } + record |= {column: 1.0 if household["source"] else np.nan for column in RAW} + # The CPS record id corroborates the row kind the raw fields imply. + record[CPS_ID] = ( + f"cps-{origin + 1:04d}-{member}" if household["source"] else None + ) + # The ACS earnings universe the anchor resolves wage evidence in: + # adults, with the raw wage the mapped wage came from. + record["person_support_channel"] = "asec" if household["source"] else "acs" + record["age"] = 40.0 + record[RAW_WAGE] = np.nan if household["source"] else float(wages) + records.append(record) + person = pd.DataFrame(records) + person.insert(0, "person_id", np.arange(1, len(person) + 1, dtype="int64")) + for offset, group in enumerate(_GROUPS, start=1): + person[f"person_{group}_id"] = person["person_id"] + offset * 1_000_000 + tables = { + "person": person, + "household": pd.DataFrame( + {"household_id": np.arange(1, len(households) + 1, dtype="int64")} + ), + } + for group in _GROUPS: + tables[group] = pd.DataFrame( + {f"{group}_id": person[f"person_{group}_id"].to_numpy()} + ) + weights = np.asarray([household["weight"] for household in households], float) + return Frame( + tables, + US_SCHEMA, + {"household": Weights(values=weights, kind=WeightKind.IMPORTANCE)}, + ) + + +def _column(frame: Frame, column: str) -> np.ndarray: + return frame.table("person")[column].to_numpy(dtype=float) + + +def _person_weights(frame: Frame) -> np.ndarray: + return np.asarray(frame.resolve_weights("person").values, dtype=float) + + +def _source_rows(frame: Frame) -> np.ndarray: + return frame.table("person")[RAW[0]].notna().to_numpy() + + +def _total(frame: Frame, rows: np.ndarray | None = None) -> float: + weights, values = _person_weights(frame), _column(frame, EMPLOYER) + rows = np.ones(len(values), dtype=bool) if rows is None else rows + return float(weights[rows] @ values[rows]) + + +_amount = st.one_of( + st.just(0.0), + st.floats(min_value=1.0, max_value=40_000.0, allow_nan=False), +) +_person = st.tuples(_amount, _amount) +_weight = st.one_of( + st.just(0.0), + st.floats(min_value=0.5, max_value=5_000.0, allow_nan=False), + # Masses many orders apart, where a share's complement loses precision. + st.floats(min_value=1e-9, max_value=1e-3, allow_nan=False), + st.floats(min_value=1e6, max_value=1e10, allow_nan=False), +) + + +def _households(source: bool) -> st.SearchStrategy[list[dict]]: + return st.lists( + st.fixed_dictionaries( + { + "source": st.just(source), + "weight": _weight, + "people": st.lists(_person, min_size=1, max_size=3), + } + ), + min_size=1, + max_size=6, + ) + + +def _record(frame: Frame, column: str) -> np.ndarray: + """Each row's value of ``column`` on its clone-0 source record.""" + + person = frame.table("person") + native = person["person_support_clone_index"].eq(0) + by_source = person.loc[native].set_index("person_source_id")[column] + return person["person_source_id"].map(by_source).to_numpy(dtype=float) + + +def _masses(frame: Frame) -> tuple[float, float]: + """Household mass of the source-derived and the transferred households.""" + + person = frame.table("person") + source_households = set(person.loc[_source_rows(frame), "person_household_id"]) + household = frame.table("household") + weights = np.asarray(frame.weights_for("household").values, dtype=float) + on_source = household["household_id"].isin(source_households).to_numpy() + return float(weights[on_source].sum()), float(weights[~on_source].sum()) + + +def _transferred_mass(frame: Frame) -> float: + return _masses(frame)[1] + + +@st.composite +def _pools(draw) -> Frame: + """Valid pools: either household kind may hold zero-weight households and + support clones (index 1 and the tail's index 2). + + A source household's clone copies its people, as the pool's clone does. A + transferred household's clone gets its own draws and wages, as a transfer + that ran after the clone would leave it. + """ + + households = draw(_households(True)) + draw(_households(False)) + clone_of: dict[int, int] = {} + clone_index: dict[int, int] = {} + for position in range(len(households)): + origin = households[position] + for index in sorted(draw(st.sets(st.sampled_from([1, 2])))): + people = ( + origin["people"] + if origin["source"] + else draw( + st.lists( + _person, + min_size=len(origin["people"]), + max_size=len(origin["people"]), + ) + ) + ) + clone_of[len(households)] = position + clone_index[len(households)] = index + households.append( + {"source": origin["source"], "weight": draw(_weight), "people": people} + ) + # A frame needs weight somewhere, and the anchor needs it on a source row. + assume(any(household["weight"] > 0 for household in households)) + frame = _pool(households, clone_of=clone_of, clone_index=clone_index) + source = _source_rows(frame) + assume(_total(frame, source) > 0) + weights = _person_weights(frame) + workers = ~source & (_record(frame, WAGES) > 0) + drawn_on_workers = float(weights[workers] @ _record(frame, EMPLOYER)[workers]) + # Transferred mass needs premium on workers to scale; none needs nothing. + assume(drawn_on_workers > 0 or _transferred_mass(frame) == 0) + return frame + + +_SETTINGS = settings( + max_examples=200, + deadline=None, + suppress_health_check=[HealthCheck.too_slow, HealthCheck.filter_too_much], +) + + +@given(_pools()) +@_SETTINGS +def test_pool_total_is_the_source_total_over_its_mass_share(frame: Frame) -> None: + source = _source_rows(frame) + source_mass, transferred_mass = _masses(frame) + selected, unselected = esi._household_masses(frame, source) + share = selected / (selected + unselected) + + anchored, receipt = with_us_esi_premium_pool_anchor(frame) + + expected = _total(frame, source) * (source_mass + transferred_mass) / source_mass + assert _total(anchored) == pytest.approx(expected, rel=1e-9) + assert receipt["employer_premium_total"] == pytest.approx(expected, rel=1e-9) + assert receipt["pool_employer_premium_target"] == pytest.approx(expected, rel=1e-12) + assert receipt["source_household_mass_share"] == share + + +@given(_pools()) +@_SETTINGS +def test_both_sides_carry_the_same_premium_per_unit_of_household_mass( + frame: Frame, +) -> None: + source = _source_rows(frame) + source_mass, transferred_mass = _masses(frame) + assume(transferred_mass > 0) + + anchored, _receipt = with_us_esi_premium_pool_anchor(frame) + + assert _total(anchored, ~source) / transferred_mass == pytest.approx( + _total(anchored, source) / source_mass, rel=1e-9 + ) + + +@given(_pools()) +@_SETTINGS +def test_source_rows_and_every_other_column_are_untouched(frame: Frame) -> None: + source = _source_rows(frame) + + anchored, _receipt = with_us_esi_premium_pool_anchor(frame) + + before, after = frame.table("person"), anchored.table("person") + assert list(after.columns) == list(before.columns) + pd.testing.assert_frame_equal(after.loc[source], before.loc[source]) + untouched = [ + column + for column in before.columns + if column not in US_ESI_PREMIUMS_OUTPUT_COLUMNS + ] + pd.testing.assert_frame_equal(after[untouched], before[untouched]) + for entity in frame.entities: + if entity != "person": + pd.testing.assert_frame_equal(anchored.table(entity), frame.table(entity)) + np.testing.assert_array_equal(_person_weights(anchored), _person_weights(frame)) + + +@given(_pools()) +@_SETTINGS +def test_transferred_rows_without_wages_carry_nothing_and_the_rest_one_multiple( + frame: Frame, +) -> None: + source = _source_rows(frame) + workers = _record(frame, WAGES) > 0 + + anchored, receipt = with_us_esi_premium_pool_anchor(frame) + + cleared = ~source & ~workers + kept = ~source & workers + for column in US_ESI_PREMIUMS_OUTPUT_COLUMNS: + drawn = _record(frame, column) + assert not _column(anchored, column)[cleared].any() + assert receipt["cleared_rows"][column] == int((cleared & (drawn > 0)).sum()) + assert receipt["transferred_rows_reset_to_source_record"][column] == int( + (~source & (drawn != _column(frame, column))).sum() + ) + if column != EMPLOYER: + np.testing.assert_array_equal(_column(anchored, column)[kept], drawn[kept]) + np.testing.assert_allclose( + _column(anchored, EMPLOYER)[kept], + _record(frame, EMPLOYER)[kept] * receipt["scale_factor"], + rtol=1e-12, + ) + assert np.isfinite(_column(anchored, EMPLOYER)).all() + assert (_column(anchored, EMPLOYER) >= 0).all() + + +@given(_pools()) +@_SETTINGS +def test_every_support_clone_of_a_transferred_person_carries_one_premium( + frame: Frame, +) -> None: + anchored, _receipt = with_us_esi_premium_pool_anchor(frame) + + person = anchored.table("person") + transferred = ~_source_rows(anchored) + per_person = person.loc[transferred].groupby("person_source_id")[ + list(US_ESI_PREMIUMS_OUTPUT_COLUMNS) + ] + assert (per_person.nunique() == 1).all().all() + np.testing.assert_array_equal( + _column(anchored, EMPLOYER)[transferred], + _record(anchored, EMPLOYER)[transferred], + ) + + +@given(_pools()) +@_SETTINGS +def test_a_pool_on_the_stage_scale_is_returned_unchanged(frame: Frame) -> None: + anchored, _receipt = with_us_esi_premium_pool_anchor(frame) + + again, receipt = with_us_esi_premium_pool_anchor(anchored) + + assert again is anchored + assert receipt["status"] == ( + "already_on_anchor" if _transferred_mass(frame) > 0 else "no_transferred_mass" + ) + assert receipt["scale_factor"] == pytest.approx(1.0, rel=1e-12) + + +# Up to 1e150 either way: multiplying the source total by the transferred +# mass before dividing by the source mass overflowed well inside this range. +@given(_pools(), st.floats(min_value=1e-150, max_value=1e150, allow_nan=False)) +@_SETTINGS +def test_rescaling_every_household_weight_leaves_each_value_where_it_was( + frame: Frame, factor: float +) -> None: + rescaled = Frame( + {entity: frame.table(entity) for entity in frame.entities}, + frame.schema, + { + "household": Weights( + values=np.asarray(frame.weights_for("household").values) * factor, + kind=WeightKind.IMPORTANCE, + ) + }, + ) + + anchored, _receipt = with_us_esi_premium_pool_anchor(frame) + anchored_rescaled, _receipt = with_us_esi_premium_pool_anchor(rescaled) + + np.testing.assert_allclose( + _column(anchored_rescaled, EMPLOYER), _column(anchored, EMPLOYER), rtol=1e-9 + ) + + +def test_the_worked_two_source_pool() -> None: + # Source side: half the household mass, $600 of weighted premium. + # Transferred side: $300 drawn on a worker, $500 on a non-worker. + frame = _pool( + [ + {"source": True, "weight": 2.0, "people": [(300.0, 50_000.0)]}, + {"source": False, "weight": 1.0, "people": [(300.0, 40_000.0)]}, + {"source": False, "weight": 1.0, "people": [(500.0, 0.0)]}, + ] + ) + + anchored, receipt = with_us_esi_premium_pool_anchor(frame) + + assert receipt["source_household_mass_share"] == 0.5 + assert receipt["transferred_employer_premium_target"] == 600.0 + assert receipt["scale_factor"] == 2.0 + assert receipt["cleared_rows"][EMPLOYER] == 1 + assert receipt["cleared_weighted_total"][EMPLOYER] == 500.0 + np.testing.assert_array_equal(_column(anchored, EMPLOYER), [300.0, 600.0, 0.0]) + assert _total(anchored) == 1_200.0 + assert receipt["status"] == "scaled" + + +def test_support_clones_follow_their_source_record_wages() -> None: + # Households 3 and 4 are the support clones of 1 and 2. A clone's own + # wages are another tax-detail vector; the survey-side wages decide. + frame = _pool( + [ + {"source": True, "weight": 1.0, "people": [(400.0, 50_000.0)]}, + {"source": True, "weight": 1.0, "people": [(400.0, 0.0)]}, + {"source": False, "weight": 1.0, "people": [(200.0, 30_000.0)]}, + {"source": False, "weight": 1.0, "people": [(200.0, 0.0)]}, + {"source": False, "weight": 1.0, "people": [(200.0, 0.0)]}, + {"source": False, "weight": 1.0, "people": [(200.0, 9_000.0)]}, + ], + clone_of={4: 2, 5: 3}, + ) + + anchored, receipt = with_us_esi_premium_pool_anchor(frame) + + employer = _column(anchored, EMPLOYER) + # The worker's clone keeps the premium though its own wages are zero; the + # non-worker's clone loses it though its own wages are positive. + assert employer[2] == employer[4] > 0 + assert employer[3] == employer[5] == 0 + assert receipt["transferred_rows_without_source_wages"] == 2 + np.testing.assert_array_equal(employer[:2], [400.0, 400.0]) + + +def test_a_transfer_that_ran_after_the_clone_is_reset_to_one_premium_per_person() -> ( + None +): + # The legacy two-spine order clones first, so its transfer draws every + # support clone separately: $100 on the source record, $700 and nothing + # on its clones, whose own wages are another tax-detail vector. + frame = _pool( + [ + {"source": True, "weight": 3.0, "people": [(300.0, 50_000.0)]}, + {"source": False, "weight": 1.0, "people": [(100.0, 40_000.0)]}, + {"source": False, "weight": 1.0, "people": [(700.0, 0.0)]}, + {"source": False, "weight": 1.0, "people": [(0.0, 9.0)]}, + ], + clone_of={2: 1, 3: 1}, + clone_index={3: 2}, + ) + + anchored, receipt = with_us_esi_premium_pool_anchor(frame) + + # Every clone takes the source record's $100, then the one factor. + np.testing.assert_array_equal( + _column(anchored, EMPLOYER), [300.0, 300.0, 300.0, 300.0] + ) + assert receipt["transferred_rows_reset_to_source_record"][EMPLOYER] == 2 + assert receipt["cleared_rows"][EMPLOYER] == 0 + assert receipt["scale_factor"] == 3.0 + assert _total(anchored) == 1_800.0 + + +def test_transferred_rows_without_household_mass_are_not_scaled() -> None: + # Nothing to hold a zero-mass side to: structural zeros still apply, the + # factor stays at one and the pool total is the source total. + frame = _pool( + [ + {"source": True, "weight": 2.0, "people": [(300.0, 50_000.0)]}, + {"source": False, "weight": 0.0, "people": [(250.0, 40_000.0)]}, + {"source": False, "weight": 0.0, "people": [(500.0, 0.0)]}, + ] + ) + + anchored, receipt = with_us_esi_premium_pool_anchor(frame) + + assert receipt["source_household_mass_share"] == 1.0 + assert receipt["transferred_household_mass_share"] == 0.0 + assert receipt["transferred_employer_premium_target"] == 0.0 + assert receipt["scale_factor"] == 1.0 + np.testing.assert_array_equal(_column(anchored, EMPLOYER), [300.0, 250.0, 0.0]) + assert _total(anchored) == 600.0 == receipt["pool_employer_premium_target"] + + again, receipt = with_us_esi_premium_pool_anchor(anchored) + assert again is anchored + assert receipt["status"] == "no_transferred_mass" + + +def test_zero_mass_transferred_rows_need_no_premium_on_workers() -> None: + frame = _pool(_two_sided(h1={"weight": 0.0, "people": [(100.0, 0.0)]})) + + anchored, receipt = with_us_esi_premium_pool_anchor(frame) + + np.testing.assert_array_equal(_column(anchored, EMPLOYER), [100.0, 0.0]) + assert receipt["scale_factor"] == 1.0 + + +def test_a_frame_with_no_transferred_row_is_returned_unchanged() -> None: + frame = _pool([{"source": True, "weight": 3.0, "people": [(100.0, 1.0)]}]) + + anchored, receipt = with_us_esi_premium_pool_anchor(frame) + + assert anchored is frame + assert receipt["status"] == "no_transferred_rows" + assert receipt["source_household_mass_share"] == 1.0 + assert receipt["employer_premium_total"] == 300.0 + + +def _two_sided(**changes) -> list[dict]: + households = [ + {"source": True, "weight": 1.0, "people": [(100.0, 1.0)]}, + {"source": False, "weight": 1.0, "people": [(100.0, 1.0)]}, + ] + for position, change in changes.items(): + households[int(position.removeprefix("h"))] |= change + return households + + +def _with_person_cell( + frame: Frame, row: int, column: str | list[str], value: object +) -> Frame: + tables = {entity: frame.table(entity).copy() for entity in frame.entities} + tables["person"].loc[row, column] = value + return Frame( + tables, + frame.schema, + {"household": frame.weights_for("household")}, + ) + + +def test_a_row_with_only_some_raw_fields_is_refused() -> None: + frame = _with_person_cell(_pool(_two_sided()), 1, RAW[0], 1.0) + + with pytest.raises(SourceRuntimeError, match="only some of the raw ASEC fields"): + with_us_esi_premium_pool_anchor(frame) + + +def test_a_household_mixing_both_kinds_of_row_is_refused() -> None: + frame = _pool( + [{"source": True, "weight": 1.0, "people": [(100.0, 1.0), (50.0, 1.0)]}] + ) + mixed = _with_person_cell(frame, 1, [*RAW, CPS_ID], None) + + with pytest.raises(SourceRuntimeError, match="mix source-derived and transferred"): + with_us_esi_premium_pool_anchor(mixed) + + +def _two_cps_one_transferred() -> Frame: + return _pool( + [ + {"source": True, "weight": 1.0, "people": [(100.0, 1.0)]}, + {"source": True, "weight": 1.0, "people": [(100.0, 1.0)]}, + {"source": False, "weight": 2.0, "people": [(100.0, 1.0)]}, + ] + ) + + +def test_a_cps_record_that_lost_its_raw_fields_is_not_a_transferred_row() -> None: + # Nulls in every coverage field look like a transferred row. The CPS + # record id says otherwise, and the premium is not taken on trust. + frame = _with_person_cell(_two_cps_one_transferred(), 1, list(RAW), np.nan) + + with pytest.raises( + SourceRuntimeError, match=r"1 CPS record\(s\).*lack the raw ASEC fields" + ): + with_us_esi_premium_pool_anchor(frame) + + +@pytest.mark.parametrize("blank", [None, "", " "]) +def test_raw_fields_without_a_cps_record_id_are_refused(blank: object) -> None: + frame = _with_person_cell(_two_cps_one_transferred(), 1, CPS_ID, blank) + + with pytest.raises(SourceRuntimeError, match="without a CPS record id"): + with_us_esi_premium_pool_anchor(frame) + + +def test_a_frame_without_the_cps_record_id_cannot_hold_transferred_rows() -> None: + frame = _two_cps_one_transferred() + tables = {entity: frame.table(entity).copy() for entity in frame.entities} + tables["person"] = tables["person"].drop(columns=[CPS_ID]) + unmarked = Frame( + tables, frame.schema, {"household": frame.weights_for("household")} + ) + + with pytest.raises(SourceRuntimeError, match=f"no {CPS_ID!r} column"): + with_us_esi_premium_pool_anchor(unmarked) + + +@pytest.mark.parametrize("wage", [np.nan, None]) +def test_a_transferred_person_with_a_missing_wage_is_refused(wage: object) -> None: + # Missing evidence is not a zero: the premium is neither cleared nor kept. + frame = _with_person_cell(_pool(_two_sided()), 1, WAGES, wage) + + with pytest.raises(SourceRuntimeError, match="A missing wage is not a zero wage"): + with_us_esi_premium_pool_anchor(frame) + + +def test_a_missing_wage_on_a_source_record_blocks_its_clones_too() -> None: + # The clone's own mapped wage is a number; its source record's is not. + frame = _pool(_two_sided() + [_two_sided()[1]], clone_of={2: 1}) + frame = _with_person_cell(frame, 1, WAGES, np.nan) + + with pytest.raises(SourceRuntimeError, match="A missing wage is not a zero wage"): + with_us_esi_premium_pool_anchor(frame) + + +def test_a_zero_filled_wage_without_a_raw_wage_is_refused() -> None: + # The legacy PUF pass fills a missing mapped wage with zero. Census asks + # every person 15 or older for WAGP, so a blank raw field there is missing + # evidence, not a zero, however the mapped column was filled. + frame = _pool(_two_sided(h1={"people": [(100.0, 0.0)]})) + frame = _with_person_cell(frame, 1, RAW_WAGE, np.nan) + + with pytest.raises(SourceRuntimeError, match=r"raw_in_universe_null_rows=1"): + with_us_esi_premium_pool_anchor(frame) + + +def test_a_child_without_a_raw_wage_carries_the_named_universe_zero() -> None: + # Below 15 Census leaves WAGP blank; the mapped zero is the universe rule's, + # so the drawn premium is a structural zero and is cleared. + frame = _pool( + [ + {"source": True, "weight": 1.0, "people": [(100.0, 50_000.0)]}, + {"source": False, "weight": 1.0, "people": [(80.0, 40_000.0)]}, + {"source": False, "weight": 1.0, "people": [(50.0, 0.0)]}, + ] + ) + frame = _with_person_cell(frame, 2, ["age", RAW_WAGE], [9.0, np.nan]) + + anchored, receipt = with_us_esi_premium_pool_anchor(frame) + + np.testing.assert_array_equal(_column(anchored, EMPLOYER), [100.0, 200.0, 0.0]) + evidence = receipt["transferred_wage_evidence"] + assert evidence["rule_id"] == "acs_2024_pums_wagp_age_15_plus" + assert evidence["structurally_absent_person_rows"] == 1 + assert evidence["mapped_universe_zero_rows"] == 1 + assert evidence["eligible_acs_person_rows"] == 1 + + +def test_a_child_with_a_nonzero_mapped_wage_is_refused() -> None: + frame = _pool(_two_sided()) + frame = _with_person_cell(frame, 1, ["age", RAW_WAGE], [9.0, np.nan]) + + with pytest.raises( + SourceRuntimeError, match="out_of_universe_mapped_nonzero_rows=1" + ): + with_us_esi_premium_pool_anchor(frame) + + +@pytest.mark.parametrize("multiplier", [1.0, 0.1, 1e-3, 1e3]) +def test_a_tiny_transferred_side_keeps_one_factor_at_any_weight_scale( + multiplier: float, +) -> None: + # Household masses 1e8 and 1e-8 with equal premium per unit of mass. Taking + # the transferred share as one minus the source share loses it to rounding + # and gave factors of 1.11 and 2.22 for the same pool at two weight scales. + frame = _pool( + [ + {"source": True, "weight": 1e8 * multiplier, "people": [(100.0, 1.0)]}, + {"source": False, "weight": 1e-8 * multiplier, "people": [(100.0, 1.0)]}, + ] + ) + + anchored, receipt = with_us_esi_premium_pool_anchor(frame) + + assert receipt["scale_factor"] == pytest.approx(1.0, rel=1e-12) + assert receipt["transferred_household_mass"] == pytest.approx( + 1e-8 * multiplier, rel=1e-12 + ) + np.testing.assert_allclose(_column(anchored, EMPLOYER), [100.0, 100.0], rtol=1e-12) + + +def test_a_transferred_side_far_below_rounding_is_still_scaled() -> None: + # Source mass 1e16, transferred mass 1: the share rounds to exactly one, + # yet the transferred side holds mass and is held to the source intensity. + frame = _pool( + [ + {"source": True, "weight": 1e16, "people": [(100.0, 1.0)]}, + {"source": False, "weight": 1.0, "people": [(40.0, 1.0)]}, + ] + ) + + anchored, receipt = with_us_esi_premium_pool_anchor(frame) + + assert receipt["source_household_mass_share"] == 1.0 + assert receipt["transferred_household_mass"] == 1.0 + assert receipt["scale_factor"] == pytest.approx(2.5, rel=1e-12) + np.testing.assert_allclose(_column(anchored, EMPLOYER), [100.0, 100.0], rtol=1e-12) + + +@pytest.mark.parametrize("mass", [1.0, 1e-300, 1e-200, 1e152, 1e153, 1e300]) +def test_the_factor_and_targets_stay_finite_wherever_the_correct_ones_are( + mass: float, +) -> None: + # Equal household mass on each side, $10,000 and $5,000 of employer premium + # per unit of it: the factor is 2 at every scale. Multiplying the source + # total by the transferred mass before dividing by the source mass gave an + # infinite target at 1e152, an infinite factor at 1e153 and a zero one at + # 1e-200. + frame = _pool( + [ + {"source": True, "weight": mass, "people": [(10_000.0, 1.0)]}, + {"source": False, "weight": mass, "people": [(5_000.0, 1.0)]}, + ] + ) + + anchored, receipt = with_us_esi_premium_pool_anchor(frame) + + assert receipt["status"] == "scaled" + assert receipt["scale_factor"] == pytest.approx(2.0, rel=1e-12) + # ``abs=0``: approx's default absolute tolerance would pass anything at 1e-300. + assert receipt["transferred_employer_premium_target"] == pytest.approx( + 1e4 * mass, rel=1e-12, abs=0.0 + ) + assert receipt["pool_employer_premium_target"] == pytest.approx( + 2e4 * mass, rel=1e-12, abs=0.0 + ) + assert receipt["employer_premium_total"] == pytest.approx( + 2e4 * mass, rel=1e-12, abs=0.0 + ) + np.testing.assert_allclose( + _column(anchored, EMPLOYER), [10_000.0, 10_000.0], rtol=1e-12 + ) + + +@pytest.mark.parametrize( + "mass", + [ + # The source total itself is past the largest float. + 1e306, + # Each side's total is finite; the pool's is not. + 1.5e304, + ], +) +def test_a_pool_whose_correct_total_is_not_finite_is_refused(mass: float) -> None: + frame = _pool( + [ + {"source": True, "weight": mass, "people": [(10_000.0, 1.0)]}, + {"source": False, "weight": mass, "people": [(10_000.0, 1.0)]}, + ] + ) + + with pytest.raises(SourceRuntimeError, match="target is not finite"): + with_us_esi_premium_pool_anchor(frame) + + +def test_a_missing_wage_on_a_source_derived_row_is_not_read() -> None: + frame = _with_person_cell(_pool(_two_sided()), 0, WAGES, np.nan) + + anchored, receipt = with_us_esi_premium_pool_anchor(frame) + + assert anchored is frame + assert receipt["status"] == "already_on_anchor" + + +@pytest.mark.parametrize("value", [np.nan, np.inf, -1.0]) +def test_an_unfilled_or_negative_premium_is_refused(value: float) -> None: + frame = _with_person_cell(_pool(_two_sided()), 1, EMPLOYER, value) + + with pytest.raises(SourceRuntimeError, match="finite and nonnegative"): + with_us_esi_premium_pool_anchor(frame) + + +def test_transferred_rows_with_no_premium_on_workers_are_refused() -> None: + frame = _pool(_two_sided(h1={"people": [(100.0, 0.0)]})) + + with pytest.raises(SourceRuntimeError, match="nothing to scale"): + with_us_esi_premium_pool_anchor(frame) + + +def test_source_rows_with_no_premium_mass_are_refused() -> None: + frame = _pool(_two_sided(h0={"people": [(0.0, 1.0)]})) + + with pytest.raises(SourceRuntimeError, match="source-derived rows hold no"): + with_us_esi_premium_pool_anchor(frame) + + +def test_missing_wages_or_outputs_are_refused() -> None: + frame = _pool(_two_sided()) + for column in (WAGES, EMPLOYER, RAW[0]): + tables = {entity: frame.table(entity).copy() for entity in frame.entities} + tables["person"] = tables["person"].drop(columns=[column]) + stripped = Frame( + tables, frame.schema, {"household": frame.weights_for("household")} + ) + with pytest.raises(SourceRuntimeError, match=column): + with_us_esi_premium_pool_anchor(stripped) + + +def test_a_support_clone_without_its_source_record_is_refused() -> None: + frame = _pool(_two_sided(), clone_of={1: 0}) + orphaned = _with_person_cell(frame, 1, "person_source_id", 999_999) + + with pytest.raises(SourceRuntimeError, match="no clone-0 source record"): + with_us_esi_premium_pool_anchor(orphaned) + + +def test_household_masses_are_weight_not_headcount() -> None: + frame = _pool( + [ + {"source": True, "weight": 3.0, "people": [(1.0, 1.0)]}, + {"source": False, "weight": 1.0, "people": [(1.0, 1.0)] * 3}, + ] + ) + + assert esi._household_masses(frame, _source_rows(frame)) == (3.0, 1.0) + assert esi._household_masses(frame, ~_source_rows(frame)) == (1.0, 3.0) + with pytest.raises(SourceRuntimeError, match="one flag per person"): + esi._household_masses(frame, np.array([True])) + + +# --- The default keeps the single-source rule --------------------------------- + + +@pytest.fixture(scope="module") +def alone() -> Frame: + """A single-source CPS frame, staged as the base builder stages it.""" + + return staged(asec_arm()) + + +@pytest.fixture(scope="module") +def mixed() -> Frame: + """320 CPS rows beside 280 transferred rows, on the stage's scale.""" + + return mixed_frame() + + +def test_the_default_refuses_a_transferred_row(mixed, alone) -> None: + with pytest.raises( + SourceRuntimeError, match=r"280 row\(s\) lack some of the raw ASEC fields" + ): + us_esi_premiums_summary(mixed) + for gate in ( + us_esi_premiums_signal_gate(mixed), + us_esi_premiums_anchor_gate(mixed, time_period=YEAR), + ): + assert not gate.passed + assert "allow_transferred_rows=True" in gate.failures[0] + # One row with neither the raw fields nor a CPS record id is enough. + one = with_person_cells(alone, [3], [*RAW, CPS_ID], None) + with pytest.raises(SourceRuntimeError, match=r"1 row\(s\) lack some"): + us_esi_premiums_summary(one) + assert not us_esi_premiums_signal_gate(one).passed + assert ( + us_esi_premiums_summary(one, allow_transferred_rows=True)["transferred_rows"] + == 1 + ) + + +def test_the_default_refuses_a_partial_row(mixed, alone) -> None: + transferred = np.flatnonzero(~cps_rows(mixed)) + for frame in ( + with_person_cells(alone, [5], RAW[0], np.nan), + with_person_cells(mixed, transferred[:1], RAW[0], 2), + ): + with pytest.raises(SourceRuntimeError, match="lack some of the raw ASEC"): + us_esi_premiums_summary(frame) + with pytest.raises(SourceRuntimeError, match="only some of the raw ASEC"): + us_esi_premiums_summary(frame, allow_transferred_rows=True) + + +def test_the_default_never_reads_the_cps_record_id(alone) -> None: + frame = with_person_cells(alone, [5], CPS_ID, None) + + assert us_esi_premiums_signal_gate(frame).passed + assert us_esi_premiums_anchor_gate(frame, time_period=YEAR).passed + lane = us_esi_premiums_signal_gate(frame, allow_transferred_rows=True) + assert not lane.passed + assert "without a CPS record id" in lane.failures[0] + + +# --- Grading a mixed frame (allow_transferred_rows=True) ----------------------- + + +def _gates(frame: Frame) -> tuple: + return ( + us_esi_premiums_signal_gate(frame, allow_transferred_rows=True), + us_esi_premiums_anchor_gate( + frame, time_period=YEAR, allow_transferred_rows=True + ), + ) + + +def test_both_gates_pass_on_the_mixed_frame(mixed, alone) -> None: + signal, anchor = _gates(mixed) + + assert signal.passed, signal.failures + assert anchor.passed, anchor.failures + # The cell proofs ran on the CPS rows, and found them one common multiple + # of their MEPS-IC shares: the single-source factor. + reference = us_esi_premiums_summary(alone) + assert signal.details["source_rows"] == 320 + assert signal.details["transferred_rows"] == 280 + assert signal.details["scale_factor"] == pytest.approx( + reference["scale_factor"], rel=1e-9 + ) + assert signal.details["employer_premium_outside_universe_rows"] == 0 + assert signal.details["clone_disagreement_source_persons"] == 0 + assert signal.details["transferred_source_records_with_premium_and_no_wages"] == 0 + assert anchor.details["anchor_universe_employer_total"] == pytest.approx( + ANCHOR, rel=1e-9 + ) + assert anchor.details["relative_error"] == pytest.approx(0.0, abs=1e-9) + assert anchor.details["source_household_mass_share"] == pytest.approx( + 0.5, rel=1e-12 + ) + assert anchor.details[ + "transferred_to_source_per_household_mass_ratio" + ] == pytest.approx(1.0, rel=1e-9) + assert anchor.details["employed_share_of_anchor_universe"] == pytest.approx( + reference["employed_share_of_anchor_universe"], rel=1e-12 + ) + assert "employed share" in anchor.details["anchor_universe_assumption"] + # Scaled to the population, the private-sector cross-check matches the + # single-source one. + assert anchor.details["private_active_cross_check"][ + "employer_premium_private_sector" + ] == pytest.approx(reference["employer_premium_by_sector"]["private"], rel=1e-9) + + +def test_transferred_rows_without_the_premium_fail_the_signal_gate(mixed) -> None: + flattened = with_scaled_premiums(mixed, 0.0, ~cps_rows(mixed)) + + signal, _anchor = _gates(flattened) + + assert not signal.passed + assert any( + "positive share on the rows without raw ASEC columns" in failure + for failure in signal.failures + ) + + +@pytest.mark.parametrize("factor", [0.7, 1.4]) +def test_transferred_rows_off_the_cps_rows_per_mass_total_fail_the_anchor_gate( + mixed, factor: float +) -> None: + skewed = with_scaled_premiums(mixed, factor, ~cps_rows(mixed)) + + _signal, anchor = _gates(skewed) + + assert not anchor.passed + assert anchor.details[ + "transferred_to_source_per_household_mass_ratio" + ] == pytest.approx(factor, rel=1e-9) + assert any("per unit of household mass" in failure for failure in anchor.failures) + # Half the mass at ``factor`` moves the anchor-universe total by half of it. + assert anchor.details["relative_error"] == pytest.approx( + (factor - 1.0) / 2.0, rel=1e-6 + ) + + +def test_reweighting_one_side_moves_the_total_but_not_the_per_mass_ratio( + mixed, +) -> None: + # What calibration does across sources: more weight on one side. + transferred = households_of(mixed, ~cps_rows(mixed)) + tilted = reweighted(mixed, np.where(transferred, 1.06, 1.0)) + + _signal, anchor = _gates(tilted) + + assert anchor.passed, anchor.failures + assert anchor.details[ + "transferred_to_source_per_household_mass_ratio" + ] == pytest.approx(1.0, rel=1e-9) + assert anchor.details["relative_error"] == pytest.approx(0.03, rel=1e-6) + assert anchor.details["source_household_mass_share"] == pytest.approx( + 1.0 / 2.06, rel=1e-9 + ) + + +def test_a_frame_whose_transferred_rows_hold_no_mass_passes_both_gates( + mixed, +) -> None: + # Selection can leave one source without weight. The other source then + # carries the whole population, and there is no second half to compare. + transferred = households_of(mixed, ~cps_rows(mixed)) + source_only = reweighted(mixed, np.where(transferred, 0.0, 2.0)) + + signal, anchor = _gates(source_only) + + assert signal.passed, signal.failures + assert anchor.passed, anchor.failures + assert anchor.details["transferred_household_mass_share"] == 0.0 + assert anchor.details["anchor_universe_employer_total"] == pytest.approx( + ANCHOR, rel=1e-9 + ) + again, receipt = with_us_esi_premium_pool_anchor(source_only) + assert again is source_only + assert receipt["status"] == "no_transferred_mass" + + +@pytest.mark.parametrize("lane", [True, False]) +def test_cps_records_that_lost_their_raw_fields_fail_both_gates( + mixed, alone, lane: bool +) -> None: + for frame in ( + # A mixed frame, and a single-source frame: neither may read lost + # coverage codes as a transfer. + with_person_cells( + mixed, np.flatnonzero(cps_rows(mixed))[:4], list(RAW), np.nan + ), + with_person_cells(alone, np.arange(4), list(RAW), np.nan), + ): + for gate in ( + us_esi_premiums_signal_gate(frame, allow_transferred_rows=lane), + us_esi_premiums_anchor_gate( + frame, time_period=YEAR, allow_transferred_rows=lane + ), + ): + assert not gate.passed + if lane: + assert "4 CPS record(s)" in gate.failures[0] + assert "lack the raw ASEC fields" in gate.failures[0] + else: + assert "lack some of the raw ASEC fields" in gate.failures[0] + + +def test_transferred_support_clones_that_disagree_fail_the_signal_gate() -> None: + cloned = mixed_frame(acs_clones=True) + person = cloned.table("person") + clone = np.flatnonzero( + ~cps_rows(cloned) + & person["person_support_clone_index"].eq(1).to_numpy() + & (person[EMPLOYER] > 0).to_numpy() + )[:1] + split = with_person_cells(cloned, clone, EMPLOYER, 1.0) + + signal, _anchor = _gates(split) + + assert _gates(cloned)[0].passed + assert signal.details["transferred_clone_disagreement_source_records"] == 1 + assert any( + "support-clone disagreement(s) on the rows without raw ASEC columns" in failure + for failure in signal.failures + ) + # The anchor restores one premium per person. + restored, receipt = with_us_esi_premium_pool_anchor(split) + assert receipt["transferred_rows_reset_to_source_record"][EMPLOYER] == 1 + assert _gates(restored)[0].passed + + +@pytest.mark.parametrize("factor", [1e-12, 1e12]) +def test_the_gates_grade_a_tiny_transferred_side_against_its_own_mass( + mixed, factor: float +) -> None: + # The per-mass ratio divides each side's total by that side's own mass, so + # a side many orders smaller than the other still compares at 1. + transferred = households_of(mixed, ~cps_rows(mixed)) + tilted = reweighted(mixed, np.where(transferred, factor, 1.0)) + + summary = us_esi_premiums_summary(tilted, allow_transferred_rows=True) + + assert summary["transferred_household_mass_share"] > 0 + assert summary["transferred_to_source_per_household_mass_ratio"] == pytest.approx( + 1.0, rel=1e-9 + ) + + +def test_a_transferred_side_whose_mass_share_rounds_to_zero_is_still_gated( + mixed, +) -> None: + # Household masses about 1e340 apart: the transferred side's share of the + # frame underflows to zero though that side holds mass, so both gates read + # whether it is weighed from its absolute mass. A tenth of the premium on + # it must still fail them. + rows = ~cps_rows(mixed) + tilted = reweighted( + with_scaled_premiums(mixed, 0.1, rows), + np.where(households_of(mixed, rows), 1e-170, 1e170), + ) + + summary = us_esi_premiums_summary(tilted, allow_transferred_rows=True) + signal, anchor = _gates(tilted) + + assert summary["transferred_household_mass_share"] == 0.0 + assert summary["transferred_household_mass"] > 0 + assert summary["transferred_to_source_per_household_mass_ratio"] == pytest.approx( + 0.1, rel=1e-9 + ) + assert any( + "mean per positive person on the rows without raw ASEC columns" in failure + for failure in signal.failures + ) + assert any("per unit of household mass" in failure for failure in anchor.failures) + + +def _cps_policyholder_without_a_job(frame: Frame) -> np.ndarray: + """One CPS policyholder without a job whose employer pays all: a raw + MEPS-IC share outside the employed universe.""" + + person = frame.table("person") + candidates = np.flatnonzero( + cps_rows(frame) + & person["NOW_OWNGRP"].eq(1).to_numpy() + & person["NOW_HIPAID"].eq(1).to_numpy() + & ~person["PEMLR"].isin([1, 2]).to_numpy() + ) + assert candidates.size + rows = np.zeros(len(person), dtype=bool) + rows[candidates[0]] = True + return rows + + +def test_cps_rows_whose_employed_policyholders_hold_no_weight_fail_both_gates( + mixed, +) -> None: + # Weight stays on one CPS policyholder without a job and on the + # transferred rows; every employed CPS policyholder holds none. The CPS + # rows' raw anchor-universe total is then positive and their employed + # share of it zero, which the transferred rows' total would be divided by. + cps = cps_rows(mixed) + kept = _cps_policyholder_without_a_job(mixed) + starved = reweighted(mixed, np.where(households_of(mixed, cps & ~kept), 0.0, 1.0)) + + for gate in _gates(starved): + assert not gate.passed + assert gate.failures == (gate.details["structural_error"],) + assert ( + "give their employed policyholders no weighted MEPS-IC employer share" + in gate.failures[0] + ) + assert "hold no household mass" not in gate.failures[0] + + +def test_cps_rows_without_weight_fail_both_gates(mixed) -> None: + # Selection can leave the CPS side without weight. The transferred rows + # then have nothing to be priced against, and the CPS rows' raw mean has + # no weight to divide by. + cps = households_of(mixed, cps_rows(mixed)) + transferred_only = reweighted(mixed, np.where(cps, 0.0, 2.0)) + + for gate in _gates(transferred_only): + assert not gate.passed + assert gate.failures == (gate.details["structural_error"],) + assert "hold no household mass (0.0)" in gate.failures[0] + assert ( + "give their policyholders no weighted MEPS-IC employer share (0.0)" + in gate.failures[0] + ) + assert "employed policyholders no weighted" in gate.failures[0] + + +def test_cps_rows_whose_policyholders_hold_no_weight_fail_both_gates(mixed) -> None: + # Every household with a CPS policyholder holds no weight; the CPS rows + # still hold household mass through the others. Their policyholders' + # weighted MEPS-IC share, which prices every other policyholder, is zero. + cps = cps_rows(mixed) + holder = mixed.table("person")["NOW_OWNGRP"].eq(1).to_numpy() + starved = reweighted(mixed, np.where(households_of(mixed, cps & holder), 0.0, 1.0)) + + assert esi._household_masses(starved, cps)[0] > 0 + for gate in _gates(starved): + assert not gate.passed + assert gate.failures == (gate.details["structural_error"],) + assert ( + "give their policyholders no weighted MEPS-IC employer share (0.0)" + in gate.failures[0] + ) + assert "hold no household mass" not in gate.failures[0] + + +def test_a_cps_side_whose_mass_share_rounds_to_zero_still_gets_a_verdict( + mixed, +) -> None: + # Household masses about 1e340 apart, the CPS side the small one: its + # share of the frame underflows to zero though it holds mass. The anchor + # gate still grades the frame, and its private-sector cross-check, which + # scales the CPS rows' sector total by that share, is recorded without a + # value instead of dividing by zero. + cps = cps_rows(mixed) + tilted = reweighted(mixed, np.where(households_of(mixed, cps), 1e-170, 1e170)) + + summary = us_esi_premiums_summary(tilted, allow_transferred_rows=True) + _signal, anchor = _gates(tilted) + + assert summary["source_household_mass_share"] == 0.0 + assert summary["source_household_mass"] > 0 + assert anchor.details[ + "transferred_to_source_per_household_mass_ratio" + ] == pytest.approx(1.0, rel=1e-9) + cross_check = anchor.details["private_active_cross_check"] + assert np.isnan(cross_check["employer_premium_private_sector"]) + assert np.isnan(cross_check["ratio"]) + assert "share of household mass (0.0)" in cross_check["unavailable"] + # Nearly all the mass sits on the transferred rows at 1e170 times their + # weight, so the total is far off the anchor: a red verdict, not a crash. + assert not anchor.passed + assert any("from BEA NIPA 7.8" in failure for failure in anchor.failures) + + +@pytest.mark.parametrize( + ("private", "share", "named", "not_named"), + [ + # A share of household mass that scales normally: the sector total is + # what has no value, and the share is not blamed. + ( + float("nan"), + None, + "private-sector employer total (nan) is not finite", + "share of household mass", + ), + ( + float("inf"), + None, + "private-sector employer total (inf) is not finite", + "share of household mass", + ), + # Both finite, but the quotient overflows. + ( + 1e10, + 5e-324, + "total (10000000000.0) over their share of household mass (5e-324) " + "is not finite", + "is not a positive number", + ), + ], +) +def test_the_cross_check_names_the_term_without_a_finite_value( + mixed, monkeypatch, private, share, named, not_named +) -> None: + # The private-sector cross-check is recorded, not gated. When it has no + # finite value its reason names the term at fault, which is not always + # the CPS rows' share of household mass. + real = esi.us_esi_premiums_summary + + def summary(frame, **kwargs): + result = dict(real(frame, **kwargs)) + result["employer_premium_by_sector"] = dict( + result["employer_premium_by_sector"], private=private + ) + if share is not None: + result["source_household_mass_share"] = share + return result + + monkeypatch.setattr(esi, "us_esi_premiums_summary", summary) + anchor = us_esi_premiums_anchor_gate( + mixed, time_period=YEAR, allow_transferred_rows=True + ) + + cross_check = anchor.details["private_active_cross_check"] + assert np.isnan(cross_check["employer_premium_private_sector"]) + assert np.isnan(cross_check["ratio"]) + assert named in cross_check["unavailable"] + assert not_named not in cross_check["unavailable"] + + +def _with_household_factors( + frame: Frame, cps_factor: float, other_factor: float +) -> Frame: + """``frame`` with its person weights stored as they resolve, and the + weights of households with CPS rows times ``cps_factor``, the others + times ``other_factor``: household mass moves, person weights do not.""" + + person = frame.resolve_weights("person") + households = np.asarray(frame.weights_for("household").values, np.float64) + on_cps = households_of(frame, cps_rows(frame)) + tables = {entity: frame.table(entity) for entity in frame.entities} + tables.update({name: frame.link(name) for name in frame.links}) + return Frame( + tables, + frame.schema, + { + "household": Weights( + households * np.where(on_cps, cps_factor, other_factor), + WeightKind.CALIBRATED, + ), + "person": Weights(np.asarray(person.values, np.float64), person.kind), + }, + frame.strata, + mass_log=frame.mass_log, + metadata=frame.metadata, + ) + + +def test_household_mass_past_the_largest_float_fails_both_gates(mixed) -> None: + # Finite household weights can sum past the largest float. Positive + # infinity passes a ``not x > 0`` check, so without a refusal both shares + # of household mass would read 0.0 instead of about 0.5. + cps_mass, other_mass = esi._household_masses(mixed, cps_rows(mixed)) + # Each side at 1e307: the sum is finite, and the frame grades as at its + # own weights, since every premium total reads the person weights. + signal, anchor = _gates( + _with_household_factors(mixed, 1e307 / cps_mass, 1e307 / other_mass) + ) + assert signal.passed, signal.failures + assert anchor.passed, anchor.failures + assert anchor.details["source_household_mass_share"] == pytest.approx( + 0.5, rel=1e-12 + ) + for factors, named, not_named in ( + # Each side finite at about 1e308; together past the largest float. + ( + (1e308 / cps_mass, 1e308 / other_mass), + "the two sides' household mass together (inf)", + "rows' household mass (", + ), + # The CPS side alone sums past it, every household weight finite. + ( + (2.0 * (1e308 / cps_mass), 1.0), + "the source-derived rows' household mass (inf)", + "the transferred rows' household mass (", + ), + ): + frame = _with_household_factors(mixed, *factors) + assert np.isfinite(frame.weights_for("household").values).all() + for gate in _gates(frame): + assert not gate.passed + assert gate.failures == (gate.details["structural_error"],) + assert named in gate.failures[0] + assert "ran past the largest float" in gate.failures[0] + assert not_named not in gate.failures[0] + + +def _with_person_factors(frame: Frame, cps_factor: float, other_factor: float) -> Frame: + """``frame`` with its person weights stored as they resolve, those of CPS + rows times ``cps_factor`` and the others times ``other_factor``: person + weights move, household weights and so household mass do not.""" + + person = frame.resolve_weights("person") + households = frame.weights_for("household") + tables = {entity: frame.table(entity) for entity in frame.entities} + tables.update({name: frame.link(name) for name in frame.links}) + return Frame( + tables, + frame.schema, + { + "household": Weights( + np.asarray(households.values, np.float64), households.kind + ), + "person": Weights( + np.asarray(person.values, np.float64) + * np.where(cps_rows(frame), cps_factor, other_factor), + person.kind, + ), + }, + frame.strata, + mass_log=frame.mass_log, + metadata=frame.metadata, + ) + + +def _overflow_failures(frame: Frame) -> list[str]: + """Both gates' failures on ``frame``: each a single named overflow, with + every person weight and both household masses finite.""" + + assert np.isfinite(frame.resolve_weights("person").values).all() + masses = esi._household_masses(frame, cps_rows(frame)) + assert np.isfinite(masses).all() and np.isfinite(sum(masses)) + failures = [] + for gate in _gates(frame): + assert not gate.passed + assert gate.failures == (gate.details["structural_error"],) + assert "ran past the largest float" in gate.failures[0] + failures.append(gate.failures[0]) + return failures + + +def test_a_cps_weighted_meps_ic_total_past_the_largest_float_fails_both_gates( + mixed, +) -> None: + # The CPS rows' raw MEPS-IC totals read the person weights at thousands + # of dollars per unit of weight, so they can overflow while the household + # masses stay finite. The test divides the CPS premiums by the same + # factor, so the premium totals stay finite and only these terms + # overflow: the policyholders' share, then the employed policyholders' + # share too, then also the weight of the employed policyholders with a + # positive share. + base = us_esi_premiums_summary(mixed, allow_transferred_rows=True) + policyholders = float(base["raw_anchor_universe_total"]) + employed = float(base["raw_employer_share_total"]) + positive_weight = employed / float( + base["raw_employer_share_mean_per_positive_person"] + ) + labels = ( + "the source-derived rows' policyholders' weighted MEPS-IC employer share", + "their employed policyholders' weighted MEPS-IC employer share", + "their employed policyholders' weight with a positive share", + ) + for factor, overflowing in ( + (2.0 * (1e308 / policyholders), 1), + (2.0 * (1e308 / employed), 2), + (4.0 * (1e308 / positive_weight), 3), + ): + frame = _with_person_factors( + with_scaled_premiums(mixed, 1.0 / factor, cps_rows(mixed)), factor, 1.0 + ) + for failure in _overflow_failures(frame): + for label in labels[:overflowing]: + assert f"{label} (inf)" in failure + for label in labels[overflowing:]: + assert f"{label} (" not in failure + assert "weighted employer premium" not in failure + + +@pytest.mark.parametrize("transferred", [True, False], ids=["transferred", "cps"]) +def test_a_weighted_employer_premium_past_the_largest_float_fails_both_gates( + mixed, transferred: bool +) -> None: + # Person weights on one side alone, large enough that its premium total + # overflows while the household masses stay finite. That refusal comes + # before the CPS rows' MEPS-IC totals are read. + base = us_esi_premiums_summary(mixed, allow_transferred_rows=True) + if transferred: + side, other = "transferred", "source-derived" + factor = 2.0 * (1e308 / float(base["transferred_employer_premium_total"])) + frame = _with_person_factors(mixed, 1.0, factor) + else: + side, other = "source-derived", "transferred" + factor = 2.0 * (1e308 / float(base["source_employer_premium_total"])) + frame = _with_person_factors(mixed, factor, 1.0) + for failure in _overflow_failures(frame): + assert f"the {side} rows' weighted employer premium (inf)" in failure + assert f"the {other} rows' weighted employer premium (" not in failure + assert "MEPS-IC" not in failure + + +@pytest.mark.parametrize( + ("target", "named", "not_named"), + [ + # Each side's premium at about 1e308: both side totals stay finite, + # and the frame-wide total and the anchor-universe total do not. + ( + "each_side", + ( + "the weighted employer premium of both kinds of row together (inf)", + "the anchor-universe employer total (inf)", + ), + (), + ), + # The frame-wide total at 1.75e308 stays finite. The anchor-universe + # total divides it by the employed share, at most 0.95 on a frame the + # anchor gate passes, so it does not. + ( + "frame_wide", + ("the anchor-universe employer total (inf)",), + ("the weighted employer premium of both kinds of row together (",), + ), + ], +) +def test_a_combined_employer_premium_past_the_largest_float_fails_both_gates( + mixed, target: str, named: tuple[str, ...], not_named: tuple[str, ...] +) -> None: + # Every premium times one factor, weights untouched. The two side checks + # pass, so without a refusal of the sums formed from them the signal + # gate's ratios would pass and the anchor gate would blame absent MEPS-IC + # evidence for the infinite anchor-universe total. + base = us_esi_premiums_summary(mixed, allow_transferred_rows=True) + assert float(base["employed_share_of_anchor_universe"]) <= 0.95 + factor = ( + 1e308 / float(base["source_employer_premium_total"]) + if target == "each_side" + else 1.75e308 / float(base["employer_premium_total"]) + ) + frame = with_scaled_premiums(mixed, factor) + weights = np.asarray(frame.resolve_weights("person").values, np.float64) + employer = frame.table("person")[EMPLOYER].to_numpy(dtype=np.float64) + cps = cps_rows(frame) + sides = (weights[cps] @ employer[cps], weights[~cps] @ employer[~cps]) + assert np.isfinite(sides).all() + assert bool(np.isfinite(weights @ employer)) == (target == "frame_wide") + for failure in _overflow_failures(frame): + for label in named: + assert label in failure + for label in not_named: + assert label not in failure + assert "rows' weighted employer premium (" not in failure + assert "MEPS-IC" not in failure + + +def _cps_households_tilted(frame: Frame, small: np.ndarray, large: np.ndarray) -> Frame: + """CPS households of ``small`` rows at 1e-200 times their weight and of + ``large`` rows at 1e200 times it; transferred households unchanged.""" + + return reweighted( + frame, + np.where( + households_of(frame, small), + 1e-200, + np.where(households_of(frame, large), 1e200, 1.0), + ), + ) + + +def test_a_cps_side_whose_premium_per_mass_rounds_to_zero_still_gets_a_verdict( + mixed, +) -> None: + # CPS policyholders at 1e-200 times their weight, the rest of the CPS + # side at 1e200: the CPS rows' premium per unit of household mass rounds + # to zero though both its terms are positive. Their own evidence is + # intact (the policyholders compare among themselves), so the frame is + # graded, and the per-mass ratio, which divides by that rate, has no value + # and fails the anchor gate instead of dividing by zero. + cps = cps_rows(mixed) + holder = mixed.table("person")["NOW_OWNGRP"].eq(1).to_numpy() + tilted = _cps_households_tilted(mixed, cps & holder, cps & ~holder) + + summary = us_esi_premiums_summary(tilted, allow_transferred_rows=True) + signal, anchor = _gates(tilted) + + assert summary["source_employer_premium_total"] > 0 + assert summary["source_household_mass"] > 0 + assert np.isnan(summary["transferred_to_source_per_household_mass_ratio"]) + for gate in (signal, anchor): + assert not gate.passed + assert "structural_error" not in gate.details + assert any("per unit of household mass" in failure for failure in anchor.failures) + + +def test_cps_rows_whose_employed_share_rounds_to_zero_fail_both_gates( + mixed, +) -> None: + # CPS premium holders at 1e-200 times their weight, every other CPS + # person, policyholders without a job among them, at 1e200: the employed + # policyholders' part of the CPS rows' weighted MEPS-IC share is positive + # but rounds to zero, and the transferred rows' total would be divided by + # it. The frame is refused, not crashed. + cps = cps_rows(mixed) + held = cps & (mixed.table("person")[EMPLOYER].to_numpy(dtype=float) > 0) + tilted = _cps_households_tilted(mixed, held, cps & ~held) + + for gate in _gates(tilted): + assert not gate.passed + assert gate.failures == (gate.details["structural_error"],) + assert "that rounds to zero" in gate.failures[0] + assert "no weighted" not in gate.failures[0] + assert "no household mass" not in gate.failures[0] + + +def test_a_row_with_only_some_raw_columns_fails_both_gates(mixed) -> None: + transferred = np.flatnonzero(~cps_rows(mixed)) + broken = with_person_cells(mixed, transferred[:1], RAW[0], 2) + + for gate in _gates(broken): + assert not gate.passed + assert "only some of the raw ASEC fields" in gate.failures[0] + + +@pytest.mark.parametrize("lane", [False, True]) +def test_a_single_source_frame_gets_no_mixed_frame_keys(alone, lane: bool) -> None: + summary = us_esi_premiums_summary(alone, allow_transferred_rows=lane) + anchor = us_esi_premiums_anchor_gate( + alone, time_period=YEAR, allow_transferred_rows=lane + ) + + assert "transferred_rows" not in summary + assert "source_household_mass_share" not in anchor.details + assert anchor.passed, anchor.failures diff --git a/packages/microcosm-build/tests/engine_free/us/test_us_esi_premiums_route_a_differential.py b/packages/microcosm-build/tests/engine_free/us/test_us_esi_premiums_route_a_differential.py new file mode 100644 index 0000000000..f52289fa01 --- /dev/null +++ b/packages/microcosm-build/tests/engine_free/us/test_us_esi_premiums_route_a_differential.py @@ -0,0 +1,601 @@ +"""Route A's ESI premiums and gate verdicts stay main's (d2283 PR 0, d3062). + +Route A reaches ``esi_premiums.py`` in two places, both with the default +``allow_transferred_rows=False``: + +* the base builder (``tools/build_us_puf_support_base.py``) stages the + premium, runs the signal gate, runs the PUF support clone and runs the + signal gate again; and +* the release (``tools/build_us_fiscal_refresh_release.py``) runs the signal + gate on the base, then the signal and anchor gates on the calibrated export. + +On Route A-shaped frames, in one process, this module checks that the +premium column is byte-equal to main's stage expression and that every gate's +verdict is main's. Main's gates are the vendored oracle +(``test_support/microcosm_build/us_esi_premiums_main_oracle.py``). Where main +grades a frame without a structural error, the failures and every summary and +``details`` value are identical too, bit for bit. Where main refuses a frame, +only the verdict is compared: the refusal text may differ. A null raw field +is still refused with main's diagnosis (the column, its row count and the +remediation), which one test checks. + +One part of the summary's all-CPS guard is out of this module's reach: on a +frame of CPS rows the summary does not subset by ``source``. A subset by an +all-True mask holds identical values in the same order, so no in-process test +can tell the two apart. That part holds by construction, as the code reads, +not by these tests. + +Fixtures, by the branch the row rule takes: + +* F1: no ``PERIDNUM`` column, every row complete. +* F2: ``PERIDNUM`` on every row, through the production PUF clone. +* F3: red on both: premiums off the anchor, a raw column missing, a row with + some raw fields null. +* F4: ``PERIDNUM`` blank on a complete row. Main never reads it. +* F5: a row with neither the raw fields nor ``PERIDNUM``. + +The last tests check, statically, that neither tool imports the ACS local +lane's modules, which pass ``allow_transferred_rows=True``, and that the +tools' own calls to the summary and gates, the stage's call and the shadow's +bindings keep the default. +""" + +from __future__ import annotations + +import ast +import importlib.util +from collections.abc import Mapping +from functools import cache +from pathlib import Path + +import numpy as np +import pytest +from hypothesis import HealthCheck, given, settings +from hypothesis import strategies as st + +from microcosm.build.source_runtime import SourceRuntimeError +from microcosm.build.us_runtime import esi_premiums as esi +from microcosm.build.us_runtime.esi_premiums import ( + us_esi_premiums_anchor_gate, + us_esi_premiums_signal_gate, + us_esi_premiums_summary, + with_us_esi_premium_inputs, +) +from microcosm.frame import Frame +from test_support.microcosm_build import us_esi_premiums_main_oracle as main +from test_support.microcosm_build.us_esi_premiums_frames import ( + CPS_ID, + EMPLOYER, + RAW, + YEAR, + asec_arm, + calibration_factors, + puf_cloned, + reweighted, + staged, + with_person_cells, + with_scaled_premiums, + without_person_columns, +) +from test_support.paths import REPOSITORY_ROOT + +_BLANK_IDS = [None, "", " "] + + +def _identical(actual: object, expected: object, path: str) -> None: + """Equal values of equal types; floats equal bit for bit (NaN included).""" + + assert type(actual) is type(expected), f"{path}: {type(actual)} != {type(expected)}" + if isinstance(expected, Mapping): + assert list(actual) == list(expected), f"{path}: keys differ" + for key in expected: + _identical(actual[key], expected[key], f"{path}[{key!r}]") + elif isinstance(expected, (list, tuple)): + assert len(actual) == len(expected), f"{path}: lengths differ" + for index, (left, right) in enumerate(zip(actual, expected, strict=True)): + _identical(left, right, f"{path}[{index}]") + elif isinstance(expected, (float, np.floating)): + assert np.float64(actual).tobytes() == np.float64(expected).tobytes(), ( + f"{path}: {actual!r} != {expected!r}" + ) + else: + assert actual == expected, f"{path}: {actual!r} != {expected!r}" + + +def _mains_verdicts(frame: Frame, *, anchor: bool = True) -> list[bool]: + """Grade ``frame`` with the live gates and main's; return main's verdicts. + + Signal gate first, then the anchor gate, as the release runs them. The + live gates take their default, as every Route A caller does. + """ + + try: + expected_summary = main.us_esi_premiums_summary(frame) + except SourceRuntimeError: + with pytest.raises(SourceRuntimeError): + us_esi_premiums_summary(frame) + else: + _identical(us_esi_premiums_summary(frame), expected_summary, "summary") + pairs = [ + (us_esi_premiums_signal_gate(frame), main.us_esi_premiums_signal_gate(frame)) + ] + if anchor: + pairs.append( + ( + us_esi_premiums_anchor_gate(frame, time_period=YEAR), + main.us_esi_premiums_anchor_gate(frame, time_period=YEAR), + ) + ) + verdicts = [] + for live, expected in pairs: + assert live.name == expected.name + assert live.passed == expected.passed, (live.failures, expected.failures) + if "structural_error" not in expected.details: + assert live.failures == expected.failures + _identical(dict(live.details), dict(expected.details), "details") + verdicts.append(expected.passed) + return verdicts + + +def _mains_stage_premiums(frame: Frame) -> np.ndarray: + """Main's stage expression on the table ``with_us_esi_premium_inputs`` builds. + + ``derive_us_employer_esi_premiums_from_manifest`` at main 5499382772: + ``_anchor(year) / float(weights @ raw)`` times each raw share in the + employed-policyholder universe, zero elsewhere. Recomputed in this process, + so both sides make the same BLAS call. + """ + + person = esi._person_with_state(frame) + person[esi._PERSON_WEIGHT_COLUMN] = frame.resolve_weights("person").values + codes, raw, _premium, _contribution = esi._person_raw_shares(person) + weights = esi._person_weights(person) + scale = esi._anchor(YEAR) / float(weights @ raw) + return np.where(codes.universe, raw * scale, 0.0) + + +@pytest.fixture( + scope="module", + params=[False, True], + ids=["F1_no_id_column", "F2_id_on_every_row"], +) +def route_a(request) -> dict[str, object]: + raw = asec_arm(record_ids=request.param) + pre_clone = staged(raw) + base = puf_cloned(pre_clone) + return { + "record_ids": request.param, + "raw": raw, + "pre_clone": pre_clone, + "base": base, + "export": reweighted(base, calibration_factors(base)), + } + + +@pytest.fixture(scope="module") +def f2() -> dict[str, Frame]: + pre_clone = staged(asec_arm()) + base = puf_cloned(pre_clone) + return { + "pre_clone": pre_clone, + "base": base, + "export": reweighted(base, calibration_factors(base)), + } + + +def test_the_fixtures_have_route_a_shape(route_a) -> None: + for name in ("pre_clone", "base", "export"): + person = route_a[name].table("person") + assert person[list(RAW)].notna().all().all() + if route_a["record_ids"]: + # The production PUF clone copies the CPS record id to every row. + assert person[CPS_ID].notna().all() + else: + assert CPS_ID not in person.columns + assert len(route_a["base"].table("person")) == 2 * len( + route_a["pre_clone"].table("person") + ) + + +def test_the_stage_writes_mains_premium_bytes(route_a) -> None: + live = route_a["pre_clone"].table("person")[EMPLOYER].to_numpy() + expected = _mains_stage_premiums(route_a["raw"]) + + assert live.dtype == expected.dtype == np.float64 + assert np.array_equal(live, expected) + assert live.tobytes() == expected.tobytes() + # The PUF clone carries each person's premium to both support rows. + cloned = route_a["base"].table("person")[EMPLOYER].to_numpy() + assert cloned.tobytes() == np.concatenate([expected, expected]).tobytes() + + +def test_a_staged_frame_is_returned_unchanged(route_a) -> None: + # The idempotent branch grades the frame with the default signal gate. + for name in ("pre_clone", "base"): + frame = route_a[name] + assert with_us_esi_premium_inputs(frame, seed=0, time_period=YEAR) is frame + + +def test_the_base_builder_order_gets_mains_verdicts(route_a) -> None: + # Stage, signal gate, PUF support clone, signal gate. + assert _mains_verdicts(route_a["pre_clone"], anchor=False) == [True] + assert _mains_verdicts(route_a["base"], anchor=False) == [True] + + +def test_the_release_order_gets_mains_verdicts(route_a) -> None: + # Signal gate on the base, then signal and anchor gates on the export. + assert _mains_verdicts(route_a["base"], anchor=False) == [True] + assert _mains_verdicts(route_a["export"]) == [True, True] + + +@pytest.mark.parametrize( + ("edit", "expected"), + [ + (lambda frame: with_scaled_premiums(frame, 1.2), [True, False]), + (lambda frame: without_person_columns(frame, ["NOEMP"]), [False, False]), + ( + lambda frame: with_person_cells(frame, [5], [RAW[0], RAW[3]], np.nan), + [False, False], + ), + ], + ids=["F3_premiums_off_the_anchor", "F3_raw_column_missing", "F3_partial_row"], +) +def test_frames_main_refuses_are_refused(route_a, edit, expected) -> None: + assert _mains_verdicts(edit(route_a["base"]), anchor=False) == expected[:1] + assert _mains_verdicts(edit(route_a["export"])) == expected + + +_NOT_RESTORED = ( + "the Census column was not restored for every vintage " + "(asec_census_person_columns) and is never defaulted" +) + + +def test_a_null_raw_field_is_refused_with_mains_diagnosis(route_a) -> None: + # The base builder prints this text in its SystemExit and the release + # writes it to esi_premiums.json, so it keeps main's diagnosis: the column, + # its row count and the remediation. + for name, anchor in (("pre_clone", False), ("base", False), ("export", True)): + frame = with_person_cells(route_a[name], [7], "NOW_HIPAID", np.nan) + with pytest.raises(SourceRuntimeError) as refused: + us_esi_premiums_summary(frame) + gates = [us_esi_premiums_signal_gate(frame)] + if anchor: + gates.append(us_esi_premiums_anchor_gate(frame, time_period=YEAR)) + for gate in gates: + assert not gate.passed + assert gate.failures[0] == gate.details["structural_error"] + for text in (str(refused.value), *(gate.failures[0] for gate in gates)): + assert "1 row(s) lack some of the raw ASEC fields" in text + assert "NOW_HIPAID has 1 missing row(s)" in text + # Only the incomplete column is named. + assert not any(column in text for column in RAW if column != "NOW_HIPAID") + assert _NOT_RESTORED in text + # The keyword is the ACS local lane's, not a Route A remedy. + assert ( + "Only a frame that holds transferred ACS rows needs " + "allow_transferred_rows=True; on any other frame, restore the " + "fields." in text + ) + # Main says the same of the same row. + assert _NOT_RESTORED in main.us_esi_premiums_signal_gate(frame).failures[0] + # Several columns: each is named with its own count, and the lead + # count is rows, not cells (row 7 lacks both fields). + frame = with_person_cells( + with_person_cells(route_a["export"], [7], "NOW_HIPAID", np.nan), + [7, 9], + "PEMLR", + np.nan, + ) + text = us_esi_premiums_signal_gate(frame).failures[0] + assert "2 row(s) lack some of the raw ASEC fields" in text + assert "NOW_HIPAID has 1 missing row(s), PEMLR has 2 missing row(s);" in text + assert ( + "the Census columns were not restored for every vintage " + "(asec_census_person_columns) and are never defaulted" in text + ) + + +@pytest.mark.parametrize("blank", _BLANK_IDS) +def test_f4_a_blank_record_id_on_a_complete_row_keeps_mains_verdict(f2, blank) -> None: + for name, anchor in (("pre_clone", False), ("base", False), ("export", True)): + frame = with_person_cells(f2[name], [7], CPS_ID, blank) + assert _mains_verdicts(frame, anchor=anchor) == [True] * (1 + anchor) + # Grading transferred rows reads the id, and a row with the raw fields + # but no id is neither kind. + frame = with_person_cells(f2["export"], [7], CPS_ID, blank) + with pytest.raises(SourceRuntimeError, match="without a CPS record id"): + us_esi_premiums_summary(frame, allow_transferred_rows=True) + + +def test_f5_a_row_with_neither_raw_fields_nor_record_id_keeps_mains_verdict( + f2, +) -> None: + for name, anchor in (("pre_clone", False), ("base", False), ("export", True)): + frame = with_person_cells(f2[name], [7], [*RAW, CPS_ID], None) + assert _mains_verdicts(frame, anchor=anchor) == [False] * (1 + anchor) + assert "structural_error" in us_esi_premiums_signal_gate(frame).details + # Only a caller that grades transferred rows reads it as one. + frame = with_person_cells(f2["export"], [7], [*RAW, CPS_ID], None) + summary = us_esi_premiums_summary(frame, allow_transferred_rows=True) + assert summary["transferred_rows"] == 1 + + +def test_the_lane_keyword_grades_an_all_cps_frame_as_main_does(route_a) -> None: + # Every row a CPS row: the keyword changes nothing, bit for bit. + for name, anchor in (("pre_clone", False), ("base", False), ("export", True)): + frame = route_a[name] + _identical( + us_esi_premiums_summary(frame, allow_transferred_rows=True), + main.us_esi_premiums_summary(frame), + "summary", + ) + live = [us_esi_premiums_signal_gate(frame, allow_transferred_rows=True)] + expected = [main.us_esi_premiums_signal_gate(frame)] + if anchor: + live.append( + us_esi_premiums_anchor_gate( + frame, time_period=YEAR, allow_transferred_rows=True + ) + ) + expected.append(main.us_esi_premiums_anchor_gate(frame, time_period=YEAR)) + for left, right in zip(live, expected, strict=True): + assert left.passed and right.passed + _identical(dict(left.details), dict(right.details), "details") + + +# --- any mix of complete, incomplete and blank-id rows ---------------------- + + +@cache +def _small_export(record_ids: bool) -> Frame: + base = puf_cloned(staged(asec_arm(60, record_ids=record_ids))) + return reweighted(base, calibration_factors(base)) + + +_ROW_EDITS = ("blank_id", "some_fields", "all_fields", "all_fields_and_id") + + +@st.composite +def _edited_frames(draw) -> Frame: + record_ids = draw(st.booleans()) + frame = _small_export(record_ids) + rows = len(frame.table("person")) + edits = draw( + st.lists( + st.tuples( + st.integers(min_value=0, max_value=rows - 1), + st.sampled_from(_ROW_EDITS), + st.lists(st.sampled_from(RAW), min_size=1, max_size=len(RAW) - 1), + st.sampled_from(_BLANK_IDS), + ), + max_size=4, + ) + ) + for row, edit, fields, blank in edits: + if edit == "blank_id": + if record_ids: + frame = with_person_cells(frame, [row], CPS_ID, blank) + elif edit == "some_fields": + frame = with_person_cells(frame, [row], sorted(set(fields)), np.nan) + elif edit == "all_fields": + frame = with_person_cells(frame, [row], list(RAW), np.nan) + else: + columns = [*RAW, CPS_ID] if record_ids else list(RAW) + frame = with_person_cells(frame, [row], columns, None) + return frame + + +@settings( + max_examples=60, + deadline=None, + derandomize=True, + suppress_health_check=[HealthCheck.too_slow], +) +@given(_edited_frames()) +def test_any_mix_of_rows_gets_mains_verdict(frame: Frame) -> None: + """Any mix of complete, partial, field-less and blank-id rows: main's verdict. + + It compares statistics too wherever main grades without a structural + error, but it is not the evidence that they are bit-equal: a mutant that + swapped main's ``other_policyholder_employer_total`` expression for + #1199's passed it. The named F1/F2 tests (the base builder and release + orders, and the lane keyword on an all-CPS frame) pin the bit-equal + statistics. + """ + + _mains_verdicts(frame) + + +# --- Route A's tools never reach the ACS local lane --------------------------- + +#: The ACS local lane's modules, which grade with ``allow_transferred_rows=True``. +_LANE_MODULES = ( + "microcosm.build.us_runtime.acs_multispine", + "microcosm.build.us_runtime.acs_local_esi_premiums", +) +_ROUTE_A_TOOLS = ( + "build_us_puf_support_base.py", + "build_us_fiscal_refresh_release.py", +) + + +@cache +def _package_modules() -> dict[str, Path]: + """Every module under ``packages/*/src``, by its dotted name.""" + + modules: dict[str, Path] = {} + packages = REPOSITORY_ROOT / "packages" + for source in sorted(packages.glob("*/src/**/*.py")): + parts = source.relative_to(packages).parts[2:] + name = ( + parts[:-1] if parts[-1] == "__init__.py" else (*parts[:-1], parts[-1][:-3]) + ) + modules[".".join(name)] = source + return modules + + +def _static_imports(name: str | None, source: Path) -> set[str]: + """The package modules ``source`` imports anywhere in its body (a literal + ``import_module`` included), with every package initializer they run.""" + + modules = _package_modules() + package = name if source.name == "__init__.py" else (name or "").rpartition(".")[0] + found: set[str] = set() + for node in ast.walk(ast.parse(source.read_bytes(), filename=str(source))): + if isinstance(node, ast.Import): + names = [alias.name for alias in node.names] + elif isinstance(node, ast.ImportFrom): + base = ( + importlib.util.resolve_name( + "." * node.level + (node.module or ""), package + ) + if node.level + else node.module or "" + ) + names = [base, *(f"{base}.{alias.name}" for alias in node.names)] + elif ( + isinstance(node, ast.Call) + and getattr(node.func, "attr", getattr(node.func, "id", None)) + == "import_module" + and node.args + and isinstance(node.args[0], ast.Constant) + and isinstance(node.args[0].value, str) + ): + names = [node.args[0].value] + else: + continue + for imported in names: + parts = imported.split(".") + found.update( + prefix + for prefix in ( + ".".join(parts[:end]) for end in range(1, len(parts) + 1) + ) + if prefix in modules + ) + return found + + +@pytest.mark.parametrize("tool", _ROUTE_A_TOOLS) +def test_route_as_tools_never_import_the_acs_local_lane(tool: str) -> None: + """Route A keeps the default keyword because its tools never reach the + lane's modules. Static: the transitive package imports of the tool, read + from the source (nothing is imported), package initializers included.""" + + modules = _package_modules() + closure: set[str] = set() + pending = list(_static_imports(None, REPOSITORY_ROOT / "tools" / tool)) + while pending: + name = pending.pop() + if name not in closure: + closure.add(name) + pending.extend(_static_imports(name, modules[name]) - closure) + + # Not vacuous: the tool reaches the stage and gates it grades with. + assert "microcosm.build.us_runtime.esi_premiums" in closure + assert len(closure) > 100 + assert not set(_LANE_MODULES) & closure + + +# --- Route A's call sites keep the default keyword ---------------------------- + +_KEYWORD = "allow_transferred_rows" +#: The functions that take the keyword. +_GRADERS = ( + "us_esi_premiums_summary", + "us_esi_premiums_signal_gate", + "us_esi_premiums_anchor_gate", +) +_US_RUNTIME = ( + REPOSITORY_ROOT / "packages/microcosm-build/src/microcosm/build/us_runtime" +) + + +def _called_name(call: ast.Call) -> str | None: + return getattr(call.func, "id", getattr(call.func, "attr", None)) + + +def _grader_calls(tree: ast.AST) -> list[ast.Call]: + return [ + node + for node in ast.walk(tree) + if isinstance(node, ast.Call) and _called_name(node) in _GRADERS + ] + + +def _keyword_lines(tree: ast.AST) -> list[int]: + """Lines that pass the keyword to any call or spell it as a string.""" + + return sorted( + { + node.lineno + for node in ast.walk(tree) + if (isinstance(node, ast.keyword) and node.arg == _KEYWORD) + or (isinstance(node, ast.Constant) and node.value == _KEYWORD) + } + ) + + +@pytest.mark.parametrize("tool", _ROUTE_A_TOOLS) +def test_route_as_tools_call_the_gates_with_the_default_keyword(tool: str) -> None: + """Static, from the source (it imports nothing): the tool calls the ESI + summary and gates by their own names, passes ``allow_transferred_rows`` + to no call, spells it in no string and passes no ``**`` keywords to them, + so each call grades with the default. The differential above calls the + gates directly; this pins the tools' own call sites.""" + + tree = ast.parse((REPOSITORY_ROOT / "tools" / tool).read_bytes(), filename=tool) + calls = _grader_calls(tree) + called = {_called_name(call) for call in calls} + # Not vacuous: the signal gate runs in both tools, the anchor gate in the + # release. + assert "us_esi_premiums_signal_gate" in called + if tool == "build_us_fiscal_refresh_release.py": + assert "us_esi_premiums_anchor_gate" in called + assert _keyword_lines(tree) == [] + assert [ + call.lineno + for call in calls + if any(keyword.arg is None for keyword in call.keywords) + ] == [] + aliased = [ + alias.name + for node in ast.walk(tree) + if isinstance(node, ast.ImportFrom) + for alias in node.names + if alias.name in _GRADERS and alias.asname not in (None, alias.name) + ] + assert aliased == [] + + +def test_the_stage_and_the_shadow_bindings_keep_the_default_keyword() -> None: + """Static: inside ``esi_premiums.py`` only the two gates pass the keyword, + and only their own parameter on to the summary; the stage's own gate call + (``with_us_esi_premium_inputs``, which the base builder runs) passes none. + The battery bindings Route A's shadow evaluates never name it.""" + + tree = ast.parse((_US_RUNTIME / "esi_premiums.py").read_bytes()) + pass_through = ast.dump( + ast.keyword(arg=_KEYWORD, value=ast.Name(id=_KEYWORD, ctx=ast.Load())) + ) + callers = [] + for function in tree.body: + if not isinstance(function, ast.FunctionDef): + continue + for call in _grader_calls(function): + callers.append(function.name) + keywords = [ + ast.dump(keyword) + for keyword in call.keywords + if keyword.arg in (None, _KEYWORD) + ] + if function.name in _GRADERS[1:]: + assert keywords == [pass_through], (function.name, call.lineno) + else: + assert keywords == [], (function.name, call.lineno) + assert "with_us_esi_premium_inputs" in callers + assert ( + _keyword_lines(ast.parse((_US_RUNTIME / "battery_bindings.py").read_bytes())) + == [] + ) diff --git a/packages/microcosm-build/tests/engine_free/us/test_us_modal_build_programs_telemetry.py b/packages/microcosm-build/tests/engine_free/us/test_us_modal_build_programs_telemetry.py index 471028e8cb..be1fe0f11a 100644 --- a/packages/microcosm-build/tests/engine_free/us/test_us_modal_build_programs_telemetry.py +++ b/packages/microcosm-build/tests/engine_free/us/test_us_modal_build_programs_telemetry.py @@ -477,6 +477,8 @@ def test_the_acs_staging_builder_records_its_phases_up_to_a_failure( location_seed=0, location_clones=1, block_ladder=None, + # microcosm#454: the ESI premium is enforced by default. + allow_esi_premium_gaps=False, ) base = SimpleNamespace(weights_for=lambda unit: SimpleNamespace(total=1.0)) monkeypatch.setattr(module, "_parse_args", lambda argv: args) @@ -498,6 +500,7 @@ def test_the_acs_staging_builder_records_its_phases_up_to_a_failure( "_require_ssi_disability_donor", "_require_donor_work_experience", "_require_dense_donor_coverage", + "_qualify_esi_premium_donor", ): monkeypatch.setattr(module, check, _passes) monkeypatch.setattr(module, "declared_acs_transfer_target_families", tuple) diff --git a/packages/microcosm-build/tests/engine_free/us/test_us_modal_stage_acs_multispine_staging.py b/packages/microcosm-build/tests/engine_free/us/test_us_modal_stage_acs_multispine_staging.py index 03477b59dc..9bf44aff29 100644 --- a/packages/microcosm-build/tests/engine_free/us/test_us_modal_stage_acs_multispine_staging.py +++ b/packages/microcosm-build/tests/engine_free/us/test_us_modal_stage_acs_multispine_staging.py @@ -61,6 +61,8 @@ "--location-seed", "--location-clones", "--block-ladder", + # microcosm#454: a Modal staging run always enforces the ESI premium. + "--allow-esi-premium-gaps", } @@ -192,6 +194,7 @@ def test_only_all_is_registered(stage: str) -> None: "puma_ladder", "donor_release_manifest", "allow_dirty", + "allow_esi_premium_gaps", ], ) def test_plan_cannot_control_sources_or_outputs(option: str) -> None: diff --git a/packages/microcosm-build/tests/engine_free/us/test_us_modal_stage_plan_tool.py b/packages/microcosm-build/tests/engine_free/us/test_us_modal_stage_plan_tool.py index 944df1ac3d..ff665739b4 100644 --- a/packages/microcosm-build/tests/engine_free/us/test_us_modal_stage_plan_tool.py +++ b/packages/microcosm-build/tests/engine_free/us/test_us_modal_stage_plan_tool.py @@ -338,6 +338,46 @@ def test_package_argv_adds_release_root_and_bool_flags() -> None: assert "--allow-dirty" not in argv +@pytest.mark.parametrize("stage", ["finalize", "package"]) +def test_the_esi_premium_waiver_reaches_the_stages_that_grade_it(stage) -> None: + # microcosm#454: a diagnostic run on a checkpoint without the premium + # needs the waiver forwarded; a release plan leaves it unset. + data = _plan_data(stage) + data["options"] = {"allow_esi_premium_gaps": True} + assert "--allow-esi-premium-gaps" in plan_lib.planned_argv( + plan_lib.parse_plan(data) + ) + data["options"] = {"allow_esi_premium_gaps": False} + assert "--allow-esi-premium-gaps" not in plan_lib.planned_argv( + plan_lib.parse_plan(data) + ) + assert "--allow-esi-premium-gaps" not in plan_lib.planned_argv( + plan_lib.parse_plan(_plan_data(stage)) + ) + + +def test_modal_staging_never_forwards_the_esi_premium_waiver() -> None: + # microcosm#454: the staging waiver is the builder's own diagnostic flag. + # A staging plan cannot name it, and the runner owns it so that no + # option can reach it, so every Modal staging run qualifies the donor + # and enforces both ESI gates. + staging = plan_lib.US_ACS_MULTISPINE_STAGING + assert "allow_esi_premium_gaps" not in staging.options + assert "--allow-esi-premium-gaps" in staging.owned_flags + assert "--allow-esi-premium-gaps" not in { + option.flag for option in staging.options.values() + } + # The release stages that grade the premium are the only ones that take it. + assert { + tool.name + for tool in plan_lib.TOOLS.values() + if any( + option.flag == "--allow-esi-premium-gaps" + for option in tool.options.values() + ) + } == {plan_lib.US_ACS_LOCAL_RELEASE.name} + + def test_argv_paths_are_stable_across_stages() -> None: # run_identity.json records the staging path and every later stage # re-verifies the staging digest, so staged paths must not move. 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 44664623b6..5d76acfe5e 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 @@ -253,6 +253,12 @@ # Exact source-universe validator/receipt owner; no population treatment. "acs_income_universe.py", "acs_inputs.py", + # Legacy local-lane employer premium (#454): donor qualification, a + # one-family transfer plan and narrow views for the pool anchor and + # the two ESI gates. It selects donors by support role and tells the + # rows apart by whether the raw ASEC fields are present, never by a + # spine or support-channel column, so it owns no provenance boundary. + "acs_local_esi_premiums.py", # Legacy source-hours completion and release gate; outside the registry. "acs_local_hours.py", # Legacy local-lane take-up fill and release gate; outside the registry. @@ -279,6 +285,11 @@ # receipt and grade helpers (#1022); tag-free, the take-up stage # passes the spine masks. Outside the registry. "acs_local_vehicles_head_start.py", + # Legacy local-lane WIC take-up draw on the ACS-only frame before + # pooling, and its completeness check (#1154); tag-free: it runs before + # origin tags exist, and the take-up gate grades both spines. Outside + # the registry. + "acs_local_wic_take_up.py", # Reviewed-fill consumer register loader, dependency walk and release # gate (#1022); reads fill manifests and the packaged register, never a # frame. Outside the registry. @@ -344,8 +355,11 @@ "engine_lifecycle.py", # MEPS-IC employer-premium input (#454): a base-builder pre-clone # stage keyed on restored ASEC coverage fields, - # not yet a multispine pool operator. Reads no spine or support-channel - # column and remains subject to the all-runtime source-identity scan. + # not yet a multispine pool operator. Its gates also grade frames that + # mix CPS rows with rows a transfer filled (allow_transferred_rows, + # d2283), telling them apart by whether the raw ASEC fields are + # present. Reads no spine or support-channel column and remains + # subject to the all-runtime source-identity scan. "esi_premiums.py", "exact_k_ladder.py", # Calibration/selection seam; no source treatment. "fiscal_targets.py", @@ -3555,12 +3569,13 @@ def test_acs_local_hours_provenance_is_limited_to_reviewed_boundaries() -> None: def test_acs_local_take_up_provenance_is_limited_to_reviewed_boundaries() -> None: """Pin the ACS-row take-up fill and per-origin take-up gate (#1019). - Each boundary reads exactly three origin tags, spm_unit, person and - household: the engine-free fills (#1022) are person- and SPM-unit-level, - and the ACS VEH availability receipt and owned-count grade are - household-level. Their helpers, including the tag-free - acs_local_vehicles_head_start module, receive the resulting masks and - read no tag themselves. + Each boundary reads exactly four origin tags, spm_unit, person, household + and tax_unit: the engine-free fills (#1022) are person- and SPM-unit-level, + the ACS VEH availability receipt and owned-count grade are + household-level, and EITC take-up (#1675) is tax-unit-level. Their + helpers, including the tag-free acs_local_vehicles_head_start module, + receive the resulting masks and read no tag themselves, and the WIC + take-up module (#1154) runs before pooling, so it reads none either. """ source = (_US_RUNTIME / "acs_local_take_up.py").read_text() @@ -3570,7 +3585,7 @@ def test_acs_local_take_up_provenance_is_limited_to_reviewed_boundaries() -> Non ) assert tuple( sorted(caller for caller, _line in _function_callers(source, "spine_column")) - ) == tuple(sorted(boundaries * 3)) + ) == tuple(sorted(boundaries * 4)) tree = ast.parse(source) remaining = ast.Module( body=[ @@ -3584,9 +3599,10 @@ def test_acs_local_take_up_provenance_is_limited_to_reviewed_boundaries() -> Non type_ignores=[], ) assert not _source_spine_accesses(ast.unparse(remaining)) - helpers = (_US_RUNTIME / "acs_local_vehicles_head_start.py").read_text() - assert not _function_callers(helpers, "spine_column") - assert not _source_spine_accesses(helpers) + for module in ("acs_local_vehicles_head_start.py", "acs_local_wic_take_up.py"): + helpers = (_US_RUNTIME / module).read_text() + assert not _function_callers(helpers, "spine_column"), module + assert not _source_spine_accesses(helpers), module def test_acs_local_immigration_provenance_is_limited_to_reviewed_boundaries() -> None: diff --git a/packages/microcosm-build/tests/engine_workflow/us/test_us_acs_county_agi_support_engine.py b/packages/microcosm-build/tests/engine_workflow/us/test_us_acs_county_agi_support_engine.py new file mode 100644 index 0000000000..a21402d9dd --- /dev/null +++ b/packages/microcosm-build/tests/engine_workflow/us/test_us_acs_county_agi_support_engine.py @@ -0,0 +1,325 @@ +"""The pre-R2 county AGI check against R2's SOI AGI measure (microcosm#922). + +``tools/check_us_acs_county_agi_support.py`` computes each household's AGI +with R2's projection, reviewed-null fill and dataset builder, in household +chunks. The engine counts only the positive income sources of a tax unit's +head and spouse (``irs_gross_income``), and only an adult can be a head or a +spouse, so income held by a dependent, or by a tax unit without an adult, +adds nothing. This test runs the check's engine pass on six households and +compares it with the production SOI materializer's AGI measure, the value +R2's state AGI row stores (#1660 review). +""" + +from __future__ import annotations + +import importlib.util +import json +import sys + +import numpy as np +import pandas as pd + +from microcosm.frame import US_SCHEMA, Frame, WeightKind, Weights +from test_support.microcosm_build.us_batched_target_materialization import ( + _load_builder_module, + _soi, +) +from test_support.paths import paths_for + +_TEST_PATHS = paths_for("microcosm-build") +#: Household AGI: a dependent's wages (1), a head's wages (2), a retiree's +#: interest beside a dependent's wages (3), a spouse's wages (4), a tax unit +#: of one 16-year-old with wages (5), and a capital loss alone (6). +_EXPECTED_AGI = [0.0, 30_000.0, 100.0, 20_000.0, 0.0, -2_000.0] + + +def _check(): + path = _TEST_PATHS.repository / "tools" / "check_us_acs_county_agi_support.py" + spec = importlib.util.spec_from_file_location("check_us_county_agi_engine", path) + module = importlib.util.module_from_spec(spec) + assert spec.loader is not None + sys.modules[spec.name] = module + spec.loader.exec_module(module) + return module + + +def _frame(*, with_nulls: bool) -> Frame: + household = np.asarray([1, 1, 2, 3, 3, 4, 4, 5, 6, 6], "int64") + tax_unit = np.asarray([10, 10, 20, 30, 30, 40, 40, 50, 60, 60], "int64") + interest = [0.0, 0.0, 0.0, 100.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0] + if with_nulls: + # A registered null: the fill step gives it the engine default, 0. + interest[0] = np.nan + persons = pd.DataFrame( + { + "person_id": np.arange(1, 11, dtype="int64"), + "person_household_id": household, + "person_tax_unit_id": tax_unit, + "person_spm_unit_id": tax_unit * 10, + "person_family_id": tax_unit * 100, + "person_marital_unit_id": np.asarray( + [1, 2, 3, 4, 5, 6, 6, 7, 8, 9], "int64" + ) + * 10_000, + "age": np.asarray( + [40.0, 10.0, 40.0, 70.0, 16.0, 40.0, 38.0, 16.0, 50.0, 12.0] + ), + "employment_income_before_lsr": np.asarray( + [0.0, 5_000.0, 30_000.0, 0.0, 8_000.0, 0.0, 20_000.0, 6_000.0, 0.0, 0.0] + ), + "taxable_interest_income": np.asarray(interest), + "short_term_capital_gains": np.asarray( + [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, -2_000.0, 0.0] + ), + } + ) + tables = {"person": persons} + for entity in ("tax_unit", "spm_unit", "family", "marital_unit"): + ids = np.unique(persons[f"person_{entity}_id"].to_numpy()) + tables[entity] = pd.DataFrame({f"{entity}_id": ids}) + if with_nulls: + # A runtime-owned take-up flag that R2's stages fill on ACS rows and + # the AGI does not read: the check holds it back while its nulls are + # on ACS rows only. + tables["spm_unit"]["takes_up_snap_if_eligible"] = pd.Series( + [True, None, True, True, True, True], dtype=object + ) + tables["spm_unit"]["spm_unit_spine"] = "acs_2024_1yr" + tables["household"] = pd.DataFrame( + { + "household_id": np.arange(1, 7, dtype="int64"), + "state_fips": np.full(6, 6, dtype="int64"), + } + ) + return Frame( + tables, + US_SCHEMA, + {"household": Weights(np.ones(6), WeightKind.DESIGN)}, + ) + + +def test_no_column_an_r2_stage_fills_is_an_agi_input() -> None: + """The check holds back a null stage-filled column on ACS rows because + the AGI does not read it in R2's year; an engine release whose AGI read + one would make the check refuse a staging file R2 accepts (review of + #1660). The closure follows reads inside the engine's helper functions: + the self-employed health insurance deduction reads its two Form 7206 + inputs only in the module-level ``form_7206_line_13`` (microcosm#1675).""" + + from policyengine_us import CountryTaxBenefitSystem + + from microcosm.frame.adapters.policyengine_us import ( + PolicyEngineUSVariableMetadataIndex, + ) + + check = _check() + release = check._release_tool() + unread = check.unread_variables(release.PERIOD, system=CountryTaxBenefitSystem()) + inputs = check.agi_engine_inputs( + PolicyEngineUSVariableMetadataIndex(follow_helpers=True), unread=unread + ) + gapped = check.agi_engine_inputs( + PolicyEngineUSVariableMetadataIndex(), unread=unread + ) + stage_filled = check.reviewed_fills.stage_filled_never_default(release) + + assert "employment_income_before_lsr" in inputs + form_7206 = { + "s_corp_shareholder_medicare_wages", + "self_employed_health_insurance_plan_business", + } + assert form_7206 <= inputs - gapped + assert stage_filled + assert inputs.isdisjoint(column for _entity, column in stage_filled) + + +def test_the_closure_stops_at_the_behavioral_responses_a_pass_without_a_reform_skips() -> ( + None +): + """Through the engine's ``get_behavioral_response_measurements`` helper, + the behavioral responses read ``household_net_income``, and through it + the take-up flags R2's stages fill. An engine pass without a reform has no + baseline, so the responses return 0 before reading anything and the labor + supply elasticity effects are never computed (microcosm#1675).""" + + from policyengine_us import CountryTaxBenefitSystem, Simulation + + from microcosm.frame.adapters.policyengine_us import ( + PolicyEngineUSVariableMetadataIndex, + ) + + check = _check() + release = check._release_tool() + system = CountryTaxBenefitSystem() + index = PolicyEngineUSVariableMetadataIndex(follow_helpers=True) + stage_filled = { + column + for _entity, column in check.reviewed_fills.stage_filled_never_default(release) + } + deductions = check.unread_deductions(release.PERIOD, system=system) + through_responses = check.agi_engine_inputs(index, unread=deductions) + assert not through_responses.isdisjoint(stage_filled) + assert check.unread_variables(release.PERIOD, system=system) == ( + *deductions, + *check.NO_REFORM_UNREAD, + ) + stopped = check.agi_engine_inputs( + index, unread=check.unread_variables(release.PERIOD, system=system) + ) + assert stopped.isdisjoint(stage_filled) + + y = str(release.PERIOD) + members = {"members": ["filer"]} + simulation = Simulation( + situation={ + "people": { + "filer": { + "age": {y: 40}, + "employment_income_before_lsr": {y: 50_000}, + "self_employment_income_before_lsr": {y: 10_000}, + "long_term_capital_gains_before_response": {y: 20_000}, + "weekly_hours_worked_before_lsr": {y: 40}, + } + }, + "tax_units": {"tax_unit": members}, + "spm_units": {"spm_unit": members}, + "families": {"family": members}, + "marital_units": {"marital_unit": members}, + "households": {"household": {**members, "state_code_str": {y: "TX"}}}, + } + ) + assert simulation.baseline is None + for name in ( + "labor_supply_behavioral_response", + "capital_gains_behavioral_response", + "weekly_hours_worked_behavioural_response", + ): + assert float(simulation.calculate(name, release.PERIOD)[0]) == 0.0, name + assert float(simulation.calculate("adjusted_gross_income", release.PERIOD)[0]) > 0 + for name in ("income_elasticity_lsr", "substitution_elasticity_lsr"): + assert simulation.get_holder(name).get_known_periods() == [], name + + +def test_the_closure_stops_only_at_a_deduction_whose_year_does_not_list_it() -> None: + """policyengine-us 2.145.3's 2020 charitable deduction for non-itemizers + reads the itemization choice in 2020 alone: 2020 lists it and it lowers + AGI there, while in R2's year it is not listed and is 0, so the walk may + stop at it.""" + + from policyengine_us import CountryTaxBenefitSystem, Simulation + + from microcosm.frame.adapters.policyengine_us import ( + PolicyEngineUSVariableMetadataIndex, + ) + + check = _check() + release = check._release_tool() + system = CountryTaxBenefitSystem() + assert check.unread_deductions(2020, system=system) == () + unread = check.unread_deductions(release.PERIOD, system=system) + assert unread == ("charitable_contributions_ald",) + + index = PolicyEngineUSVariableMetadataIndex(follow_helpers=True) + static = check.agi_engine_inputs(index) + assert check.agi_engine_inputs(index, unread=unread) <= static + + for year, deduction in ((2020, 300.0), (release.PERIOD, 0.0)): + y = str(year) + members = {"members": ["filer"]} + simulation = Simulation( + situation={ + "people": { + "filer": { + "age": {y: 40}, + "employment_income": {y: 50_000}, + "charitable_cash_donations": {y: 1_000}, + } + }, + "tax_units": {"tax_unit": members}, + "spm_units": {"spm_unit": members}, + "families": {"family": members}, + "marital_units": {"marital_unit": members}, + "households": {"household": {**members, "state_code_str": {y: "TX"}}}, + } + ) + got = simulation.calculate("charitable_contributions_ald", year) + assert float(got[0]) == deduction, year + + +def test_household_agi_counts_only_heads_and_spouses_as_the_soi_row_does( + tmp_path, +) -> None: + check = _check() + release = check._release_tool() + summary = tmp_path / "staging.summary.json" + summary.write_text( + json.dumps( + { + "reviewed_engine_input_nulls": [ + { + "entity": "person", + "column": "taxable_interest_income", + "missing_rows": 1, + "rows": 10, + } + ] + } + ) + ) + + agi, receipt = check.household_agi( + _frame(with_nulls=True), summary, release=release, hh_chunk=2 + ) + + np.testing.assert_array_equal(agi, _EXPECTED_AGI) + assert receipt["chunks"] == 3 + assert receipt["reviewed_fill_columns"] == 1 + assert receipt["null_runtime_columns_held_back"] == { + "spm_unit": ["takes_up_snap_if_eligible"] + } + + builder = _load_builder_module() + target_frame, _registry, compilation = builder._materialize_target_frame( + _frame(with_nulls=False), + (_soi("agi_amount", "adjusted_gross_income"),), + maximum_microsim_batch_size=None, + ) + assert compilation["dropped_target_names"] == [] + np.testing.assert_array_equal( + target_frame.table("household")["agi_amount"].to_numpy(dtype=np.float64), agi + ) + + +def test_r2s_own_agi_pass_stores_the_soi_rows_agi(tmp_path) -> None: + """R2 computes each household's AGI before minimum support on a county + SOI surface (microcosm#1661), one chunk at a time; it must be the value + the state SOI AGI row stores, as the pre-check's is.""" + + check = _check() + release = check._release_tool() + summary = tmp_path / "staging.summary.json" + summary.write_text( + json.dumps( + { + "reviewed_engine_input_nulls": [ + { + "entity": "person", + "column": "taxable_interest_income", + "missing_rows": 1, + "rows": 10, + } + ] + } + ) + ) + + # R2's stages have filled the take-up flags by then, so its pass holds + # nothing back; the registered interest null is filled chunk by chunk. + frame = _frame(with_nulls=True) + tables = {entity: frame.table(entity) for entity in frame.entities} + tables["spm_unit"] = tables["spm_unit"].assign(takes_up_snap_if_eligible=True) + frame = Frame(tables, frame.schema, {"household": frame.weights_for("household")}) + + agi = release._household_agi(frame, summary, hh_chunk=2) + + np.testing.assert_array_equal(agi, _EXPECTED_AGI) diff --git a/packages/microcosm-frame/src/microcosm/frame/adapters/_policyengine_us_source_index.py b/packages/microcosm-frame/src/microcosm/frame/adapters/_policyengine_us_source_index.py index 68357896e1..e0c411c26e 100644 --- a/packages/microcosm-frame/src/microcosm/frame/adapters/_policyengine_us_source_index.py +++ b/packages/microcosm-frame/src/microcosm/frame/adapters/_policyengine_us_source_index.py @@ -12,7 +12,7 @@ import copy import hashlib from collections.abc import Callable, Mapping -from dataclasses import dataclass +from dataclasses import dataclass, field, replace from pathlib import Path from types import MappingProxyType @@ -263,10 +263,18 @@ def computed_at(self, period: int | str) -> bool: @dataclass(frozen=True) class _PolicyEngineUSSourceIndex: definitions: Mapping[str, _SourceVariableDefinition] + #: Each variable's reference sites. A read inside a module-level helper + #: function in ``variables/`` is recorded under the helper's name, which + #: no variable's dependency graph follows. consumers: Mapping[str, tuple[ConsumerReceipt, ...]] #: Qualified names of the package helpers the formulas call, each #: answered from its review. reviewed_helpers: tuple[str, ...] = () + #: The same helper reads, recorded again under each variable whose + #: formula reaches the helper call, directly or through other helpers. + helper_consumers: Mapping[str, tuple[ConsumerReceipt, ...]] = field( + default_factory=lambda: MappingProxyType({}) + ) @dataclass(frozen=True) @@ -954,6 +962,9 @@ class _EvaluationFrame: # Local functions the enclosing function calls directly by name; any # other local function is interpreted where it is defined. called_local_functions: frozenset[str] = frozenset() + # The formula-module helper call this frame interprets from the queue; + # None for a variable's own formula and for a helper's value-only pass. + context: _FunctionContext | None = None def _make_alternative(values: tuple[_ExactValue, ...]) -> _ExactValue: @@ -2324,6 +2335,13 @@ def __init__( self._helper_digests: dict[_FunctionID, str] = {} self._local_calls: set[tuple[int, object]] = set() self._receipts: dict[str, set[ConsumerReceipt]] = {} + self._helper_receipts: dict[str, set[ConsumerReceipt]] = {} + # What reaches each queued helper context: a variable's formula (its + # name) or another helper context, and what each context read. + self._context_callers: dict[_FunctionContext, set[str | _FunctionContext]] = {} + self._context_receipts: dict[ + _FunctionContext, set[tuple[str, ConsumerReceipt]] + ] = {} self._queue: list[_FunctionContext] = [] self._seen_contexts: set[_FunctionContext] = set() self._return_values: dict[_FunctionContext, _ExactValue] = {} @@ -2379,11 +2397,55 @@ def run(self) -> Mapping[str, tuple[ConsumerReceipt, ...]]: args=context.args, keywords=context.keywords, apply_defaults=context.apply_defaults, + context=context, ) + self._attribute_helper_reads() return MappingProxyType( {target: tuple(sorted(items)) for target, items in self._receipts.items()} ) + @property + def helper_consumers(self) -> Mapping[str, tuple[ConsumerReceipt, ...]]: + """Helper reads under their calling variables (after :meth:`run`).""" + + return MappingProxyType( + { + target: tuple(sorted(items)) + for target, items in self._helper_receipts.items() + } + ) + + def _attribute_helper_reads(self) -> None: + """Record each formula-module helper's reads under its callers. + + The queue interprets a helper once per distinct call context, under + the helper's own name, which no variable's dependency graph follows. + Every variable whose formula reaches that context, directly or + through other helpers' contexts, reads what the context reads, so + each such receipt is recorded again under each such variable, at the + same site, in ``helper_consumers``. A variable's read of itself is + skipped, as in its own formula. + """ + + for context, items in self._context_receipts.items(): + variables: set[str] = set() + seen = {context} + pending = [context] + while pending: + for caller in self._context_callers.get(pending.pop(), ()): + if isinstance(caller, _FunctionContext): + if caller not in seen: + seen.add(caller) + pending.append(caller) + elif caller in self._definitions: + variables.add(caller) + for variable in variables: + for target, receipt in items: + if target != variable: + self._helper_receipts.setdefault(target, set()).add( + replace(receipt, consumer=variable) + ) + @staticmethod def _root_argument(name: str) -> _ExactValue: if name in _ENTITY_CALL_NAMES: @@ -2529,13 +2591,15 @@ def _analyze_function( defer_unresolved_sinks: bool = False, enqueue_helpers: bool = True, apply_defaults: bool = False, + context: _FunctionContext | None = None, ) -> list[_Flow]: """Interpret ``function`` for one set of arguments. With ``apply_defaults`` (a call context that names its arguments exactly), a parameter the call omits takes its declared default, evaluated in the module's scope as Python does; otherwise it is an - unknown root argument. + unknown root argument. ``context`` is the queued helper call being + interpreted, whose reads its callers inherit. """ frame = _EvaluationFrame( @@ -2546,6 +2610,7 @@ def _analyze_function( defer_unresolved_sinks=defer_unresolved_sinks, enqueue_helpers=enqueue_helpers, called_local_functions=_directly_called_local_functions(function), + context=context, ) env: dict[str, _ExactValue] = {} parameters = _function_parameters(function) @@ -3360,6 +3425,10 @@ def _enqueue_helper( or any(keyword.arg is None for keyword in call.keywords) ), ) + # A variable's formula, or another helper's context, reaches this one. + self._context_callers.setdefault(context, set()).add( + frame.context if frame.context is not None else frame.consumer + ) if context not in self._seen_contexts: self._seen_contexts.add(context) self._queue.append(context) @@ -3542,16 +3611,19 @@ def _record_receipts( kind = f"constructed_{base_kind}" else: kind = base_kind - self._receipts.setdefault(item.value, set()).add( - ConsumerReceipt( - consumer=consumer, - path=module.display_path, - line=expression.lineno, - kind=kind, - receiver_entity=receiver_entity, - aggregation_entity=aggregation_entity, - ) + receipt = ConsumerReceipt( + consumer=consumer, + path=module.display_path, + line=expression.lineno, + kind=kind, + receiver_entity=receiver_entity, + aggregation_entity=aggregation_entity, ) + self._receipts.setdefault(item.value, set()).add(receipt) + if frame.context is not None: + self._context_receipts.setdefault(frame.context, set()).add( + (item.value, receipt) + ) def _receipt_strings( self, @@ -3753,6 +3825,7 @@ def _index_policyengine_us_sources( definitions=MappingProxyType(definitions), consumers=consumers, reviewed_helpers=tuple(sorted(interpreter.reviewed_helpers)), + helper_consumers=interpreter.helper_consumers, ) diff --git a/packages/microcosm-frame/src/microcosm/frame/adapters/policyengine_us.py b/packages/microcosm-frame/src/microcosm/frame/adapters/policyengine_us.py index 7657711abf..3ee9d83675 100644 --- a/packages/microcosm-frame/src/microcosm/frame/adapters/policyengine_us.py +++ b/packages/microcosm-frame/src/microcosm/frame/adapters/policyengine_us.py @@ -478,6 +478,24 @@ def _installed_policyengine_us_variable_sources() -> _PolicyEngineUSSourceIndex: return _PolicyEngineUSSourceIndex( definitions=MappingProxyType(definitions), consumers=source_index.consumers, + helper_consumers=source_index.helper_consumers, + ) + + +@lru_cache(maxsize=1) +def _installed_policyengine_us_consumers_following_helpers() -> Mapping[ + str, tuple[ConsumerReceipt, ...] +]: + """Every reference site, a helper's reads also under its calling variables.""" + + source_index = _installed_policyengine_us_variable_sources() + merged = { + target: set(receipts) for target, receipts in source_index.consumers.items() + } + for target, receipts in source_index.helper_consumers.items(): + merged.setdefault(target, set()).update(receipts) + return MappingProxyType( + {target: tuple(sorted(receipts)) for target, receipts in merged.items()} ) @@ -505,12 +523,24 @@ class PolicyEngineUSVariableMetadataIndex: compact metadata. The default system's generated variables come from a compact audited snapshot whose source and activation files are fingerprinted; an unreviewed wheel version or source change fails closed. + + A read inside a module-level helper function in ``variables/`` belongs to + the helper's name, which :meth:`variable_dependency_closure` does not + follow, so by default a variable's graph stops where its formula calls + such a helper. That is the graph the pool's pinned SSI contract and the + US engine ABI lock record. With ``follow_helpers``, each helper read is + also a read of every variable whose formula reaches the helper call, + directly or through other helpers, at the helper's own reference site. """ - def __init__(self) -> None: + def __init__(self, *, follow_helpers: bool = False) -> None: source_index = _installed_policyengine_us_variable_sources() self._definitions = source_index.definitions - self._consumers = source_index.consumers + self._consumers = ( + _installed_policyengine_us_consumers_following_helpers() + if follow_helpers + else source_index.consumers + ) self._engine_version = distribution("policyengine-us").version # Public names the engine migrates to their sources: storable inputs # although their classes have formulas. diff --git a/packages/microcosm-frame/tests/engine_free/us/test_policyengine_us_consumer_index.py b/packages/microcosm-frame/tests/engine_free/us/test_policyengine_us_consumer_index.py index 33e24f72e9..1e17731c97 100644 --- a/packages/microcosm-frame/tests/engine_free/us/test_policyengine_us_consumer_index.py +++ b/packages/microcosm-frame/tests/engine_free/us/test_policyengine_us_consumer_index.py @@ -2458,3 +2458,181 @@ def test_reads_by_argument_record_only_the_reads_for_the_value_passed( }, specs=_COMPONENT_SPECS, ) + + +def _helper_identities( + index: module._PolicyEngineUSSourceIndex, + target: str, +) -> set[tuple[str, str, str]]: + return { + (receipt.consumer, receipt.path, receipt.kind) + for receipt in index.helper_consumers.get(target, ()) + } + + +def _caller(name: str, call: str, *, imports: str) -> str: + return ( + _clean(imports) + + "\n" + + _variable( + name, + f""" + def formula(person, period, parameters): + return {call} + """, + ) + ) + + +def test_helper_reads_are_recorded_again_under_each_calling_variable( + tmp_path: Path, +) -> None: + """A helper's read stays the helper's in ``consumers``; ``helper_consumers`` + gives it to each variable whose call reaches it, for that call's own + arguments, at the helper's reference site (microcosm#1675).""" + + imports = "from policyengine_us.variables.helper import read" + index = _index( + tmp_path, + { + "helper.py": """ + def read(entity, period, name): + return entity(name, period) + """, + "first.py": _caller( + "first_caller", 'read(person, period, "first_leaf")', imports=imports + ), + "second.py": _caller( + "second_caller", 'read(person, period, "second_leaf")', imports=imports + ), + "leaves.py": _variables("first_leaf", "second_leaf", "unread_leaf"), + }, + ) + + assert _receipt_identities(index, "first_leaf") == { + ("read", "variables/helper.py", "entity_call") + } + assert _helper_identities(index, "first_leaf") == { + ("first_caller", "variables/helper.py", "entity_call") + } + assert _helper_identities(index, "second_leaf") == { + ("second_caller", "variables/helper.py", "entity_call") + } + assert index.helper_consumers.get("unread_leaf", ()) == () + (receipt,) = index.helper_consumers["first_leaf"] + (helper_receipt,) = index.consumers["first_leaf"] + assert (receipt.line, receipt.receiver_entity) == ( + helper_receipt.line, + helper_receipt.receiver_entity, + ) + + +def test_helper_reads_reach_the_variable_through_helpers_that_call_each_other( + tmp_path: Path, +) -> None: + """A read two helpers down, through mutually recursive helpers, is still + the calling variable's.""" + + index = _index( + tmp_path, + { + "helpers.py": """ + def ping(entity, period): + return pong(entity, period) + entity("ping_leaf", period) + + def pong(entity, period): + return ping(entity, period) + entity("pong_leaf", period) + """, + "consumer.py": _caller( + "caller", + "ping(person, period)", + imports="from policyengine_us.variables.helpers import ping", + ), + "leaves.py": _variables("ping_leaf", "pong_leaf"), + }, + ) + + assert _helper_identities(index, "ping_leaf") == { + ("caller", "variables/helpers.py", "entity_call") + } + assert _helper_identities(index, "pong_leaf") == { + ("caller", "variables/helpers.py", "entity_call") + } + + +def test_a_variable_reading_itself_through_a_helper_is_not_its_own_consumer( + tmp_path: Path, +) -> None: + index = _index( + tmp_path, + { + "helper.py": """ + def read(entity, period, name): + return entity(name, period.last_year) + """, + "consumer.py": _caller( + "self_reader", + 'read(person, period, "self_reader")', + imports="from policyengine_us.variables.helper import read", + ), + }, + ) + + assert _receipt_identities(index, "self_reader") == { + ("read", "variables/helper.py", "entity_call") + } + assert index.helper_consumers.get("self_reader", ()) == () + + +def test_follow_helpers_closes_the_dependency_graph_over_helper_reads( + tmp_path: Path, + monkeypatch: pytest.MonkeyPatch, +) -> None: + """By default a variable's graph stops at a helper call, as the pinned + SSI contract records it; ``follow_helpers`` goes on through the helper.""" + + source_index = _index( + tmp_path, + { + "helper.py": """ + def read(entity, period, name): + return entity(name, period) + """, + "program.py": _caller( + "program", + 'read(person, period, "leaf") + person("direct_leaf", period)', + imports="from policyengine_us.variables.helper import read", + ), + "leaves.py": _variables("leaf", "direct_leaf"), + }, + ) + + class _Distribution: + version = "0.0.0" + + monkeypatch.setattr( + module, "_installed_policyengine_us_variable_sources", lambda: source_index + ) + monkeypatch.setattr( + module, "_installed_policyengine_us_migrated_inputs", lambda: frozenset() + ) + monkeypatch.setattr(module, "distribution", lambda _name: _Distribution()) + module._installed_policyengine_us_consumers_following_helpers.cache_clear() + try: + gapped = module.PolicyEngineUSVariableMetadataIndex() + followed = module.PolicyEngineUSVariableMetadataIndex(follow_helpers=True) + default_closure = gapped.variable_dependency_closure("program") + helper_closure = followed.variable_dependency_closure("program") + helper_receipts = followed.consumer_receipts("leaf") + finally: + module._installed_policyengine_us_consumers_following_helpers.cache_clear() + + assert default_closure.input_leaves == ("direct_leaf",) + assert default_closure.edges == (("program", "direct_leaf"),) + assert helper_closure.input_leaves == ("direct_leaf", "leaf") + assert helper_closure.edges == (("program", "direct_leaf"), ("program", "leaf")) + assert helper_closure.sha256 != default_closure.sha256 + assert {receipt.consumer for receipt in gapped.consumer_receipts("leaf")} == { + "read" + } + assert {receipt.consumer for receipt in helper_receipts} == {"read", "program"} diff --git a/test_support/microcosm_build/us_acs_local_esi_premiums.py b/test_support/microcosm_build/us_acs_local_esi_premiums.py new file mode 100644 index 0000000000..0f7b735ae7 --- /dev/null +++ b/test_support/microcosm_build/us_acs_local_esi_premiums.py @@ -0,0 +1,430 @@ +"""Fixtures for the ACS local lane's ESI employer premium (microcosm #454). + +The lane pools a dense ASEC-by-PUF donor release with the ACS spine. These +builders make both sides small: a donor the ``meps_esi_premiums`` stage ran on +before the PUF clone, and an ACS frame as the PUMS loader hands it over. +:func:`income_donor` and ``raw_acs(income_sources=True)`` add what the lane's +hours and income passes read, so the ESI pass can run beside them. +""" + +from __future__ import annotations + +from pathlib import Path +from typing import Any + +import numpy as np +import pandas as pd +import pytest + +from microcosm.build.us_runtime import acs_multispine +from microcosm.build.us_runtime.acs_local_esi_premiums import ( + prepare_acs_local_esi_premium_donor, +) +from microcosm.build.us_runtime.acs_local_income import ( + ACS_LOCAL_INCOME_PREDICTOR_EXTENSIONS, + ACS_LOCAL_INCOME_TRANSFER_COLUMNS, +) +from microcosm.build.us_runtime.acs_multispine import AcsMultispineResult +from microcosm.build.us_runtime.acs_pums import AcsPumsSource +from microcosm.build.us_runtime.base_pool import with_optional_acs_spine +from microcosm.build.us_runtime.esi_premiums import ( + US_ESI_EMPLOYER_PREMIUM_COLUMN, + US_ESI_PREMIUMS_WAGE_COLUMN, + with_us_esi_premium_inputs, +) +from microcosm.build.us_runtime.puf_support import clone_us_frame_for_puf_support +from microcosm.frame import US_SCHEMA, Frame, WeightKind, Weights + +EMPLOYER = US_ESI_EMPLOYER_PREMIUM_COLUMN +WAGES = US_ESI_PREMIUMS_WAGE_COLUMN +USUAL_HOURS = "weekly_hours_worked_before_lsr" +ASEC_PUF = "asec_puf" +ACS = "acs_2024_1yr" +_STATES = (6, 36, 48, 12, 17, 39, 53, 13) +_GROUP_OFFSETS = { + "tax_unit": 100_000, + "spm_unit": 200_000, + "family": 300_000, + "marital_unit": 400_000, +} + + +def _one_person_households( + person: pd.DataFrame, + household: pd.DataFrame, + weights: np.ndarray, + *, + stratum: str, + kind: WeightKind, +) -> Frame: + tables = {"person": person, "household": household} + for group, offset in _GROUP_OFFSETS.items(): + person[f"person_{group}_id"] = person["person_household_id"] + offset + tables[group] = pd.DataFrame( + {f"{group}_id": household["household_id"] + offset} + ) + return Frame( + tables, + US_SCHEMA, + {"household": Weights(np.asarray(weights, dtype=np.float64), kind)}, + pd.Series([stratum] * len(person), dtype=object), + ) + + +def asec_observations(households: int = 320) -> Frame: + """One-person ASEC households with the raw fields the stage reads. + + Of every 20 people, 7 are employed policyholders, 2 are policyholders + without a job, 5 are employed without a policy and 6 are neither. Wages + are the measured wages: positive exactly for the employed. Age and sex do + not tell the employed from the rest, so only wages can. + """ + + index = np.arange(households) + kind = index % 20 + holder = kind < 9 + employed = (kind < 7) | ((kind >= 9) & (kind < 14)) + tier = np.where(holder, np.asarray([1, 2, 3])[index % 3], 0) + person = pd.DataFrame( + { + "person_id": index + 1, + "person_household_id": index + 1, + # The CPS record id: with the raw fields, it marks a row the + # stage derived. + "PERIDNUM": [f"asec-{position:05d}" for position in index], + "age": 24.0 + index % 41, + "is_female": index % 2 == 0, + WAGES: np.where(employed, 28_000.0 + 850.0 * (index % 97), 0.0), + "NOW_OWNGRP": np.where(holder, 1, 2), + "NOW_HIPAID": np.where(holder, np.asarray([1, 2, 2, 3])[index % 4], 0), + "NOW_GRPFTYP2": tier, + "NOW_GRPFTYP": np.asarray([0, 1, 1, 2])[tier], + "PEMLR": np.where(employed, 1, 5), + "NOEMP": np.where(employed, np.asarray([1, 3, 6, 0])[index % 4], 0), + "PEIO1COW": np.where( + employed, np.asarray([4, 4, 5, 2, 3, 1])[index % 6], 0 + ), + "source_year": 2024, + "source_household_id": index + 1, + "source_person_id": 1, + } + ) + household = pd.DataFrame( + { + "household_id": index + 1, + "state_fips": np.asarray(_STATES, dtype=np.int64)[index % len(_STATES)], + } + ) + return _one_person_households( + person, + household, + 900.0 + 37.0 * (index % 11), + stratum=ASEC_PUF, + kind=WeightKind.DESIGN, + ) + + +def dense_donor(households: int = 320, *, puf_wage_seed: int = 5) -> Frame: + """A dense ASEC-by-PUF donor release that ran the ``meps_esi_premiums`` stage. + + The stage assigns one premium per source person; the PUF clone copies it. + The clone's wages are then replaced, as PUF imputation replaces them: a + seeded permutation, so a PUF-detail row's wages no longer say whether its + source person holds a job. Weights are calibrated, as a release's are. + """ + + staged = with_us_esi_premium_inputs( + asec_observations(households), seed=0, time_period=2024 + ) + cloned = clone_us_frame_for_puf_support(staged) + person = cloned.table("person").copy() + puf = person["person_support_clone_index"].to_numpy() == 1 + rng = np.random.default_rng(puf_wage_seed) + person.loc[puf, WAGES] = rng.permutation(person.loc[puf, WAGES].to_numpy()) + return Frame( + { + entity: person if entity == "person" else cloned.table(entity) + for entity in cloned.entities + }, + US_SCHEMA, + { + "household": Weights( + np.asarray(cloned.weights_for("household").values, dtype=np.float64), + WeightKind.CALIBRATED, + ) + }, + cloned.strata, + ) + + +def with_person_values(frame: Frame, columns: dict[str, np.ndarray]) -> Frame: + """The frame with person columns added or replaced; weights kept.""" + + person = frame.table("person").copy() + for column, values in columns.items(): + person[column] = values + return Frame( + { + entity: person if entity == "person" else frame.table(entity) + for entity in frame.entities + }, + frame.schema, + {"household": frame.weights_for("household")}, + frame.strata, + ) + + +def income_donor(households: int = 320, *, seed: int = 1056) -> Frame: + """:func:`dense_donor` with what the lane's hours and income passes read. + + The ASEC observation role carries measured usual hours (positive exactly + for the employed), the income pass's leaves and the components of its + two predictor extensions, half of each leaf positive. The PUF clones + repeat the hours and components and carry the leaves far outside the + ASEC role's support, as main's income tests build them, so a fit on the + wrong role shows. The ESI stage's columns are the donor's own. + """ + + donor = dense_donor(households) + person = donor.table("person") + asec = person["person_support_clone_index"].eq(0).to_numpy() + source = person["person_source_id"].to_numpy() + unique = np.unique(source) + position = np.searchsorted(unique, source) + sources = unique.size + rng = np.random.default_rng(seed) + + def per_source(values: np.ndarray) -> np.ndarray: + # One value per source person, repeated on each of its clones. + return values[position] + + # Measured wages are the ASEC role's; the PUF clones' are permuted. + working = np.zeros(sources, dtype=bool) + working[position[asec]] = person[WAGES].to_numpy(dtype=np.float64)[asec] > 0 + hours = np.where(working, rng.integers(10, 61, sources), 0).astype(np.float64) + columns: dict[str, np.ndarray] = {USUAL_HOURS: per_source(hours)} + for offset, column in enumerate(ACS_LOCAL_INCOME_TRANSFER_COLUMNS): + measured = np.where( + rng.random(sources) < 0.5, rng.integers(100, 20_000, sources), 0 + ).astype(np.float64) + repeated = per_source(measured) + columns[column] = np.where( + asec, repeated, np.where(repeated > 0, 5_000_000.0 + offset, 0.0) + ) + for extension in ACS_LOCAL_INCOME_PREDICTOR_EXTENSIONS: + for component in extension.donor_components: + if component in columns: + continue + values = np.where( + rng.random(sources) < 0.3, rng.integers(100, 9_000, sources), 0 + ).astype(np.float64) + columns[component] = per_source(values) + return with_person_values(donor, columns) + + +def raw_acs( + households: int = 280, + *, + first_id: int = 1, + children: int = 0, + income_sources: bool = False, +) -> Frame: + """One-person ACS households as the PUMS loader returns them. + + Three in five adults report wages, at any age. ``first_id`` defaults to 1 + so the ACS ids repeat the donor's, as the two real id spaces may. + ``children`` appends that many people aged 9, whose ``WAGP`` is blank: + PUMS asks earnings of people aged 15 and older. ``income_sources`` adds + the other PUMS income fields the lane's income pass reads (``OIP``, + ``RETP`` and the rest), blank for children; the default frame is + unchanged. + """ + + index = np.arange(households + children) + child = index >= households + employed = (index % 5 < 3) & ~child + person = pd.DataFrame( + { + "person_id": index + first_id, + "person_household_id": index + first_id, + "AGEP": np.where(child, 9, 23 + index % 43), + "SEX": np.where(index % 2 == 1, 2, 1), + "ADJINC": 1_000_000, + "WAGP": np.where( + child, + np.nan, + np.where(employed, 26_000.0 + 1_100.0 * (index % 83), 0.0), + ), + } + ) + if income_sources: + for column, every, amount in ( + ("SEMP", 7, 9_000.0), + ("SSP", 6, 14_000.0), + ("SSIP", 11, 6_000.0), + ("RETP", 4, 12_000.0), + ("INTP", 5, 300.0), + ("OIP", 3, 4_000.0), + ): + values = np.where(index % every == 0, amount + 10.0 * (index % 17), 0.0) + person[column] = np.where(child, np.nan, values) + household = pd.DataFrame( + { + "household_id": index + first_id, + "state_fips": np.asarray(_STATES, dtype=np.int64)[ + (index + 3) % len(_STATES) + ], + "TYPEHUGQ": 1, + } + ) + return _one_person_households( + person, + household, + 40.0 + 3.0 * (index % 13), + stratum=ACS, + kind=WeightKind.DESIGN, + ) + + +def transferred_acs( + premiums: np.ndarray, + wages: np.ndarray, + weights: np.ndarray, + *, + households: np.ndarray | None = None, + ages: np.ndarray | None = None, + first_id: int = 1, +) -> Frame: + """An ACS frame after the lane's transfers. + + ``premiums`` stands for whatever the ESI transfer drew, so a property can + range over every draw without fitting a forest. ``households`` gives each + person's household position (nondecreasing, starting at 0; one person per + household by default) and ``weights`` one weight per household. ``ages`` + defaults to adults; a NaN wage is a blank the source left, in the raw + ``WAGP`` and the mapped wage alike. + """ + + index = np.arange(len(premiums)) + members = index if households is None else np.asarray(households, dtype=np.int64) + count = int(members.max()) + 1 + person = pd.DataFrame( + { + "person_id": index + first_id, + "person_household_id": members + first_id, + "age": ( + 30.0 + index % 40 if ages is None else np.asarray(ages, dtype=float) + ), + "is_female": index % 2 == 0, + WAGES: np.asarray(wages, dtype=np.float64), + # The raw PUMS field the wage is mapped from: blank where the + # mapped wage is. + "WAGP": np.asarray(wages, dtype=np.float64), + EMPLOYER: np.asarray(premiums, dtype=np.float64), + } + ) + household_index = np.arange(count) + household = pd.DataFrame( + { + "household_id": household_index + first_id, + "state_fips": np.asarray(_STATES, dtype=np.int64)[ + household_index % len(_STATES) + ], + } + ) + return _one_person_households( + person, household, weights, stratum=ACS, kind=WeightKind.DESIGN + ) + + +def reweighted(frame: Frame, factor: float | np.ndarray) -> Frame: + """The frame with its household weights multiplied by ``factor``. + + ``factor`` is one number for every household or one per household. + """ + + weights = frame.weights_for("household") + return Frame( + {entity: frame.table(entity) for entity in frame.entities}, + frame.schema, + { + "household": Weights( + np.asarray(weights.values, dtype=np.float64) * factor, weights.kind + ) + }, + frame.strata, + metadata=frame.metadata, + ) + + +def pooled(donor: Frame, acs: Frame, *, acs_share: float = 0.5) -> Frame: + """The lane's pooled frame before the anchor.""" + + return with_optional_acs_spine(donor, acs, acs_share=acs_share) + + +def donor_rows(frame: Frame) -> np.ndarray: + """People whose premium the stage derived: they carry the CPS record id.""" + + return frame.table("person")["PERIDNUM"].notna().to_numpy() + + +def person_weights(frame: Frame) -> np.ndarray: + return np.asarray(frame.resolve_weights("person").values, dtype=np.float64) + + +def employer_total(frame: Frame, rows: np.ndarray | None = None) -> float: + """Weighted employer premium over ``rows`` (every person by default).""" + + weights = person_weights(frame) + values = frame.table("person")[EMPLOYER].to_numpy(dtype=np.float64) + rows = np.ones(len(values), dtype=bool) if rows is None else rows + return float(weights[rows] @ values[rows]) + + +def household_mass_share(frame: Frame, rows: np.ndarray) -> float: + """Share of household mass in the households of ``rows``.""" + + household = frame.table("household") + members = frame.table("person").loc[rows, "person_household_id"] + selected = household["household_id"].isin(members).to_numpy() + weights = np.asarray(frame.weights_for("household").values, dtype=np.float64) + return float(weights[selected].sum() / weights.sum()) + + +def build_lane( + donor: Frame, + acs: Frame, + *, + acs_share: float = 0.5, + n_estimators: int = 20, + seed: int = 0, + target_families: dict | None = None, + esi_premiums: bool = True, + **options: Any, +) -> AcsMultispineResult: + """Run the lane's staging orchestration on fixture frames. + + Only the PUMS loader is replaced; native mapping, the ESI transfer, the + pooling and the anchor are the production code. ``esi_premiums=False`` + runs the same orchestration without the ESI donor factory; ``options`` + go to :func:`~.acs_multispine.build_optional_acs_multispine` as given + (the hours donor and the income pass, for example). + """ + + with pytest.MonkeyPatch.context() as patch: + patch.setattr( + acs_multispine, "build_acs_pums_unit_frame", lambda *a, **k: (acs, {}) + ) + return acs_multispine.build_optional_acs_multispine( + donor, + AcsPumsSource(Path("unused-hus.zip"), Path("unused-pus.zip")), + acs_share=acs_share, + target_families=target_families or {}, + esi_premium_donor_factory=( + prepare_acs_local_esi_premium_donor if esi_premiums else None + ), + seed=seed, + n_estimators=n_estimators, + **options, + ) diff --git a/test_support/microcosm_build/us_acs_local_release_tool.py b/test_support/microcosm_build/us_acs_local_release_tool.py new file mode 100644 index 0000000000..5a39d5d01c --- /dev/null +++ b/test_support/microcosm_build/us_acs_local_release_tool.py @@ -0,0 +1,34 @@ +"""Loaders for the ACS local release chain's two tools. + +``tools/`` is not a package, so tests in more than one category load the +tools by path through these helpers. +""" + +from __future__ import annotations + +import importlib.util +from types import ModuleType + +from test_support.paths import paths_for + +_TOOLS = paths_for("microcosm-build").repository / "tools" + + +def _load(name: str) -> ModuleType: + spec = importlib.util.spec_from_file_location(name, _TOOLS / f"{name}.py") + assert spec is not None and spec.loader is not None + module = importlib.util.module_from_spec(spec) + spec.loader.exec_module(module) + return module + + +def load_tool_module() -> ModuleType: + """``tools/build_us_acs_local_release.py``, freshly executed.""" + + return _load("build_us_acs_local_release") + + +def load_staging_builder_module() -> ModuleType: + """``tools/build_us_acs_multispine_base.py``, the staging shim.""" + + return _load("build_us_acs_multispine_base") diff --git a/test_support/microcosm_build/us_esi_premiums_frames.py b/test_support/microcosm_build/us_esi_premiums_frames.py new file mode 100644 index 0000000000..c0114ac7c1 --- /dev/null +++ b/test_support/microcosm_build/us_esi_premiums_frames.py @@ -0,0 +1,294 @@ +"""ESI employer premium frames: Route A's shape and a mixed frame (microcosm #454). + +Route A writes the premium on CPS ASEC rows in its base builder (the stage, +the signal gate, the PUF support clone, the signal gate again), and its +release grades the base and the calibrated export. :func:`asec_arm` is that +CPS side, with or without the CPS record id, and :func:`staged`, +:func:`puf_cloned` and :func:`reweighted` take it through those steps. + +:func:`mixed_frame` adds rows a cross-source transfer filled, which carry none +of the raw ASEC fields and no CPS record id: the frame +``allow_transferred_rows=True`` grades (d2283 PR 0). +""" + +from __future__ import annotations + +from collections.abc import Sequence + +import numpy as np +import pandas as pd + +from microcosm.build.us_runtime import esi_premiums as esi +from microcosm.build.us_runtime.esi_premiums import ( + US_ESI_EMPLOYER_PREMIUM_COLUMN, + US_ESI_PREMIUMS_CPS_RECORD_COLUMN, + US_ESI_PREMIUMS_WAGE_COLUMN, + with_us_esi_premium_inputs, + with_us_esi_premium_pool_anchor, +) +from microcosm.build.us_runtime.puf_support import clone_us_frame_for_puf_support +from microcosm.frame import US_SCHEMA, Frame, WeightKind, Weights +from test_support.microcosm_build.us_stacked_spine import _source_frame + +EMPLOYER = US_ESI_EMPLOYER_PREMIUM_COLUMN +WAGES = US_ESI_PREMIUMS_WAGE_COLUMN +CPS_ID = US_ESI_PREMIUMS_CPS_RECORD_COLUMN +RAW = esi._RAW_EVIDENCE_COLUMNS +RAW_WAGE = esi._RAW_ACS_WAGE_COLUMN +YEAR = 2024 +#: BEA NIPA 7.8 line 17 for :data:`YEAR`: the stage's anchor. +ANCHOR = float(esi.EMPLOYER_PREMIUM_ANCHOR["values"][str(YEAR)]) +STATES = (6, 36, 48, 12, 17, 39, 53, 13) +_CHANNEL = "person_support_channel" +_CLONE_INDEX = "person_support_clone_index" +_SOURCE_ID = "person_source_id" + + +def rebuilt( + frame: Frame, + *, + person: pd.DataFrame | None = None, + household: pd.DataFrame | None = None, + household_weights: Weights | None = None, +) -> Frame: + """``frame`` with some tables or the household weights replaced.""" + + tables = {entity: frame.table(entity) for entity in frame.entities} + if person is not None: + tables["person"] = person + if household is not None: + tables["household"] = household + tables.update({name: frame.link(name) for name in frame.links}) + return Frame( + tables, + frame.schema, + { + "household": household_weights + if household_weights is not None + else frame.weights_for("household") + }, + frame.strata, + mass_log=frame.mass_log, + metadata=frame.metadata, + ) + + +def asec_arm( + households: int = 320, + *, + first_household_id: int = 1, + record_ids: bool = True, +) -> Frame: + """One-person CPS ASEC households: a mix inside the signal-gate bands. + + Of every 20 people, 7 are employed policyholders, 2 are policyholders + without a job (retirees), 5 are employed without a policy and 6 are + neither. ``record_ids=False`` leaves out the CPS record id column. + """ + + frame = _source_frame( + household_ids=list(range(first_household_id, first_household_id + households)), + weights=[900.0 + 37.0 * (index % 11) for index in range(households)], + stratum="asec_2024", + ) + index = np.arange(households) + kind = index % 20 + holder = kind < 9 + employed = (kind < 7) | ((kind >= 9) & (kind < 14)) + tier = np.where(holder, np.asarray([1, 2, 3])[index % 3], 0) + wages = np.where(employed, 28_000.0 + 850.0 * (index % 97), 0.0) + person = frame.table("person").copy() + if record_ids: + person[CPS_ID] = [f"asec-{position:05d}" for position in index] + person["source_year"] = YEAR + person["source_household_id"] = person["person_household_id"].to_numpy() + person["source_person_id"] = 1 + person["age"] = np.where(employed, 24.0 + index % 40, 66.0 + index % 20) + person["is_female"] = index % 2 == 0 + person[WAGES] = wages + person["NOW_OWNGRP"] = np.where(holder, 1, 2) + person["NOW_HIPAID"] = np.where(holder, np.asarray([1, 2, 2, 3])[index % 4], 0) + person["NOW_GRPFTYP2"] = tier + person["NOW_GRPFTYP"] = np.asarray([0, 1, 1, 2])[tier] + person["PEMLR"] = np.where(employed, 1, 5) + person["NOEMP"] = np.where(employed, np.asarray([1, 3, 6, 0])[index % 4], 0) + person["PEIO1COW"] = np.where( + employed, np.asarray([4, 4, 5, 2, 3, 1])[index % 6], 0 + ) + household = frame.table("household").copy() + household["state_fips"] = np.asarray(STATES, dtype=np.int64)[index % len(STATES)] + return rebuilt(frame, person=person, household=household) + + +def staged(frame: Frame) -> Frame: + """The base builder's stage call (``tools/build_us_puf_support_base.py``).""" + + return with_us_esi_premium_inputs(frame, seed=0, time_period=YEAR) + + +def puf_cloned(frame: Frame) -> Frame: + """The production PUF support clone the base builder runs after the stage.""" + + return clone_us_frame_for_puf_support(frame) + + +def calibration_factors(frame: Frame, *, spread: float = 0.03) -> np.ndarray: + """Deterministic household weight factors within ``1 +/- spread``.""" + + count = len(frame.table("household")) + return 1.0 + spread * np.cos(np.arange(count, dtype=np.float64)) + + +def reweighted(frame: Frame, factors: np.ndarray | float) -> Frame: + """The same people at household weights times ``factors``: an export.""" + + values = np.asarray(frame.weights_for("household").values, dtype=np.float64) + return rebuilt( + frame, + household_weights=Weights(values * factors, WeightKind.CALIBRATED), + ) + + +def with_person_cells( + frame: Frame, rows: Sequence[int] | np.ndarray, columns, value: object +) -> Frame: + """``frame`` with ``value`` written into ``columns`` at person positions ``rows``. + + An integer column takes a value that is not an integer as float64 first, + so a null lands as NaN. + """ + + person = frame.table("person").copy() + for column in [columns] if isinstance(columns, str) else list(columns): + if pd.api.types.is_integer_dtype(person[column]) and not isinstance( + value, (int, np.integer) + ): + person[column] = person[column].astype(np.float64) + person.loc[person.index[np.asarray(rows, dtype=np.int64)], columns] = value + return rebuilt(frame, person=person) + + +def without_person_columns(frame: Frame, columns: Sequence[str]) -> Frame: + return rebuilt(frame, person=frame.table("person").drop(columns=list(columns))) + + +def with_scaled_premiums( + frame: Frame, factor: float, rows: np.ndarray | None = None +) -> Frame: + """``frame`` with the employer premium times ``factor`` on ``rows`` (all).""" + + person = frame.table("person").copy() + rows = np.ones(len(person), dtype=bool) if rows is None else np.asarray(rows) + values = person[EMPLOYER].to_numpy(dtype=np.float64).copy() + values[rows] *= factor + person[EMPLOYER] = values + return rebuilt(frame, person=person) + + +def cps_rows(frame: Frame) -> np.ndarray: + """Rows that carry the raw ASEC fields.""" + + return frame.table("person")[RAW[0]].notna().to_numpy() + + +def households_of(frame: Frame, rows: np.ndarray) -> np.ndarray: + """Household-table flags for the households of person ``rows``.""" + + person = frame.table("person") + household = frame.table("household") + return ( + household["household_id"] + .isin(person.loc[np.asarray(rows), "person_household_id"]) + .to_numpy() + ) + + +def mixed_frame( + asec_households: int = 320, + acs_households: int = 280, + *, + acs_clones: bool = False, +) -> Frame: + """CPS rows beside rows a cross-source transfer filled, on the stage's scale. + + The CPS side is :func:`asec_arm` staged on its own weights, then given + half of them: half the household mass of one population. The transfer + gives each of ``acs_households`` one-person households the age, sex, wages + and premium of the CPS person at the same position, with none of the raw + ASEC fields and no CPS record id, and their household weights carry the + other half of the mass. ``acs_clones`` gives every transferred person one + support clone, and splits its household weight between the two. + :func:`with_us_esi_premium_pool_anchor` then holds the transferred + premiums to the CPS rows' premium per unit of household mass, so the + frame's anchor-universe total is the anchor. + """ + + if not 0 < acs_households <= asec_households: + raise ValueError("mixed_frame copies each transferred row from a CPS row.") + donor = staged(asec_arm(asec_households)) + donor_person = donor.table("person") + donor_household = donor.table("household") + donor_weights = np.asarray(donor.weights_for("household").values, np.float64) + pattern = 40.0 + 3.0 * (np.arange(acs_households) % 13) + acs_weights = pattern * (donor_weights.sum() / 2.0 / pattern.sum()) + acs_ids = np.arange(10_001, 10_001 + acs_households) + household_ids = [*range(1, asec_households + 1), *acs_ids.tolist()] + weights = [*(donor_weights / 2.0)] + # Each person row's donor position, and its transferred origin (-1: CPS). + donor_position = [*range(asec_households), *range(acs_households)] + origin = [-1] * asec_households + list(range(acs_households)) + if acs_clones: + household_ids += list(range(20_001, 20_001 + acs_households)) + weights += [*(acs_weights / 2.0), *(acs_weights / 2.0)] + donor_position += list(range(acs_households)) + origin += list(range(acs_households)) + else: + weights += list(acs_weights) + frame = _source_frame( + household_ids=household_ids, weights=weights, stratum="asec_acs_2024" + ) + position = np.asarray(donor_position) + origin_array = np.asarray(origin) + cps = origin_array < 0 + clone = np.zeros(len(position), dtype=bool) + clone[asec_households + acs_households :] = True + person = frame.table("person").copy() + for column in ("age", "is_female", WAGES, EMPLOYER): + person[column] = donor_person[column].to_numpy()[position] + for column in RAW: + values = donor_person[column].to_numpy(dtype=np.float64)[position] + person[column] = np.where(cps, values, np.nan) + ids = donor_person[CPS_ID].to_numpy(dtype=object)[position] + person[CPS_ID] = np.where(cps, ids, None) + person[RAW_WAGE] = np.where(cps, np.nan, person[WAGES].to_numpy()) + person["source_year"] = YEAR + source_household = donor_person["source_household_id"].to_numpy()[position] + source_household[~cps] = acs_ids[origin_array[~cps]] + person["source_household_id"] = source_household + person["source_person_id"] = 1 + person[_CHANNEL] = np.where(cps, "asec", "acs") + person[_CLONE_INDEX] = clone.astype(np.int64) + person[_SOURCE_ID] = [ + f"cps-{index}" if from_cps else f"acs-{source}" + for index, (from_cps, source) in enumerate(zip(cps, origin_array, strict=True)) + ] + household = frame.table("household").copy() + donor_states = donor_household["state_fips"].to_numpy(dtype=np.int64) + acs_states = np.asarray(STATES, dtype=np.int64)[ + (np.arange(acs_households) + 3) % len(STATES) + ] + household["state_fips"] = np.concatenate( + [donor_states, acs_states, *([acs_states] if acs_clones else [])] + ) + filled = Frame( + { + **{entity: frame.table(entity) for entity in frame.entities}, + "person": person, + "household": household, + }, + US_SCHEMA, + {"household": Weights(np.asarray(weights, np.float64), WeightKind.DESIGN)}, + frame.strata, + ) + anchored, _receipt = with_us_esi_premium_pool_anchor(filled) + return anchored diff --git a/test_support/microcosm_build/us_esi_premiums_main_oracle.py b/test_support/microcosm_build/us_esi_premiums_main_oracle.py new file mode 100644 index 0000000000..603d2a8164 --- /dev/null +++ b/test_support/microcosm_build/us_esi_premiums_main_oracle.py @@ -0,0 +1,435 @@ +"""Main's ESI premium gates, vendored as the oracle for PR 0's Route A test. + +Source: PolicyEngine/microcosm main at +5499382772a41a956f0c0ddc86a27d506436ced6, +``packages/microcosm-build/src/microcosm/build/us_runtime/esi_premiums.py``: +``_clone_disagreements``, ``us_esi_premiums_summary``, +``_missing_source_failure``, ``us_esi_premiums_signal_gate`` and +``us_esi_premiums_anchor_gate``, copied verbatim. Every helper and constant +they read comes from the live module; the slice of microcosm#1199 (d2283 +PR 0) left each of those unchanged. + +The shared helpers are ``_person_raw_shares``, ``_person_with_state``, +``_stable_person_keys``, ``_weighted``, ``load_meps_ic_esi_premium_cells`` and +``meps_ic_private_active_employer_totals``, beside the constants imported with +them, and everything those call: ``_EsiCodes``, ``_cell_values``, +``_esi_person_codes``, ``_government_cell``, ``_integer_codes``, +``_no_contribution_share``, ``_private_cell``, ``_raw_employer_share`` and +constants such as ``_CODE_DOMAINS``, ``_SIZE_BY_NOEMP`` and +``_GRPFTYP_FOR_GRPFTYP2``. A change to any of them moves the oracle and the +live gates together, so the differential test (T2) cannot detect it. For those names the evidence is +main's own file or an AST comparison against it, not T2. + +Track main only; do not edit otherwise. This file exists so that one process +grades the same frame with main's gates and the live ones +(``tests/engine_free/us/test_us_esi_premiums_route_a_differential.py``). +""" + +from __future__ import annotations + +import numpy as np +import pandas as pd + +from microcosm.build.gates import GateResult +from microcosm.build.source_runtime import SourceRuntimeError +from microcosm.build.us_runtime.esi_premiums import ( + _CELLS_SHA256, + _EMPLOYED_SHARE_BAND, + _FEDERAL, + _LOCAL_GOVERNMENT, + _PAYS_ALL, + _PAYS_NONE, + _PAYS_SOME, + _POSITIVE_SHARE_BAND, + _PRIVATE_EMPLOYER_CODES, + _RAW_MEAN_BAND, + _STATE_GOVERNMENT, + _TIER_BY_CODE, + ANCHOR_RELATIVE_TOLERANCE, + EMPLOYER_PREMIUM_ANCHOR, + EMPLOYER_PREMIUM_CROSS_CHECK, + US_ESI_EMPLOYER_PREMIUM_COLUMN, + US_ESI_PREMIUMS_OUTPUT_COLUMNS, + US_ESI_PREMIUMS_REQUIRED_SOURCE_COLUMNS, + _person_raw_shares, + _person_with_state, + _stable_person_keys, + _weighted, + load_meps_ic_esi_premium_cells, + meps_ic_private_active_employer_totals, +) +from microcosm.frame import Frame + +__all__ = [ + "us_esi_premiums_anchor_gate", + "us_esi_premiums_signal_gate", + "us_esi_premiums_summary", +] + + +def _clone_disagreements(person: pd.DataFrame) -> int: + if not {"source_year", "source_household_id", "source_person_id"} <= set( + person.columns + ): + return 0 + keys = _stable_person_keys(person) + work = person[list(US_ESI_PREMIUMS_OUTPUT_COLUMNS)].copy() + work["_key"] = keys.to_numpy() + return int( + work.groupby("_key", sort=False)[list(US_ESI_PREMIUMS_OUTPUT_COLUMNS)] + .nunique() + .gt(1) + .any(axis=1) + .sum() + ) + + +def us_esi_premiums_summary(frame: Frame) -> dict[str, object]: + """Weighted ESI premium lineage and structure, for gates and manifests. + + It recomputes the raw MEPS-IC shares from the raw ASEC columns, so the + scale factor, the anchor-universe total and every structural zero are + checked against the cells rather than trusted. A frame that lacks those + columns gets the column totals only, with ``source_columns_missing`` + naming what is absent; both gates fail on it. + """ + + person = frame.table("person") + weights = np.asarray(frame.resolve_weights("person").values, dtype=np.float64) + employer = person[US_ESI_EMPLOYER_PREMIUM_COLUMN].to_numpy(dtype=np.float64) + positive = employer > 0 + total_weight = float(weights.sum()) + holders = float(weights[positive].sum()) + person = _person_with_state(frame) + summary: dict[str, object] = { + "employer_premium_total": _weighted(weights, employer), + "employer_premium_positive_persons": holders, + "employer_premium_mean_per_positive_person": ( + _weighted(weights, employer, positive) / holders if holders else 0.0 + ), + "employer_premium_positive_share": holders / total_weight + if total_weight + else 0.0, + "nonfinite_rows": int((~np.isfinite(employer)).sum()), + "negative_rows": int((employer < 0).sum()), + "clone_disagreement_source_persons": _clone_disagreements(person), + "anchor": dict(EMPLOYER_PREMIUM_ANCHOR), + "cross_check": dict(EMPLOYER_PREMIUM_CROSS_CHECK), + "cells_sha256": _CELLS_SHA256, + "source_columns_missing": [ + column + for column in US_ESI_PREMIUMS_REQUIRED_SOURCE_COLUMNS + if column not in person.columns + ], + } + if summary["source_columns_missing"]: + return summary + codes, raw, premium, contribution = _person_raw_shares(person) + universe = codes.universe + holder = codes.policyholder + other = holder & ~universe + raw_positive = universe & (raw > 0) + raw_universe_total = _weighted(weights, raw, universe) + raw_anchor_total = _weighted(weights, raw) + scale = ( + summary["employer_premium_total"] / raw_universe_total + if raw_universe_total + else float("nan") + ) + by_tier = { + tier: _weighted(weights, employer, universe & (codes.tier == code)) + for code, tier in _TIER_BY_CODE.items() + } + by_sector = { + "private": _weighted( + weights, employer, np.isin(codes.sector, _PRIVATE_EMPLOYER_CODES) + ), + "federal": _weighted(weights, employer, codes.sector == _FEDERAL), + "state_and_local": _weighted( + weights, + employer, + np.isin(codes.sector, [_STATE_GOVERNMENT, _LOCAL_GOVERNMENT]), + ), + } + with np.errstate(invalid="ignore", divide="ignore"): + ratio = np.where( + raw_positive, employer / np.where(raw_positive, raw, 1.0), np.nan + ) + # MEPS-IC's published employer mean of a cell is premium less average + # contribution over every enrollee the employer pays for. + employer_pays = universe & np.isin(codes.hipaid, [_PAYS_ALL, _PAYS_SOME]) + published = _weighted(weights, premium - contribution, employer_pays) + summary |= { + "weighted_policyholders": float(weights[holder].sum()), + "weighted_employed_policyholders": float(weights[universe].sum()), + "weighted_employed_policyholders_by_payment": { + name: float(weights[universe & (codes.hipaid == code)].sum()) + for name, code in ( + ("all", _PAYS_ALL), + ("some", _PAYS_SOME), + ("none", _PAYS_NONE), + ) + }, + "weighted_other_policyholders": float(weights[other].sum()), + "weighted_other_policyholders_with_employer_share": float( + weights[other & (raw > 0)].sum() + ), + "raw_employer_share_total": raw_universe_total, + "raw_anchor_universe_total": raw_anchor_total, + "raw_employer_share_mean_per_positive_person": ( + _weighted(weights, raw, raw_positive) / float(weights[raw_positive].sum()) + if raw_positive.any() + else 0.0 + ), + "raw_employer_share_band": list(_RAW_MEAN_BAND), + "raw_over_published_employer_mean": ( + _weighted(weights, raw, employer_pays) / published + if published + else float("nan") + ), + "scale_factor": scale, + "scale_factor_spread": ( + float(np.nanmax(ratio) - np.nanmin(ratio)) if raw_positive.any() else 0.0 + ), + "anchor_universe_employer_total": scale * raw_anchor_total, + "other_policyholder_employer_total": scale + * (raw_anchor_total - raw_universe_total), + "employed_share_of_anchor_universe": ( + raw_universe_total / raw_anchor_total if raw_anchor_total else float("nan") + ), + "employer_premium_by_tier": by_tier, + "employer_premium_by_sector": by_sector, + "employer_premium_outside_universe_rows": int((positive & ~universe).sum()), + "employer_premium_where_employer_pays_none_rows": int( + (positive & (codes.hipaid == _PAYS_NONE)).sum() + ), + "employer_premium_without_raw_share_rows": int( + (positive & ~raw_positive).sum() + ), + "meps_ic_private_active_employer_total": ( + meps_ic_private_active_employer_totals(load_meps_ic_esi_premium_cells()) + ), + } + return summary + + +def _missing_source_failure(missing: list[str], consequence: str) -> str: + return ( + f"assignment provenance incomplete: the person table lacks {missing}, so " + f"{consequence}. Rebuild the base with the meps_esi_premiums stage; a " + "release must carry the raw ASEC coverage columns the assignment read." + ) + + +def us_esi_premiums_signal_gate(frame: Frame) -> GateResult: + """Structure and scale-invariant signal of the ESI employer premium input. + + Holds on any frame size (smoke builds included). It proves every positive + value sits in the employed-policyholder universe and equals one common + multiple of its MEPS-IC cell. Those proofs read the raw ASEC columns, so a + frame without them fails: it cannot be certified. + """ + + person = frame.table("person") + missing = [ + column + for column in US_ESI_PREMIUMS_OUTPUT_COLUMNS + if column not in person.columns + ] + if missing: + return GateResult( + name="esi_premiums_signal", + passed=False, + failures=tuple(f"person column missing: {column}." for column in missing), + details={"missing": missing}, + ) + try: + summary = us_esi_premiums_summary(frame) + except SourceRuntimeError as exc: + return GateResult( + name="esi_premiums_signal", + passed=False, + failures=(str(exc),), + details={"structural_error": str(exc)}, + ) + failures: list[str] = [] + if summary["source_columns_missing"]: + failures.append( + _missing_source_failure( + list(summary["source_columns_missing"]), + "the universe, payment-status and MEPS-IC cell checks did not run", + ) + ) + for column in US_ESI_PREMIUMS_OUTPUT_COLUMNS: + if person[column].dropna().nunique() < 2: + failures.append(f"{column}: constant column — zero mass or no signal.") + for key, label in ( + ("nonfinite_rows", "non-finite value(s)"), + ("negative_rows", "negative value(s)"), + ("clone_disagreement_source_persons", "support-clone disagreement(s)"), + ( + "employer_premium_outside_universe_rows", + "employer premium(s) outside employed policyholders", + ), + ( + "employer_premium_where_employer_pays_none_rows", + "employer premium(s) where the employer pays none", + ), + ( + "employer_premium_without_raw_share_rows", + "employer premium(s) with no MEPS-IC share", + ), + ): + count = int(summary.get(key, 0)) + if count: + failures.append(f"ESI premiums: {count} {label}.") + share = float(summary["employer_premium_positive_share"]) + low, high = _POSITIVE_SHARE_BAND + if not low <= share <= high: + failures.append( + f"employer premium positive share {share:.4f} outside [{low}, {high}]." + ) + if "raw_employer_share_mean_per_positive_person" in summary: + mean = float(summary["raw_employer_share_mean_per_positive_person"]) + low, high = _RAW_MEAN_BAND + if not low <= mean <= high: + failures.append( + f"raw MEPS-IC employer share per holder ${mean:,.0f} outside " + f"[${low:,.0f}, ${high:,.0f}]: the cell table's units are broken." + ) + # Relative to the factor: a float32 round trip leaves ~1e-7. + spread = float(summary["scale_factor_spread"]) + if spread > 1e-6 * float(summary["scale_factor"]): + failures.append( + f"employer premiums are not one common multiple of their MEPS-IC " + f"cells (scale-factor spread {spread:.3g})." + ) + return GateResult( + name="esi_premiums_signal", + passed=not failures, + failures=tuple(failures), + details=summary, + ) + + +def us_esi_premiums_anchor_gate(frame: Frame, *, time_period: int) -> GateResult: + """Hold a release's weighted ESI employer premium total to its anchor. + + Runs on the calibrated export (dense and sparse). The anchor, BEA NIPA + 7.8 line 17, counts employer contributions for every policyholder, so the + gate compares the anchor-universe total: the column (employed + policyholders) plus the same scale factor applied to the other + policyholders' MEPS-IC shares, recomputed from the raw ASEC columns at the + frame's weights. It fails when the column is absent or zero-mass, when + the raw columns are absent, when that total leaves + ±``ANCHOR_RELATIVE_TOLERANCE`` of the anchor for ``time_period``, or when + the employed share of it leaves its band. CMS NHE Table 24 and MEPS-IC's + own private-sector enrollment total are recorded beside the verdict, not + gated. + """ + + person = frame.table("person") + missing = [ + column + for column in US_ESI_PREMIUMS_OUTPUT_COLUMNS + if column not in person.columns + ] + if missing: + return GateResult( + name="esi_premiums_anchor", + passed=False, + failures=tuple(f"person column missing: {column}." for column in missing), + details={"missing": missing}, + ) + try: + summary = us_esi_premiums_summary(frame) + except SourceRuntimeError as exc: + return GateResult( + name="esi_premiums_anchor", + passed=False, + failures=(str(exc),), + details={"structural_error": str(exc)}, + ) + employer_total = float(summary["employer_premium_total"]) + year = str(int(time_period)) + failures: list[str] = [] + details: dict[str, object] = { + "time_period": int(time_period), + "employer_premium_total": employer_total, + "employer_premium_positive_persons": summary[ + "employer_premium_positive_persons" + ], + "employer_premium_mean_per_positive_person": summary[ + "employer_premium_mean_per_positive_person" + ], + "relative_tolerance": ANCHOR_RELATIVE_TOLERANCE, + "anchor": dict(EMPLOYER_PREMIUM_ANCHOR), + "cross_check": dict(EMPLOYER_PREMIUM_CROSS_CHECK), + } + if not employer_total > 0: + failures.append(f"{US_ESI_EMPLOYER_PREMIUM_COLUMN}: zero weighted mass.") + anchor = EMPLOYER_PREMIUM_ANCHOR["values"].get(year) + if anchor is None: + failures.append(f"no BEA NIPA 7.8 line 17 anchor for {year}.") + if summary["source_columns_missing"]: + failures.append( + _missing_source_failure( + list(summary["source_columns_missing"]), + "the anchor-universe total (every policyholder) cannot be computed", + ) + ) + else: + universe_total = float(summary["anchor_universe_employer_total"]) + employed_share = float(summary["employed_share_of_anchor_universe"]) + details |= { + key: summary[key] + for key in ( + "anchor_universe_employer_total", + "other_policyholder_employer_total", + "employed_share_of_anchor_universe", + "scale_factor", + "weighted_policyholders", + "weighted_employed_policyholders", + "weighted_other_policyholders", + "employer_premium_by_sector", + ) + } + if not np.isfinite(universe_total): + failures.append( + "the anchor-universe employer total is not finite: no employed " + "policyholder carries a MEPS-IC share to recover the scale from." + ) + elif anchor is not None: + relative = universe_total / float(anchor) - 1.0 + details |= {"anchor_value": float(anchor), "relative_error": relative} + if abs(relative) > ANCHOR_RELATIVE_TOLERANCE: + failures.append( + "employer premiums over every policyholder total " + f"${universe_total / 1e9:,.1f}B, {relative:+.1%} from BEA NIPA 7.8 " + f"line 17 ${float(anchor) / 1e9:,.1f}B ({year}); tolerance " + f"±{ANCHOR_RELATIVE_TOLERANCE:.0%}." + ) + low, high = _EMPLOYED_SHARE_BAND + details["employed_share_band"] = [low, high] + if not low <= employed_share <= high: + failures.append( + f"employed policyholders carry {employed_share:.4f} of the " + f"anchor-universe employer total, outside [{low}, {high}]." + ) + nhe = EMPLOYER_PREMIUM_CROSS_CHECK["values"].get(year) + if nhe is not None and np.isfinite(universe_total): + details["cross_check_ratio"] = universe_total / float(nhe) + active = dict(summary["meps_ic_private_active_employer_total"]) + if year in active: + private = float(dict(summary["employer_premium_by_sector"])["private"]) + details["private_active_cross_check"] = { + "meps_ic_private_active_employer_total": active[year], + "employer_premium_private_sector": private, + "ratio": private / active[year], + } + return GateResult( + name="esi_premiums_anchor", + passed=not failures, + failures=tuple(failures), + details=details, + ) diff --git a/tools/_legacy/build_us_acs_multispine_base.py b/tools/_legacy/build_us_acs_multispine_base.py index fd5e394855..d0badf2f3a 100644 --- a/tools/_legacy/build_us_acs_multispine_base.py +++ b/tools/_legacy/build_us_acs_multispine_base.py @@ -17,6 +17,14 @@ summary (``household_location``, ``orchestration``, ``geography_ladder``) and the staging H5's root attributes. The legacy default is unchanged. +The ESI employer premium (microcosm#454) is qualified on the donor before the +ACS fetch, transferred onto the ACS spine and anchored by +:mod:`microcosm.build.us_runtime.acs_local_esi_premiums`, and graded by both +ESI gates on the final frame before export; a red gate stops the build before +the staging H5 is written. ``--allow-esi-premium-gaps`` (diagnostic builds +only) records a refused donor and red gates in the summary +(``local_esi_premiums``) instead. + Telemetry: after parsing its arguments the builder starts the emitter (``microcosm.build.program_telemetry``, pipeline ``us_acs_multispine_staging``), records a stage change at each main phase (``load_donor``, @@ -51,6 +59,12 @@ from microcosm.build.telemetry_emitter import LocalTelemetryEmitter from microcosm.build.us_runtime import acs_sources from microcosm.build.us_runtime.acs_inputs import acs_self_employment_identity_gate +from microcosm.build.us_runtime.acs_local_esi_premiums import ( + acs_local_esi_premium_gate_payload, + acs_local_esi_premium_gates, + acs_local_esi_premium_transfer_target_families, + prepare_acs_local_esi_premium_donor, +) from microcosm.build.us_runtime.acs_local_hours import ( ACS_UNDER15_ZERO_POLICY, acs_local_hours_signal_gate, @@ -317,6 +331,19 @@ def _parse_args(argv: list[str] | None = None) -> argparse.Namespace: "cache, downloading the pinned 3.73 GB file on first use." ), ) + parser.add_argument( + "--allow-esi-premium-gaps", + action="store_true", + help=( + "Diagnostic escape hatch (microcosm#454): build from a donor " + "release that predates the meps_esi_premiums stage. No row then " + "carries employer_sponsored_insurance_premiums and both ESI gates " + "are red; what was red is written to the staging summary. A donor " + "that carries the column but fails qualification leaves it null " + "on the ACS spine, which the release tool refuses. Release builds " + "must leave this unset." + ), + ) parser.add_argument( "--donor-release-manifest", type=Path, @@ -485,6 +512,25 @@ def _attribute_text(value: object) -> str: return str(value) +def _engine_versions() -> dict[str, str | None]: + """The engine this staging runs, for R2 to match before it loads the file. + + Staging audits the nulls of every input the installed policyengine-us + defines (``reviewed_engine_input_nulls``), so its summary only holds for + that engine. A package that is not installed is recorded as ``None``. + """ + + from importlib.metadata import PackageNotFoundError, version + + versions: dict[str, str | None] = {} + for package in ("policyengine-us", "policyengine-core"): + try: + versions[package.replace("-", "_")] = version(package) + except PackageNotFoundError: + versions[package.replace("-", "_")] = None + return versions + + def main(argv: list[str] | None = None) -> int: args = _parse_args(argv) with program_telemetry(pipeline=TELEMETRY_PIPELINE) as telemetry: @@ -532,6 +578,13 @@ def _build(args: argparse.Namespace, telemetry: LocalTelemetryEmitter) -> int: donor_channel=args.donor_channel, target_families=transfer_plan, ) + # microcosm#454: qualify the ESI employer premium's donor before the SIPP + # donor load and the ACS fetch, so a donor that cannot carry the premium + # onto the ACS spine fails in minutes, not after the transfer. + esi_premium_waiver = _qualify_esi_premium_donor( + base, allow_gaps=args.allow_esi_premium_gaps + ) + transfer_esi_premiums = esi_premium_waiver is None # microcosm#1022: resolve and verify the pinned SIPP donor before the ACS # fetch and transfer, so an unavailable donor fails in minutes, not hours. ssi_disability_donor, ssi_disability_identity = _load_ssi_disability_donor( @@ -578,9 +631,14 @@ def _build(args: argparse.Namespace, telemetry: LocalTelemetryEmitter) -> int: donor, seed=args.seed, period=args.period ), hours_under15_policy=args.hours_under15_policy, + esi_premium_donor_factory=( + prepare_acs_local_esi_premium_donor if transfer_esi_premiums else None + ), work_disability_inputs=True, income_transfer=True, native_receipt_anchors=True, + # microcosm#1154: the ACS rows' WIC decisions, drawn before pooling. + wic_take_up=True, # microcosm#1387: ACS SEMP already includes own-partnership income. semp_covers_partnership_income=True, donor_channel=args.donor_channel, @@ -606,7 +664,7 @@ def _build(args: argparse.Namespace, telemetry: LocalTelemetryEmitter) -> int: transfer_coverage = _require_default_transfer_coverage( result, base, - target_families=acs_local_transfer_target_families(), + target_families=_local_coverage_plan(esi_premiums=transfer_esi_premiums), ) weights_audit = _audit_fits(result) @@ -654,6 +712,14 @@ def _build(args: argparse.Namespace, telemetry: LocalTelemetryEmitter) -> int: raise SystemExit( "Local staging hours gate failed: " + "; ".join(hours_gate.failures) ) + # microcosm#454: grade the employer premium on the frame the staging H5 + # is written from, after the last stage that replaces the frame. + local_esi_premiums = _local_esi_premium_evidence( + result, + period=args.period, + waiver=esi_premium_waiver, + allow_gaps=args.allow_esi_premium_gaps, + ) telemetry.transition_stage("export") args.out_h5.parent.mkdir(parents=True, exist_ok=True) @@ -686,6 +752,14 @@ def _build(args: argparse.Namespace, telemetry: LocalTelemetryEmitter) -> int: base_mass=base_mass, base_sha256=base_sha256, donor_release=donor_release, + # The legacy rule keeps a donor's assigned tract, district and county, + # a block_v1 base's among them, so the summary records which rule + # located the donors under either rule. + base_location=( + base_location + if base_location is not None + else _base_location_rule(args.base_h5) + ), manifest_sha256=manifest_sha256, result=result, weights_audit=weights_audit, @@ -724,6 +798,7 @@ def _build(args: argparse.Namespace, telemetry: LocalTelemetryEmitter) -> int: summary.update(work_disability) summary.update(income) summary.update(ssi_disability) + summary["local_esi_premiums"] = local_esi_premiums summary_path.parent.mkdir(parents=True, exist_ok=True) rendered = json.dumps(summary, indent=2, sort_keys=True, allow_nan=False) + "\n" summary_path.write_text(rendered, encoding="utf-8") @@ -731,6 +806,78 @@ def _build(args: argparse.Namespace, telemetry: LocalTelemetryEmitter) -> int: return 0 +def _qualify_esi_premium_donor(base: Frame, *, allow_gaps: bool) -> str | None: + """Qualify the donor of the employer premium before ACS acquisition. + + Returns ``None`` for a qualified donor, or the refusal a diagnostic build + waived (``--allow-esi-premium-gaps``). The transfer qualifies the donor + again when it selects its rows, so no selection is held through the ACS + load. + """ + + try: + prepare_acs_local_esi_premium_donor(base) + except ValueError as exc: + if not allow_gaps: + raise SystemExit( + "Dense ASEC-by-PUF donor failed the ESI employer premium " + f"qualification: {exc} Pass --allow-esi-premium-gaps only for " + "a diagnostic build." + ) from exc + return str(exc) + return None + + +def _local_coverage_plan(*, esi_premiums: bool) -> TargetFamilies: + """Every input the lane's transfers owe the ACS spine.""" + + plan = { + entity: dict(families) + for entity, families in acs_local_transfer_target_families().items() + } + if esi_premiums: + local = acs_local_esi_premium_transfer_target_families() + for entity, families in local.items(): + plan.setdefault(entity, {}).update(families) + return plan + + +def _local_esi_premium_evidence( + result: AcsMultispineResult, + *, + period: int, + waiver: str | None, + allow_gaps: bool, +) -> dict[str, object]: + """Grade the employer premium on the pooled staging frame (microcosm#454). + + Both gates run on the frame the staging H5 is written from: the donor + rows get the MEPS-IC recomputation and the ACS rows are compared with + them. A red gate fails the build unless a diagnostic build waived it; the + verdicts are recorded either way. + """ + + signal, anchor = acs_local_esi_premium_gates(result.frame, time_period=period) + evidence: dict[str, object] = { + "enforced": not allow_gaps, + "transferred": waiver is None, + "donor_qualification_waived": waiver, + "provenance": result.provenance.get("local_esi_premiums"), + "signal_gate": acs_local_esi_premium_gate_payload(signal), + "anchor_gate": acs_local_esi_premium_gate_payload(anchor), + } + failures = [ + f"{gate.name}: {failure}" + for gate in (signal, anchor) + for failure in gate.failures + ] + if failures and not allow_gaps: + raise SystemExit( + "Local staging ESI employer premium gates failed: " + "; ".join(failures) + ) + return evidence + + def _audit_fits(result: AcsMultispineResult) -> dict[str, object]: records = result.fit_records if not records: @@ -2011,6 +2158,7 @@ def _build_summary( base_mass: float, base_sha256: str, donor_release: dict[str, object] | None, + base_location: dict[str, object], manifest_sha256: str, result: AcsMultispineResult, weights_audit: dict[str, object], @@ -2040,6 +2188,7 @@ def _build_summary( "n_estimators": args.n_estimators, "max_targets_per_fit": args.max_targets_per_fit, "donor_channel": args.donor_channel, + "allow_esi_premium_gaps": bool(args.allow_esi_premium_gaps), "provenance": result.provenance, } if block_location: @@ -2085,7 +2234,9 @@ def _build_summary( "rows": base_rows, "household_weight_total": base_mass, "donor_release": donor_release, + "location": base_location, }, + "engine_versions": _engine_versions(), "acs_sources": _source_provenance( manifest, source, diff --git a/tools/build_us_acs_local_release.py b/tools/build_us_acs_local_release.py index a92d124e92..2232417f2b 100644 --- a/tools/build_us_acs_local_release.py +++ b/tools/build_us_acs_local_release.py @@ -63,8 +63,9 @@ participation rate). finalize : release-style gate report (PUMA-ladder gate, calibration gate, district ESS collapse gate -- report-only unless - ``--district-ess-gate-blocking`` --, spine-composition - evidence) + the reviewed-limitations + ``--district-ess-gate-blocking`` --, both ESI employer-premium + gates on the calibrated artifact (microcosm#454), + spine-composition evidence) + the reviewed-limitations register for this lineage (inherited #507 SSI aged-band collapse, #393 miscellaneous-income defect, CD marginal vintage, ESS concentration, sparse-selection donor, mixed @@ -114,6 +115,7 @@ import argparse import gc import hashlib +import io import json import resource import shutil @@ -122,9 +124,11 @@ import threading import time from collections import defaultdict +from collections.abc import Mapping from contextlib import contextmanager from datetime import UTC, datetime from pathlib import Path +from types import MappingProxyType import numpy as np import pandas as pd @@ -133,6 +137,11 @@ 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 +from microcosm.build.us_runtime.acs_local_esi_premiums import ( + acs_local_esi_premium_anchor_gate, + acs_local_esi_premium_gate_payload, + acs_local_esi_premium_signal_gate, +) from microcosm.build.us_runtime.acs_local_hours import acs_local_hours_signal_gate from microcosm.build.us_runtime.acs_local_immigration import ( ACS_LOCAL_IMMIGRATION_COLUMNS, @@ -181,11 +190,13 @@ with_recorded_acs_local_ssi_medicaid_take_up, ) from microcosm.build.us_runtime.acs_local_take_up import ( + ACS_LOCAL_EITC_TAKE_UP_ISSUE, ACS_LOCAL_ENGINE_FREE_FILL_COLUMNS, ACS_LOCAL_ENGINE_FREE_FILLS_ISSUE, ACS_LOCAL_TAKE_UP_COLUMNS, ACS_LOCAL_TAKE_UP_GATE_NAME, ACS_VEHICLES_AVAILABLE_RECEIPT, + US_EITC_TAKE_UP_OUTPUT_COLUMN, acs_local_take_up_signal_gate, with_acs_local_take_up_inputs, ) @@ -193,12 +204,16 @@ US_VEHICLES_OWNED_COLUMN, US_VEHICLES_VALUE_COLUMN, ) +from microcosm.build.us_runtime.acs_local_wic_take_up import ( + ACS_LOCAL_WIC_TAKE_UP_ISSUE, + US_WIC_TAKE_UP_COLUMN, +) from microcosm.build.us_runtime.acs_local_work_disability import ( ACS_LOCAL_DISABILITY_COLUMNS, ACS_LOCAL_WORK_DISABILITY_GATE_NAME, ACS_LOCAL_WORK_DISABILITY_ISSUE, ACS_NATIVE_PROVENANCE, - WEEKS_WORKED_EXPORT_BLOCKER, + WEEKS_WORKED_INPUT_CHANGE, acs_local_work_disability_signal_gate, ) from microcosm.build.us_runtime.acs_pums import ACS_2024_1YR_SPINE @@ -233,9 +248,11 @@ rewrite_release_dir, ) from microcosm.data.contract import ( + US_EVIDENCE_RELEASE_ID, US_LOCAL_AREA_SPM_MEASUREMENT_STAGE, US_LOCAL_AREA_STORED_INPUTS_STAGE, US_LOCAL_RELEASE_ID, + US_NATIONAL_RELEASE_ID, US_RELEASE_DATASET_FILES, US_SPM_MEASUREMENT_EVIDENCE_KEY, US_STORED_INPUTS_EVIDENCE_KEY, @@ -843,6 +860,13 @@ class DeniedDefaultFillError(ValueError): ) for column in ACS_LOCAL_TAKE_UP_COLUMNS }, + # microcosm#1675: likewise EITC take-up, which the ACS take-up stage draws + # from the take-up contract on ACS tax units. + ("tax_unit", US_EITC_TAKE_UP_OUTPUT_COLUMN): ( + "the engine default is universal EITC take-up " + f"({ACS_LOCAL_EITC_TAKE_UP_ISSUE}); run the ACS local take-up stage " + "first" + ), # microcosm#1020: the immigration defaults are a citizen with a valid SSN # and 5 years since entry; staging's ACS local immigration stage fills # them. @@ -935,6 +959,14 @@ class DeniedDefaultFillError(ValueError): ACS_LOCAL_SSI_MEDICAID_TAKE_UP_COLUMNS, ("SSI", "Medicaid"), strict=True ) }, + # microcosm#1154: the WIC take-up default, True, is universal take-up; + # staging draws the ACS rows' decisions with the national generator and + # the donor release carries its own. + ("person", US_WIC_TAKE_UP_COLUMN): ( + "the engine default is universal WIC take-up " + f"({ACS_LOCAL_WIC_TAKE_UP_ISSUE}); re-run staging with the current " + "builder" + ), } NEVER_DEFAULT_FILLED = frozenset(_NEVER_DEFAULT_FILLED_REASONS) @@ -1044,6 +1076,7 @@ def fill_reviewed_nulls( *, engine=None, system=None, + quiet: bool = False, ): """Apply the nullable-artifact contract for the engine pass (H5 untouched). @@ -1056,7 +1089,9 @@ def fill_reviewed_nulls( one, or a null one, raises :class:`DeclaredSourceInputNullError`. Nor is the ESI employer premium input, registered or not: a null there refuses the build. ``engine`` and ``system`` default to the - PolicyEngine-US adapter and tax-benefit system. + PolicyEngine-US adapter and tax-benefit system. ``quiet`` logs nothing, + for a pass over one household chunk of the frame, whose null counts + never match the register's. """ denied = [ @@ -1070,9 +1105,12 @@ def fill_reviewed_nulls( f"Refusing to default-fill runtime-owned input(s): {'; '.join(denied)}." ) - # microcosm#454: the ESI employer premium exists only where the - # meps_esi_premiums stage ran (the ASEC donor rows). Refuse before any - # fill: a registered null here would become a silent zero on the ACS spine. + # microcosm#454: the staging build transfers the ESI employer premium onto + # the ACS spine and holds it to the donor rows' scale, so every row of a + # current staging frame carries it. A null means a staging H5 built before + # that, or a diagnostic one that waived it (--allow-esi-premium-gaps). + # Refuse before any fill: a registered null here would become a silent + # zero on the ACS spine. refuse_unassigned_us_esi_premiums( frame, consumer="ACS local release (fill_reviewed_nulls)" ) @@ -1182,16 +1220,17 @@ def fill_reviewed_nulls( indent=2, ) ) - log( - f"reviewed-null fill: {len(fills)} registered column(s), " - f"{sum(f['filled_rows'] for f in fills):,} values (engine pass only)" - ) - for drift in drift_warnings: + if not quiet: log( - f" WARNING count drift {drift['entity']}.{drift['column']}: " - f"actual {drift['filled_rows']} vs register " - f"{drift['register_missing_rows']}" + f"reviewed-null fill: {len(fills)} registered column(s), " + f"{sum(f['filled_rows'] for f in fills):,} values (engine pass only)" ) + for drift in drift_warnings: + log( + f" WARNING count drift {drift['entity']}.{drift['column']}: " + f"actual {drift['filled_rows']} vs register " + f"{drift['register_missing_rows']}" + ) if violations: detail = "; ".join( f"{v['entity']}.{v['column']} ({v['missing_rows']} null rows, " @@ -1312,6 +1351,109 @@ def _household_codes(release_tool, households, column: str) -> np.ndarray: ) +def _needs_county_soi_support(args, geographies) -> bool: + """Whether minimum support must give county SOI rows support too. + + Only a county SOI surface (``--soi-mode state_county`` with county + geography) builds county AGI rows, and ``--county-min-support 0`` turns + minimum support off altogether (microcosm#1661). + """ + + return ( + getattr(args, "soi_mode", None) == SOI_MODE_STATE_COUNTY + and "county" in geographies + and int(getattr(args, "county_min_support", 0) or 0) > 0 + ) + + +#: Households per chunk of the AGI pass: the AGI's dependencies alone are +#: light (the pre-R2 AGI check's chunk). +AGI_PASS_HH_CHUNK = 100_000 + + +def _household_agi( + frame, + summary_path: Path, + *, + hh_chunk: int = AGI_PASS_HH_CHUNK, + period: int = PERIOD, +) -> np.ndarray: + """Each household's AGI as the state SOI AGI row stores it, before the + engine pass (microcosm#1661). + + The household sum of ``adjusted_gross_income`` over its tax units, in the + household table's order, from the same input projection and reviewed-null + fill as :func:`materialize_chunked`, one household chunk at a time so no + second copy of the frame is held. Minimum support reads it to give a + county whose households all store an AGI of 0 households with an AGI. In + the build's year the AGI does not read a household's county, so the moves + that follow leave it unchanged. + """ + + import build_us_fiscal_refresh_release as release_tool + from policyengine_us import CountryTaxBenefitSystem, Microsimulation + + from microcosm.frame.adapters.policyengine_us import PolicyEngineUSEngine + + engine = PolicyEngineUSEngine() + system = CountryTaxBenefitSystem() + household_ids = frame.table("household")["household_id"].to_numpy() + n_households = len(household_ids) + positions = pd.Index(household_ids) + if not positions.is_unique: + raise ValueError("Household ids must be unique.") + person_position = positions.get_indexer( + frame.table("person")["person_household_id"].to_numpy() + ) + if (person_position < 0).any(): + raise RuntimeError( + "person rows reference household ids absent from the household " + "table; frame is invalid." + ) + if n_households > hh_chunk: + release_tool._assert_group_entities_nest_in_households(frame) + agi = np.zeros(n_households, dtype=np.float64) + started = time.time() + for low in range(0, n_households, hh_chunk): + high = min(low + hh_chunk, n_households) + chunk = frame.select((person_position >= low) & (person_position < high)) + projected, _held = project_input_only(chunk, period=period) + fill_reviewed_nulls( + projected, + summary_path, + manifest_path=None, + period=period, + engine=engine, + system=system, + quiet=True, + ) + simulation = Microsimulation( + dataset=release_tool._dataset_from_frame( + projected, assert_no_formula_owned_columns=False, period_only=True + ) + ) + got = np.asarray(simulation.calculate("household_id", period).values) + if not np.array_equal(got, household_ids[low:high]): + raise RuntimeError( + "The AGI pass's engine chunk does not carry its households in " + "frame order; refusing to place its AGI." + ) + agi[low:high] = np.asarray( + simulation.calculate( + "adjusted_gross_income", period, map_to="household" + ).values, + dtype=np.float64, + ) + del simulation, projected, chunk + gc.collect() + log( + f"household AGI for county SOI support: {n_households} households, " + f"{int((agi.astype(np.float32) != 0).sum())} with a nonzero AGI " + f"({time.time() - started:.1f}s)" + ) + return agi + + def materialize_chunked( base_frame, specs, @@ -2300,6 +2442,12 @@ def do_materialize(args) -> None: _require_local_income_transfer(staging_summary) _require_local_ssi_disability(staging_summary) _require_local_receipt_anchors(staging_summary) + _require_staging_engine(staging_summary) + # microcosm#1661: the donor's REVIEWED_DONOR_LINEAGES entry is required + # from calibrate on, not here. Materialize writes nothing the entry + # decides, so it can run while the new donor's evidence is reviewed; + # calibrate fixes the commit package accepts, so the entry must be in + # the checkout before calibrate starts, and finalize checks it again. # microcosm#1022: the SSI and Medicaid take-up counts, from the same feed # and compile path, before the staging frame is loaded. ssi_medicaid_targets = acs_local_ssi_medicaid_take_up_targets(args.feed) @@ -2360,8 +2508,18 @@ def do_materialize(args) -> None: Path(args.gate_report).unlink(missing_ok=True) # microcosm#922: a county with ladder population but no household gets a # fixed number of same-PUMA households before any measure is built; the - # frame returned carries their rewritten county columns. - frame = county_surface.check_support(frame, populations, args) + # frame returned carries their rewritten county columns. On a county SOI + # surface, a county whose households all store an AGI of 0 gets + # households with an AGI too (microcosm#1661), so the AGI comes first. + household_agi = ( + _household_agi(frame, summary_path, period=PERIOD) + if _needs_county_soi_support(args, geographies) + else None + ) + frame = county_surface.check_support( + frame, populations, args, household_agi=household_agi + ) + del household_agi materialized = materialize_chunked( frame, registry.specs, @@ -3029,6 +3187,10 @@ def do_calibrate(args) -> None: _require_local_income_transfer(staging_summary) _require_local_ssi_disability(staging_summary) _require_local_receipt_anchors(staging_summary) + # microcosm#1661: and a donor of another lineage whose inherited + # limitations nobody reviewed. Calibrate fixes the commit package accepts, + # so the entry must be in the checkout before the solve starts. + _require_reviewed_donor_lineage(staging_summary) # microcosm#1022: and a checkpoint without the recorded ACS SSI/Medicaid # take-up the export must apply. _recorded_ssi_medicaid_take_up(identity, args.checkpoint_dir) @@ -3463,12 +3625,9 @@ def _write_calibrated_artifact( f"{len(staging_ids)} households." ) - # TODO(policyengine-us#9660): the staging ACS rows carry native - # weeks_worked (microcosm#1021), but the pinned policyengine-us gives it a - # formula_2025, so this projection holds it back as formula-owned. Once - # #9660 part A1 deletes that formula and the pin/ABI lock are bumped, it - # becomes an input and ships; the donor rows then need weeks_worked from - # WKSWORK too (US_HOURS_WORKED_POOL_EXCLUDED_COLUMNS). + # On policyengine-us 2.145.3 weeks_worked is an input (policyengine-us#9660 + # part A1), so this projection keeps it: ACS rows carry native WKWN weeks + # (microcosm#1021), and donor rows the national's WKSWORK weeks. projected, dropped = project_input_only(frame, period=PERIOD) del frame gc.collect() @@ -4078,6 +4237,53 @@ def _ess_concentration_limitation(diagnostics: dict) -> dict: #: release discloses the inherited erasure. DONORS_WITHOUT_SOCIAL_SECURITY_ERASURE: frozenset[str] = frozenset() +#: The inherited limitations ``finalize_reviewed_limitations`` writes about +#: the donor. Each describes the Build O lineage (the certified Build O sparse +#: release and the enrichments built on it): its aged SSI take-up, its +#: miscellaneous income loss side, its tip-return count, its 57,240-household +#: selection and its Social Security erasure. +BUILD_O_LINEAGE_LIMITATIONS = ( + "ssi_aged_band_collapse_inherited", + "miscellaneous_income_loss_side_donor_defect", + "tips_return_count_carrier_deficit_inherited", + "donor_sparse_selection_training_set", + "social_security_cps_reporters_erased_inherited", +) +#: Donor builds outside the Build O lineage, each with the +#: :data:`BUILD_O_LINEAGE_LIMITATIONS` that a review of its own evidence found +#: to hold for it; the others leave its releases' register (microcosm#1661). +REVIEWED_DONOR_LINEAGES: Mapping[str, frozenset[str]] = MappingProxyType({}) +#: A national build published into a build folder of these releases (since +#: microcosm#1570 and #1585 item 11) is not of the Build O lineage, so a +#: staging from one is refused until it has a :data:`REVIEWED_DONOR_LINEAGES` +#: entry. +_REVIEWED_LINEAGE_DONOR_RELEASES = frozenset( + {US_NATIONAL_RELEASE_ID, US_EVIDENCE_RELEASE_ID} +) + + +def _require_reviewed_donor_lineage(staging_summary: dict) -> None: + """Refuse a national donor whose inherited limitations nobody reviewed. + + A release's register says what its donor carries. Without this, a donor + of another lineage would publish the Build O lineage's limitations as its + own (microcosm#1661). + """ + + donor = (staging_summary.get("base") or {}).get("donor_release") or {} + if donor.get("release") not in _REVIEWED_LINEAGE_DONOR_RELEASES: + return + build = _donor_build_id(donor) + if build not in REVIEWED_DONOR_LINEAGES: + raise SystemExit( + f"The staging's donor is national build {build!r} of " + f"{donor.get('release')!r}, which is not of the Build O lineage " + "that the release's inherited limitations " + f"({', '.join(BUILD_O_LINEAGE_LIMITATIONS)}) describe. Review each " + "against the donor's own evidence and add the build to " + "REVIEWED_DONOR_LINEAGES with those that hold (microcosm#1661)." + ) + def _donor_build_id(donor_release: dict) -> str | None: """The donor build's ID from either reference form (microcosm#1570). @@ -4244,10 +4450,13 @@ def finalize_reviewed_limitations( "donor spine's share among ages 3-5 " "(acs_engine_free_default_fills), and SSI and Medicaid " "take-up are assigned after an engine pre-pass " - "(acs_local_ssi_medicaid_take_up). The other runtime-owned " - "takes_up_* flags (EITC, ACA, Early Head Start and the rest) " - "are neither transferred nor seeded on ACS rows, so they ship " - "at the engine default, universal take-up; the reviewed-fill " + "(acs_local_ssi_medicaid_take_up). EITC take-up is the take-up " + "contract's seeded draw by number of qualifying children " + "(microcosm#1675), and WIC take-up the national generator's " + "draw, made in staging (microcosm#1154). The other " + "runtime-owned takes_up_* flags (ACA, Early Head Start and the " + "rest) are neither transferred nor seeded on ACS rows, so they " + "ship at the engine default, universal take-up; the reviewed-fill " "consumer register records their known biases " "(acs_reviewed_default_fill_consumers). The QA " "probe's SNAP take-up table is a December-eligible snapshot " @@ -4325,21 +4534,24 @@ def finalize_reviewed_limitations( "at home and available to the household, long-term leased and " "employer-provided ones included, while the donor's SIPP " "TVEH_NUM and the engine count vehicles owned. policyengine-us " - "2.2.1 reads the owned count on its own in San Francisco CAAP's " - "one-vehicle limit for a single person " + "2.145.3 reads the owned count on its own only in San " + "Francisco CAAP's one-vehicle limit for a single person " "(ca_sf_caap_vehicle_eligible), Los Angeles General Relief's " "vehicle cap (la_general_relief_motor_vehicle_value_eligible) " "and lives_in_vehicle, which Los Angeles and Marin General " "Relief read, so VEH as the owned count would deny a single San " - "Francisco applicant who leases two cars and owns none. The " - "engine has no vehicles-available input, so VEH is recorded in " + "Francisco applicant who leases two cars and owns none. Its " + "other readers only scale exemptions of the value by the count " + "or average the value over it, which the zero value leaves at " + "zero. The engine has no vehicles-available input, so VEH is " + "recorded in " "the take-up receipt as availability only. A zero count always " "passes the San Francisco CAAP and Los Angeles General Relief " "count caps, so they overstate eligibility for households that " "own more vehicles than the cap, the same direction as the zero " "value; lives_in_vehicle is never true on ACS rows, which only " "picks Los Angeles's value limit and Marin's vehicle exemption, " - "both applied to the zero value. In policyengine-us 2.2.1 the " + "both applied to the zero value. In policyengine-us 2.145.3 the " "value's only SNAP consumer is Texas's broad-based categorical " "eligibility asset test (meets_tanf_non_cash_asset_test), which " "counts vehicle value above $22,500 for the first vehicle and " @@ -4407,16 +4619,16 @@ def finalize_reviewed_limitations( "arriving (arrival in 2014 and status in 2023 gives 10 " "modeled years in 2024, against one qualifying year; " "policyengine-us#9658). That affects the policyengine-us " - "2.2.1 tests that read the clock: Medicaid (CHIP follows " - "it) and Washington TANF read it against a five-year bar, " - "so the long clock can clear the bar early; Washington RCA " - "reads it as a window that closes (years_since_us_entry < " - "window_years), so the long clock can wrongly exclude a " - "recently qualified person from RCA. Under the statute the " - "SNAP five-year bar also runs from entry with qualified " - "status, but the pinned engine's federal SNAP status test " - "reads the status, not this clock, so any SNAP effect is " - "indirect. The receipt " + "2.145.3 tests that read the clock. SNAP's qualified-alien " + "waiting period, the federal Medicaid and CHIP " + "immigration-status tests, Medicare Part B for permanent " + "residents, Washington TANF, Missouri and New Hampshire SSP, " + "Nevada LIHEAP and Utah HEAT read it against a bar, five years " + "for SNAP and Medicaid, so the long clock can clear the bar " + "early; Washington RCA reads it as a window that closes " + "(years_since_us_entry < window_years), so the long clock can " + "wrongly exclude a recently qualified person from RCA. The " + "receipt " "reports the size of the affected group under each lag of " "one to ten, 15 and 20 years; the real-data check is " "microcosm#1093." @@ -4447,10 +4659,11 @@ def finalize_reviewed_limitations( "definition), and is_blind is DEYE == 1. An item below its " "minimum question age (5 for DPHY/DREM/DDRS, 15 for DOUT) is " "blank and reads as no difficulty. Native ACS weeks_worked " - "(WKWN, under the WKHP universe rules) is carried on the " - "staging ACS spine only: the pinned policyengine-us gives " - "weeks_worked a formula_2025, so the export holds it back as " - f"formula-owned until {WEEKS_WORKED_EXPORT_BLOCKER}. is_veteran " + "(WKWN, under the WKHP universe rules) is exported on ACS " + "rows: on policyengine-us 2.145.3 it is an input " + f"({WEEKS_WORKED_INPUT_CHANGE}). Its blank cells, persons " + "under 16 among them, take the reviewed fill 0, the value the " + "donor gives its own not-in-universe rows. is_veteran " "(ACS MIL == 2) is not exported because policyengine-us " "computes it from veterans_benefits for every year; " "is_incapable_of_self_care stays on the ASEC transfer." @@ -4584,7 +4797,7 @@ def finalize_reviewed_limitations( "probability residual / anchored eligible weight on a keyed " "draw, and the state's excess is recorded. The treatment is " "state-level because the CMS counts carry no child/adult " - "split; policyengine-us 2.2.1 keeps CHIP take-up separate " + "split; policyengine-us 2.145.3 keeps CHIP take-up separate " "and CHIP eligibility exclusive of Medicaid eligibility. " "Draws are keyed on acs_2024_1yr:SERIALNO:SPORDER and the " "build seed. The targets bind the pre-calibration frame; the " @@ -4772,6 +4985,15 @@ def finalize_reviewed_limitations( acs_wic = _acs_wic_takeup_limitation(consumer_export) if acs_wic is not None: limitations.append(acs_wic) + # A donor outside the Build O lineage keeps only the inherited + # limitations its review found to hold (microcosm#1661). + reviewed = REVIEWED_DONOR_LINEAGES.get(_donor_build_id(donor_release)) + if reviewed is not None: + limitations = [ + item + for item in limitations + if item["id"] not in BUILD_O_LINEAGE_LIMITATIONS or item["id"] in reviewed + ] deduped: dict[str, dict] = {} for limitation in limitations: deduped[limitation["id"]] = limitation @@ -5441,6 +5663,32 @@ def _require_local_receipt_anchors(staging_summary: dict) -> dict: ) +def _require_staging_engine( + staging_summary: dict, *, installed: str | None = None +) -> None: + """Refuse a staging run made on another policyengine-us than this one. + + Staging audits the nulls of every input its own engine defines + (``reviewed_engine_input_nulls``), so on another engine the fill step + meets inputs that audit never listed, hours into materialize, and package + refuses the columns that engine retired. A staging summary that records + no engine predates the record, so it is refused too: re-run staging on + this engine. ``installed`` defaults to the installed policyengine-us (the + reviewed-fill pre-check passes its own). + """ + + recorded = (staging_summary.get("engine_versions") or {}).get("policyengine_us") + if installed is None: + installed = _installed_engine_version() + if recorded != installed: + raise SystemExit( + f"The staging summary records policyengine-us {recorded!r} and this " + f"release runs {installed!r}. Staging audits the nulls of the " + "inputs its own engine defines, so re-run staging on this engine " + "(the summary's engine_versions)." + ) + + def _installed_engine_version() -> str: try: from importlib.metadata import version @@ -5615,6 +5863,64 @@ def _require_acs_self_employment_identity(frame): ) +#: The lane's verdict on the ESI employer premium (microcosm#454), in the +#: gate report finalize writes and package requires. +ESI_PREMIUM_GATE_NAMES = ("esi_premiums_signal", "esi_premiums_anchor") + + +def _esi_premium_gate_entry(gate, *, artifact_sha256: str, enforced: bool) -> dict: + """One ESI premium verdict, bound to the artifact bytes it graded.""" + + payload = acs_local_esi_premium_gate_payload(gate) + return { + "passed": payload["passed"], + "failures": payload["failures"], + "detail": payload["details"], + "artifact_sha256": artifact_sha256, + "enforced": enforced, + } + + +def _require_esi_premium_gates(gates, *, h5_sha: str, allow_gaps: bool) -> None: + """Refuse to package without the lane's ESI premium verdict on these bytes. + + Without ``--allow-esi-premium-gaps`` both gates must be present, passing + and bound to the bytes being packaged, the check every other finalize + gate gets (:func:`_require_bound_finalize_gate`). With it, each gate must + still carry a boolean verdict bound to these bytes: a report finalized + before the gates existed carries neither and is always refused. A red + gate then packages only as the waiver finalize recorded (``enforced: + false``), so the shipped report says the waiver was taken; a red gate + finalize enforced is refused, whatever this stage's flag says. + """ + + for name in ESI_PREMIUM_GATE_NAMES: + if not allow_gaps: + _require_bound_finalize_gate(gates, name, h5_sha) + continue + gate = gates.get(name) if isinstance(gates, dict) else None + if not isinstance(gate, dict) or not isinstance(gate.get("passed"), bool): + raise SystemExit( + f"The finalize gate report carries no {name} verdict " + "(microcosm#454); an old simulation_ready summary is " + "insufficient. Re-run --stage finalize." + ) + if gate.get("artifact_sha256") != h5_sha: + raise SystemExit( + f"The {name} gate is missing its artifact binding or certifies " + "different H5 bytes. Re-run --stage finalize against the " + "current artifact." + ) + if not gate["passed"] and gate.get("enforced") is not False: + raise SystemExit( + f"The {name} gate is red and finalize did not record a waiver " + "for it (enforced is not false), so the report would ship a " + "red verdict marked enforced. --allow-esi-premium-gaps at " + "package admits only a waiver finalize recorded: re-run --stage " + "finalize with --allow-esi-premium-gaps." + ) + + def do_finalize(args) -> None: from microcosm.build.us_runtime.hours_worked import ( US_HOURS_WORKED_POOL_OUTPUT_COLUMNS, @@ -5627,6 +5933,7 @@ def do_finalize(args) -> None: from microcosm.calibrate import TargetRegistry staging_summary = _load_json(_staging_summary_path(args)) + _require_reviewed_donor_lineage(staging_summary) diagnostics = _load_json(args.checkpoint_dir / "calibration_summary.json") if not diagnostics: raise SystemExit( @@ -5751,7 +6058,8 @@ def do_finalize(args) -> None: # 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. + # staging, where its blanks are the ACS universe's; the packaged file + # carries it with the reviewed fill in those cells. work_disability_gate = shadow_gate( "us_local_work_disability", lambda frame=frame: acs_local_work_disability_signal_gate( @@ -5835,6 +6143,24 @@ def do_finalize(args) -> None: }, ), ) + # microcosm#454: the lane's own verdict on the ESI employer premium, on + # the calibrated bytes. The donor rows get the MEPS-IC recomputation, the + # ACS rows are compared with them, and the anchor-universe total is held + # to the stage's national anchor at the calibrated weights. + esi_signal_gate = _shadow_local_frame_gate( + "us_local_esi_premiums_signal", + lambda frame=frame: acs_local_esi_premium_signal_gate(frame), + frame, + ) + esi_anchor_gate = shadow_gate( + "us_local_esi_premiums_anchor", + lambda frame=frame: acs_local_esi_premium_anchor_gate( + frame, time_period=PERIOD + ), + lambda frame=frame: EvidenceContext( + frame=frame, artifacts={"time_period": PERIOD} + ), + ) del frame gc.collect() if _sha256(args.out_h5) != hours_artifact_sha: @@ -6003,17 +6329,35 @@ def do_finalize(args) -> None: ), "detail": diagnostics.get("weight_origin"), }, + "esi_premiums_signal": _esi_premium_gate_entry( + esi_signal_gate, + artifact_sha256=hours_artifact_sha, + enforced=not args.allow_esi_premium_gaps, + ), + "esi_premiums_anchor": _esi_premium_gate_entry( + esi_anchor_gate, + artifact_sha256=hours_artifact_sha, + enforced=not args.allow_esi_premium_gaps, + ), "input_coverage": { - # Enforced upstream: the staging driver's donor-coverage gate - # hard-fails before transfer, so reaching finalize means it held. - "passed": True, + # The donor's own coverage is enforced upstream: the staging + # driver's donor-coverage gate hard-fails before transfer, so + # reaching finalize means it held. That says nothing about a + # required input on the ACS spine, so the one this lane produces + # there from a stage output, the ESI employer premium, is graded + # on this artifact by the two gates above (microcosm#454). + "passed": bool(esi_signal_gate.passed and esi_anchor_gate.passed), "binds": "donor_certified_release", + "graded_on_artifact": list(ESI_PREMIUM_GATE_NAMES), "note": ( "Input coverage is enforced on the certified donor release " "before transfer; the ACS spine inherits required inputs via " - "QRF transfer. ACS native GQ-housing / source-universe nulls " - "are reviewed_limitations (calibration_blocker: false) and " - "are NOT re-imposed on the ACS spine. Take-up draws are not " + "QRF transfer. The ESI employer premium (microcosm#454) is " + "also graded on the calibrated artifact: esi_premiums_signal " + "and esi_premiums_anchor. ACS native GQ-housing / " + "source-universe nulls are reviewed_limitations " + "(calibration_blocker: false) and are NOT re-imposed on the " + "ACS spine. Take-up draws are not " "transferred: ACS SNAP/TANF take-up is seeded by this tool " "and gated by acs_local_take_up_signal (microcosm#1019). The " "same stage fills the ACS rows' discretionary ABAWD exemption " @@ -6041,8 +6385,8 @@ def do_finalize(args) -> None: "row, gated by acs_local_work_disability_signal " "(microcosm#1021; reviewed limitation " "acs_work_disability_inputs). Native ACS weeks_worked is " - "staged but held back from the export until " - f"{WEEKS_WORKED_EXPORT_BLOCKER}. ACS child support " + "exported: on policyengine-us 2.145.3 it is an input " + f"({WEEKS_WORKED_INPUT_CHANGE}). ACS child support " "received/paid, workers' compensation, disability benefits " "and 401(k)/403(b)/SEP/Keogh/Roth-IRA distributions come from " "a separate local QRF pass on the donor's ASEC observation " @@ -6168,6 +6512,12 @@ def do_finalize(args) -> None: hard_failures.append(DISTRICT_ESS_GATE) if block_location_gate is not None and not block_location_gate.passed: hard_failures.append("us_block_location_gate") + # microcosm#454: --allow-esi-premium-gaps records a red ESI premium gate + # without failing a diagnostic build; the gate entries keep what was red. + if not args.allow_esi_premium_gaps: + hard_failures += [ + name for name in ESI_PREMIUM_GATE_NAMES if not gates[name]["passed"] + ] updated_summary = dict(staging_summary) updated_summary.update( { @@ -6188,7 +6538,7 @@ def do_finalize(args) -> None: "reviewed_limitations": limitations, "generated_at": datetime.now(UTC).isoformat(), } - args.gate_report.write_text(json.dumps(gate_report, indent=2)) + _write_gate_report(args, gate_report) if hard_failures: raise SystemExit( f"finalize: hard gate failure(s): {hard_failures} — see {args.gate_report}." @@ -6448,7 +6798,7 @@ def do_package(args) -> dict: "calibration_summary.json has no valid calibration_diagnostics status; " "run --stage calibrate with the current builder." ) - gate_report = _load_json(args.gate_report) + gate_report = _load_gate_report(args) staging_summary = _load_json(_staging_summary_path(args)) final_summary = _load_json(args.out_summary) held_back = _load_json(args.checkpoint_dir / "held_back_columns.json") @@ -6530,6 +6880,14 @@ def do_package(args) -> dict: out_h5_sha256=h5_sha, stage="package", ) + # microcosm#454: the lane's verdict on the ESI employer premium must be + # in the report and bound to these bytes. A refusal leaves no release + # directory behind. + _require_esi_premium_gates( + gate_report.get("gates"), + h5_sha=h5_sha, + allow_gaps=args.allow_esi_premium_gaps, + ) code = _repo_code_identity(args.allow_dirty) writer_dirty = _require_artifact_written_by( @@ -7234,6 +7592,22 @@ def _parse_args(argv: list[str] | None = None) -> argparse.Namespace: ), ) parser.add_argument("--allow-dirty", action="store_true") + parser.add_argument( + "--allow-esi-premium-gaps", + action="store_true", + help=( + "Diagnostic escape hatch (microcosm#454): record the ESI premium " + "gates on the calibrated artifact -- " + "employer_sponsored_insurance_premiums absent, zero-mass, missing " + "on the ACS spine, missing its raw ASEC coverage columns, or off " + "the stage's national anchor -- without failing finalize or " + "package (for example on a staging H5 built from a donor that " + "predates the meps_esi_premiums stage). The failures are still " + "written to the gate report. Package takes a red gate only as the " + "waiver finalize recorded, so finalize needs the flag too. Release " + "builds must leave this unset." + ), + ) parser.add_argument( "--allow-partial-geography", action="store_true", @@ -7358,7 +7732,282 @@ 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: +#: The --allow-* flags that waive one of this scope's entries today, by +#: argparse destination: (destination, flag, stage, entry ids), where the +#: stage is the one that evaluates those entries. The shadow records them by +#: entry id; the battery evaluates every entry as if unwaived. The stages may +#: run as separate processes with different flags, so an entry's waiver is +#: the one its own stage ran with (:func:`_recorded_local_gate_waivers`). +_LOCAL_GATE_WAIVERS: tuple[tuple[str, str, str, tuple[str, ...]], ...] = ( + ( + "allow_esi_premium_gaps", + "--allow-esi-premium-gaps", + "finalize", + ("us_local_esi_premiums_signal", "us_local_esi_premiums_anchor"), + ), +) + + +def _local_gate_waivers(args, *, stage: str | None = None) -> dict[str, list[str]]: + """The waivers these flags apply, by entry id. + + With ``stage``, only to the entries that stage evaluates. + """ + + waivers: dict[str, list[str]] = {} + for destination, flag, evaluated_at, entry_ids in _LOCAL_GATE_WAIVERS: + if stage is not None and evaluated_at != stage: + continue + if getattr(args, destination, False): + for entry_id in entry_ids: + waivers.setdefault(entry_id, []).append(flag) + return waivers + + +def _local_stage_waivers(args, stage: str) -> Path: + return _local_gate_shadow_directory(args) / f"{stage}.waivers.json" + + +#: The stage that writes the gate report package selects (``--gate-report``). +#: Its waiver record names that report by SHA-256, so the shadow attaches the +#: record only to the report the same finalize run wrote. +_GATE_REPORT_STAGE = "finalize" + + +def _gate_report_sha256(args) -> str | None: + """The SHA-256 of the gate report at ``args.gate_report``; None without one.""" + + path = getattr(args, "gate_report", None) + if path is None or not Path(path).is_file(): + return None + return _sha256(Path(path)) + + +def _write_gate_report(args, gate_report: dict) -> None: + """Finalize's write of its gate report to ``args.gate_report``. + + Once the write succeeds, it sets ``args.gate_report_bytes_sha256`` to the + SHA-256 of the bytes written, which finalize's waiver record names + (:func:`_local_gate_shadow_stage`). + """ + + payload = json.dumps(gate_report, indent=2).encode("utf-8") + Path(args.gate_report).write_bytes(payload) + args.gate_report_bytes_sha256 = hashlib.sha256(payload).hexdigest() + + +def _load_gate_report(args) -> dict: + """Package's read of the gate report, parsed as :func:`_load_json` parses it. + + It reads ``args.gate_report`` once and sets ``args.gate_report_bytes_sha256`` + to the SHA-256 of the bytes it parses (None without a file), so the + shadow matches finalize's waiver record to those bytes, not to whatever + file the path holds when the stage ends. + """ + + path = Path(args.gate_report) + if not path.exists(): + args.gate_report_bytes_sha256 = None + return {} + payload = path.read_bytes() + args.gate_report_bytes_sha256 = hashlib.sha256(payload).hexdigest() + # Decoded as ``Path.read_text`` decodes: default encoding, universal newlines. + with io.TextIOWrapper(io.BytesIO(payload)) as text: + return json.loads(text.read()) + + +def _save_local_stage_waivers( + args, stage: str, *, gate_report_sha256: str | None = None +) -> None: + """Record the waivers ``stage`` applied to its own entries, for later stages. + + The gate report stage's record also names, by SHA-256, the gate report + that stage wrote, or None when it wrote none. + """ + + record: dict[str, object] = {"waivers": _local_gate_waivers(args, stage=stage)} + if stage == _GATE_REPORT_STAGE: + record["gate_report_sha256"] = gate_report_sha256 + path = _local_stage_waivers(args, stage) + path.parent.mkdir(parents=True, exist_ok=True) + staging = path.with_name(f"{path.name}.tmp") + staging.write_text( + json.dumps(record, indent=2, sort_keys=True) + "\n", + encoding="utf-8", + ) + staging.replace(path) + + +#: A record's ``gate_report_sha256`` when it has none: records saved before +#: they named a gate report held only the waivers, by entry id. +_NO_RECORDED_GATE_REPORT = object() + + +def _read_local_stage_waivers( + path: Path, stage: str +) -> tuple[dict[str, list[str]], object]: + """A stage's saved waivers by entry id, and the gate report digest it names. + + Raises ``FileNotFoundError`` when there is no file, and another + ``OSError``, ``RecursionError`` (JSON nested past the decoder's depth) or + ``ValueError`` (``json.JSONDecodeError`` among them) when it cannot read + the file or the file is not a waiver record: a mapping of the entries + ``stage`` evaluates to lists of flags, under ``waivers`` with an optional + ``gate_report_sha256``, or bare, as earlier records were. + """ + + saved = json.loads(path.read_text(encoding="utf-8")) + if not isinstance(saved, dict): + raise ValueError(f"the record is a {type(saved).__name__}, not a mapping") + digest: object = _NO_RECORDED_GATE_REPORT + waivers = saved + if "waivers" in saved: + unexpected = sorted(set(saved) - {"waivers", "gate_report_sha256"}) + if unexpected: + raise ValueError(f"the record has unexpected keys {unexpected}") + waivers = saved["waivers"] + digest = saved.get("gate_report_sha256", _NO_RECORDED_GATE_REPORT) + if digest is not None and digest is not _NO_RECORDED_GATE_REPORT: + if not ( + isinstance(digest, str) + and len(digest) == 64 + and all(character in "0123456789abcdef" for character in digest) + ): + raise ValueError( + f"gate_report_sha256 {digest!r} is not a SHA-256 hex digest" + ) + if not isinstance(waivers, dict) or not all( + isinstance(flags, list) and all(isinstance(flag, str) for flag in flags) + for flags in waivers.values() + ): + raise ValueError("its waivers are not lists of flags by entry id") + evaluated = { + entry_id + for _destination, _flag, evaluated_at, entry_ids in _LOCAL_GATE_WAIVERS + if evaluated_at == stage + for entry_id in entry_ids + } + foreign = sorted(set(waivers) - evaluated) + if foreign: + raise ValueError( + f"it names entries the {stage} stage does not waive: {foreign}" + ) + return {entry_id: list(flags) for entry_id, flags in waivers.items()}, digest + + +#: ``args.gate_report_bytes_sha256`` before package reads the gate report. +_GATE_REPORT_NOT_READ = object() + + +def _waiver_gate_report_mismatch(args, stage: str, recorded: object) -> str | None: + """Why ``stage``'s waiver record does not belong to the selected gate + report, or None when it names that report's digest, or names none and + the selected path holds no file (package then refuses: no gate report). + + The selected report is the bytes package parsed (:func:`_load_gate_report`). + A package run stopped before it read the report has none, so the shadow + then hashes the file at the path when the stage ends. + """ + + selected = getattr(args, "gate_report_bytes_sha256", _GATE_REPORT_NOT_READ) + if selected is _GATE_REPORT_NOT_READ: + try: + selected = _gate_report_sha256(args) + except OSError as error: + return ( + f"the selected gate report {getattr(args, 'gate_report', None)} " + f"could not be read to match the {stage} stage's waiver record " + f"to it ({type(error).__name__}: {error})" + ) + if recorded is _NO_RECORDED_GATE_REPORT: + return ( + f"the {stage} stage's waiver record names no gate report, so it " + "cannot be matched to the selected gate report " + f"{selected or 'none (no file)'}" + ) + if recorded != selected: + unnamed = ( + "none (that run wrote no gate report, or its report could not be read)" + ) + return ( + f"the {stage} stage's waiver record belongs to gate report " + f"{recorded or unnamed}, not to the selected gate report " + f"{selected or 'none (no file)'}" + ) + return None + + +#: What the shadow records as the waiver of an entry whose stage's waiver +#: record it cannot attach, since it then cannot know the flags that stage +#: ran with. +_UNKNOWN_STAGE_WAIVER = "unknown: {reason}" + + +def _recorded_local_gate_waivers(args, stage: str) -> dict[str, list[str]]: + """Each entry's waivers as the stage that evaluated it ran, by entry id. + + This stage's come from ``args``, and an earlier stage's from the record it + saved beside its observations (:func:`_local_gate_shadow_stage`), so a + later stage's flags never rewrite the waivers an earlier stage took or + refused. Finalize's record also names, by SHA-256, the gate report bytes + that run wrote, and the shadow attaches it only when those are the bytes + package read (:func:`_waiver_gate_report_mismatch`): a package run on + another finalize run's report would otherwise show that run's waiver. + + Each entry an earlier stage can waive records + :data:`_UNKNOWN_STAGE_WAIVER`, with the reason, instead of a waiver when + the stage left observations without a record (as a checkpoint saved + before stages kept one does), when the shadow cannot open or read its + record (JSON nested past the decoder's depth among the causes) or it is + not a waiver record, or when finalize's names another gate report, names + none while package read a gate report, or lacks the digest (as records + saved before they named one do). The shadow still rebuilds the + comparison. An earlier stage with neither file contributes none. The + shadow matches only the waiver to the gate report: it reads the latest + saved finalize observations, whichever report package selects. + """ + + waivers = _local_gate_waivers(args, stage=stage) + for name in _LOCAL_GATE_SHADOW_STAGES[: _LOCAL_GATE_SHADOW_STAGES.index(stage)]: + path = _local_stage_waivers(args, name) + # The read tells an absent record from one the shadow cannot open; + # ``Path.is_file`` would report a stat error as no file. + try: + saved, recorded = _read_local_stage_waivers(path, name) + except FileNotFoundError: + if not _local_stage_observations(args, name).is_file(): + continue + reason = f"the {name} stage saved no waiver record" + except (OSError, RecursionError, ValueError) as error: + reason = ( + f"{path.name} could not be read as a waiver record " + f"({type(error).__name__}: {error})" + ) + else: + reason = ( + _waiver_gate_report_mismatch(args, name, recorded) + if name == _GATE_REPORT_STAGE + else None + ) + if reason is None: + for entry_id, flags in saved.items(): + waivers.setdefault(entry_id, []).extend(flags) + continue + unknown = _UNKNOWN_STAGE_WAIVER.format(reason=reason) + for _destination, _flag, evaluated_at, entry_ids in _LOCAL_GATE_WAIVERS: + if evaluated_at == name: + for entry_id in entry_ids: + waivers.setdefault(entry_id, []).append(unknown) + log( + f"WARNING: gate battery shadow: {reason}; it records the {name} " + "stage's waivers as unknown." + ) + return waivers + + +def _local_gate_shadow( + args, directory: Path, *, waivers: dict[str, list[str]] | None = None +) -> GateBatteryShadow: gates = us_scoped_gate_manifest(US_LOCAL_GATE_SCOPE) report_path, comparison_path = shadow_file_paths(directory, US_LOCAL_GATE_SCOPE) return GateBatteryShadow( @@ -7368,6 +8017,7 @@ def _local_gate_shadow(args, directory: Path) -> GateBatteryShadow: report_path=report_path, comparison_path=comparison_path, registry=us_gate_registry(US_LOCAL_GATE_SCOPE, tool=globals()), + waivers=_local_gate_waivers(args) if waivers is None else waivers, overrides=us_flag_overrides(gates, us_gate_specs(US_LOCAL_GATE_SCOPE), args), ) @@ -7386,7 +8036,11 @@ def _finish_local_gate_scope(args, *, stage: str, stopped_by=None) -> None: stages_run = _LOCAL_GATE_SHADOW_STAGES[ : _LOCAL_GATE_SHADOW_STAGES.index(stage) + 1 ] - shadow = _local_gate_shadow(args, _local_gate_shadow_directory(args)) + shadow = _local_gate_shadow( + args, + _local_gate_shadow_directory(args), + waivers=_recorded_local_gate_waivers(args, stage), + ) for name in _LOCAL_GATE_SHADOW_STAGES: observations = _local_stage_observations(args, name) if observations.is_file(): @@ -7412,11 +8066,14 @@ def _finish_local_gate_scope(args, *, stage: str, stopped_by=None) -> None: 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. + The stages may run as separate processes, so each saves what it observed, + and the waivers its flags applied to its own entries, beside the + checkpoint; finalize's waiver record also names, by SHA-256, the gate + report bytes that run wrote (:func:`_write_gate_report`), or none. + Rerunning a stage discards its own and every later stage's files. + 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(): @@ -7425,6 +8082,7 @@ def _local_gate_shadow_stage(args, stage: str): try: for name in _LOCAL_GATE_SHADOW_STAGES[_LOCAL_GATE_SHADOW_STAGES.index(stage) :]: _local_stage_observations(args, name).unlink(missing_ok=True) + _local_stage_waivers(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. @@ -7434,10 +8092,25 @@ def _local_gate_shadow_stage(args, stage: str): 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}") + # Only this stage's own write or read of the gate report counts + # (:func:`_write_gate_report`, :func:`_load_gate_report`): finalize's + # record names the bytes it wrote, none if it wrote none, and package's + # match uses the bytes it read. + try: + del args.gate_report_bytes_sha256 + except AttributeError: + pass shadow = _local_gate_shadow(args, _local_gate_shadow_directory(args) / stage) def save() -> None: try: + # The waiver record first, so observations this code saves always + # have one (:func:`_recorded_local_gate_waivers`). + _save_local_stage_waivers( + args, + stage, + gate_report_sha256=getattr(args, "gate_report_bytes_sha256", None), + ) 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}") diff --git a/tools/check_us_acs_county_agi_support.py b/tools/check_us_acs_county_agi_support.py new file mode 100644 index 0000000000..e40adb8ac6 --- /dev/null +++ b/tools/check_us_acs_county_agi_support.py @@ -0,0 +1,644 @@ +"""List counties whose county SOI AGI row R2 would build empty (pre-check). + +The ACS local release (R2, ``tools/build_us_acs_local_release.py``) builds a +county's IRS SOI rows in ``attach_surface`` from the stored entries of the +state SOI rows for the county's households (``split_state_rows``). The state +AGI row stores no zero, so when every household of a county has an AGI of +exactly 0 the county's AGI row is empty. ``attach_surface`` then refuses the +run, after the materialize stage's engine pass (microcosm#1630 review, +finding 1). On a county SOI surface R2's minimum support now also moves +households with an AGI into such a county, and refuses one it cannot fill +before the engine pass (microcosm#1661). + +This check runs on the staging H5 (R1's output) and its summary, before R2. +It computes the value R2 stores, with R2's own functions and the engine: + +- It loads the staging frame as R2's materialize stage does + (``_load_staging_frame``), holds back the formula-owned columns + (``project_input_only``) and fills the reviewed nulls with the engine + defaults (``fill_reviewed_nulls``, which refuses what R2 refuses). +- It builds each household chunk's policyengine-us dataset as R2's engine + pass does (``_dataset_from_frame``) and computes the household sum of + ``adjusted_gross_income``. That is the value R2's SOI materializer stores + in the state AGI row: it counts every tax unit, filer or not (the + engine-tier test compares the two). +- The engine counts only the positive income sources of a tax unit's head + and spouse (``irs_gross_income``), and only an adult can be a head or a + spouse. A household whose income is all on dependents, or on a tax unit + without an adult, has an AGI of 0 unless a deduction makes it negative. +- R2's stages fill some ``NEVER_DEFAULT_FILLED`` columns on the ACS rows + before its fill step (``stage_filled_never_default``, shared with the + reviewed-fill pre-check). The check holds back such a column while its + nulls are on ACS rows only and the AGI does not read it. It refuses every + other null in a never-default column, as R2's fill step does: a null on a + donor row, a null in a column that no R2 stage fills, and a null the AGI + reads. What the AGI reads is the engine's static dependency closure of + ``adjusted_gross_income`` in the check's year, through the reads inside + the engine's helper functions as well (``follow_helpers``): the walk stops + at an above-the-line deduction that year's ``gov.irs.ald.deductions`` does + not list (:data:`YEAR_LISTED_DEDUCTIONS`), whose formula then reads + nothing, and at the behavioral responses an engine pass without a reform + does not read through (:data:`NO_REFORM_UNREAD`). +- With ``--puma-ladder`` it applies R2's own minimum-support moves + (``plan_minimum_support`` with ``--county-min-support``, default R2's 3, + and the AGI it computed, as R2 passes its own) and takes the county list + from the ladder, as R2 does. +- A county is **at risk** when it has households but none with a nonzero AGI + as R2 stores it (float32). Return-count rows count every tax unit, so they + are never empty. +- R2's ``check_support`` (materialize, after the staging load and the + SSI/Medicaid pre-pass, before its engine pass) refuses the run when a + household names a county outside + the ladder or a ladder county has no household-universe record after the + minimum-support moves. With ``--puma-ladder`` the check lists both + (``counties_outside_ladder``, ``unsupported_counties``) with R2's set + rules, and, as R2 does, moves no household when a county is outside the + ladder. + +The check needs memory for the full staging frame, as R2's materialize stage +does, and runs the engine for the AGI alone (minutes, not R2's full pass). + +Exit status 0: no county at risk and none that R2 refuses. Exit status 2: at +least one county at risk after R2's minimum-support moves; the JSON report +(``--out``) lists them. R2 refuses such a county: before its engine pass on a +county SOI surface with minimum support on, else after it, when its AGI row +is empty. Exit status 3: R2 would refuse the run in materialize before its +engine pass (a county outside the ladder, or without a household-universe +record); fix the staging file or the ladder first. Status 3 takes precedence +over 2 and needs ``--puma-ladder``. + +Usage:: + + python tools/check_us_acs_county_agi_support.py \\ + --h5 /acs_multispine_staging.h5 \\ + --county-column county_fips_2023 \\ + --puma-ladder build/us/us_puma_ladder_2020.npz \\ + --out /county_agi_support.json + +``--staging-summary`` defaults to the H5 path with ``.summary.json``, as in +R2. +""" + +# No ``from __future__ import annotations``: test loaders run this file +# without registering it in ``sys.modules``. +import argparse +import gc +import importlib.util +import json +import sys +import time +from collections import defaultdict +from collections.abc import Collection, Mapping, Sequence +from pathlib import Path +from typing import Any + +import numpy as np +import pandas as pd + +_TOOLS = Path(__file__).resolve().parent +if str(_TOOLS) not in sys.path: + sys.path.insert(0, str(_TOOLS)) + +import check_us_acs_local_reviewed_fills as reviewed_fills # noqa: E402 +import us_acs_local_county_surface as county_surface # noqa: E402 + +from microcosm.frame import Frame # noqa: E402 + +TOOL = "tools/check_us_acs_county_agi_support.py" +ISSUE = "microcosm#922" +#: The engine variable whose household sum R2's state SOI AGI row stores. +AGI_VARIABLE = "adjusted_gross_income" +EXIT_AT_RISK = 2 +#: R2's ``check_support`` refuses the run, before its engine pass. +EXIT_R2_REFUSES = 3 +#: Households per engine chunk; the AGI closure alone is light. +DEFAULT_HH_CHUNK = 100_000 +_RELEASE_TOOL = _TOOLS / "build_us_acs_local_release.py" + + +def _release_tool(): + """R2's module, for its loader, projection, fill and constants.""" + + spec = importlib.util.spec_from_file_location( + "build_us_acs_local_release_for_agi_check", _RELEASE_TOOL + ) + module = importlib.util.module_from_spec(spec) + assert spec.loader is not None + sys.modules[spec.name] = module + spec.loader.exec_module(module) + return module + + +#: Above-the-line deductions whose formula reads nothing in a year whose +#: ``gov.irs.ald.deductions`` does not list them. On policyengine-us 2.145.3 +#: the 2020-only charitable deduction for non-itemizers reads the itemization +#: choice in 2020, and through it the inputs of every itemized deduction, +#: among them take-up flags R2's stages fill. The static closure follows that +#: path in every year, so in another year it would refuse those flags' nulls, +#: which cannot change the AGI then. +YEAR_LISTED_DEDUCTIONS = ("charitable_contributions_ald",) + + +#: Variables an engine pass without a reform, as R2's and this check's are, +#: does not read through. ``labor_supply_behavioral_response`` and +#: ``capital_gains_behavioral_response`` return 0 before reading anything +#: while the simulation has no baseline (``simulation.baseline is None``, +#: which policyengine-core sets when no reform is applied). The labor supply +#: elasticity effects are computed only where +#: ``labor_supply_behavioral_response`` is nonzero. Each reads +#: ``household_net_income`` on a measurement branch through the engine's +#: ``get_behavioral_response_measurements`` helper, so a closure that +#: follows helpers reaches every benefit through them, the take-up flags R2's +#: stages fill among them. +NO_REFORM_UNREAD = ( + "capital_gains_behavioral_response", + "income_elasticity_lsr", + "labor_supply_behavioral_response", + "substitution_elasticity_lsr", +) + + +def unread_deductions(period: int, *, system: Any = None) -> tuple[str, ...]: + """The :data:`YEAR_LISTED_DEDUCTIONS` that ``period`` does not list. + + ``system`` is a policyengine-us ``CountryTaxBenefitSystem``; it is built + when not given. + """ + + if system is None: + from policyengine_us import CountryTaxBenefitSystem + + system = CountryTaxBenefitSystem() + listed = set(system.parameters(f"{int(period)}-01-01").gov.irs.ald.deductions) + return tuple(name for name in YEAR_LISTED_DEDUCTIONS if name not in listed) + + +def unread_variables(period: int, *, system: Any = None) -> tuple[str, ...]: + """Where the AGI walk stops in ``period``: :func:`unread_deductions`, then + :data:`NO_REFORM_UNREAD`.""" + + return (*unread_deductions(period, system=system), *NO_REFORM_UNREAD) + + +def agi_engine_inputs(index: Any, *, unread: Collection[str] = ()) -> frozenset[str]: + """The engine inputs ``adjusted_gross_income`` can read (static closure). + + ``index`` is a ``PolicyEngineUSVariableMetadataIndex`` (or a stand-in + with ``variable_dependency_closure``); the check passes one with + ``follow_helpers``. The walk does not go on past a variable in ``unread`` + (:func:`unread_variables`), which the check's engine pass does not read + through in its year. + """ + + closure = index.variable_dependency_closure(AGI_VARIABLE) + unread = frozenset(unread) + if not unread: + return frozenset(closure.input_leaves) + targets: dict[str, set[str]] = defaultdict(set) + for consumer, target in closure.edges: + targets[consumer].add(target) + reached: set[str] = set() + pending = [AGI_VARIABLE] + while pending: + name = pending.pop() + if name in reached: + continue + reached.add(name) + if name not in unread: + pending.extend(targets[name]) + return frozenset(reached.intersection(closure.input_leaves)) + + +def hold_back_null_runtime_columns( + frame: Frame, + *, + never_default_filled: Collection[tuple[str, str]], + stage_filled: Collection[tuple[str, str]], + agi_inputs: Collection[str], +) -> tuple[Frame, dict[str, list[str]]]: + """Drop the null never-default columns that R2's stages fill first. + + R2's stages fill the ``stage_filled`` columns on the ACS rows before its + fill step, and the fill step refuses any null left in a never-default + column. So the check holds back a null column only when an R2 stage fills + it, every null is on an ACS row (the ``_spine`` tag) and the AGI + does not read it. Every other null in a never-default column is refused, + as R2 refuses it. + """ + + from microcosm.build.us_runtime.base_pool import spine_column + + agi_inputs = frozenset(agi_inputs) + stage_filled = frozenset(stage_filled) + held: dict[str, list[str]] = {} + tables = {} + refused = [] + for entity in frame.entities: + table = frame.table(entity) + tag = spine_column(entity) + null = [] + for column in sorted( + column + for owner, column in never_default_filled + if owner == entity + and column in table.columns + and table[column].isna().any() + ): + name = f"{entity}.{column}" + missing = table[column].isna() + if (entity, column) not in stage_filled: + refused.append(f"{name}: no R2 stage fills it (re-run staging)") + elif tag not in table.columns: + refused.append(f"{name}: no {tag} column places its null rows") + elif off := int((missing & table[tag].ne(county_surface.ACS_SPINE)).sum()): + refused.append( + f"{name}: null on {off} non-ACS row(s); R2's stages fill " + "the ACS rows only" + ) + elif column in agi_inputs: + refused.append(f"{name}: the AGI reads it") + else: + null.append(column) + if null: + held[entity] = null + table = table.drop(columns=null) + tables[entity] = table + if refused: + raise SystemExit( + "Null never-default-filled column(s) that R2's materialize stage " + f"refuses too (fill_reviewed_nulls): {'; '.join(refused)}." + ) + if not held: + return frame, held + weights = {entity: frame.weights_for(entity) for entity in frame.weighted_entities} + held_frame = Frame( + tables, frame.schema, weights, frame.strata, mass_log=frame.mass_log + ) + return held_frame, held + + +def household_agi( + frame: Frame, + summary_path: Path, + *, + release: Any, + period: int | None = None, + hh_chunk: int = DEFAULT_HH_CHUNK, +) -> tuple[np.ndarray, dict[str, Any]]: + """Each household's AGI as R2's SOI materializer stores it. + + Returns the household sum of ``adjusted_gross_income`` in the order of + ``frame``'s household table, and a JSON-ready receipt. ``release`` is + R2's module (``_release_tool()``). + """ + + import build_us_fiscal_refresh_release as fiscal + from policyengine_us import CountryTaxBenefitSystem, Microsimulation + + from microcosm.frame.adapters.policyengine_us import ( + PolicyEngineUSVariableMetadataIndex, + ) + + period = release.PERIOD if period is None else int(period) + system = CountryTaxBenefitSystem() + unread = unread_variables(period, system=system) + projected, formula_owned = release.project_input_only(frame, period=period) + projected, held = hold_back_null_runtime_columns( + projected, + never_default_filled=release.NEVER_DEFAULT_FILLED, + stage_filled=reviewed_fills.stage_filled_never_default(release), + agi_inputs=agi_engine_inputs( + PolicyEngineUSVariableMetadataIndex(follow_helpers=True), unread=unread + ), + ) + fills, drift = release.fill_reviewed_nulls( + projected, summary_path, manifest_path=None, period=period, system=system + ) + household_ids = projected.table("household")["household_id"].to_numpy() + n_households = len(household_ids) + positions = pd.Index(household_ids) + if not positions.is_unique: + raise ValueError("Household ids must be unique.") + person_position = positions.get_indexer( + projected.table("person")["person_household_id"].to_numpy() + ) + if (person_position < 0).any(): + raise ValueError("Persons name households the household table lacks.") + if n_households > hh_chunk: + # A chunk keeps every group its persons reference, so a group across + # two chunks would be simulated twice, each time in part. + fiscal._assert_group_entities_nest_in_households(projected) + agi = np.zeros(n_households, dtype=np.float64) + chunks = 0 + for low in range(0, n_households, hh_chunk): + high = min(low + hh_chunk, n_households) + chunk = projected.select((person_position >= low) & (person_position < high)) + simulation = Microsimulation( + dataset=fiscal._dataset_from_frame( + chunk, assert_no_formula_owned_columns=False, period_only=True + ) + ) + got = np.asarray(simulation.calculate("household_id", period).values) + if not np.array_equal(got, household_ids[low:high]): + raise RuntimeError( + f"Engine chunk {chunks} does not carry its households in frame " + "order; refusing to place its AGI." + ) + agi[low:high] = np.asarray( + simulation.calculate(AGI_VARIABLE, period, map_to="household").values, + dtype=np.float64, + ) + chunks += 1 + del simulation, chunk + gc.collect() + return agi, { + "variable": AGI_VARIABLE, + "aggregation": "household sum over tax units", + "period": period, + "engine_version": release._installed_engine_version(), + "households_per_chunk": int(hh_chunk), + "chunks": chunks, + "formula_owned_columns_held_back": sum(len(c) for c in formula_owned.values()), + "null_runtime_columns_held_back": held, + "agi_closure_stops_at": list(unread), + "reviewed_fill_columns": len(fills), + "reviewed_fill_count_drift": len(drift), + } + + +def county_agi_report( + households: pd.DataFrame, + nonzero_agi: np.ndarray, + *, + county_column: str, + county_populations: Mapping[int, float] | None = None, +) -> dict[str, Any]: + """Per-county household counts, the counties at risk and R2's refusals. + + ``nonzero_agi`` flags the households (in ``households`` order) whose AGI + R2 would store as nonzero; the ``households_with_agi_income`` keys count + them. ``county_populations`` (the ladder's, as R2 uses) sets the county + list; without it the list is the counties the households name, and + ``counties_outside_ladder`` and ``unsupported_counties`` are None (not + checked). With it, they are what R2's ``check_support`` refuses: counties + the households name that are not in the ladder, and ladder counties + without a household-universe record (``support_universe``). + """ + + codes = county_surface.county_codes(households, county_column=county_column) + support = county_surface.support_universe(households) + totals, supporting, with_income = (defaultdict(int) for _ in range(3)) + for code, supports, earns in zip( + codes.tolist(), support.tolist(), np.asarray(nonzero_agi).tolist(), strict=True + ): + totals[code] += 1 + supporting[code] += int(supports) + with_income[code] += int(earns) + if county_populations is None: + counties = sorted(totals) + ladder = None + else: + counties = sorted( + int(code) for code, value in county_populations.items() if float(value) > 0 + ) + ladder = {int(code) for code in county_populations} + at_risk, no_household, thin = [], [], [] + rows = {} + for code in counties: + record = { + "households": totals.get(code, 0), + "supporting_households": supporting.get(code, 0), + "households_with_agi_income": with_income.get(code, 0), + } + rows[f"{code:05d}"] = record + if record["households"] == 0: + no_household.append(f"{code:05d}") + elif record["households_with_agi_income"] == 0: + at_risk.append(f"{code:05d}") + elif ( + record["households_with_agi_income"] + < county_surface.DEFAULT_COUNTY_MIN_SUPPORT + ): + thin.append(f"{code:05d}") + # R2's check_support compares with every ladder county, whatever its + # population. + outside = unsupported = None + if ladder is not None: + outside = sorted(set(totals) - ladder) + unsupported = sorted(ladder - {code for code, n in supporting.items() if n}) + return { + "county_column": county_column, + "counties": len(counties), + "households": int(len(households)), + "households_with_agi_income": int(np.asarray(nonzero_agi).sum()), + "at_risk": at_risk, + "at_risk_detail": {code: rows[code] for code in at_risk}, + "no_household": no_household, + "fewer_than_min_support_with_agi_income": thin, + "counties_outside_ladder": ( + None if outside is None else [f"{code:05d}" for code in outside] + ), + "unsupported_counties": ( + None if unsupported is None else [f"{code:05d}" for code in unsupported] + ), + "by_county": rows, + } + + +def _parse_args(argv: Sequence[str] | None = None) -> argparse.Namespace: + parser = argparse.ArgumentParser( + description=( + "List counties whose county SOI AGI row R2 would build empty: " + "counties with households but none with a nonzero AGI, computed " + "with R2's own fill and engine path." + ) + ) + parser.add_argument( + "--h5", required=True, type=Path, help="Staging H5 (R1 output)." + ) + parser.add_argument( + "--staging-summary", + type=Path, + help=( + "R1's staging summary, for the reviewed-null fills (default: the " + "H5 path with .summary.json, as in R2)." + ), + ) + parser.add_argument( + "--county-column", + default=county_surface.COUNTY_COLUMN_2023, + choices=county_surface.COUNTY_FIPS_COLUMNS, + help="R2's --county-column (default county_fips_2023).", + ) + parser.add_argument( + "--puma-ladder", + type=Path, + help=( + "R2's PUMA ladder. With it, the check takes the county list from " + "the ladder, applies R2's minimum-support moves first and lists " + "the counties R2 refuses (exit status 3)." + ), + ) + parser.add_argument( + "--county-min-support", + type=int, + default=county_surface.DEFAULT_COUNTY_MIN_SUPPORT, + help=( + "R2's --county-min-support (default " + f"{county_surface.DEFAULT_COUNTY_MIN_SUPPORT}); used only with --puma-ladder." + ), + ) + parser.add_argument( + "--hh-chunk", + type=int, + default=DEFAULT_HH_CHUNK, + help=f"Households per engine chunk (default {DEFAULT_HH_CHUNK:,}).", + ) + parser.add_argument("--out", type=Path, help="JSON report path.") + return parser.parse_args(argv) + + +def ladder_support( + households: pd.DataFrame, + ladder_path: Path, + *, + county_column: str, + county_min_support: int, + household_agi: np.ndarray | None = None, +) -> tuple[pd.DataFrame, dict[int, float], dict[str, Any] | None]: + """R2's ladder county populations and minimum-support moves. + + Returns ``(households, county_populations, support)``: the households + after the moves, as ``check_support`` rewrites them, and the moves' + receipt (None when nothing was planned). As in R2, no household moves + when one names a county outside the ladder; R2 then refuses the run. + With ``household_agi`` (in ``households`` order) the moves include R2's + SOI support moves (microcosm#1661). + """ + + from microcosm.build.us_runtime.puma_ladder import load_us_puma_ladder + + ladder = load_us_puma_ladder(ladder_path) + populations = county_surface.with_county_populations( + ladder, {}, {"county": True}, county_column=county_column + )["county"] + codes = county_surface.county_codes(households, county_column=county_column) + outside = {int(code) for code in codes.tolist()} - { + int(code) for code in populations + } + needed = county_surface.unsupported_counties( + households, populations, county_column=county_column + ) + support = None + if county_min_support > 0 and not outside and (needed or household_agi is not None): + overlaps = county_surface.county_puma_overlaps(ladder_path, county_column) + moves, support = county_surface.plan_minimum_support( + households, + populations, + overlaps, + county_column=county_column, + per_county=county_min_support, + household_agi=household_agi, + ) + households = county_surface.apply_support_moves( + households, + moves, + county_column=county_column, + columns=support["rewritten_columns"], + ) + return households, populations, support + + +def exit_status(report: Mapping[str, Any]) -> int: + """3 when R2's ``check_support`` refuses the run, else 2 when one is at risk.""" + + if report.get("counties_outside_ladder") or report.get("unsupported_counties"): + return EXIT_R2_REFUSES + return EXIT_AT_RISK if report["at_risk"] else 0 + + +def main(argv: Sequence[str] | None = None) -> int: + args = _parse_args(argv) + started = time.time() + summary_path = args.staging_summary or args.h5.with_suffix(".summary.json") + if not summary_path.exists(): + raise SystemExit( + f"Staging summary not found at {summary_path}; the reviewed-null " + "fills need its reviewed_engine_input_nulls register." + ) + release = _release_tool() + frame = release._load_staging_frame(args.h5) + households = frame.table("household") + agi, engine = household_agi( + frame, summary_path, release=release, hh_chunk=args.hh_chunk + ) + del frame + gc.collect() + # R2 stores the household measures as float32 and keeps only nonzeros. + nonzero = agi.astype(np.float32) != 0 + populations = None + support = None + if args.puma_ladder is not None: + households, populations, support = ladder_support( + households, + args.puma_ladder, + county_column=args.county_column, + county_min_support=args.county_min_support, + household_agi=agi, + ) + report = county_agi_report( + households, + nonzero, + county_column=args.county_column, + county_populations=populations, + ) + report.update( + { + "tool": TOOL, + "issue": ISSUE, + "h5": str(args.h5), + "staging_summary": str(summary_path), + "agi_engine": engine, + "minimum_support": ( + None + if support is None + else { + "households_per_county": args.county_min_support, + "moves": len(support.get("moves", [])), + "moves_sha256": support.get("moves_sha256"), + "moved_counties": support.get("moved_counties", []), + "soi_support": support.get("soi_support"), + } + ), + "seconds": round(time.time() - started, 1), + } + ) + status = exit_status(report) + report["exit_status"] = status + rendered = json.dumps(report, indent=2, sort_keys=True) + "\n" + if args.out is not None: + args.out.parent.mkdir(parents=True, exist_ok=True) + args.out.write_text(rendered, encoding="utf-8") + summary = { + key: report[key] + for key in ( + "county_column", + "counties", + "households", + "households_with_agi_income", + "at_risk", + "at_risk_detail", + "no_household", + "fewer_than_min_support_with_agi_income", + "counties_outside_ladder", + "unsupported_counties", + "exit_status", + "seconds", + ) + } + print(json.dumps(summary, indent=2, sort_keys=True)) + return status + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/tools/check_us_acs_local_reviewed_fills.py b/tools/check_us_acs_local_reviewed_fills.py new file mode 100644 index 0000000000..bdcbca42a0 --- /dev/null +++ b/tools/check_us_acs_local_reviewed_fills.py @@ -0,0 +1,321 @@ +"""Grade a staging run's nulls against R2's reviewed-fill rules (pre-check). + +The ACS local release (R2, ``tools/build_us_acs_local_release.py``) fills +each reviewed engine-input null of the staging H5 with the policyengine-us +default (``fill_reviewed_nulls``). Its materialize stage refuses a null in a +``NEVER_DEFAULT_FILLED`` column and a null ESI employer premium. Its finalize +stage, hours later, grades every applied fill against +``acs_local_reviewed_fill_consumers.yaml`` with +``acs_local_reviewed_fill_consumer_gate``: it refuses a fill without a +register entry, a fill value or spines that differ from the entry, and a +policyengine-us other than the register's ``reviewed_against``. + +This check runs in seconds after the staging (R1), before R2: + +- It reads the staging summary's ``reviewed_engine_input_nulls`` (column + names and null counts by spine; no row values). +- A null in a ``NEVER_DEFAULT_FILLED`` column is refused, as materialize + refuses it, unless it is on the ACS spine alone and in a column that one of + R2's own stages fills on the ACS rows first (``stage_filled_never_default``: + the take-up stage's SPM-unit take-up flags and engine-free fills, and the + SSI and Medicaid take-up flags). R2 expects staging to fill every other + never-default column (immigration, disability, income transfers, SSI + disability criteria); its reason for those says to re-run staging. +- A null in an ESI premium output is refused, as materialize refuses it. +- A staging summary whose ``engine_versions`` names another policyengine-us + than the installed one, or none, is refused, as materialize refuses it + before it loads the staging file. +- Every other null becomes the fill record R2 writes, with the fill value R2 + resolves from the installed engine, and R2's own gate grades the records. + A null that one of R2's stages fills before the fill step counts as a fill + here, so the check errs towards a refusal. + +Exit status 0: R2's fill rules pass. Exit status 2: R2 would refuse; the +JSON report (``--out``) says why. Add the missing register entries (each a +reviewed ruling) and commit them before R2's calibrate stage. + +Usage:: + + python tools/check_us_acs_local_reviewed_fills.py \\ + --staging-summary /acs_multispine_staging.summary.json \\ + --out /reviewed_fills_precheck.json +""" + +# No ``from __future__ import annotations``: test loaders run this file +# without registering it in ``sys.modules``. +import argparse +import importlib.util +import json +import sys +from collections.abc import Callable, Collection, Mapping, Sequence +from pathlib import Path +from typing import Any + +from microcosm.build.us_runtime.acs_local_reviewed_fill_consumers import ( + acs_local_reviewed_fill_consumer_gate, + load_reviewed_fill_consumer_register, +) +from microcosm.build.us_runtime.esi_premiums import US_ESI_PREMIUMS_OUTPUT_COLUMNS + +TOOL = "tools/check_us_acs_local_reviewed_fills.py" +ISSUE = "microcosm#922" +ACS_SPINE = "acs_2024_1yr" +EXIT_REFUSED = 2 +_RELEASE_TOOL = Path(__file__).resolve().parent / "build_us_acs_local_release.py" + + +def _release_tool(): + """R2's module, for its own fill constants and default resolver.""" + + tools = str(_RELEASE_TOOL.parent) + if tools not in sys.path: + sys.path.insert(0, tools) + spec = importlib.util.spec_from_file_location( + "build_us_acs_local_release_for_fill_check", _RELEASE_TOOL + ) + module = importlib.util.module_from_spec(spec) + assert spec.loader is not None + sys.modules[spec.name] = module + spec.loader.exec_module(module) + return module + + +def stage_filled_never_default(release: Any) -> frozenset[tuple[str, str]]: + """The ``NEVER_DEFAULT_FILLED`` columns that R2's own stages fill on ACS rows. + + Materialize's ACS take-up stage fills the SPM-unit take-up flags, EITC + take-up and the engine-free fills; its SSI/Medicaid take-up stage fills + those two flags. + R2's reasons for every other never-default column (immigration, + disability, income transfers, SSI disability criteria) say to re-run + staging, and a null there stops materialize on any spine. + """ + + filled = frozenset( + { + *(("spm_unit", column) for column in release.ACS_LOCAL_TAKE_UP_COLUMNS), + ("tax_unit", release.US_EITC_TAKE_UP_OUTPUT_COLUMN), + *(tuple(key) for key in release.ACS_LOCAL_ENGINE_FREE_FILL_COLUMNS), + *( + ("person", column) + for column in release.ACS_LOCAL_SSI_MEDICAID_TAKE_UP_COLUMNS + ), + } + ) + unknown = sorted(filled - set(release.NEVER_DEFAULT_FILLED)) + if unknown: + raise SystemExit( + f"R2's stage-filled columns {unknown} are not in NEVER_DEFAULT_FILLED." + ) + return filled + + +def expected_fills( + nulls: Sequence[Mapping[str, Any]], + *, + never_default_filled: Collection[tuple[str, str]], + stage_filled: Collection[tuple[str, str]], + resolve_default: Callable[[str], tuple[object, str]], +) -> dict[str, list]: + """Split the staged nulls as R2's fill step treats them. + + Returns ``fills`` (the records R2 writes, in its manifest's shape), + ``denied`` (never-default nulls that materialize refuses), ``esi`` (null + ESI premium outputs) and ``natively_filled`` (never-default nulls on the + ACS spine only, in a ``stage_filled`` column: one that R2's stages fill + there). Each denied record says whether an R2 stage fills its column + (``r2_stage_fills``). + """ + + never = set(never_default_filled) + by_stage = set(stage_filled) + result: dict[str, list] = { + "fills": [], + "denied": [], + "esi": [], + "natively_filled": [], + } + for item in nulls: + entity, column = str(item["entity"]), str(item["column"]) + by_spine = { + str(spine): int(rows) + for spine, rows in dict(item.get("missing_rows_by_spine") or {}).items() + if int(rows) + } + name = f"{entity}.{column}" + if entity == "person" and column in US_ESI_PREMIUMS_OUTPUT_COLUMNS: + result["esi"].append({"column": name, "missing_rows_by_spine": by_spine}) + continue + if (entity, column) in never: + off_acs = { + spine: rows for spine, rows in by_spine.items() if spine != ACS_SPINE + } + stage = (entity, column) in by_stage + record = {"column": name, "missing_rows_by_spine": by_spine} + if stage and by_spine and not off_acs: + result["natively_filled"].append(record) + else: + result["denied"].append({**record, "r2_stage_fills": stage}) + continue + fill_value, kind = resolve_default(column) + missing = int(item["missing_rows"]) + result["fills"].append( + { + "entity": entity, + "column": column, + "filled_rows": missing, + "rows": int(item.get("rows", missing)), + "fill_value": repr(fill_value), + "fill_kind": kind, + "register_missing_rows": missing, + "missing_rows_by_spine": by_spine, + } + ) + return result + + +def grade( + split: Mapping[str, list], + *, + manifest_names: Sequence[str], + never_default_filled: Collection[tuple[str, str]], + installed_engine_version: str, + document: object | None = None, + staging_refusals: Sequence[str] = (), +) -> dict[str, Any]: + """Run R2's finalize gate on the expected fills; add materialize's refusals. + + ``staging_refusals`` are materialize's refusals of the staging run itself + (:func:`staging_engine_refusal`). + """ + + manifest = {"fills": list(split["fills"]), "unregistered_violations": []} + gate = acs_local_reviewed_fill_consumer_gate( + {name: manifest for name in manifest_names}, + document=document + if document is not None + else load_reviewed_fill_consumer_register(), + never_default_filled=never_default_filled, + installed_engine_version=installed_engine_version, + ) + refusals = [ + *staging_refusals, + *(_denied_refusal(item) for item in split["denied"]), + *( + f"{item['column']}: null ESI employer premium (materialize refuses it)" + for item in split["esi"] + ), + *(f"finalize gate: {failure}" for failure in gate.failures), + ] + return { + "passed": not refusals, + "refusals": refusals, + "expected_fills": len(split["fills"]), + "natively_filled": split["natively_filled"], + "gate": { + "name": gate.name, + "passed": gate.passed, + "failures": list(gate.failures), + }, + } + + +def staging_engine_refusal(summary: Mapping[str, Any], *, release, installed: str): + """Materialize's refusal of a staging run made on another engine, or None. + + R2 refuses it before it loads the staging file + (``_require_staging_engine``), as the nulls it audited are that engine's. + """ + + try: + release._require_staging_engine(dict(summary), installed=installed) + except SystemExit as refusal: + return f"staging: {refusal} (materialize refuses it)" + return None + + +def _denied_refusal(item: Mapping[str, Any]) -> str: + where = f"{item['column']}: null on {sorted(item['missing_rows_by_spine'])}" + if item.get("r2_stage_fills", True): + return f"{where}, a column R2 never default-fills (materialize refuses it)" + return ( + f"{where}, a never-default column that staging fills and no R2 stage " + "does (materialize refuses it; re-run staging)" + ) + + +def _parse_args(argv: Sequence[str] | None = None) -> argparse.Namespace: + parser = argparse.ArgumentParser( + description=( + "Grade a staging summary's reviewed nulls against R2's fill " + "rules and its finalize reviewed-fill gate, before R2 runs." + ) + ) + parser.add_argument("--staging-summary", required=True, type=Path) + parser.add_argument("--out", type=Path, help="JSON report path.") + return parser.parse_args(argv) + + +def _tax_benefit_system(): + from policyengine_us import CountryTaxBenefitSystem + + return CountryTaxBenefitSystem() + + +def _engine_version(release) -> str: + return release._installed_engine_version() + + +def main(argv: Sequence[str] | None = None) -> int: + args = _parse_args(argv) + summary = json.loads(args.staging_summary.read_text()) + nulls = summary.get("reviewed_engine_input_nulls") + if not isinstance(nulls, list): + raise SystemExit( + f"{args.staging_summary} carries no reviewed_engine_input_nulls list." + ) + release = _release_tool() + system = _tax_benefit_system() + stage_filled = stage_filled_never_default(release) + split = expected_fills( + nulls, + never_default_filled=release.NEVER_DEFAULT_FILLED, + stage_filled=stage_filled, + resolve_default=lambda column: release._resolve_engine_default(system, column), + ) + installed = _engine_version(release) + engine_refusal = staging_engine_refusal( + summary, release=release, installed=installed + ) + report = { + "tool": TOOL, + "issue": ISSUE, + "staging_summary": str(args.staging_summary), + "staged_null_columns": len(nulls), + "staging_engine_versions": summary.get("engine_versions"), + "r2_stage_filled_never_default": sorted( + f"{entity}.{column}" for entity, column in stage_filled + ), + **grade( + split, + manifest_names=release.REVIEWED_FILL_MANIFESTS, + never_default_filled=release.NEVER_DEFAULT_FILLED, + installed_engine_version=installed, + staging_refusals=[engine_refusal] if engine_refusal else [], + ), + } + rendered = json.dumps(report, indent=2, sort_keys=True) + "\n" + if args.out is not None: + args.out.parent.mkdir(parents=True, exist_ok=True) + args.out.write_text(rendered, encoding="utf-8") + print( + json.dumps( + {key: report[key] for key in ("passed", "refusals", "expected_fills")}, + indent=2, + ) + ) + return 0 if report["passed"] else EXIT_REFUSED + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/tools/modal_us_stage_plan.py b/tools/modal_us_stage_plan.py index 82ce9328d2..22c4f1efae 100644 --- a/tools/modal_us_stage_plan.py +++ b/tools/modal_us_stage_plan.py @@ -765,6 +765,9 @@ def _acs_local_release_argv( "batch": OptionFlag("--batch", int), "hh_chunk": OptionFlag("--hh-chunk", int), "allow_partial_geography": OptionFlag("--allow-partial-geography", bool), + # Diagnostic only (microcosm#454): finalize and package record a red + # ESI premium verdict instead of failing on it. + "allow_esi_premium_gaps": OptionFlag("--allow-esi-premium-gaps", bool), }, owned_flags=frozenset( { @@ -1278,6 +1281,11 @@ def _acs_multispine_staging_argv( "--location-seed", "--location-clones", "--block-ladder", + # The ESI premium waiver (microcosm#454) is for a diagnostic + # build on a donor that predates the meps_esi_premiums stage. The + # runner never passes it, so a Modal staging run always + # qualifies the donor and enforces both ESI gates. + "--allow-esi-premium-gaps", } ), argv_builder=_acs_multispine_staging_argv, diff --git a/tools/us_acs_local_county_surface.py b/tools/us_acs_local_county_surface.py index 35d128d1e9..8c303be6c1 100644 --- a/tools/us_acs_local_county_surface.py +++ b/tools/us_acs_local_county_surface.py @@ -2119,6 +2119,29 @@ def unsupported_counties(households, county_populations, *, county_column): ) +def counties_without_agi( + households, household_agi, county_populations, *, county_column=COUNTY_COLUMN +): + """Counties with support whose households all store an AGI of 0. + + Such a county's AGI row is empty, and ``attach_surface`` refuses it after + the engine pass (microcosm#1661). ``household_agi`` is in ``households`` + order; R2 stores the household measures as float32. + """ + codes = county_codes(households, county_column=county_column) + universe = support_universe(households) + nonzero = np.asarray(household_agi, dtype=np.float32) != 0 + supported = {int(code) for code in np.unique(codes[universe])} + with_agi = {int(code) for code in np.unique(codes[nonzero])} + return sorted( + int(code) + for code, population in county_populations.items() + if float(population) > 0 + and int(code) in supported + and int(code) not in with_agi + ) + + def plan_minimum_support( households, county_populations, @@ -2127,6 +2150,7 @@ def plan_minimum_support( county_column=COUNTY_COLUMN, per_county=DEFAULT_COUNTY_MIN_SUPPORT, key=COUNTY_MIN_SUPPORT_KEY, + household_agi=None, ): """Choose ``per_county`` donor households for each unsupported county. @@ -2140,6 +2164,22 @@ def plan_minimum_support( move or none do (the county is then still unsupported and named). Counties with support are never chosen; state and PUMA never change. Returns ``(moves, receipt)``. + + With ``household_agi`` (each household's AGI as the SOI materializer + stores it, in ``households`` order) the step also gives every county's + SOI rows support (microcosm#1661). A county whose households all store an + AGI of 0 gets an empty county AGI row, which ``attach_surface`` refuses + after the engine pass. In the first pass, when none of a county's + ``per_county`` picks has a positive AGI, the last pick is swapped for the + next eligible household in rank order that has one (its move carries + ``"reason": "positive_agi"``), so the other picks keep their PUMA's AGI + mix; ``soi_support["first_pass"]`` reports the movers' share with a + positive AGI beside their PUMAs' share. After the first pass, each county + with support and no household whose AGI is nonzero receives + ``per_county`` more households, chosen as above but with a positive AGI + (``soi_support`` in the receipt; their moves carry + ``"reason": "soi_support"``). No move leaves a donor county without a + household whose AGI is nonzero. Without it, nothing differs from before. """ if per_county < 0: raise ValueError("Minimum county support must be nonnegative.") @@ -2151,6 +2191,17 @@ def plan_minimum_support( unsupported = unsupported_counties( households, county_populations, county_column=county_column ) + agi = None + if household_agi is not None: + # R2 stores household measures as float32 and keeps only nonzeros. + agi = np.asarray(household_agi, dtype=np.float32) + if agi.shape != (len(households),) or not np.isfinite(agi).all(): + raise ValueError( + "household_agi must give one finite AGI per household, in the " + "household table's order." + ) + nonzero = agi != 0 + positive = agi > 0 receipt = { "households_per_county": int(per_county), "key": key, @@ -2166,7 +2217,49 @@ def plan_minimum_support( "counties": {}, "moves": [], } - if per_county == 0 or not unsupported: + if agi is not None: + receipt["soi_support"] = { + "issue": "microcosm#1661", + "criterion": ( + "a county with a household in the household universe and no " + "household whose AGI, as R2 stores it (float32), is nonzero" + ), + "donors": ( + "eligible as above, with a positive AGI; the donor county " + "keeps a household with a nonzero AGI" + ), + "first_pass": { + "rule": ( + "the households_per_county eligible households first in " + "rank order; when none of them has a positive AGI, the " + "last is swapped for the next eligible household in rank " + 'order that has one (its move carries "reason": ' + '"positive_agi")' + ), + "movers": 0, + "movers_with_positive_agi": 0, + "mover_share_with_positive_agi": None, + "puma_share_with_positive_agi": None, + "puma_share_basis": ( + "for each first-pass mover, the share of its PUMA's " + "eligible households with a positive AGI before any " + "move, averaged over the movers" + ), + "swapped_counties": [], + }, + "needed": [], + "counties": {}, + "still_without_agi": [], + } + if per_county == 0 or ( + not unsupported + and ( + agi is None + or not counties_without_agi( + households, agi, county_populations, county_column=county_column + ) + ) + ): receipt["moves_sha256"] = _moves_digest([]) return [], receipt pumas = _household_pumas(households) @@ -2195,9 +2288,215 @@ def plan_minimum_support( counts = defaultdict(int) for code in codes[universe]: counts[int(code)] += 1 + # The AGI floor counts every household, as the county's SOI row does. + with_agi = defaultdict(int) + if agi is not None: + for code in codes[nonzero]: + with_agi[int(code)] += 1 + + def keeps_agi(position, donor, taken): + """Whether moving ``position`` leaves ``donor`` an AGI household.""" + if agi is None or not nonzero[position]: + return True + pending = sum( + 1 + for taken_position, from_county, _r in taken + if from_county == donor and nonzero[taken_position] + ) + return with_agi[donor] - pending - 1 >= 1 + + def record_move(position, donor, county, puma, reason=None): + counts[donor] -= 1 + counts[county] += 1 + if agi is not None and nonzero[position]: + with_agi[donor] -= 1 + with_agi[county] += 1 + moved[position] = True + household_id = ids[position] + move = { + "household_id": ( + int(household_id) + if isinstance(household_id, (int, np.integer)) + else str(household_id) + ), + "from_county": f"{donor:05d}", + "to_county": f"{county:05d}", + "puma": f"{puma:07d}", + "rank": support_rank(key, county, household_id), + } + if reason is not None: + move["reason"] = reason + moves.append(move) + moved = np.zeros(len(households), dtype=bool) moves = [] + + def visit(county, order, tried): + """Eligible unmoved households of ``county``'s PUMAs, in rank order. + + PUMAs come largest ladder overlap first, each one's households in + :func:`support_rank` order; ``tried`` names the PUMAs reached. + """ + for puma, _population in order: + if puma // 100_000 != county // 1000: + raise ValueError( + f"Ladder overlap puts county {county:05d} in PUMA {puma:07d} " + "of another state." + ) + tried.append(f"{puma:07d}") + positions = by_puma.get(puma, np.empty(0, dtype=np.int64)) + for position in sorted( + ( + position + for position in positions.tolist() + if eligible[position] and not moved[position] + ), + key=lambda position: ( + support_rank(key, county, ids[position]), + position, + ), + ): + yield puma, position + + def can_take(position, donor, taken): + """Whether ``donor`` keeps both floors once ``position`` moves too.""" + pending = sum(1 for _p, from_county, _r in taken if from_county == donor) + if counts[donor] - pending - 1 < per_county: + return False + return keeps_agi(position, donor, taken) + + first_movers = [] for county in unsupported: + order = overlaps.get(county, []) + tried, taken = [], [] + candidates = visit(county, order, tried) + for puma, position in candidates: + donor = int(codes[position]) + if can_take(position, donor, taken): + taken.append((position, donor, puma)) + if len(taken) == per_county: + break + swapped = None + if ( + agi is not None + and len(taken) == per_county + and not any(positive[position] for position, _d, _p in taken) + ): + # The county's AGI row needs a household with an AGI. The last + # pick gives way to the next one in rank order that has one, and + # the other picks keep their PUMA's AGI mix. + kept = taken[:-1] + for puma, position in candidates: + donor = int(codes[position]) + if positive[position] and can_take(position, donor, kept): + taken = [*kept, (position, donor, puma)] + swapped = position + break + status = "moved" if len(taken) == per_county else "insufficient_eligible_donors" + if status == "moved": + for position, donor, puma in taken: + record_move( + position, + donor, + county, + puma, + reason="positive_agi" if position == swapped else None, + ) + first_movers.append((position, puma)) + receipt["counties"][f"{county:05d}"] = { + "ladder_population": float(county_populations[county]), + "pumas_by_overlap": [f"{puma:07d}" for puma, _population in order], + "pumas_tried": tried, + "moved": per_county if status == "moved" else 0, + "status": status, + } + if swapped is not None: + receipt["soi_support"]["first_pass"]["swapped_counties"].append( + f"{county:05d}" + ) + if agi is not None: + _report_first_pass_agi( + receipt["soi_support"]["first_pass"], + first_movers, + positive=positive, + eligible=eligible, + by_puma=by_puma, + ) + _plan_soi_support( + receipt["soi_support"], + county_populations, + overlaps, + per_county=per_county, + key=key, + ids=ids, + by_puma=by_puma, + eligible=eligible & positive, + moved=moved, + codes=codes, + counts=counts, + with_agi=with_agi, + keeps_agi=keeps_agi, + record_move=record_move, + ) + receipt["moves"] = moves + receipt["moves_sha256"] = _moves_digest(moves) + receipt["moved_counties"] = sorted({move["to_county"] for move in moves}) + return moves, receipt + + +def _report_first_pass_agi(report, movers, *, positive, eligible, by_puma): + """Fill ``soi_support["first_pass"]``: the first-pass movers' share with a + positive AGI beside the share their PUMAs would give a random draw. + + ``movers`` is ``[(position, puma), ...]``. A PUMA's share is that of its + eligible households (``eligible`` before any move) with a positive AGI. + """ + shares = {} + for _position, puma in movers: + if puma not in shares: + pool = by_puma[puma][eligible[by_puma[puma]]] + shares[puma] = float(positive[pool].mean()) if len(pool) else 0.0 + count = len(movers) + with_positive = sum(bool(positive[position]) for position, _puma in movers) + report["movers"] = count + report["movers_with_positive_agi"] = with_positive + if count: + report["mover_share_with_positive_agi"] = round(with_positive / count, 6) + report["puma_share_with_positive_agi"] = round( + sum(shares[puma] for _position, puma in movers) / count, 6 + ) + + +def _plan_soi_support( + receipt, + county_populations, + overlaps, + *, + per_county, + key, + ids, + by_puma, + eligible, + moved, + codes, + counts, + with_agi, + keeps_agi, + record_move, +): + """The SOI support pass of :func:`plan_minimum_support` (microcosm#1661). + + ``eligible`` already requires a positive AGI. Each county with support + and no household whose AGI is nonzero gets exactly ``per_county`` donors + from its PUMAs, largest ladder overlap first, or none. + """ + needed = sorted( + int(code) + for code, population in county_populations.items() + if float(population) > 0 and counts[int(code)] > 0 and not with_agi[int(code)] + ) + receipt["needed"] = [f"{code:05d}" for code in needed] + for county in needed: order = overlaps.get(county, []) tried, taken = [], [] for puma, _population in order: @@ -2212,7 +2511,9 @@ def plan_minimum_support( ( position for position in positions.tolist() - if eligible[position] and not moved[position] + if eligible[position] + and not moved[position] + and int(codes[position]) != county ), key=lambda position: ( support_rank(key, county, ids[position]), @@ -2228,40 +2529,33 @@ def plan_minimum_support( ) if counts[donor] - pending - 1 < per_county: continue + if not keeps_agi(position, donor, taken): + continue taken.append((position, donor, puma)) if len(taken) == per_county: break status = "moved" if len(taken) == per_county else "insufficient_eligible_donors" + before = counts[county] if status == "moved": for position, donor, puma in taken: - counts[donor] -= 1 - counts[county] += 1 - moved[position] = True - household_id = ids[position] - moves.append( - { - "household_id": ( - int(household_id) - if isinstance(household_id, (int, np.integer)) - else str(household_id) - ), - "from_county": f"{donor:05d}", - "to_county": f"{county:05d}", - "puma": f"{puma:07d}", - "rank": support_rank(key, county, household_id), - } - ) + record_move(position, donor, county, puma, reason="soi_support") receipt["counties"][f"{county:05d}"] = { - "ladder_population": float(county_populations[county]), + "supporting_households_before": int(before), "pumas_by_overlap": [f"{puma:07d}" for puma, _population in order], "pumas_tried": tried, "moved": per_county if status == "moved" else 0, "status": status, } - receipt["moves"] = moves - receipt["moves_sha256"] = _moves_digest(moves) - receipt["moved_counties"] = sorted({move["to_county"] for move in moves}) - return moves, receipt + receipt["still_without_agi"] = [ + f"{code:05d}" + for code in sorted( + int(code) + for code, population in county_populations.items() + if float(population) > 0 + and counts[int(code)] > 0 + and not with_agi[int(code)] + ) + ] def _county_value(template, code): @@ -2524,10 +2818,15 @@ def prepare_run(args, geographies, populations, *, surface=None): raise SystemExit(str(error)) from error -def check_support(frame, populations, args): +def check_support(frame, populations, args, *, household_agi=None): """Apply minimum support, write county_support.json, refuse what remains. Returns the frame, with county columns rewritten for any moved household. + ``household_agi`` (each household's AGI as the SOI materializer stores + it, in the household table's order) turns on the SOI support pass of + :func:`plan_minimum_support`, and a county that still has households but + none with a nonzero AGI is refused here, before the engine pass, rather + than by ``attach_surface`` after it (microcosm#1661). """ if "county" not in populations: return frame @@ -2541,13 +2840,23 @@ def check_support(frame, populations, args): needed = unsupported_counties( households, populations["county"], county_column=column ) - overlaps = county_puma_overlaps(args.ladder, column) if needed else {} + without_agi = ( + counties_without_agi( + households, household_agi, populations["county"], county_column=column + ) + if household_agi is not None + else [] + ) + overlaps = ( + county_puma_overlaps(args.ladder, column) if needed or without_agi else {} + ) moves, support = plan_minimum_support( households, populations["county"], overlaps, county_column=column, per_county=per_county, + household_agi=household_agi, ) if moves: frame = with_household_table( @@ -2570,6 +2879,12 @@ def check_support(frame, populations, args): "moved_counties": support.get("moved_counties", []), "rewritten_columns": support["rewritten_columns"], } + if "soi_support" in support: + args.county_support_receipt["soi_supported_counties"] = sorted( + county + for county, record in support["soi_support"]["counties"].items() + if record["status"] == "moved" + ) # A state_county run trains an ACS households row for every county, which # only household-universe records support; refuse a county with group # quarters alone here, before the engine pass, not after it. @@ -2600,6 +2915,14 @@ def check_support(frame, populations, args): raise SystemExit(f"Households name counties outside the ladder: {unknown}.") smoke = bool(args.allow_partial_geography and args.sample_fraction < 1) require_support(report["unsupported_counties"], capped_smoke=smoke) + without_agi = ((support or {}).get("soi_support") or {}).get("still_without_agi") + if without_agi and not smoke: + raise SystemExit( + "County cells have households but none with a nonzero AGI after " + f"minimum support: {without_agi}. Their county AGI rows would be " + "empty, which the run refuses after the engine pass; refusing " + "before it (microcosm#1661)." + ) return frame