diff --git a/README.md b/README.md index c0ef54002c..fe9c9e4cde 100644 --- a/README.md +++ b/README.md @@ -479,7 +479,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/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/docs/agent-guide.md b/docs/agent-guide.md index 58a385c1b1..86c5e50221 100644 --- a/docs/agent-guide.md +++ b/docs/agent-guide.md @@ -558,6 +558,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-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 14c7b4d1fa..8f266f2905 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_multispine.py b/packages/microcosm-build/src/microcosm/build/us_runtime/acs_multispine.py index 5bae4819e1..1c5fe83667 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, @@ -118,6 +122,8 @@ 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, @@ -170,8 +176,17 @@ def build_optional_acs_multispine( 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, @@ -362,6 +377,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 +421,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: @@ -442,6 +489,11 @@ 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) provenance = { "enabled": True, @@ -470,6 +522,11 @@ def build_optional_acs_multispine( 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_free/us/test_us_acs_block_location.py b/packages/microcosm-build/tests/engine_free/us/test_us_acs_block_location.py index 901a878f31..67f80fd35c 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, {}) ) @@ -991,6 +996,7 @@ def test__legacy_tool__block_v1_main_records_rule_seed_gate_and_attributes( "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_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_release_tool.py b/packages/microcosm-build/tests/engine_free/us/test_us_acs_local_release_tool.py index fd5998bdcf..240758b58f 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") @@ -177,30 +181,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: @@ -3083,6 +3104,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 @@ -4004,8 +4026,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 @@ -4027,6 +4054,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: @@ -4037,8 +4066,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 = ( @@ -5352,6 +5381,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 = { @@ -8020,3 +8051,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_multispine_legacy_builder.py b/packages/microcosm-build/tests/engine_free/us/test_us_acs_multispine_legacy_builder.py index 2cab37a3ca..a86c27e98d 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 @@ -156,6 +156,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 +204,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 +249,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 +384,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 +408,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): @@ -554,6 +599,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 +669,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 +713,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, @@ -624,8 +756,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,6 +770,8 @@ 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")) @@ -708,6 +845,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 +924,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.""" 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 53123ca617..9c5d842d78 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 @@ -95,15 +95,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..d96a2c1d69 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. @@ -344,8 +350,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", 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..32711a024d 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, @@ -532,6 +559,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,6 +612,9 @@ 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, @@ -606,7 +643,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 +691,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) @@ -724,6 +769,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 +777,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: @@ -2040,6 +2158,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: diff --git a/tools/build_us_acs_local_release.py b/tools/build_us_acs_local_release.py index a92d124e92..5675699b6a 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 @@ -133,6 +135,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, @@ -1070,9 +1077,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)" ) @@ -5615,6 +5625,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, @@ -5835,6 +5903,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 +6089,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 " @@ -6168,6 +6272,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 +6298,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 +6558,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 +6640,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 +7352,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 +7492,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 +7777,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 +7796,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 +7826,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 +7842,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 +7852,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/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,