diff --git a/changelog.d/us-one-population-contract.added.md b/changelog.d/us-one-population-contract.added.md new file mode 100644 index 0000000000..058a86170b --- /dev/null +++ b/changelog.d/us-one-population-contract.added.md @@ -0,0 +1 @@ +Add `us_runtime/one_population_contract.py`, the population contract library for d2283's national one-population file. `to_assembled_provenance` rewrites the parent export's CPS rows (Route A's `asec` and `puf_tax_detail` labels kept, spine source id = source id, spine tag `asec_puf`) and staging's ACS rows (`acs_2024_1yr`, spine source id = staging's native id) into the assembled form with a clone-0, three-channel spine assembly record, taking each origin's household weights keyed (CPS by household id, ACS by the selection's unit key) and refusing weights given by position or held as complex or temporal values, incomplete support metadata, an id, clone index, lineage number or person-to-group link held as anything but integers, real numbers or strings (such as a complex value, a time or an Arrow dictionary of times), colliding ids, a repeated (source id, rank) pair, lost `SERIALNO`/`SPORDER` lineage (it compares each ACS person's pair with staging's lineage, keyed on native household and person ids), a group unit spanning two households, and an ACS household with more than one SPM unit. `require_one_population` refuses a joined frame that breaks any clause, each with its own message: provenance (including a spine assembly record count that is not a nonnegative integer), one native row per CPS key and one row per ACS household against the selection manifest (`one_population_selection`), location clones, a missing congressional district, `TYPEHUGQ` on ACS households, columns the engine computes at 2024, unregistered lower-case columns, a null ESI premium, an SPM unit without a classified adult, a null engine input outside the release-written list, or a null inside it other than None or a float NaN (`pd.NA`, `pd.NaT` and numpy's `NaT` refuse), null PUF tail columns, a tail donor set unlike the parent's, applied twice or applied on an ACS tax unit, and an undeclared register column ACS rows lack while CPS rows hold it. `combined_spm_role_record` builds the SPM role record from a CPS record and staging's ACS receipt, checked against a recount of the frame and, on ACS rows, against the role each person's `RELSHIPP` gives (a code held as anything but an integer, real number or string refuses); `absences` and `write_absences` list what each origin lacks, by support channel, as owner-declared, release-written, raw source column, reviewed default fill, zero written or origin-native (the six ACS-native `acs_*` amounts CPS rows lack); they record declarations a frame does not use instead of refusing them, and refuse a fill receipt that gives a spine a negative row count. `cps_unit_ids` derives the CPS selection keys, and `one_population_selection`'s key digest is now public as `keys_sha256`. The engine's variable classes come from an injected index, built from the installed engine only at call time. No build calls it yet. diff --git a/packages/microcosm-build/src/microcosm/build/us_runtime/one_population_contract.py b/packages/microcosm-build/src/microcosm/build/us_runtime/one_population_contract.py new file mode 100644 index 0000000000..744e921723 --- /dev/null +++ b/packages/microcosm-build/src/microcosm/build/us_runtime/one_population_contract.py @@ -0,0 +1,3820 @@ +"""The d2283 one-population contract: provenance, refusals, role record, absences. + +d2283's national child population joins every CPS row of the parent's Route A +export (native ASEC rows at clone index 0 and their PUF tax-detail clones at +clone indices 1 and 2) with the ACS households PR 1's selection +(:mod:`~microcosm.build.us_runtime.one_population_selection`) takes from a +staging run built on that export as donor. The prepare step applies this +library between the selection and the H5 write: + +- :func:`to_assembled_provenance` rewrites both origins' support provenance + into the assembled form (``_spine_source_id`` on every row) and + builds the spine assembly record from the clone-0 rows; +- :func:`require_one_population` refuses a joined frame that breaks any + clause of the contract, with a message that names the clause's rule; +- :func:`combined_spm_role_record` writes the SPM independence role record + for the joined frame, with per-origin counts; +- :func:`absences` lists the columns one origin carries as a reviewed + default fill, a zero written in place of a measure, or not at all, each + with its kind, and :func:`write_absences` writes that list as + :data:`ABSENCES_FILENAME`; +- :func:`cps_unit_ids` derives each CPS household's unit key, so the + selection manifest's digest and the contract's key check share one rule. + +The engine's variable classes at 2024 (known, computed, input) come from an +injected :class:`EngineVariableIndex`. The default, +:class:`PolicyEngineUSVariableIndex`, reads the installed policyengine-us +source metadata the first time it is asked, never at import, so importing +this module loads no engine. + +Who reads the spine assembly record. At this module's commit +``validate_assembly_provenance`` is called by ``spine_assembly.py`` (:136), +``spine_agreement.py`` (:330), ``acs_release_predictors.py`` (:1407, only +when a row carries channel ``acs``, which this module never writes), +``puf_support.py`` (:797, :859, :878), ``multispine_pool.py`` (:3597, +:3605, :3629, :3660, :3681, all inside ``run_multispine_pool_path``, the +stacked-pool build path, not a loader), ``stacked_spine.py`` (:1442), +``support_provenance.py``'s receipt and count helpers (:265, :284) and +``tools/build_us_multispine_pool.py`` (:3390, :4217). The release tool calls +none of them, and the pool loader it uses +(``h5_io.load_authenticated_us_multispine_pool_for_release``) never +validates. So on main nothing on the release tool's arm reads the record: +it serves :func:`require_one_population`, PR 5's loader and later callers. + +What the later d2283 PRs owe this library: + +- PR 3 flips six strict xfails of the whole-frame differential. Four + compare statistics on the reader frame: the weeks-unemployed UC-rule + scope, Medicare take-up, retirement contributions and retirement + distributions. Two compare verdicts on a frame with one clone-only + defect (d2283 lead call L7): a clone row's ``MCARE`` disagreeing with its + take-up flag fails Route A's Medicare reconciliation and passes the + assembled one, and a clone row with weeks unemployed and no + unemployment compensation fails Route A's UC rule and passes the + assembled one. On the assembled form the weeks UC rows key on the + stored channel and clone index (``weeks_unemployed.py`` :1366-1373), and + the other three readers' ``_asec_source_mask`` returns the + stored-``asec`` rows. +- PR 4 (prepare) fills on ACS rows every engine input outside + :data:`RELEASE_WRITTEN_INPUTS`, ``takes_up_snap_if_eligible`` included + (the SNAP take-up gate misgrades an ACS null). Lead call L1 moved ten + producer outputs off that list: the release's first engine pass refuses + a null in the nine float and integer ones at load, and later passes + compute from ``is_self_employed`` before its producer writes it. The + lead-call review moved an eleventh, ``takes_up_medicaid_if_eligible``, + which the ACA pass computes from before Medicaid writes it. Their fill + sources: the + three integer recodes (``detailed_occupation_recode``, + ``detailed_industry_recode``, ``major_industry_recode``) come from + staging, which writes them natively from ``OCCP`` and ``INDP`` + (``acs_inputs.ACS_WORK_EXPERIENCE_NATIVE_MAPPINGS``); any finite value + serves for ``cps_race``, ``hourly_wage``, ``fsla_overtime_premium``, + ``selected_marketplace_plan_benchmark_ratio`` and + ``other_health_insurance_premiums``, and any boolean for + ``takes_up_medicaid_if_eligible``, since their producers rewrite them and + no earlier pass's result depends on them (the ACA pass's two reads of the + Medicaid flag are masked by Medicaid eligibility in policyengine-us + 2.2.1). ``health_insurance_premiums`` and ``is_self_employed`` take the + producer's own pinned rule, so the ACA, Medicaid and SNAP-state passes, + which compute from them on ACS rows before their producer runs (staging + writes neither), see there the values the producer later ships (the + 11-19 call of the US data owner, who owns d2283 Q2). Prepare runs + ``other_health_insurance.attribute_us_se_health_premiums_from_manifest`` + with the one operation of kind ``attribute_self_employed_health_premiums`` + in the packaged stage (``us_other_health_insurance_stage_spec()``; by + kind, never by position, and never the function's defaults), on the + joined person table after the reviewed default fill and before this + contract. That fill holds both columns out, as it holds out the SSI and + Medicaid take-up columns, or it would write 0/False and file fills the + attribution then overwrites. Prepare writes the two outputs on ACS rows + only, as float64 and bool; refuses unless the rule reproduces every CPS + row's carried values (premiums within the export gate's 1e-9, the flag + exactly), a parity check that the binding and inputs reproduce the + parent's producer; and records the operation, its parameters and the + ``us/source_stages.json`` sha256 in its manifest. Nothing after it may + write the rule's inputs or outputs. A null PR 4 leaves in an exempt + column must be None or a float NaN, never ``pd.NA``, ``pd.NaT``, numpy's + ``NaT`` or any other null. The first engine pass cannot load a + ``pd.NA`` in the twelve flags it reads before their producers write + them; the other six (the four SCF amounts, + ``meets_ssi_disability_criteria`` and ``takes_up_head_start_if_eligible``) + have producers that run before that pass and rewrite a non-finite + value. R6 refuses every other null in all 18 as a fail-closed rule. +- PR 4 writes on ACS rows every raw predictor of + ``acs_release_predictors._MODEL_PREDICTORS``, all fourteen + (:data:`RAW_COLUMN_READERS` names each one's readers): ``PEDISDRS``, + ``PEDISEAR``, ``PEDISEYE``, ``PEDISOUT``, ``PEDISPHY``, ``PEDISREM``, + ``PRDTRACE``, ``PRDTHSP``, ``SPM_TENMORTSTATUS``, ``PEIOOCC``, + ``POCCU2``, ``WEIND``, ``WEMIND`` and ``WKSWORK``, by the join's own + crosswalk from the ACS PUMS sources or from staging where staging writes + them. The join itself passes the joined frame through, since no row + carries channel ``acs``. A null stops the build in the SSI disability + stage (a non-finite ``PEDIS*``) or the ORG stage (incomplete ``WEIND``, + ``WEMIND`` or ``WKSWORK``; ``org_wages.py`` :590-655), and passes + silently where a reader fills it (``sipp_vehicles`` reads a null + ``SPM_TENMORTSTATUS`` as 3, ``scf_wealth`` a null ``PRDTRACE`` or + ``PRDTHSP`` as 0). PR 4 also writes the six + :data:`PUF_TAIL_TAX_UNIT_COLUMNS` defaults on ACS tax units (applied + False, donor id -1), which R7 and R8 require. +- PR 4 passes :func:`to_assembled_provenance` each origin's household + weights keyed: CPS by ``household_id``, ACS by ``acs_unit_key(SERIALNO)`` + (``pd.Series(starting.acs, index=plan.acs_keys)``). PR 1's ACS starting + weights come in selection order and staging's household table in id + order, so a weight given by position is refused (lead call L3's check). +- PR 4 runs the reviewed default fill on the joined frame so its + manifest's row counts are the frame's; reads the parent's applied tail + donor ids from the export's tax-unit columns (checked against the base + manifest's ``records[*].donor_source_id`` when the base run folder is at + hand); re-derives the CPS role record with + ``with_us_spm_independence_role`` on the selected CPS rows, in the joined + frame's row order and dtypes (the digest is dtype-sensitive); builds the + selection keys with :func:`cps_unit_ids`; builds ``staging_lineage`` from + staging's output, not from the ACS tables it passes, keyed by each + person's native (household id, person id) (staging's + ``household_source_id`` of its household and its ``person_source_id``) + with its (``SERIALNO``, ``SPORDER``) as the value; keeps staging's + ``RELSHIPP`` on every ACS person row, from which + :func:`combined_spm_role_record` re-derives each ACS role (inferred, to + confirm at spike step 0: staging's pooled tables keep it, as they keep + ``TYPEHUGQ``; if they drop it, prepare joins it from the ACS PUMS + person source, which requires it, by (``SERIALNO``, ``SPORDER``), the + pair the lineage check ties to each person). Nothing ties the retained + ``RELSHIPP`` itself to staging, so a swap of both ``RELSHIPP`` and the + role between two persons passes; a keyed staging role projection would + catch it. PR 4 also supplies + :func:`absences` with the reviewed default fill's manifest for the + joined frame and the ``zero_written`` receipts; and declares (or fills) + each CPS-only register entry the first live run of :func:`absences` + lists, the US data owner deciding. +- PR 4 reads the id dtypes of staging's real pooled tables, then tightens + :func:`_integral_ids`, which today passes object-held digit strings and + booleans through ``pd.to_numeric`` and refuses a boolean dtype and any + data but integers, real numbers and strings (lead call L5). +- PR 4 writes both frame records into the population manifest: the spine + assembly record :func:`to_assembled_provenance` puts under + ``SPINE_ASSEMBLY_MANIFEST_KEY`` and the record + :func:`combined_spm_role_record` returns, with the CPS role record and + staging's receipt it keeps under ``evidence``. The shared H5 writer + stores tables, household weights, the period and its own small metadata + row, never ``Frame.metadata`` (``h5_io``'s module docstring; + ``_artifact_metadata``), so a record left only in the frame is lost at + the write. +- PR 5 (the loader) restores both records from the population manifest + into ``Frame.metadata`` (``us_spine_assembly_manifest`` and + ``spm_independence_role``) and checks each on the loaded frame: the + assembly record through + :func:`~microcosm.build.us_runtime.support_provenance.validate_assembly_provenance` + (a loader that restores only the role record leaves every reader of the + assembly record without one), and the role record recomputed after the + load rather than trusted by its pre-write digest. It also joins the + absences file to the release's ``us_register_consistency_gate``. The + absences record names no frame or H5 digest, so PR 5 binds it to its + file by the run folder. +- PR 5's continuity anchor compares the CPS row set and the native and + clone structure both ways against the parent export. Whether a clone + row's values cohere with its native row's is out of this library's + scope (lead call L6). + +Two upstream conditions: R4 (the ESI employer premium on every person) +refuses every real child until d2283 PR 0 lands, and PR 4's CPS role +record re-derivation (d2283 Q6 (a)) needs spike step 0 to find the raw +ASEC role inputs on the export; if they are absent, Q6 reopens. + +The module certifies no numbers: no build calls it yet. +""" + +from __future__ import annotations + +import decimal +import json +import math +import numbers +from collections.abc import Collection, Iterable, Mapping +from dataclasses import dataclass +from pathlib import Path +from types import MappingProxyType +from typing import Any, Protocol, runtime_checkable + +import numpy as np +import pandas as pd + +from microcosm.build.source_runtime import SourceRuntimeError +from microcosm.build.us_runtime.esi_premiums import ( + US_ESI_EMPLOYER_PREMIUM_COLUMN, + refuse_unassigned_us_esi_premiums, +) +from microcosm.build.us_runtime.one_population_selection import ( + SelectionManifest, + acs_unit_key, + cps_unit_key, + keys_sha256, +) +from microcosm.build.us_runtime.puf_capital_gains_tail import ( + PUF_CAPITAL_GAINS_TAIL_APPLIED_COLUMN, + PUF_CAPITAL_GAINS_TAIL_DONOR_AGI_BAND_COLUMN, + PUF_CAPITAL_GAINS_TAIL_DONOR_FILING_STATUS_COLUMN, + PUF_CAPITAL_GAINS_TAIL_DONOR_SOURCE_ID_COLUMN, + PUF_CAPITAL_GAINS_TAIL_DONOR_SYNTHETIC_COLUMN, + PUF_CAPITAL_GAINS_TAIL_TRANSFER_WEIGHT_COLUMN, +) +from microcosm.build.us_runtime.spm_composition import ( + check_spm_composition, + spm_independence_role, +) +from microcosm.build.us_runtime.spm_independence_role import _role_binding_sha256 +from microcosm.build.us_runtime.spm_role_source import ( + NATIVE_SPM_ROLE, + SPM_ADULT_RULE, + SPM_ROLE_RULE, +) +from microcosm.build.us_runtime.support_provenance import ( + BASE_ASEC_SUPPORT_CHANNEL, + PUF_CAPITAL_GAINS_TAIL_CLONE_INDEX, + PUF_TAX_DETAIL_CLONE_INDEX, + PUF_TAX_DETAIL_SUPPORT_CHANNEL, + SPINE_ASSEMBLY_MANIFEST_KEY, + require_assembled_support_provenance, + spine_assembly_manifest, + spine_source_id_column, + support_channel_column, + support_clone_index_column, + support_copy_rank_series, + support_source_id_column, + validate_assembly_provenance, +) +from microcosm.frame import US_SCHEMA, Frame, WeightKind, Weights + +__all__ = [ + "ABSENCES_FILENAME", + "ABSENCE_KINDS", + "ACS_NATIVE_AMOUNTS", + "ACS_SUPPORT_CHANNEL", + "ASSEMBLED_CHANNELS", + "CPS_SPINE_TAG", + "ENGINE_PERIOD", + "PUF_TAIL_TAX_UNIT_COLUMNS", + "RAW_COLUMN_READERS", + "RELEASE_WRITTEN_INPUTS", + "STRUCTURAL_COLUMNS", + "EngineVariableIndex", + "OnePopulationContractError", + "PolicyEngineUSVariableIndex", + "absences", + "combined_spm_role_record", + "cps_unit_ids", + "require_one_population", + "to_assembled_provenance", + "write_absences", +] + +#: The national period the engine's variable classes are read at: the +#: release tool's ``PERIOD``, which its export guard passes to the same +#: classifier (F-14, F-15). +ENGINE_PERIOD = 2024 + +#: The support channel (and ``_spine`` tag) staging gives ACS rows, +#: ``acs_pums.ACS_2024_1YR_SPINE``. A test pins the two together. +ACS_SUPPORT_CHANNEL = "acs_2024_1yr" + +#: The ``_spine`` tag staging gives donor rows, +#: ``base_pool.ASEC_PUF_SPINE``. The contract stamps it on every CPS row +#: (d2283 Q3), so no row of the joined frame has a null tag. A test pins the +#: two together. +CPS_SPINE_TAG = "asec_puf" + +#: The channels an assembled one-population frame declares, in record order. +#: ``puf_tax_detail`` is declared because CPS clones carry it, with a clone-0 +#: count of 0 on every entity. +ASSEMBLED_CHANNELS = ( + BASE_ASEC_SUPPORT_CHANNEL, + PUF_TAX_DETAIL_SUPPORT_CHANNEL, + ACS_SUPPORT_CHANNEL, +) + +#: The file the prepare step writes :func:`absences` to. +ABSENCES_FILENAME = "us_population_absences.json" + +#: The person id and each group's id and membership column. None of them is +#: an engine input or an engine-computed column for this contract, as in +#: the release tool's export guard. +STRUCTURAL_COLUMNS = frozenset( + { + US_SCHEMA.person_id_column, + *(US_SCHEMA.id_column(group) for group in US_SCHEMA.group_entities), + *(US_SCHEMA.membership_column(group) for group in US_SCHEMA.group_entities), + } +) + +# Raw source columns the clauses read. CPS rows carry the ASEC person id; +# ACS rows carry the PUMS household serial number (household table) and the +# person's line in it (person table), plus the household type code. +_PERIDNUM = "PERIDNUM" +_SERIALNO = "SERIALNO" +_SPORDER = "SPORDER" +_TYPEHUGQ = "TYPEHUGQ" +_SOURCE_YEAR = "source_year" +_SOURCE_HOUSEHOLD_ID = "source_household_id" +_SOURCE_PERSON_ID = "source_person_id" +#: A CPS unit id is the first 20 characters of PERIDNUM (H_IDNUM), as the +#: support-mix bake-off reads it. +_CPS_UNIT_ID_LENGTH = 20 +#: The ``source_year`` staging's ACS rows carry: ``acs_pums`` writes the +#: source vintage, 2024 for the 2024 1-year file the channel names. +_ACS_SOURCE_YEAR = 2024 + +#: Route A's labels on the parent export's rows: the native ASEC row at +#: clone index 0, the PUF tax-detail copy at 1 and the capital-gains tail +#: copy at 2, both copies labelled ``puf_tax_detail``. +_CPS_CHANNELS = (BASE_ASEC_SUPPORT_CHANNEL, PUF_TAX_DETAIL_SUPPORT_CHANNEL) +_CPS_CLONE_INDICES = ( + 0, + PUF_TAX_DETAIL_CLONE_INDEX, + PUF_CAPITAL_GAINS_TAIL_CLONE_INDEX, +) +_CPS = "CPS" +_ACS = "ACS" +#: What each origin's household weights are keyed by for +#: :func:`to_assembled_provenance`: the CPS household's frame id (PR 1's CPS +#: starting weights follow the export's household rows) and the ACS +#: household's selection key (PR 1's ``StartingWeights.acs`` follows +#: ``plan.acs_keys``). +_WEIGHT_KEYS = { + _CPS: US_SCHEMA.id_column("household"), + _ACS: f"acs_unit_key({_SERIALNO})", +} +#: The boundary name the assembly validator reports. +_BOUNDARY = "one-population provenance" +#: The consumer name the ESI premium refusal reports. +_CONSUMER = "d2283 one-population contract" + +#: The six tax-unit provenance columns the capital-gains tail transfer +#: writes on every tax unit, with non-null defaults where it applies no donor +#: (``puf_capital_gains_tail.py`` :1697-1711). Not +#: ``PUF_CAPITAL_GAINS_TAIL_TAX_UNIT_COLUMNS``, which is the section 1250 +#: gain leg. +PUF_TAIL_TAX_UNIT_COLUMNS = ( + PUF_CAPITAL_GAINS_TAIL_APPLIED_COLUMN, + PUF_CAPITAL_GAINS_TAIL_DONOR_SOURCE_ID_COLUMN, + PUF_CAPITAL_GAINS_TAIL_DONOR_SYNTHETIC_COLUMN, + PUF_CAPITAL_GAINS_TAIL_DONOR_FILING_STATUS_COLUMN, + PUF_CAPITAL_GAINS_TAIL_DONOR_AGI_BAND_COLUMN, + PUF_CAPITAL_GAINS_TAIL_TRANSFER_WEIGHT_COLUMN, +) + +#: The column suffix location cloning adds to every entity table +#: (``block_location.LOCATION_CLONE_INDEX_COLUMN``; a test pins the two). +_LOCATION_CLONE_INDEX_SUFFIX = "_location_clone_index" + +#: The household type codes the ACS loader keeps (1 housing unit, 2 +#: institutional and 3 non-institutional group quarters). +_ACS_HOUSEHOLD_TYPES = (1, 2, 3) + +#: The release's first engine pass, on every arm: the SSI December pass +#: (``_ssi_person_uncapped_amount``). Like every pass built from the frame, +#: it loads each frame column that is an engine variable, whether or not it +#: computes anything from it. +#: +#: Release-tool citations here and below name the function or statement +#: and give its line in ``tools/build_us_fiscal_refresh_release.py`` at +#: this module's commit (blob ``f672b8465``, unchanged by the merge of main +#: ``cfd5a2a5e``); the name holds when the tool's lines move. The stage +#: order the verdicts read is pinned by name in the tests. +_SSI_DECEMBER_PASS = ( + "the _ssi_person_uncapped_amount call, " + "tools/build_us_fiscal_refresh_release.py:17060" +) +_NO_EARLIER_READER = ( + "Earlier readers: none; no engine pass runs before this stage (the first, " + f"the SSI December pass, is {_SSI_DECEMBER_PASS}) and no pool-arm stage " + "before it names the column" +) +#: How policyengine-core 3.32.5 (the lock's pin) loads a null boolean input: +#: it casts with ``astype(bool)``, skipping the null refusal it applies to +#: float and integer inputs (``holder.py`` :257, :276-291). +_BOOLEAN_NULL_LOAD = ( + "policyengine-core 3.32.5 loads a boolean NaN as True and a None as False " + "and refuses a pd.NA" +) +_LOADED_NOT_COMPUTED = ( + f"Earlier readers: the SSI December pass ({_SSI_DECEMBER_PASS}) loads it but " + "computes nothing from it (it is outside uncapped_ssi's dependency " + f"closure); {_BOOLEAN_NULL_LOAD} (static reads of policyengine-us 2.2.1 and " + "policyengine-core 3.32.5, d2283 lead call L1's trace)" +) +_SCF_ASSETS_EVIDENCE = ( + "scf_wealth stage: with_us_scf_wealth_inputs re-imputes all three asset " + "columns on every person when any value is not finite " + "(U/scf_wealth.py:1031; pass-through only when assets and net worth both " + f"carry signal, :1129; rewrite, :1149). {_NO_EARLIER_READER}" +) +_ORG_EVIDENCE = ( + "org_wages stage: with_us_org_wages_inputs re-imputes the family on every " + "entry and passes through only when each stored output equals the " + "recomputed one, which a null never does (U/org_wages.py:990, :998, " + ":1046); otherwise it writes every output on every person (:1050). " + f"{_LOADED_NOT_COMPUTED}" +) + +#: The engine inputs the release tool's always-on producers rewrite on every +#: row, or refuse on a null, before any release stage reads them on ACS rows, +#: so prepare may leave them null there (the null-input clause, R6, exempts +#: them; d2283 Q1 (a), narrowed by lead call L1 of 11-18). Each entry is the +#: column and its evidence, re-read at this module's commit: the stage +#: (whose ``us/source_stages.json`` ``outputs`` name the column; a test pins +#: that), the lines that rewrite every row or raise on a null, and the +#: release's earlier readers (an engine pass built from the frame before the +#: producer), from L1's static trace of the release tool's pool arm. A test +#: pins the stage order and the engine pins those verdicts read. +#: +#: Left out, so prepare must fill them on ACS rows: producers that pass a +#: frame through when the column carries signal after dropping nulls +#: (``is_snap_abawd_discretionary_exempt``, the three SCF auto-loan columns, +#: the two SIPP vehicle columns, the two SIPP tip columns), a stage's source +#: column (``health_insurance_premiums_without_medicare_part_b``), declared +#: outputs nothing on Route A writes (the ``scf_*`` and education-debt +#: columns), and ``takes_up_snap_if_eligible``. SNAP state take-up does +#: rewrite that one on every SPM unit and raise on a null +#: (U/snap_state_take_up.py:282-290), but the SNAP take-up stage before it +#: passes ACS nulls through (U/snap_take_up.py:231-239, :274-277), and the +#: release's SNAP take-up gate (``us_snap_take_up_signal_gate(base_frame)``, +#: tools/build_us_fiscal_refresh_release.py:16463) grades that frame through +#: ``to_numpy(dtype=bool)`` +#: (U/snap_take_up.py:319), which reads a NaN as take-up, a None as no +#: take-up and refuses a ``pd.NA``: it misgrades ACS nulls. +#: +#: Also left out (lead call L1): ten producer outputs an engine pass loads +#: before their producer writes them. policyengine-core 3.32.5 refuses a NaN +#: or None in a float or integer input at load (``holder.py`` :257, +#: :276-291, a static read), so a null in ``cps_race``, ``hourly_wage``, +#: ``fsla_overtime_premium``, ``detailed_occupation_recode``, +#: ``detailed_industry_recode``, ``major_industry_recode`` (org_wages, +#: ``with_us_org_wages_inputs``, tools/build_us_fiscal_refresh_release.py:17328), +#: ``selected_marketplace_plan_benchmark_ratio`` (aca_marketplace_inputs, +#: ``_with_aca_marketplace_source_outputs``, :17360), +#: ``other_health_insurance_premiums`` or ``health_insurance_premiums`` +#: (other_health_insurance_premiums, ``with_us_other_health_insurance_inputs``, +#: :17467) stops the build at the SSI December pass +#: (``_ssi_person_uncapped_amount``, :17060). The ACA, Medicaid and +#: SNAP-state passes (``_with_aca_marketplace_source_outputs``, :17360; +#: ``_with_medicaid_take_up_outputs``, :17395; +#: ``_with_snap_state_take_up_outputs``, :17430) also compute from +#: ``health_insurance_premiums`` and ``is_self_employed`` (the self-employed +#: health insurance deduction into AGI and MAGI, and medical expenses), and +#: a boolean null there reads silently as True or False. Staging writes the +#: three integer recodes natively on ACS rows (U/acs_inputs.py:105-120, +#: ``ACS_WORK_EXPERIENCE_NATIVE_MAPPINGS``) and none of the other seven. +#: +#: And ``takes_up_medicaid_if_eligible`` (medicaid_take_up, +#: ``_with_medicaid_take_up_outputs``, :17395; moved by the lead-call +#: review, fail closed): the ACA stage's pass +#: (``_with_aca_marketplace_source_outputs``, :17360) computes +#: ``medicaid_enrolled`` from it before Medicaid writes it, by two +#: routes in policyengine-us 2.2.1. One is the ineligible-coverage sum's +#: qualifying non-marketplace coverage; the other is CHIP's disqualifying +#: coverage, into ``is_chip_eligible_child`` and so ``is_chip_eligible``, +#: which the ineligible-coverage sum and Basic Health Program eligibility +#: read. Both are masked today: ``medicaid_enrolled`` is defined for +#: ``is_medicaid_eligible``, which sits in the same sum, and +#: ``is_chip_eligible_child`` and Basic Health Program eligibility each +#: require not ``is_medicaid_eligible``. L1 let only the two +#: self-employed-premium inputs argue a harmless read, and nothing here +#: checks the masking, so the column is filled like the others. +RELEASE_WRITTEN_INPUTS: Mapping[str, str] = MappingProxyType( + { + "bank_account_assets": _SCF_ASSETS_EVIDENCE, + "bond_assets": _SCF_ASSETS_EVIDENCE, + "stock_assets": _SCF_ASSETS_EVIDENCE, + "net_worth": ( + "scf_wealth stage: with_us_scf_wealth_inputs re-imputes net_worth " + "on every household when any value is not finite " + "(U/scf_wealth.py:1048, :1129; rewrite, :1157). " + f"{_NO_EARLIER_READER} (sipp_vehicles reads it later, " + "with_us_sipp_vehicle_inputs, " + "tools/build_us_fiscal_refresh_release.py:17198)" + ), + "meets_ssi_disability_criteria": ( + "ssi_disability_criteria stage: with_us_ssi_disability_criteria " + "passes through only when every value is finite, 0/1 and equal to " + "its prediction, else writes the prediction on every person " + "(U/ssi_disability_criteria.py:1160, :1167). " + f"{_NO_EARLIER_READER} (the SSI December pass computes from it, " + "after this stage)" + ), + "takes_up_head_start_if_eligible": ( + "sipp_head_start stage: with_us_sipp_head_start_input passes " + "through only when every value is finite, 0/1 and equal to its " + "prediction, else writes the prediction on every person " + f"(U/sipp_head_start.py:740, :747). {_NO_EARLIER_READER}" + ), + "takes_up_ssi_if_eligible": ( + "ssi_take_up stage: with_us_ssi_take_up passes through only a " + "boolean column with no null equal to its assignment, else writes " + "the assignment on every person (U/ssi_take_up.py:1260-1261, " + f":1268). {_LOADED_NOT_COMPUTED}; the pass's docstring says the " + "same (_ssi_person_uncapped_amount, " + "tools/build_us_fiscal_refresh_release.py:4564-4565)" + ), + "would_file_taxes_voluntarily": ( + "voluntary_filing_input stage: with_us_voluntary_filing_input " + "passes through only when every value is finite, 0/1 and equal to " + "its prediction, else writes the prediction on every tax unit " + f"(U/voluntary_filing.py:934, :941). {_LOADED_NOT_COMPUTED}" + ), + **dict.fromkeys( + ( + "is_hispanic", + "worked_last_year", + "has_never_worked", + "is_military", + "is_computer_scientist", + "is_executive_administrative_professional", + "is_farmer_fisher", + "is_paid_hourly", + "is_union_member_or_covered", + ), + _ORG_EVIDENCE, + ), + "takes_up_aca_if_eligible": ( + "aca_marketplace_inputs stage: _with_aca_marketplace_source_outputs " + "raises if the output misses a tax unit and writes it on every tax " + "unit (tools/build_us_fiscal_refresh_release.py:4422, :4428). " + f"{_LOADED_NOT_COMPUTED}; the stage's own pass reads the potential " + "aca_ptc, not the take-up flag " + "(_aca_source_tax_unit_table_from_simulation, :4216-4222)" + ), + } +) + +#: The kinds an :func:`absences` entry carries. Only "owner-declared" needs +#: an owner's decision (N-2). "release-written" is a column of +#: :data:`RELEASE_WRITTEN_INPUTS`; "raw source column" a column the +#: stored-input rule ignores (not model-named, such as the upper-case survey +#: columns); "reviewed default fill" a value prepare's fill wrote in place +#: of a null, reviewed by staging's ``reviewed_engine_input_nulls`` register +#: (``tools/_legacy/build_us_acs_multispine_base.py``, summary key at +#: :2099, built at :2336-2392); "zero written" a zero staging wrote in place +#: of a measure, reviewed by the receipt the caller cites; "origin-native" a +#: column of :data:`ACS_NATIVE_AMOUNTS` CPS rows lack (d2283 lead call (a), +#: 11-18). +ABSENCE_KINDS = ( + "owner-declared", + "release-written", + "raw source column", + "reviewed default fill", + "zero written", + "origin-native", +) +( + _OWNER_DECLARED, + _RELEASE_WRITTEN, + _RAW_SOURCE, + _DEFAULT_FILL, + _ZERO_WRITTEN, + _ORIGIN_NATIVE, +) = ABSENCE_KINDS + +_ACS_TRANSFER_READER = ( + "acs_transfer (a recipient-side predictor, read on ACS rows only; " + "acs_transfer._RECIPIENT_COMBINED_SOURCES)" +) + +#: The six ACS-native reported amounts, each with its entity and the +#: release's readers: the ``acs_*`` keys of +#: ``operator_boundary._ACS_NATIVE_INPUT_CONTRACTS``. A test pins the two by +#: reading that module's source. The import would cost nothing extra +#: (``us_runtime``'s ``__init__`` already imports ``operator_boundary``); the +#: copy stays by d2283 lead call L8. Staging maps them from ACS source +#: columns on ACS rows only, and the stored-input register files each as +#: "not a model input", so CPS rows lack them by origin: :func:`absences` +#: files that as "origin-native", with no owner's decision. The ACS transfer +#: reads the three combined amounts as recipient-side predictors on ACS +#: rows; no release producer reads the three housing amounts, which are +#: source lineage the native-input receipt records. +ACS_NATIVE_AMOUNTS: Mapping[str, tuple[str, tuple[str, ...]]] = MappingProxyType( + { + "acs_social_security_income": ("person", (_ACS_TRANSFER_READER,)), + "acs_retirement_income": ("person", (_ACS_TRANSFER_READER,)), + "acs_interest_dividend_rental_income": ("person", (_ACS_TRANSFER_READER,)), + "acs_monthly_contract_rent": ("household", ()), + "acs_monthly_gross_rent": ("household", ()), + "acs_annual_property_tax": ("household", ()), + } +) +_ORIGIN_NATIVE_EVIDENCE = ( + "an ACS-native reported amount, not a model input " + "(operator_boundary._ACS_NATIVE_INPUT_CONTRACTS; the stored-input " + "register's acs_ entries): staging maps it from ACS source columns on ACS " + "rows only, so CPS rows lack it by origin" +) + +_HOUSEHOLD_TYPE_READER = "household_type (#1610's household-type materializer)" + +#: Raw source columns the release reads, each with its readers, so the +#: absences file never files them as harmless. The fourteen ACS release +#: predictors (``acs_release_predictors._MODEL_PREDICTORS``, :992-1006; a +#: test pins the two) feed these always-on producers; the join writes them +#: only on channel ``acs`` rows, which this module never writes, so on the +#: joined frame each producer reads them null on every row that lacks them. +#: ``TYPEHUGQ``, ``HRHTYPE``, ``A_EXPRRP`` and ``A_MARITL`` are what +#: PolicyEngine/microcosm#1610's household-type materializer +#: (``household_type_targets.household_type_household_values``, not on main +#: at this module's commit) reads and refuses on. +RAW_COLUMN_READERS: Mapping[str, tuple[str, ...]] = MappingProxyType( + { + **dict.fromkeys( + ( + "PEDISDRS", + "PEDISEAR", + "PEDISEYE", + "PEDISOUT", + "PEDISPHY", + "PEDISREM", + ), + ("ssi_disability_criteria",), + ), + **dict.fromkeys( + ("PRDTRACE", "PRDTHSP"), + ("org_wages", "scf_auto_loans", "scf_wealth"), + ), + "SPM_TENMORTSTATUS": ("sipp_vehicles",), + "PEIOOCC": ("sipp_tips",), + **dict.fromkeys(("POCCU2", "WEIND", "WEMIND", "WKSWORK"), ("org_wages",)), + **dict.fromkeys( + ("TYPEHUGQ", "HRHTYPE", "A_EXPRRP", "A_MARITL"), + (_HOUSEHOLD_TYPE_READER,), + ), + } +) + +#: The ACS RELSHIPP role rule and its SPM partition, as staging's receipt +#: states them: copies of ``acs_inputs.ACS_SPM_ROLE_RULE`` and +#: ``acs_inputs.ACS_SPM_ROLE_PARTITION``, which a test pins by reading that +#: module's source. The import would cost nothing extra (``us_runtime``'s +#: ``__init__`` already imports ``acs_inputs`` through ``operator_boundary``); +#: the copies stay by d2283 lead call L8. +_ACS_SPM_ROLE_RULE = ( + "RELSHIPP == 20 OR RELSHIPP in {21, 23} OR RELSHIPP in {37, 38}, " + "on the one-SPM-unit-per-household ACS partition" +) +_ACS_SPM_ROLE_PARTITION = "household (ACS PUMS carries no SPM_ID)" +#: That rule's ``RELSHIPP`` codes: the role holders (20 the reference +#: person, 21/23 the spouse, 37/38 the sole group-quarters person) and the +#: codes it reads at all (20 to 38). Copies of ``acs_inputs``' +#: ``_ACS_REFERENCE_PERSON``, ``_ACS_SPOUSE_OF_REFERENCE``, +#: ``_ACS_GROUP_QUARTERS_PERSON`` and ``_ACS_RELSHIPP_CODES``, which a test +#: pins, by lead call L8. +_RELSHIPP = "RELSHIPP" +_ACS_ROLE_RELSHIPP = frozenset({20, 21, 23, 37, 38}) +_ACS_RELSHIPP_CODES = frozenset(range(20, 39)) + +#: The keys staging's ACS role receipt carries +#: (``acs_inputs.with_acs_spm_independence_role``, :478-511; a test pins the +#: two), and the values that identify it as the ACS RELSHIPP rule's. +_ACS_ROLE_RECEIPT_KEYS = frozenset( + { + "column", + "entity", + "source_columns", + "rule", + "partition", + "asec_rule", + "adult_rule", + "provenance", + "persons", + "spm_units", + "role_true_persons", + "role_branches", + "persons_aged_15_to_17", + "independent_minor_persons", + "housing_units_classified_only_by_role", + "group_quarters_units_without_classified_adult", + "weighted_role_share", + "weighted_minor_role_share", + } +) +_ACS_ROLE_RECEIPT_IDENTITY: Mapping[str, object] = MappingProxyType( + { + "column": NATIVE_SPM_ROLE, + "entity": US_SCHEMA.person_entity, + "source_columns": ["RELSHIPP"], + "rule": _ACS_SPM_ROLE_RULE, + "partition": _ACS_SPM_ROLE_PARTITION, + "asec_rule": SPM_ROLE_RULE, + "adult_rule": SPM_ADULT_RULE, + "provenance": "acs_2024_1yr_native", + } +) +#: The receipt's counts and the frame's ACS counts they must cover: the +#: receipt counts every staged ACS person, the frame only the selected ones. +_ACS_ROLE_RECEIPT_COVERAGE = ( + ("persons", "persons"), + ("spm_units", "spm_units"), + ("role_true_persons", "true_role_persons"), +) +#: The keys :func:`~microcosm.build.us_runtime.spm_independence_role.us_spm_independence_role_signal_gate` +#: compares with the frame (``spm_independence_role.py`` :574-586). +_ROLE_GATE_COUNT_KEYS = ( + "persons_joined", + "table_rows", + "native_spm_units", + "true_role_persons", +) +_ROLE_GATE_DIGEST_KEY = "person_role_binding_sha256" +_ROLE_SOURCE_COLUMN = "source_column" + +#: The top-level keys and per-fill keys of the reviewed default fill's +#: manifest (``tools/build_us_acs_local_release.py``, ``fill_reviewed_nulls``, +#: :1135-1144 and :1151-1165). +_FILL_MANIFEST_KEYS = frozenset( + { + "period", + "register_entries", + "columns_filled", + "total_values_filled", + "count_mismatch_warnings", + "unregistered_violations", + "fills", + } +) +_FILL_KEYS = frozenset( + { + "entity", + "column", + "filled_rows", + "rows", + "fill_value", + "fill_kind", + "register_missing_rows", + "missing_rows_by_spine", + } +) +#: The absences file's layout version. +_ABSENCES_SCHEMA_VERSION = 1 + + +class OnePopulationContractError(ValueError): + """A one-population frame, or one origin's input, breaks a contract clause. + + Each message names the clause's rule, so a caller (and a test) can tell + the refusals apart. + """ + + +# ------------------------------------------------------------ provenance + + +def _spine_column(entity: str) -> str: + """The ``_spine`` tag column staging writes on every pooled row.""" + + return f"{entity}_spine" + + +def _provenance_columns(entity: str) -> tuple[str, str, str, str, str]: + """``entity``'s source id, channel, clone index, spine source id and spine tag.""" + + return ( + support_source_id_column(entity), + support_channel_column(entity), + support_clone_index_column(entity), + spine_source_id_column(entity), + _spine_column(entity), + ) + + +#: Why :func:`_complex_or_temporal`'s refusals refuse, in their messages. +_READ_AS_NUMBERS = ( + "the contract reads only integer, real-number and string data as numbers, " + "since a conversion would drop an imaginary part, turn a time into a count " + "or misread other data." +) + + +def _is_real_number(value: object) -> bool: + """``value`` is a real-number scalar, and not a boolean or a numpy time. + + Numpy registers ``timedelta64`` as an integer (it derives it from + ``signedinteger``), so an ``isinstance`` test against :mod:`numbers` + takes it for one. Comparisons read it as its count of time units for + every unit, and for some units ``int()`` does too + (``np.timedelta64(1, "ns") in (1, 2, 3)`` holds). A ``timedelta64`` and a + ``datetime64`` are never numbers here (PR #1685 review r3, should-fix 2). + """ + + return isinstance(value, numbers.Real) and not isinstance( + value, bool | np.bool_ | np.timedelta64 | np.datetime64 + ) + + +def _is_integer(value: object) -> bool: + """``value`` is an integer scalar: a real number (:func:`_is_real_number`) + of an integral type.""" + + return _is_real_number(value) and isinstance(value, numbers.Integral) + + +def _readable_value(value: object) -> bool: + """``value`` may sit in an object column read as numbers. + + A string, a real number (booleans included, which ``pd.to_numeric`` + reads as 0 and 1, and ``decimal.Decimal``), or a null the null checks + after this one count. Anything else refuses: a complex value, a time, + and any other object ``pd.to_numeric`` might read as a number (a + zero-dimensional numpy array of a ``timedelta64`` or a complex value + reads as its count or its real part). + """ + + return ( + value is None + or value is pd.NA + or isinstance(value, str | bytes | bool | np.bool_ | decimal.Decimal) + or _is_real_number(value) + ) + + +def _complex_or_temporal(series: pd.Series) -> str | None: + """What ``series`` holds other than integers, real numbers or strings. + + Returns None when the data may be read as numbers. The name is older + than the rule: review r2 found complex and temporal data read as + numbers, and review r3 an Arrow dictionary of times (PR #1685, + should-fix 1 each), so the check now names the data it accepts and + refuses the rest. It reads the value type behind a categorical's + categories and behind an Arrow dictionary, then accepts an integer, + unsigned or floating type, a string type, or an object column whose + every value passes :func:`_readable_value`. Any other dtype refuses by + name: complex, datetime, timedelta, period, interval, boolean, Arrow + decimal and the rest. + """ + + dtype = series.dtype + if isinstance(dtype, pd.CategoricalDtype): + found = _complex_or_temporal(pd.Series(dtype.categories)) + return None if found is None else f"categories of {found}" + if isinstance(dtype, pd.ArrowDtype): + import pyarrow as pa + + value_type = dtype.pyarrow_dtype + if pa.types.is_dictionary(value_type): + value_type = value_type.value_type + readable = ( + pa.types.is_integer(value_type) + or pa.types.is_floating(value_type) + or pa.types.is_string(value_type) + or pa.types.is_large_string(value_type) + ) + return None if readable else f"{dtype} values" + if isinstance(dtype, pd.StringDtype) or dtype.kind in ("i", "u", "f"): + return None + if not pd.api.types.is_object_dtype(dtype): + return f"{dtype} values" + values = series.to_numpy() + unreadable = { + kind + for kind, value in {type(value): value for value in values}.items() + if not _readable_value(value) + } + if not unreadable: + return None + found = [value for value in values if type(value) in unreadable] + return ( + f"{len(found)} value(s) that are not real numbers or strings, such as " + f"{found[:3]!r}" + ) + + +def _integral_ids(series: pd.Series, *, refusal: str) -> np.ndarray: + """``series`` as int64 if every value is a non-null integer, else refuse. + + Integer dtypes pass as they are; float and object values must be finite, + integral and inside int64 (staging's pooled form turns an origin's + integer column into float64 when the other origin lacks it). Object + values go through ``pd.to_numeric``, so digit strings (``"601"``, + ``"6.0"``) and booleans held in an object column pass as their numbers. + A boolean dtype refuses, and so does any data but integers, real + numbers and strings, as a dtype or as values, before that conversion + reads it (:func:`_complex_or_temporal`). + """ + + if pd.api.types.is_bool_dtype(series.dtype): + raise OnePopulationContractError(f"{refusal}: it holds booleans, not ids.") + found = _complex_or_temporal(series) + if found is not None: + raise OnePopulationContractError( + f"{refusal}: it holds {found}, not integers; {_READ_AS_NUMBERS}" + ) + nulls = int(series.isna().sum()) + if nulls: + raise OnePopulationContractError(f"{refusal}: {nulls} value(s) are null.") + if pd.api.types.is_integer_dtype(series.dtype): + return series.to_numpy(dtype=np.int64) + numeric = pd.to_numeric(series, errors="coerce") + if pd.api.types.is_integer_dtype(numeric.dtype): + # Object-held Python ints: exact, never through float64. + return numeric.to_numpy(dtype=np.int64) + values = numeric.to_numpy(dtype=np.float64, na_value=np.nan) + bad = ( + ~np.isfinite(values) | (values != np.floor(values)) | (np.abs(values) >= 2**63) + ) + if bad.any(): + examples = series[bad].head(5).tolist() + raise OnePopulationContractError( + f"{refusal}: {int(bad.sum())} value(s) are not integers, such as " + f"{examples!r}." + ) + return values.astype(np.int64) + + +def _origin_tables( + tables: Mapping[str, pd.DataFrame], *, origin: str +) -> dict[str, pd.DataFrame]: + """The six US entity tables of one origin, or a refusal.""" + + if not isinstance(tables, Mapping): + raise TypeError( + f"{origin} tables must be a mapping of entity to table, got " + f"{type(tables).__name__}." + ) + expected = set(US_SCHEMA.entities) + missing = sorted(expected - set(tables)) + unexpected = sorted(str(name) for name in set(tables) - expected) + if missing or unexpected: + raise OnePopulationContractError( + f"{origin} rows lack complete support metadata: the tables must be " + f"the six US entities; missing {missing}, unexpected {unexpected}." + ) + for entity in US_SCHEMA.entities: + if not isinstance(tables[entity], pd.DataFrame): + raise TypeError( + f"{origin} {entity!r} table must be a DataFrame, got " + f"{type(tables[entity]).__name__}." + ) + return {entity: tables[entity] for entity in US_SCHEMA.entities} + + +def _require_support_columns( + table: pd.DataFrame, entity: str, *, origin: str +) -> tuple[np.ndarray, np.ndarray, np.ndarray]: + """Presence and completeness of one table's support metadata (P5). + + Returns the integral ids, source ids and clone indices. + """ + + source, channel, clone, spine_source, spine = _provenance_columns(entity) + id_column = US_SCHEMA.entity_id_column(entity) + rule = f"{origin} rows lack complete support metadata" + missing = [column for column in (source, channel, clone) if column not in table] + if missing: + raise OnePopulationContractError( + f"{rule}: {entity!r} is missing {missing}; every entity needs its " + "source id, support channel and clone index." + ) + if id_column not in table: + raise OnePopulationContractError( + f"{rule}: {entity!r} is missing {id_column!r}." + ) + if spine_source in table: + raise OnePopulationContractError( + f"{origin} rows already carry {spine_source!r}: the contract writes " + "the spine source id, so its input must not hold one." + ) + for column in (source, channel, clone): + nulls = int(table[column].isna().sum()) + if nulls: + raise OnePopulationContractError( + f"{rule}: {column!r} has {nulls} null value(s)." + ) + return ( + _integral_ids( + table[id_column], refusal=f"{origin} {id_column!r} must hold ids" + ), + _integral_ids( + table[source], refusal=f"{origin} {source!r} must hold source ids" + ), + _integral_ids( + table[clone], refusal=f"{origin} {clone!r} must hold clone indices" + ), + ) + + +def _unexpected(values: pd.Series, allowed: Collection[object]) -> list[str]: + """Sorted reprs of the values outside ``allowed`` (strings only allowed).""" + + good = values.map(lambda value: isinstance(value, str) and value in allowed) + return sorted({repr(value) for value in values[~good.astype(bool)]}) + + +def _require_cps_support_metadata(tables: Mapping[str, pd.DataFrame]) -> None: + """P5 on the parent export's rows: Route A's labels, complete.""" + + for entity in US_SCHEMA.entities: + table = tables[entity] + _, channel, clone, _, spine = _provenance_columns(entity) + _, _, clones = _require_support_columns(table, entity, origin=_CPS) + bad_clones = sorted(set(clones.tolist()) - set(_CPS_CLONE_INDICES)) + if bad_clones: + raise OnePopulationContractError( + "CPS clone indices must be 0, 1 or 2 (Route A's native rows, PUF " + f"tax-detail copies and capital-gains tail copies); {clone!r} " + f"holds {bad_clones[:5]}." + ) + bad_channels = _unexpected(table[channel], _CPS_CHANNELS) + if bad_channels: + raise OnePopulationContractError( + f"CPS rows must carry channel {BASE_ASEC_SUPPORT_CHANNEL!r} or " + f"{PUF_TAX_DETAIL_SUPPORT_CHANNEL!r} (Route A's labels); " + f"{channel!r} holds {bad_channels[:5]}." + ) + native = table[channel].eq(BASE_ASEC_SUPPORT_CHANNEL).to_numpy() + disagree = int(np.count_nonzero(native != (clones == 0))) + if disagree: + raise OnePopulationContractError( + f"CPS rows must carry channel {BASE_ASEC_SUPPORT_CHANNEL!r} exactly " + f"on clone index 0; {disagree} {entity!r} row(s) disagree." + ) + if spine in table: + tags = table[spine] + wrong = tags.notna() & tags.ne(CPS_SPINE_TAG) + if wrong.any(): + raise OnePopulationContractError( + f"CPS rows carry a spine tag other than {CPS_SPINE_TAG!r} in " + f"{spine!r}: {sorted({repr(tag) for tag in tags[wrong]})[:5]}; " + "staging tags the donor's rows " + f"{CPS_SPINE_TAG!r}." + ) + + +def _require_acs_support_metadata(tables: Mapping[str, pd.DataFrame]) -> None: + """P5 on staging's ACS rows: staging's labels, complete, one id offset.""" + + for entity in US_SCHEMA.entities: + table = tables[entity] + _, channel, clone, _, spine = _provenance_columns(entity) + ids, sources, clones = _require_support_columns(table, entity, origin=_ACS) + bad_channels = _unexpected(table[channel], (ACS_SUPPORT_CHANNEL,)) + if bad_channels: + raise OnePopulationContractError( + f"ACS rows must carry channel {ACS_SUPPORT_CHANNEL!r} (staging's); " + f"{channel!r} holds {bad_channels[:5]}." + ) + bad_clones = sorted(set(clones.tolist()) - {0}) + if bad_clones: + raise OnePopulationContractError( + f"ACS rows must carry clone index 0; {clone!r} holds {bad_clones[:5]}." + ) + offsets = sorted(set((ids - sources).tolist())) + if len(offsets) > 1: + raise OnePopulationContractError( + f"ACS {entity!r} ids must sit one constant offset from staging's " + f"native source ids (staging shifts each entity's ids by one " + f"amount); found offsets {offsets[:5]}." + ) + if spine in table: + tags = table[spine] + wrong = tags.notna() & tags.ne(ACS_SUPPORT_CHANNEL) + if wrong.any(): + raise OnePopulationContractError( + f"ACS rows carry a spine tag other than {ACS_SUPPORT_CHANNEL!r} " + f"in {spine!r}: {sorted({repr(tag) for tag in tags[wrong]})[:5]}." + ) + + +def _keyed_weights(values: object, *, origin: str) -> dict[object, float]: + """One origin's household weights, by key, before they meet its table. + + Only a keyed input is taken (d2283 lead call L3's check): PR 1's ACS + starting weights come in selection order and staging's ACS households + in id order, so a weight given by position cannot be tied to its + household, and no later clause would see the permutation. The weights + pass the shared guard (:func:`_complex_or_temporal`) before the float64 + conversion, which drops a complex weight's imaginary part and reads a + ``timedelta64`` or ``datetime64`` as its count (PR #1685 review r3, + should-fix 2). + """ + + key = _WEIGHT_KEYS[origin] + if isinstance(values, pd.Series): + keys, given = values.index.tolist(), values.to_numpy() + found = _complex_or_temporal(values) + elif isinstance(values, Mapping): + keys, given = list(values), list(values.values()) + found = _complex_or_temporal(pd.Series(given, dtype=object)) + else: + raise OnePopulationContractError( + f"{origin} household weights must be keyed by {key} (a pandas Series " + f"or a mapping), not a {type(values).__name__}: a weight given by " + "position cannot be tied to its household." + ) + if found is not None: + raise OnePopulationContractError( + f"{origin} household weights must be real numbers; they hold {found}: " + f"{_READ_AS_NUMBERS}" + ) + try: + array = np.asarray(given, dtype=np.float64) + except (TypeError, ValueError): + array = None + if ( + array is None + or array.ndim != 1 + or not np.isfinite(array).all() + or (array < 0).any() + ): + raise OnePopulationContractError( + f"{origin} household weights must be finite and non-negative." + ) + seen: set[object] = set() + repeated = [] + for k in keys: + if k in seen: + repeated.append(k) + seen.add(k) + if repeated: + raise OnePopulationContractError( + f"{origin} household weights repeat a key: {repeated[:5]!r}." + ) + return dict(zip(keys, array.tolist(), strict=True)) + + +def _aligned_weights( + weights: Mapping[object, float], keys: list[object], *, origin: str +) -> np.ndarray: + """``weights`` in the order of ``keys``, each household's by its key.""" + + missing = [k for k in keys if k not in weights] + extra = sorted(repr(k) for k in set(weights) - set(keys)) + if missing or extra: + raise OnePopulationContractError( + f"{origin} household weights must name each {origin} household by its " + f"{_WEIGHT_KEYS[origin]} exactly once: {len(missing)} household(s) " + f"have no weight (such as {missing[:3]!r}) and {len(extra)} weight(s) " + f"name no household (such as {extra[:3]})." + ) + return np.array([weights[k] for k in keys], dtype=np.float64) + + +def _acs_weight_keys(household: pd.DataFrame) -> list[object]: + """Each ACS household's weight key, ``acs_unit_key(SERIALNO)``, in row order.""" + + try: + return [acs_unit_key(serial) for serial in household[_SERIALNO]] + except ValueError as exc: + raise OnePopulationContractError( + f"ACS household weights need each household's SERIALNO key: {exc}" + ) from exc + + +def _object_column(value: object, index: pd.Index) -> pd.Series: + return pd.Series(value, index=index, dtype=object) + + +def _assembled_cps(tables: Mapping[str, pd.DataFrame]) -> dict[str, pd.DataFrame]: + """P1 and Q3: keep Route A's labels, add the spine source id and tag.""" + + result: dict[str, pd.DataFrame] = {} + for entity in US_SCHEMA.entities: + source, _, _, spine_source, spine = _provenance_columns(entity) + table = tables[entity].copy() + table[spine_source] = table[source].to_numpy(copy=True) + table[spine] = _object_column(CPS_SPINE_TAG, table.index) + result[entity] = table + return result + + +def _assembled_acs(tables: Mapping[str, pd.DataFrame]) -> dict[str, pd.DataFrame]: + """P2: ``assemble_spines``'s rule on staging's rows, channel unchanged. + + The spine source id takes staging's native source id and the source id + the pooled ``_id``; channel ``acs_2024_1yr`` and clone index 0 + stay. Nothing writes the predictor join's ``acs`` channel (P3). + """ + + result: dict[str, pd.DataFrame] = {} + for entity in US_SCHEMA.entities: + source, _, _, spine_source, _ = _provenance_columns(entity) + table = tables[entity].copy() + table[spine_source] = table[source].to_numpy(copy=True) + table[source] = table[US_SCHEMA.entity_id_column(entity)].to_numpy(copy=True) + result[entity] = table + return result + + +def _require_spine_tags(origins: Mapping[str, Mapping[str, pd.DataFrame]]) -> None: + """Q3: no row of the joined frame may carry a null ``_spine``.""" + + for origin, tables in origins.items(): + for entity in US_SCHEMA.entities: + spine = _spine_column(entity) + table = tables[entity] + nulls = len(table) if spine not in table else int(table[spine].isna().sum()) + if nulls: + raise OnePopulationContractError( + f"A null spine tag: {nulls} {origin} {entity!r} row(s) carry no " + f"{spine!r} after the rewrite; every row needs its origin's tag " + f"({CPS_SPINE_TAG!r} on CPS rows, {ACS_SUPPORT_CHANNEL!r} on " + "ACS rows)." + ) + + +def _require_disjoint_ids(origins: Mapping[str, Mapping[str, pd.DataFrame]]) -> None: + """P6b: each entity's ids unique across origins, memberships resolved. + + Every person membership must resolve to exactly one group row of its own + origin, and every group row must hold a person of its origin. Staging + offsets ACS ids clear of its own donor only, so an ACS frame staged on + another donor than the parent export collides here. Each membership + column passes the shared guard (:func:`_complex_or_temporal`) before it + is matched: ``isin`` matches a complex ``5+0j`` with the id 5 (PR #1685 + review r3, nit 2). This is the one place the five person links resolve, + on both paths, before any other clause reads them. + """ + + for entity in US_SCHEMA.entities: + id_column = US_SCHEMA.entity_id_column(entity) + ids = { + origin: _integral_ids( + tables[entity][id_column], + refusal=f"{origin} {id_column!r} must hold ids", + ) + for origin, tables in origins.items() + } + joined = pd.Series(np.concatenate(list(ids.values()))) + repeated = joined[joined.duplicated(keep=False)] + if len(repeated): + across = sorted(set(ids[_CPS].tolist()) & set(ids[_ACS].tolist())) + where = "across origins" if across else "within one origin" + raise OnePopulationContractError( + f"Frame ids collide: {id_column!r} repeats {where} " + f"({sorted(set(repeated.tolist()))[:5]}); each entity's id must be " + "unique across the joined CPS and ACS rows (an ACS frame staged on " + "another donor than the parent export does this)." + ) + for origin, tables in origins.items(): + person = tables[US_SCHEMA.person_entity] + for group in US_SCHEMA.group_entities: + membership_column = US_SCHEMA.membership_column(group) + group_ids = tables[group][US_SCHEMA.id_column(group)] + if membership_column not in person: + raise OnePopulationContractError( + f"Memberships do not resolve: {origin} persons lack " + f"{membership_column!r}." + ) + membership = person[membership_column] + found = _complex_or_temporal(membership) + if found is not None: + raise OnePopulationContractError( + f"Memberships do not resolve: {origin} persons' " + f"{membership_column!r} holds {found}, not ids; " + f"{_READ_AS_NUMBERS}" + ) + unresolved = int((~membership.isin(group_ids)).sum()) + if unresolved: + raise OnePopulationContractError( + f"Memberships do not resolve: {unresolved} {origin} person(s)' " + f"{membership_column!r} match no {origin} {group} row; every " + "person membership must resolve to exactly one group row of its " + "own origin." + ) + empty = int((~group_ids.isin(membership)).sum()) + if empty: + raise OnePopulationContractError( + f"Memberships do not resolve: {empty} {origin} {group} row(s) " + f"hold no {origin} person." + ) + + +def _require_nested_groups(origins: Mapping[str, Mapping[str, pd.DataFrame]]) -> None: + """P6c: every group unit inside one household; each ACS household one SPM unit. + + A tax unit, SPM unit, family or marital unit whose persons sit in two + households resolves every id and keeps every channel, so P6b and the + assembly validator pass it, but the release reads it as one unit split + across households (the ACA pass refuses one, and a tax unit whose + households carry unequal weights has no single weight). ACS rows must + also keep staging's partition, one SPM unit per household + (``acs_inputs.ACS_SPM_ROLE_PARTITION``), the only partition the ACS role + rule and its receipt are defined on (PR #1685 review, blocking 3). It + runs after P6b, which resolves every membership within its origin. + """ + + household_column = US_SCHEMA.membership_column("household") + for origin, tables in origins.items(): + person = tables[US_SCHEMA.person_entity] + if not len(person): + continue + households = person[household_column].to_numpy() + for group in US_SCHEMA.group_entities: + if group == "household": + continue + units = pd.DataFrame( + { + "unit": person[US_SCHEMA.membership_column(group)].to_numpy(), + "household": households, + } + ) + spans = units.groupby("unit", sort=True)["household"].nunique() + split = spans.index[spans.to_numpy() > 1].tolist() + if split: + raise OnePopulationContractError( + f"Group units do not nest in households: {len(split)} {origin} " + f"{group} unit(s) hold persons of more than one household, " + f"such as {split[:5]}; every tax unit, SPM unit, family and " + "marital unit lies inside one household." + ) + if origin != _ACS: + continue + spm_units = pd.DataFrame( + { + "household": households, + "unit": person[US_SCHEMA.membership_column("spm_unit")].to_numpy(), + } + ) + per_household = spm_units.groupby("household", sort=True)["unit"].nunique() + several = per_household.index[per_household.to_numpy() > 1].tolist() + if several: + raise OnePopulationContractError( + "ACS SPM units must be the households (staging's one-SPM-unit-" + f"per-household partition): {len(several)} ACS household(s) hold " + f"more than one SPM unit, such as {several[:5]}." + ) + + +def _require_unique_source_ranks( + origins: Mapping[str, Mapping[str, pd.DataFrame]], +) -> None: + """P6: no (source id, rank) pair repeats anywhere in the joined frame. + + The rank is :func:`support_copy_rank_series`'s, the clone index, read on + the rewritten (assembled) rows. + """ + + for entity in US_SCHEMA.entities: + source = support_source_id_column(entity) + pairs = pd.concat( + [ + pd.DataFrame( + { + "source_id": _integral_ids( + tables[entity][source], + refusal=f"{origin} {source!r} must hold source ids", + ), + "rank": support_copy_rank_series( + tables[entity], entity=entity + ).to_numpy(), + "origin": origin, + } + ) + for origin, tables in origins.items() + ], + ignore_index=True, + ) + repeated = pairs[pairs.duplicated(["source_id", "rank"], keep=False)] + if len(repeated): + examples = sorted( + { + (int(row.source_id), int(row.rank)) + for row in repeated.itertuples(index=False) + } + ) + origins_hit = sorted(set(repeated["origin"])) + raise OnePopulationContractError( + f"A (source id, rank) pair repeats in {entity!r}: {examples[:5]} " + f"({len(examples)} pair(s), on {origins_hit} rows); each support " + "copy needs its own source id and clone index." + ) + + +#: Staging's lineage for the selected ACS persons: each person's native +#: (household id, person id) to its (``SERIALNO``, ``SPORDER``). +_Lineage = dict[tuple[int, int], tuple[str, int]] + + +def _integral_value(value: object) -> int | None: + """``value`` as an int when it is a non-boolean integral number, else None. + + A ``numpy.timedelta64`` registers as an integer (numpy derives it from + ``signedinteger``), and for some units ``int()`` reads it as its count of + time units (``"ns"``; ``"us"`` raises), so it is refused like a boolean + (PR #1685 review r2, should-fix 1), through the shared + :func:`_is_real_number` (review r3, should-fix 2). + """ + + if not _is_real_number(value): + return None + if isinstance(value, numbers.Integral): + return int(value) + as_float = float(value) + return int(as_float) if as_float.is_integer() else None + + +def _lineage_rows(staging_lineage: object) -> _Lineage: + """Staging's lineage, keyed by each ACS person's native ids, checked. + + A set of (``SERIALNO``, ``SPORDER``) pairs is refused: it cannot tie a + ``SERIALNO`` to its household, so two households that swap serial + numbers would keep the set and trade weights (PR #1685 review, + blocking 2). + """ + + rule = "ACS lineage does not survive" + if not isinstance(staging_lineage, Mapping): + raise TypeError( + "staging_lineage must map each staged ACS person's native (household " + "id, person id) to its (SERIALNO, SPORDER), got " + f"{type(staging_lineage).__name__}." + ) + rows: _Lineage = {} + for key, value in staging_lineage.items(): + household_id = person_id = None + if isinstance(key, tuple) and len(key) == 2: + household_id, person_id = (_integral_value(part) for part in key) + if household_id is None or person_id is None: + raise OnePopulationContractError( + f"{rule}: staging's lineage has the key {key!r}, not a native " + "(household id, person id) pair of integers." + ) + pair = value if isinstance(value, tuple) and len(value) == 2 else None + sporder = None if pair is None else _integral_value(pair[1]) + if ( + pair is None + or not isinstance(pair[0], str) + or not pair[0] + or sporder is None + ): + raise OnePopulationContractError( + f"{rule}: staging's lineage maps {key!r} to {value!r}, not a " + f"({_SERIALNO}, {_SPORDER}) pair; {_SERIALNO} must be a non-empty " + f"string and {_SPORDER} an integer." + ) + native = (household_id, person_id) + if native in rows: + raise OnePopulationContractError( + f"{rule}: staging's lineage repeats the native key {native!r}." + ) + rows[native] = (pair[0], sporder) + return rows + + +def _require_acs_lineage( + tables: Mapping[str, pd.DataFrame], + staging: Mapping[tuple[int, int], tuple[str, int]] | None, +) -> None: + """P7: every ACS row's ``SERIALNO``/``SPORDER`` lineage survives. + + ``SERIALNO`` is a non-empty string, unique per ACS household; ``SPORDER`` + an integer, with (``SERIALNO``, ``SPORDER``) unique per ACS person through + the household link; ``source_household_id`` an integer equal to the + linked household's ``household_spine_source_id`` (staging's native id); + ``source_person_id`` the string ``str(SPORDER)``; ``source_year`` the + integer 2024. A null in any of them refuses before a comparison reads it + (pandas' nullable dtypes hold ``pd.NA``, which a sum skips and a + comparison cannot decide). When ``staging`` is given, each ACS person's + (``SERIALNO``, ``SPORDER``), keyed by its native (household id, person + id), must equal staging's, person by person: the same keys, and the + same pair under each key. + """ + + rule = "ACS lineage does not survive" + household = tables["household"] + person = tables[US_SCHEMA.person_entity] + for name, table, columns in ( + ("household", household, (_SERIALNO,)), + ( + "person", + person, + (_SPORDER, _SOURCE_YEAR, _SOURCE_HOUSEHOLD_ID, _SOURCE_PERSON_ID), + ), + ): + missing = [column for column in columns if column not in table] + if missing: + raise OnePopulationContractError( + f"{rule}: the ACS {name} table lacks {missing}." + ) + serials = household[_SERIALNO] + bad = ~serials.map(lambda value: isinstance(value, str) and bool(value)).astype( + bool + ) + if bad.any(): + raise OnePopulationContractError( + f"{rule}: every ACS household needs a non-empty string {_SERIALNO}; " + f"{int(bad.sum())} hold {serials[bad].head(5).tolist()!r}." + ) + if serials.duplicated().any(): + raise OnePopulationContractError( + f"{rule}: {_SERIALNO} repeats across ACS households: " + f"{sorted(set(serials[serials.duplicated()]))[:5]}." + ) + sporder = _integral_ids( + person[_SPORDER], + refusal=f"{rule}: every ACS person needs an integral {_SPORDER}", + ) + household_id = US_SCHEMA.id_column("household") + by_household = household.set_index(household_id) + link = person[US_SCHEMA.membership_column("household")] + person_serial = link.map(by_household[_SERIALNO]).to_numpy(dtype=object) + lineage = pd.DataFrame({"serial": person_serial, "sporder": sporder}) + repeated = lineage.duplicated(keep=False) + if repeated.any(): + raise OnePopulationContractError( + f"{rule}: ({_SERIALNO}, {_SPORDER}) repeats on " + f"{int(repeated.sum())} ACS person(s)." + ) + household_spine = spine_source_id_column("household") + native = _integral_ids( + link.map(by_household[household_spine]), + refusal=f"{rule}: every ACS person's household needs an integral " + f"{household_spine}", + ) + # Nullable dtypes hold pd.NA, which a comparison cannot decide and a sum + # skips, so every lineage value is parsed or null-checked before it is + # compared (PR #1685 review, should-fix 2). + source_household = _integral_ids( + person[_SOURCE_HOUSEHOLD_ID], + refusal=f"{rule}: every ACS person needs an integral {_SOURCE_HOUSEHOLD_ID}", + ) + differs = int(np.count_nonzero(source_household != native)) + if differs: + raise OnePopulationContractError( + f"{rule}: {_SOURCE_HOUSEHOLD_ID} differs from the linked household's " + f"native id ({household_spine}) on {differs} ACS person(s)." + ) + nulls = int(person[_SOURCE_PERSON_ID].isna().sum()) + if nulls: + raise OnePopulationContractError( + f"{rule}: {_SOURCE_PERSON_ID} is null on {nulls} ACS person(s)." + ) + expected = [str(value) for value in sporder.tolist()] + actual = person[_SOURCE_PERSON_ID].tolist() + differs = sum( + 1 + for want, got in zip(expected, actual, strict=True) + if not (isinstance(got, str) and got == want) + ) + if differs: + raise OnePopulationContractError( + f"{rule}: {_SOURCE_PERSON_ID} differs from str({_SPORDER}) on {differs} " + "ACS person(s)." + ) + years = _integral_ids( + person[_SOURCE_YEAR], + refusal=f"{rule}: every ACS person needs an integral {_SOURCE_YEAR}", + ) + wrong_year = int(np.count_nonzero(years != _ACS_SOURCE_YEAR)) + if wrong_year: + raise OnePopulationContractError( + f"{rule}: {_SOURCE_YEAR} must be {_ACS_SOURCE_YEAR} on every ACS person; " + f"{wrong_year} differ." + ) + if staging is None: + return + person_spine = spine_source_id_column("person") + native_person = _integral_ids( + person[person_spine], + refusal=f"{rule}: every ACS person needs an integral {person_spine}", + ) + selected = dict( + zip( + zip(native.tolist(), native_person.tolist(), strict=True), + zip(lineage["serial"].tolist(), lineage["sporder"].tolist(), strict=True), + strict=True, + ) + ) + if len(selected) != len(person): + raise OnePopulationContractError( + f"{rule}: a native (household id, person id) repeats on the ACS " + "persons, so staging's lineage cannot be matched person by person." + ) + _require_staging_lineage(selected, staging) + + +def _require_staging_lineage( + selected: Mapping[tuple[int, int], tuple[str, int]], + staging: Mapping[tuple[int, int], tuple[str, int]], +) -> None: + """P7's last rule: each selected ACS person's pair is staging's, by key. + + The key is the person's native (household id, person id), so a + ``SERIALNO`` swapped between two households, or a ``SPORDER`` swapped + between two persons, is a moved pair even when the set of pairs holds + (PR #1685 review, blocking 2). + """ + + missing = sorted(set(staging) - set(selected)) + extra = sorted(set(selected) - set(staging)) + moved = sorted( + key for key in set(selected) & set(staging) if selected[key] != staging[key] + ) + if missing or extra or moved: + examples = [ + f"{key}: {selected[key]} here, {staging[key]} in staging" + for key in moved[:3] + ] + raise OnePopulationContractError( + "ACS lineage does not survive: the selected ACS persons' " + f"({_SERIALNO}, {_SPORDER}) lineage differs from staging's, keyed by " + f"native (household id, person id); {len(missing)} missing (such as " + f"{missing[:3]}), {len(extra)} extra (such as {extra[:3]}), " + f"{len(moved)} moved (such as {examples})." + ) + + +def _joined_tables( + origins: Mapping[str, Mapping[str, pd.DataFrame]], +) -> tuple[dict[str, pd.DataFrame], np.ndarray]: + """CPS rows then ACS rows per entity, group tables sorted by id. + + A zero-row table is left out of the join, so an empty origin changes no + dtype of the other's columns. Returns the tables and the household + order applied to the concatenated rows. + """ + + tables: dict[str, pd.DataFrame] = {} + household_order = np.arange(0) + for entity in US_SCHEMA.entities: + parts = [table[entity] for table in origins.values() if len(table[entity])] + if not parts: + parts = [origins[_CPS][entity]] + table = pd.concat(parts, ignore_index=True, sort=False) + if entity in US_SCHEMA.group_entities: + order = np.argsort( + table[US_SCHEMA.id_column(entity)].to_numpy(), kind="stable" + ) + table = table.iloc[order].reset_index(drop=True) + if entity == "household": + household_order = order + tables[entity] = table + return tables, household_order + + +def to_assembled_provenance( + cps_tables: Mapping[str, pd.DataFrame], + acs_tables: Mapping[str, pd.DataFrame], + *, + cps_household_weights: pd.Series | Mapping[object, float], + acs_household_weights: pd.Series | Mapping[object, float], + staging_lineage: Mapping[tuple[int, int], tuple[str, int]], +) -> Frame: + """Join CPS and ACS rows in the assembled provenance form (d2283 K-1). + + CPS rows (the parent export's) keep Route A's source id, channel and + clone index (``asec`` on clone 0, ``puf_tax_detail`` on clones 1 and 2), + gain ``_spine_source_id`` equal to the source id, and are tagged + ``_spine = asec_puf``, staging's donor tag (d2283 Q3). ACS rows + (staging's) follow + :func:`~microcosm.build.us_runtime.spine_assembly.assemble_spines`'s rule, + re-implemented because that function refuses inputs that already carry + provenance: the spine source id takes staging's native source id, the + source id takes the pooled ``_id`` (staging offset it clear of + the donor's ids), the channel stays ``acs_2024_1yr`` and the clone index + 0, and staging's ``_spine`` tag stays. No row is labelled + ``acs``, so the ACS predictor join passes the frame through. Ids are + never re-offset (d2283 Q9): an ACS frame staged on another donor than + the parent export is refused. + + The clauses run in order, each refusing with its own rule's message: + + - complete support metadata on each origin's input (P5). CPS: source id, + channel and clone index on all six entities, no nulls, channel + ``asec`` or ``puf_tax_detail``, ``asec`` exactly on clone index 0, + clone index 0, 1 or 2, no spine source id, and no spine tag other than + ``asec_puf``. ACS: the same three columns, no nulls, channel + ``acs_2024_1yr``, clone index 0, ``_id - _source_id`` + one constant per entity, no spine source id, and no spine tag other + than ``acs_2024_1yr``; + - household weights keyed, each key once, finite and non-negative + (d2283 lead call L3's check); + - a non-null ``_spine`` on every row after the rewrite (Q3); + - each entity's id unique across the joined rows, every person + membership resolving to exactly one group row of its own origin, and + every group row holding a person (P6b); + - no (source id, rank) pair repeated anywhere, the rank being + :func:`~microcosm.build.us_runtime.support_provenance.support_copy_rank_series`'s + (P6); + - the ACS rows' ``SERIALNO``/``SPORDER`` lineage, against + ``staging_lineage`` person by person, keyed by native ids, before any + weight is looked up by ``SERIALNO`` (P7; see + :func:`_require_acs_lineage`); + - one weight per household, found by its key: no household without a + weight, no weight without a household; + - after the frame and its record pass the assembly validator, every + tax unit, SPM unit, family and marital unit inside one household of + its origin, and each ACS household one SPM unit (staging's partition; + see :func:`_require_nested_groups`). + + The spine assembly record (P8) is + :func:`~microcosm.build.us_runtime.support_provenance.spine_assembly_manifest` + over every entity's clone-0 rows, declaring :data:`ASSEMBLED_CHANNELS` + (``puf_tax_detail`` with a clone-0 count of 0), so + :func:`~microcosm.build.us_runtime.support_provenance.validate_assembly_provenance` + accepts the clone rows. The frame is checked against it before return. + + Args: + cps_tables: The parent export's six entity tables (every CPS row: + native rows and their clones). + acs_tables: Staging's six entity tables for the selected ACS + households. A table may have no rows. + cps_household_weights: PR 1's CPS starting weights keyed by + ``household_id``: a :class:`pandas.Series` indexed by it, or a + mapping, one entry per row of ``cps_tables["household"]``, in + any order. + acs_household_weights: PR 1's ACS starting weights keyed by each + household's + :func:`~microcosm.build.us_runtime.one_population_selection.acs_unit_key` + of its ``SERIALNO`` (``pd.Series(starting.acs, + index=plan.acs_keys)``), one entry per row of + ``acs_tables["household"]``, in any order; empty when no ACS + household is selected. A weight given by position is refused: + ``StartingWeights.acs`` comes in selection order and staging's + households in id order, and no later clause would see the + permutation (d2283 lead call L3's check). + staging_lineage: Staging's lineage for the persons of the selected + ACS households, read from staging's output, not from + ``acs_tables``: each person's native (household id, person id), + that is staging's ``household_source_id`` of the person's + household and the person's ``person_source_id``, mapped to its + (``SERIALNO``, ``SPORDER``). Ids and ``SPORDER`` may be integral + floats (staging's pooled form). Empty when no ACS household is + selected. A set of pairs is refused (TypeError): it cannot tie a + ``SERIALNO`` to its household. + + Returns: + A :class:`~microcosm.frame.Frame` of the CPS rows then the ACS rows, + each group table sorted by its id. Household weights are the two + inputs, each household's by its key, carried through that sort, as + :attr:`~microcosm.frame.WeightKind.IMPORTANCE` weights (a pool + assembly's starting weights, the kind staging gives its pooled + weights). ``metadata`` holds only the spine assembly record, under + ``SPINE_ASSEMBLY_MANIFEST_KEY``; the mass log is empty. The H5 + writer does not keep the record, so PR 4 writes it into the + population manifest and PR 5's loader restores it. + + Raises: + OnePopulationContractError: Naming the first clause the inputs break, + or if the joined tables fail the frame's invariants or the + assembly validator. + TypeError: If the tables are not a mapping of DataFrames, or + ``staging_lineage`` is not a mapping. + """ + + cps = _origin_tables(cps_tables, origin=_CPS) + acs = _origin_tables(acs_tables, origin=_ACS) + _require_cps_support_metadata(cps) + _require_acs_support_metadata(acs) + cps_keyed = _keyed_weights(cps_household_weights, origin=_CPS) + acs_keyed = _keyed_weights(acs_household_weights, origin=_ACS) + staging = _lineage_rows(staging_lineage) + + origins = {_CPS: _assembled_cps(cps), _ACS: _assembled_acs(acs)} + _require_spine_tags(origins) + _require_disjoint_ids(origins) + _require_unique_source_ranks(origins) + _require_acs_lineage(origins[_ACS], staging) + # After P7, which tied each ACS household's SERIALNO to staging's by + # native id, so a weight keyed by SERIALNO lands on its own household. + cps_weights = _aligned_weights( + cps_keyed, + cps["household"][US_SCHEMA.id_column("household")].tolist(), + origin=_CPS, + ) + acs_weights = _aligned_weights( + acs_keyed, _acs_weight_keys(acs["household"]), origin=_ACS + ) + + tables, household_order = _joined_tables(origins) + record = spine_assembly_manifest( + { + entity: table.loc[ + pd.to_numeric(table[support_clone_index_column(entity)]).eq(0) + ] + for entity, table in tables.items() + }, + channels=ASSEMBLED_CHANNELS, + ) + weights = np.concatenate([cps_weights, acs_weights])[household_order] + try: + frame = Frame( + tables, + US_SCHEMA, + {"household": Weights(weights, WeightKind.IMPORTANCE)}, + metadata=record, + ) + validate_assembly_provenance(frame, boundary=_BOUNDARY) + except ValueError as exc: + raise OnePopulationContractError( + f"The joined one-population frame is not valid: {exc}" + ) from exc + _require_nested_groups(origins) + return frame + + +# ------------------------------------------------------- engine variables + + +@runtime_checkable +class EngineVariableIndex(Protocol): + """What the contract asks of the engine's variable metadata, at 2024. + + The answers must cohere: the inputs at 2024 are exactly the known + columns that are neither computed at 2024 nor structural, so no input is + left out of R6's null check. The contract refuses an index whose answers + do not. + """ + + def known_variables(self, columns: Iterable[str]) -> frozenset[str]: + """The names among ``columns`` the engine defines, formulas included.""" + ... + + def computed_at_2024(self, tables: Mapping[str, pd.DataFrame]) -> frozenset[str]: + """The tables' columns the engine computes at 2024.""" + ... + + def inputs_at_2024(self, tables: Mapping[str, pd.DataFrame]) -> frozenset[str]: + """Every known, non-structural column of the tables not computed at 2024.""" + ... + + +def _present_columns(tables: Mapping[str, pd.DataFrame]) -> frozenset[str]: + return frozenset( + column + for table in tables.values() + for column in table.columns + if isinstance(column, str) + ) + + +class PolicyEngineUSVariableIndex: + """:class:`EngineVariableIndex` over the installed policyengine-us sources. + + It wraps + :class:`~microcosm.frame.adapters.policyengine_us.PolicyEngineUSVariableMetadataIndex`, + built the first time an answer is needed (it parses the installed + wheel's variable sources without importing the engine), never at + construction or import. + + - "Computed at 2024" is that index's + ``_engine_computed_columns(tables, period=2024)``, the call the release + tool's export guard makes, so the contract and the release cannot + disagree. It refuses the four compatibility aggregates at any period + and never counts a structural id or membership column. + - "Known" is ``variables()`` plus ``formula_owned_outputs``: every name + the sources define, inputs and formulas alike. + - "Input at 2024" is known, not structural and not computed at 2024. A + variable whose only formula starts after 2024 (``weeks_worked`` at + policyengine-us 2.2.1) is therefore an input here, although the + year-blind ``variables()`` leaves it out. + + Args: + metadata_index: The index to wrap. ``None`` builds the installed one + on first use. + """ + + def __init__(self, metadata_index: Any | None = None) -> None: + self._metadata_index = metadata_index + + def _index(self) -> Any: + if self._metadata_index is None: + from microcosm.frame.adapters.policyengine_us import ( + PolicyEngineUSVariableMetadataIndex, + ) + + self._metadata_index = PolicyEngineUSVariableMetadataIndex() + return self._metadata_index + + def known_variables(self, columns: Iterable[str]) -> frozenset[str]: + names = {column for column in columns if isinstance(column, str)} + index = self._index() + inputs = names.intersection(index.variables()) + formulas = names.intersection(index.formula_owned_outputs(names)) + return frozenset(inputs | formulas) + + def computed_at_2024(self, tables: Mapping[str, pd.DataFrame]) -> frozenset[str]: + return frozenset( + self._index()._engine_computed_columns(tables, period=ENGINE_PERIOD) + ) + + def inputs_at_2024(self, tables: Mapping[str, pd.DataFrame]) -> frozenset[str]: + known = self.known_variables(_present_columns(tables)) + return frozenset(known - STRUCTURAL_COLUMNS - self.computed_at_2024(tables)) + + +@dataclass(frozen=True) +class _EngineColumns: + """One frame's columns by engine class, from one coherent index answer.""" + + known: frozenset[str] + computed: frozenset[str] + inputs: frozenset[str] + + +def _engine_columns( + tables: Mapping[str, pd.DataFrame], + variable_index: EngineVariableIndex | None, +) -> _EngineColumns: + """Ask the index (the installed engine's by default) and check the answers.""" + + index = ( + variable_index if variable_index is not None else PolicyEngineUSVariableIndex() + ) + present = _present_columns(tables) + known = frozenset(index.known_variables(sorted(present))) + computed = frozenset(index.computed_at_2024(tables)) + inputs = frozenset(index.inputs_at_2024(tables)) + problems = [ + f"{label} names columns no table holds: {sorted(names - present)[:5]}" + for label, names in ( + ("known", known), + ("computed at 2024", computed), + ("input at 2024", inputs), + ) + if not names <= present + ] + if not inputs <= known: + problems.append(f"inputs not known: {sorted(inputs - known)[:5]}") + if inputs & computed: + problems.append(f"inputs also computed: {sorted(inputs & computed)[:5]}") + if inputs & STRUCTURAL_COLUMNS: + problems.append( + f"inputs include structural columns: {sorted(inputs & STRUCTURAL_COLUMNS)}" + ) + # The other direction: R6 reads only the inputs, and R10 skips every + # known column, so an input the index leaves out would be checked by + # neither (PR #1685 review, should-fix 4). + omitted = known - computed - STRUCTURAL_COLUMNS - inputs + if omitted: + problems.append( + "inputs omit known columns that are neither computed at 2024 nor " + f"structural: {sorted(omitted)[:5]}" + ) + if problems: + raise OnePopulationContractError( + "The engine variable index answers do not cohere (the inputs must be " + "exactly the known columns not computed at 2024 and not structural): " + + "; ".join(problems) + + "." + ) + return _EngineColumns(known=known, computed=computed, inputs=inputs) + + +# ----------------------------------------------------------- the contract + + +def _frame_tables(frame: Frame) -> dict[str, pd.DataFrame]: + return {entity: frame.table(entity) for entity in US_SCHEMA.entities} + + +def _origin_of_channel(channel: object) -> str | None: + if channel in _CPS_CHANNELS: + return _CPS + if channel == ACS_SUPPORT_CHANNEL: + return _ACS + return None + + +def _require_assembled_columns(tables: Mapping[str, pd.DataFrame]) -> None: + """R1, first part: every entity assembled, provenance complete, channels known.""" + + rule = "Incomplete assembled provenance" + assembled = [ + entity + for entity in US_SCHEMA.entities + if spine_source_id_column(entity) in tables[entity] + ] + if not assembled: + raise OnePopulationContractError( + f"{rule}: the frame is not assembled; no entity carries its " + "'_spine_source_id' (build it with to_assembled_provenance)." + ) + if len(assembled) != len(US_SCHEMA.entities): + unassembled = [e for e in US_SCHEMA.entities if e not in assembled] + raise OnePopulationContractError( + "Mixed assembled and unassembled provenance: " + f"{unassembled} lack their spine source id while {assembled} carry " + "it; every entity of the frame must be assembled." + ) + for entity in US_SCHEMA.entities: + table = tables[entity] + try: + require_assembled_support_provenance(table, entity=entity) + except ValueError as exc: + raise OnePopulationContractError(f"{rule}: {exc}") from exc + _, channel, clone, spine_source, _ = _provenance_columns(entity) + for column in (channel, clone, spine_source): + nulls = int(table[column].isna().sum()) + if nulls: + raise OnePopulationContractError( + f"{rule}: {column!r} has {nulls} null value(s)." + ) + unknown = _unexpected(table[channel], ASSEMBLED_CHANNELS) + if unknown: + raise OnePopulationContractError( + f"{rule}: rows must carry one of the assembled channels " + f"{list(ASSEMBLED_CHANNELS)}; {channel!r} holds {unknown[:5]}." + ) + + +def _split_origins( + tables: Mapping[str, pd.DataFrame], +) -> dict[str, dict[str, pd.DataFrame]]: + """Each entity's CPS rows (``asec``, ``puf_tax_detail``) and ACS rows.""" + + origins: dict[str, dict[str, pd.DataFrame]] = {_CPS: {}, _ACS: {}} + for entity in US_SCHEMA.entities: + table = tables[entity] + origin = table[support_channel_column(entity)].map(_origin_of_channel) + for name in (_CPS, _ACS): + origins[name][entity] = table.loc[origin.eq(name).to_numpy()] + return origins + + +def _require_assembled_cps_values(tables: Mapping[str, pd.DataFrame]) -> None: + """P5 on the frame's CPS rows: Route A's labels, spine id = source id.""" + + for entity in US_SCHEMA.entities: + table = tables[entity] + source, channel, clone, spine_source, spine = _provenance_columns(entity) + sources = _integral_ids( + table[source], refusal=f"CPS {source!r} must hold source ids" + ) + clones = _integral_ids( + table[clone], refusal=f"CPS {clone!r} must hold clone indices" + ) + spine_sources = _integral_ids( + table[spine_source], refusal=f"CPS {spine_source!r} must hold source ids" + ) + bad_clones = sorted(set(clones.tolist()) - set(_CPS_CLONE_INDICES)) + if bad_clones: + raise OnePopulationContractError( + "CPS clone indices must be 0, 1 or 2 (Route A's native rows, PUF " + f"tax-detail copies and capital-gains tail copies); {clone!r} " + f"holds {bad_clones[:5]}." + ) + native = table[channel].eq(BASE_ASEC_SUPPORT_CHANNEL).to_numpy() + disagree = int(np.count_nonzero(native != (clones == 0))) + if disagree: + raise OnePopulationContractError( + f"CPS rows must carry channel {BASE_ASEC_SUPPORT_CHANNEL!r} exactly " + f"on clone index 0; {disagree} {entity!r} row(s) disagree." + ) + differs = int(np.count_nonzero(spine_sources != sources)) + if differs: + raise OnePopulationContractError( + f"CPS rows' spine source id must equal their source id (the " + f"parent export's rows are their own spine records); {differs} " + f"{entity!r} row(s) differ in {spine_source!r}." + ) + if spine in table: + tags = table[spine] + wrong = tags.notna() & tags.ne(CPS_SPINE_TAG) + if wrong.any(): + raise OnePopulationContractError( + f"CPS rows carry a spine tag other than {CPS_SPINE_TAG!r} in " + f"{spine!r}: {sorted({repr(tag) for tag in tags[wrong]})[:5]}; " + "staging tags the donor's rows " + f"{CPS_SPINE_TAG!r}." + ) + + +def _require_assembled_acs_values(tables: Mapping[str, pd.DataFrame]) -> None: + """P5 on the frame's ACS rows: staging's labels, source id = pooled id.""" + + for entity in US_SCHEMA.entities: + table = tables[entity] + source, _, clone, spine_source, spine = _provenance_columns(entity) + id_column = US_SCHEMA.entity_id_column(entity) + ids = _integral_ids( + table[id_column], refusal=f"ACS {id_column!r} must hold ids" + ) + sources = _integral_ids( + table[source], refusal=f"ACS {source!r} must hold source ids" + ) + clones = _integral_ids( + table[clone], refusal=f"ACS {clone!r} must hold clone indices" + ) + natives = _integral_ids( + table[spine_source], refusal=f"ACS {spine_source!r} must hold source ids" + ) + bad_clones = sorted(set(clones.tolist()) - {0}) + if bad_clones: + raise OnePopulationContractError( + f"ACS rows must carry clone index 0; {clone!r} holds {bad_clones[:5]}." + ) + differs = int(np.count_nonzero(sources != ids)) + if differs: + raise OnePopulationContractError( + f"ACS rows' source id must equal their pooled id " + f"({id_column!r}), as assembly writes it; {differs} {entity!r} " + "row(s) differ." + ) + offsets = sorted(set((ids - natives).tolist())) + if len(offsets) > 1: + raise OnePopulationContractError( + f"ACS {entity!r} ids must sit one constant offset from staging's " + f"native source ids (staging shifts each entity's ids by one " + f"amount); found offsets {offsets[:5]}." + ) + if spine in table: + tags = table[spine] + wrong = tags.notna() & tags.ne(ACS_SUPPORT_CHANNEL) + if wrong.any(): + raise OnePopulationContractError( + f"ACS rows carry a spine tag other than {ACS_SUPPORT_CHANNEL!r} " + f"in {spine!r}: {sorted({repr(tag) for tag in tags[wrong]})[:5]}." + ) + + +def _require_assembly_record(frame: Frame) -> None: + """R1, last part: the clone-0 record, three channels, validated.""" + + record = frame.metadata.get(SPINE_ASSEMBLY_MANIFEST_KEY) + channels = record.get("channels") if isinstance(record, Mapping) else None + if record is not None and ( + isinstance(channels, str | bytes) + or not isinstance(channels, Iterable) + or tuple(channels) != ASSEMBLED_CHANNELS + ): + raise OnePopulationContractError( + f"Incomplete assembled provenance: the spine assembly record must " + f"declare the channels {list(ASSEMBLED_CHANNELS)}, got {channels!r}." + ) + # The validator reads each count through int(), so 24.5, "24" or 24.0 + # would pass for 24 live rows; the writer emits integers, so anything + # else is refused here first (PR #1685 review, nit 1). A malformed + # mapping is left to the validator's own message. + counts = record.get("native_row_counts") if isinstance(record, Mapping) else None + if isinstance(counts, Mapping): + coerced = sorted( + f"{entity}.{channel}={value!r}" + for entity, by_channel in counts.items() + if isinstance(by_channel, Mapping) + for channel, value in by_channel.items() + if not (_is_count(value) and value >= 0) + ) + if coerced: + raise OnePopulationContractError( + "Incomplete assembled provenance: the spine assembly record's " + "native row counts must be nonnegative integers; " + f"{coerced[:5]} are not." + ) + try: + validate_assembly_provenance(frame, boundary=_BOUNDARY) + except ValueError as exc: + raise OnePopulationContractError( + f"Incomplete assembled provenance: {exc}" + ) from exc + + +def _require_provenance( + frame: Frame, + tables: Mapping[str, pd.DataFrame], + staging: Mapping[tuple[int, int], tuple[str, int]] | None, +) -> dict[str, dict[str, pd.DataFrame]]: + """R1: the assembled form, complete; P5's value rules, Q3, P6b, P6, P7, P6c. + + Returns each origin's rows. + """ + + _require_assembled_columns(tables) + origins = _split_origins(tables) + _require_assembled_cps_values(origins[_CPS]) + _require_assembled_acs_values(origins[_ACS]) + _require_spine_tags(origins) + _require_disjoint_ids(origins) + try: + _require_unique_source_ranks(origins) + except OnePopulationContractError: + raise + except ValueError as exc: + raise OnePopulationContractError( + f"Incomplete assembled provenance: {exc}" + ) from exc + acs = origins[_ACS] + if len(acs["household"]) or len(acs[US_SCHEMA.person_entity]): + _require_acs_lineage(acs, staging) + elif staging is not None: + # No ACS row to read, but staging's lineage still has to match. + _require_staging_lineage({}, staging) + _require_assembly_record(frame) + # After the validator, so a cross-grain move reports the validator's + # reason first; nesting reads memberships P6b resolved. + _require_nested_groups(origins) + return origins + + +def _require_one_location(tables: Mapping[str, pd.DataFrame]) -> None: + """R11: no table carries a location-clone index column.""" + + marked = sorted( + f"{entity}.{column}" + for entity, table in tables.items() + for column in table.columns + if isinstance(column, str) and column.endswith(_LOCATION_CLONE_INDEX_SUFFIX) + ) + if marked: + raise OnePopulationContractError( + f"A household with more than one location: {marked[:5]} mark location " + "clones; the contract allows one location per household, so no table " + f"may carry a '*{_LOCATION_CLONE_INDEX_SUFFIX}' column." + ) + + +def _require_selected_keys( + origins: Mapping[str, Mapping[str, pd.DataFrame]], + manifest: SelectionManifest, +) -> None: + """R2: one native row per CPS key, one row per ACS household, as selected.""" + + acs_households = origins[_ACS]["household"] + try: + acs_keys = ( + [acs_unit_key(serial) for serial in acs_households[_SERIALNO]] + if len(acs_households) + else [] + ) + except (KeyError, ValueError) as exc: + raise OnePopulationContractError( + f"ACS households need a SERIALNO key: {exc}" + ) from exc + counts = pd.Series(acs_keys, dtype=object).value_counts() + repeated = sorted(counts.index[counts.gt(1)].tolist()) + if repeated: + raise OnePopulationContractError( + f"An ACS household with more than one row: {repeated[:5]} repeat." + ) + if (len(acs_keys), keys_sha256(acs_keys)) != ( + manifest.n_acs, + manifest.selected_acs_keys_sha256, + ): + raise OnePopulationContractError( + "ACS keys do not match the selection manifest: the frame holds " + f"{len(acs_keys)} ACS household key(s) with digest " + f"{keys_sha256(acs_keys)}; the manifest selected {manifest.n_acs} with " + f"digest {manifest.selected_acs_keys_sha256}." + ) + + cps = origins[_CPS] + if len(cps[US_SCHEMA.person_entity]): + try: + units = cps_unit_ids(cps[US_SCHEMA.person_entity]) + except OnePopulationContractError as exc: + raise OnePopulationContractError( + f"A CPS key without exactly one native row: {exc}" + ) from exc + else: + units = pd.DataFrame( + {"income_year": [], "unit_id": [], "key": []}, + index=pd.Index([], dtype=np.int64, name="household_id"), + ) + # Ids and clone indices through the integral parser R1 applies, so a + # representation R1 accepts (digit strings, integral floats; lead call + # L5) joins cps_unit_ids' int64 household index (PR #1685 review, + # should-fix 3). + household = cps["household"] + household_ids = _integral_ids( + household[US_SCHEMA.id_column("household")], + refusal="CPS 'household_id' must hold ids", + ) + clone_column = support_clone_index_column("household") + clones = _integral_ids( + household[clone_column], + refusal=f"CPS {clone_column!r} must hold clone indices", + ) + clone = pd.Series(clones, index=pd.Index(household_ids)).reindex(units.index) + native = units.loc[clone.eq(0).to_numpy()] + counts = native["key"].value_counts() + repeated = sorted(counts.index[counts.gt(1)].tolist()) + if repeated: + raise OnePopulationContractError( + "A CPS key without exactly one native row: " + f"{len(repeated)} key(s) have more than one clone-0 household, such " + f"as {repeated[:3]}." + ) + orphaned = sorted(set(units["key"]) - set(native["key"])) + if orphaned: + raise OnePopulationContractError( + "A CPS key without exactly one native row: " + f"{len(orphaned)} clone household key(s) have no clone-0 household, " + f"such as {orphaned[:3]}." + ) + by_year = tuple( + (int(year), int(n)) + for year, n in native["income_year"].value_counts().sort_index().items() + ) + observed = (len(native), by_year, keys_sha256(native["key"])) + expected = ( + manifest.n_cps, + manifest.n_cps_by_income_year, + manifest.cps_keys_sha256, + ) + if observed != expected: + raise OnePopulationContractError( + "CPS keys do not match the selection manifest: the frame's clone-0 " + f"households give (count, by income year, digest) {observed}; the " + f"manifest selected {expected}." + ) + + +def _require_congressional_districts(household: pd.DataFrame) -> None: + """R12: a positive, integral CD with its state's prefix on every household.""" + + rule = "A household without a congressional district" + cd_column = "congressional_district_geoid" + missing = [c for c in (cd_column, "state_fips") if c not in household] + if missing: + raise OnePopulationContractError( + f"{rule}: the household table lacks {missing}." + ) + cd = _integral_ids( + household[cd_column], + refusal=f"{rule}: {cd_column!r} must be an integral geoid on every household", + ) + states = _integral_ids( + household["state_fips"], + refusal=f"{rule}: 'state_fips' must be integral on every household", + ) + if (cd <= 0).any(): + raise OnePopulationContractError( + f"{rule}: {int((cd <= 0).sum())} household(s) hold a non-positive " + f"{cd_column!r}." + ) + wrong = (cd // 100) != states + if wrong.any(): + raise OnePopulationContractError( + f"{rule}: {int(wrong.sum())} household(s) hold a {cd_column!r} whose " + "state prefix (geoid // 100) differs from state_fips, such as " + f"{cd[wrong][:3].tolist()}." + ) + + +def _require_acs_household_type(acs_household: pd.DataFrame) -> None: + """T1: ``TYPEHUGQ`` 1, 2 or 3 on every ACS household. + + TODO(#1610): once #1610 lands, add its wider rules: every CPS household + carries a valid ``HRHTYPE`` once any does, no household carries both + codes, and every person carries valid ``A_EXPRRP``, ``A_MARITL``, ``age`` + and ``is_female``. + """ + + if not len(acs_household): + return + rule = ( + f"{_TYPEHUGQ} must be 1, 2 or 3 on every ACS household (#1610's " + "household materializer reads it to leave group quarters out)" + ) + if _TYPEHUGQ not in acs_household: + raise OnePopulationContractError(f"{rule}; the household table lacks it.") + values = acs_household[_TYPEHUGQ] + bad = ~values.map( + lambda value: _is_real_number(value) and value in _ACS_HOUSEHOLD_TYPES + ).astype(bool) + if bad.any(): + raise OnePopulationContractError( + f"{rule}; {int(bad.sum())} ACS household(s) hold " + f"{values[bad].head(5).tolist()!r}." + ) + + +def _require_esi_premium(frame: Frame) -> None: + """R4: the ESI employer premium present on persons and never null.""" + + if US_ESI_EMPLOYER_PREMIUM_COLUMN not in frame.table(US_SCHEMA.person_entity): + raise OnePopulationContractError( + f"A null ESI premium: the person table lacks " + f"{US_ESI_EMPLOYER_PREMIUM_COLUMN!r}, so every person's premium is " + "missing (the release's ESI signal gate fails without it)." + ) + try: + refuse_unassigned_us_esi_premiums(frame, consumer=_CONSUMER) + except SourceRuntimeError as exc: + raise OnePopulationContractError(f"A null ESI premium: {exc}") from exc + + +def _require_classified_adults(frame: Frame) -> None: + """R5: every SPM unit has a classified adult (FAIL and errors refuse).""" + + rule = "An SPM unit has no classified adult" + try: + result = check_spm_composition(frame) + except ValueError as exc: + raise OnePopulationContractError( + f"{rule}: the composition check cannot run: {exc}" + ) from exc + if result.status != "PASS": + failures = "; ".join(str(failure) for failure in result.failures) + raise OnePopulationContractError(f"{rule}: {result.summary}. {failures}") + + +def _null_counts( + tables: Mapping[str, pd.DataFrame], columns: Collection[str] +) -> dict[str, int]: + return { + f"{entity}.{column}": int(table[column].isna().sum()) + for entity, table in tables.items() + for column in sorted(set(columns).intersection(table.columns)) + if table[column].isna().any() + } + + +def _refused_nulls(values: pd.Series) -> tuple[int, list[object]]: + """The nulls R6 refuses in a release-written column: ``pd.NA`` and the rest. + + Returns how many values are ``pd.NA`` and the other refused nulls. Only + None and a float NaN (a Python float or a numpy floating value) pass, so + a numpy float column, whose only null is NaN, passes by its dtype before + any value is read. A nullable ``Float32``/``Float64`` column's masked + null is ``pd.NA``; a NaN it holds unmasked is not a null to pandas. + """ + + if isinstance(values.dtype, np.dtype) and values.dtype.kind == "f": + return 0, [] + pd_na, others = 0, [] + for value in values[values.isna()].tolist(): + if value is None or ( + isinstance(value, float | np.floating) and math.isnan(value) + ): + continue + if value is pd.NA: + pd_na += 1 + else: + others.append(value) + return pd_na, others + + +def _require_filled_inputs( + tables: Mapping[str, pd.DataFrame], inputs: frozenset[str] +) -> None: + """R6: no null in an engine input at 2024, outside the release-written list. + + A release-written column may be null only as None or a float NaN (a + Python float or a numpy floating value, so any null of a numpy float + column); every other value pandas counts as null refuses, on any row of + either origin. ``pd.NA`` (a pandas nullable dtype's null) refuses with + its own message: policyengine-core 3.32.5 loads a boolean None as False + and a NaN as True but cannot cast a ``pd.NA``, and the release's first + engine pass, the SSI December pass, loads twelve of these columns before + their producers write them (PR #1685 review, blocking 1). ``pd.NaT``, + numpy's ``NaT`` and any other null refuse too, fail closed: nothing here + traces how the release loads them (review r2, nit 1). The rule covers + all of :data:`RELEASE_WRITTEN_INPUTS` present: the other six columns' + producers (``scf_wealth``, ``ssi_disability_criteria``, + ``sipp_head_start``) run before that pass and read each value through + ``pd.to_numeric(...).to_numpy(dtype=np.float64)``, so a ``pd.NA`` + there is probably rewritten like a NaN, and the refusal is stricter + than those stages need. + """ + + gaps = _null_counts(tables, inputs - set(RELEASE_WRITTEN_INPUTS)) + if gaps: + raise OnePopulationContractError( + f"A null in an engine input at 2024: {gaps} (null rows per column). " + "Prepare must fill every engine input on every row; only the " + "always-on producers' outputs in RELEASE_WRITTEN_INPUTS may be left " + "null." + ) + refused = { + f"{entity}.{column}": _refused_nulls(table[column]) + for entity, table in tables.items() + for column in sorted(set(RELEASE_WRITTEN_INPUTS).intersection(table.columns)) + } + pd_na = {name: rows for name, (rows, _) in refused.items() if rows} + if pd_na: + raise OnePopulationContractError( + f"A pd.NA in a release-written input: {pd_na} (pd.NA rows per column). " + "A column in RELEASE_WRITTEN_INPUTS may be null only as None or NaN; " + "the release's first engine pass loads twelve of them before their " + "producers write them, and policyengine-core cannot cast a pd.NA." + ) + others = {name: values for name, (_, values) in refused.items() if values} + if others: + counts = {name: len(values) for name, values in others.items()} + examples = [values[0] for values in others.values()][:3] + raise OnePopulationContractError( + f"A null other than None or NaN in a release-written input: {counts} " + f"(rows per column), such as {examples!r}. A column in " + "RELEASE_WRITTEN_INPUTS may be null only as None or a float NaN; " + "pd.NaT, numpy's NaT and any other null refuse." + ) + + +def _require_tail_columns(tax_unit: pd.DataFrame) -> None: + """R7: the six PUF tail provenance columns on every tax unit.""" + + rule = "A null PUF tail column on a tax unit" + missing = [c for c in PUF_TAIL_TAX_UNIT_COLUMNS if c not in tax_unit] + if missing: + raise OnePopulationContractError(f"{rule}: the tax-unit table lacks {missing}.") + gaps = _null_counts({"tax_unit": tax_unit}, PUF_TAIL_TAX_UNIT_COLUMNS) + if gaps: + raise OnePopulationContractError(f"{rule}: {gaps} (null rows per column).") + + +def _tail_donor_set(parent_tail_donor_ids: object) -> frozenset[int]: + if isinstance(parent_tail_donor_ids, str | bytes | Mapping) or not isinstance( + parent_tail_donor_ids, Collection + ): + raise TypeError( + "parent_tail_donor_ids must be a set of int donor ids, got " + f"{type(parent_tail_donor_ids).__name__}." + ) + # Through the shared predicate, which refuses a numpy timedelta64 that + # numbers.Integral accepts (PR #1685 review r3, should-fix 2). + if not all(_is_integer(value) for value in parent_tail_donor_ids): + raise TypeError("parent_tail_donor_ids must hold int donor ids only.") + return frozenset(int(value) for value in parent_tail_donor_ids) + + +def _require_parent_tail_donors(tax_unit: pd.DataFrame, parent: frozenset[int]) -> None: + """R8: the applied tail donor ids equal the parent's, each applied once, + and no ACS tax unit applies one.""" + + rule = "The tail donor set differs from the parent's" + applied_values = tax_unit[PUF_CAPITAL_GAINS_TAIL_APPLIED_COLUMN] + is_flag = applied_values.map( + lambda value: ( + isinstance(value, bool | np.bool_) + or (_is_real_number(value) and value in (0, 1)) + ) + ).astype(bool) + if not is_flag.all(): + raise OnePopulationContractError( + f"{rule}: {PUF_CAPITAL_GAINS_TAIL_APPLIED_COLUMN!r} holds non-flag " + f"values {applied_values[~is_flag].head(3).tolist()!r}." + ) + applied = applied_values.astype(bool).to_numpy() + acs_applied = applied & ( + tax_unit[support_channel_column("tax_unit")].eq(ACS_SUPPORT_CHANNEL).to_numpy() + ) + if acs_applied.any(): + raise OnePopulationContractError( + f"{rule}: {int(acs_applied.sum())} ACS tax unit(s) apply a tail " + "donor; the parent's tail draws apply only to CPS recipients, so " + f"every ACS tax unit holds {PUF_CAPITAL_GAINS_TAIL_APPLIED_COLUMN!r} " + "False (d2283 lead call L4)." + ) + donors = _integral_ids( + tax_unit.loc[applied, PUF_CAPITAL_GAINS_TAIL_DONOR_SOURCE_ID_COLUMN], + refusal=f"{rule}: applied donor ids must be integers", + ) + repeated = pd.Series(donors).duplicated(keep=False).to_numpy() + if repeated.any(): + raise OnePopulationContractError( + f"{rule}: donor id(s) {sorted(set(donors[repeated].tolist()))[:5]} are " + "applied on more than one tax unit; each parent donor applies to one " + "tax unit (the one-to-one rule " + "assert_puf_capital_gains_tail_survives_selection keeps)." + ) + found = frozenset(int(value) for value in donors.tolist()) + if found != parent: + missing = sorted(parent - found) + extra = sorted(found - parent) + raise OnePopulationContractError( + f"{rule}: {len(missing)} parent donor(s) missing (such as " + f"{missing[:3]}) and {len(extra)} donor(s) the parent never applied " + f"(such as {extra[:3]}). The comparison is of donor ids only, never " + "weights." + ) + + +def _declarations(declared_absences: object, *, name: str) -> Mapping[str, str]: + """The owner's declarations, checked; ``name`` is the caller's argument.""" + + if declared_absences is None: + return {} + if not isinstance(declared_absences, Mapping): + raise TypeError( + f"{name} must map each column to its owner's decision, got " + f"{type(declared_absences).__name__}." + ) + for column, decision in declared_absences.items(): + if not isinstance(column, str) or not isinstance(decision, str): + raise TypeError( + f"{name} must map str columns to str decisions, got " + f"{column!r}: {decision!r}." + ) + if not decision.strip(): + raise OnePopulationContractError( + f"A declared absence needs its owner's decision; {column!r} has none." + ) + return declared_absences + + +def _origin_gap( + null: np.ndarray, rows: np.ndarray, other_rows: np.ndarray +) -> np.ndarray | None: + """The rows of one origin a column lacks, when they make a gap. + + The one gap predicate R10 and :func:`absences` share (d2283 lead call + L2): a column is a gap of an origin when it is null on some row of that + origin (``rows``) while some row of the other origin (``other_rows``) + holds a value. Returns the origin's null rows, or ``None`` when there is + no gap: no null on the origin's rows, or no value on the other origin's. + """ + + lacking = null & rows + if not lacking.any() or not (~null & other_rows).any(): + return None + return lacking + + +def _origin_rows(channels: Mapping[str, np.ndarray], origin: str) -> np.ndarray: + """The rows of ``origin``, from one mask per assembled channel.""" + + return np.logical_or.reduce([channels[name] for name in _ORIGIN_CHANNELS[origin]]) + + +def _require_declared_absences( + tables: Mapping[str, pd.DataFrame], + engine: _EngineColumns, + register: Mapping[str, str], + declared: Mapping[str, str], +) -> None: + """R10: a register column ACS rows lack while CPS rows hold it is declared. + + Engine inputs at 2024 are R6's (it refuses any null), so this covers + model-named columns no engine variable names: register entries. It uses + :func:`absences`' gap predicate (:func:`_origin_gap`): null on some ACS + row while some CPS row holds a value. So one declaration answers both + checks, and a column partly null on CPS rows still needs one. A column + null on every row of both origins is no gap. What still differs: + :func:`absences` also reads the reverse direction (CPS rows lacking a + column ACS rows hold) and every model-named column, where this check + reads register entries in the CPS-to-ACS direction only. A declaration + this check does not use is ignored, as :func:`absences` records it. + """ + + from microcosm.data.stored_inputs import is_model_named + + gaps: dict[str, str] = {} + for entity in US_SCHEMA.entities: + table = tables[entity] + channels = _channel_masks( + table, entity, rule="A register column check needs every row's origin" + ) + cps_rows, acs_rows = _origin_rows(channels, _CPS), _origin_rows(channels, _ACS) + for column in table.columns: + if ( + not isinstance(column, str) + or not is_model_named(column) + or column in engine.known + or column not in register + or column in RELEASE_WRITTEN_INPUTS + or column in declared + ): + continue + lacking = _origin_gap(table[column].isna().to_numpy(), acs_rows, cps_rows) + if lacking is not None: + gaps[f"{entity}.{column}"] = ( + f"{int(lacking.sum())} of {int(acs_rows.sum())} ACS rows" + ) + if gaps: + raise OnePopulationContractError( + "A model-named column held on some CPS row is null on ACS rows " + f"without a declared absence: {gaps}. Fill it on ACS rows, or declare " + "it in the absences file with its owner's decision." + ) + + +def require_one_population( + frame: Frame, + manifest: SelectionManifest, + *, + parent_tail_donor_ids: frozenset[int], + declared_absences: Mapping[str, str] | None = None, + staging_lineage: Mapping[tuple[int, int], tuple[str, int]] | None = None, + variable_index: EngineVariableIndex | None = None, + register: Mapping[str, str] | None = None, +) -> None: + """Refuse a joined frame that breaks any clause of the contract. + + The clauses run in a fixed order, so a corrupted cell refuses for its own + reason, and each message names its clause's rule. An input that breaks + two clauses reports the earlier one. Two such inputs are expected: a + real location clone + (:func:`~microcosm.build.us_runtime.block_location.clone_frame_for_location`) + remaps every pooled id and keeps the provenance ids, so it refuses at + R1 (P5's ACS source id = pooled id) before R11 reads its + ``*_location_clone_index`` columns, and R11 itself reports a marker on a + frame R1 accepts; and a ``SERIALNO`` repeated across ACS households + refuses at R1 (P7) before R2's repeated-key branch, which stays as a + guard: no input reaches it through this function, since ``acs_unit_key`` + is one-to-one on the serial numbers P7 accepts (PR #1685 review, nit 2). + + - R1, incomplete assembled provenance: every entity assembled (none + mixed), complete source id, channel, clone index and spine source id, + only the three assembled channels; P5's value rules per origin (CPS: + clone index 0, 1 or 2, ``asec`` exactly on clone 0, spine source id = + source id, tag ``asec_puf``; ACS: clone index 0, source id = pooled id, + one id offset from the native id, tag ``acs_2024_1yr``); a non-null + spine tag on every row; P6b (ids and memberships within an origin); P6 + (no repeated (source id, rank)); P7 (the ACS rows' ``SERIALNO`` and + ``SPORDER`` lineage, no null among its values, and, when + ``staging_lineage`` is given, each person's pair equal to staging's + under its native (household id, person id); on a frame with no ACS + row it must then be empty); the clone-0 spine assembly record + declaring the three channels, with nonnegative integer counts (the + validator would truncate 24.5 to 24), checked by + :func:`~microcosm.build.us_runtime.support_provenance.validate_assembly_provenance`; + and P6c, after it (every group unit inside one household, and each + ACS household one SPM unit). + - R11, more than one location: no table carries a + ``*_location_clone_index`` column. Location cloning is the only + multi-location mechanism, and geography columns are household-level. + - R2, one native row per CPS key and one row per ACS household: ACS + households' :func:`~microcosm.build.us_runtime.one_population_selection.acs_unit_key` + keys unique; each CPS key (:func:`cps_unit_ids`) on exactly one clone-0 + household, clones only beside it; both key sets equal to ``manifest``'s + by count, by income year (CPS) and + :func:`~microcosm.build.us_runtime.one_population_selection.keys_sha256`. + - R12, a congressional district on every household: non-null, positive, + integral ``congressional_district_geoid`` whose state prefix + (geoid // 100) is the household's ``state_fips``, as staging checks + donor districts. The release's CD-vintage preflight needs only one + positive district (``_assert_cd_vintage_support_matches``, called at + tools/build_us_fiscal_refresh_release.py:15502-15506, its check at + :3822-3826), and its + every-household rule (``_integer_geography_codes``) runs only when CD + targets are materialized, which Route A's national surface drops. The + clause keeps every household's district for a future CD surface and + for the local lane, which reads the same H5. + - T1: ``TYPEHUGQ`` 1, 2 or 3 on every ACS household (see + :func:`_require_acs_household_type` for #1610's wider rules). + - R3: no column the engine computes at 2024 (the release's export guard, + ``computed_at(2024)``, not the lane's year-blind rule). + - R9: no stored lower-case column that is neither an engine variable + (inputs and formulas alike) nor a key of ``register``. + - R4: the ESI employer premium on the person table, never null + (:func:`~microcosm.build.us_runtime.esi_premiums.refuse_unassigned_us_esi_premiums`). + - R5: a classified adult in every SPM unit + (:func:`~microcosm.build.us_runtime.spm_composition.check_spm_composition` + returning FAIL, or unable to run, refuses). + - R6: no null in an engine input at 2024 (known, not structural, not + computed at 2024, so a variable whose only formula starts after 2024 + counts) on any row, except :data:`RELEASE_WRITTEN_INPUTS`, which may + be null only as None or a float NaN, never ``pd.NA``, ``pd.NaT``, + numpy's ``NaT`` or any other null. + - R7: the six :data:`PUF_TAIL_TAX_UNIT_COLUMNS` on every tax unit, never + null. + - R8: the ids of the tail donors applied on the frame's tax units equal + ``parent_tail_donor_ids`` as a set, and no donor is applied on two tax + units (the one-to-one rule of + ``assert_puf_capital_gains_tail_survives_selection``). No weight is + compared, so that function (whose weight check fires on the child's + new starting weights) is not used. No ACS tax unit applies a donor + (the parent's tail draws apply only to CPS recipients; d2283 lead + call L4); which CPS tax units carry the applied flags is not checked. + - R10: a model-named register column (no engine variable; R6 owns + engine inputs) null on some ACS row while some CPS row of its entity + holds a value, unless ``declared_absences`` names it: the gap + predicate :func:`absences` uses (d2283 lead call L2), so one + declaration answers both. The release-written list is the only + exemption, never a stage's declared outputs whole. A declaration R10 + does not use is ignored, so the same mapping passes :func:`absences`, + which records it as unused or needless. :func:`absences` also reads + the reverse direction and every model-named column, so it refuses + some frames R10 passes. + + Args: + frame: The joined frame, built by :func:`to_assembled_provenance`. + manifest: PR 1's selection manifest for the same selection. + parent_tail_donor_ids: The parent export's applied capital-gains tail + donor ids (PR 4 reads them from the export's tax-unit columns). + declared_absences: Column to the owner's decision, for each register + column ACS rows lack by decision: the mapping :func:`absences` + takes as ``declared``. + staging_lineage: Staging's lineage for the selected ACS persons, in + :func:`to_assembled_provenance`'s keyed form (native household + and person id to (``SERIALNO``, ``SPORDER``)); ``None`` checks + the lineage's form only. + variable_index: The engine's variable classes at 2024. ``None`` uses + :class:`PolicyEngineUSVariableIndex`, built at call time. + register: The stored non-variable register. ``None`` uses + ``microcosm.data.stored_inputs.US_STORED_NON_VARIABLE_COLUMNS``, + imported at call time. + + Raises: + OnePopulationContractError: Naming the first clause the frame breaks. + TypeError: If an argument has the wrong type. + """ + + if not isinstance(frame, Frame): + raise TypeError(f"frame must be a Frame, got {type(frame).__name__}.") + if frame.schema != US_SCHEMA: + raise OnePopulationContractError( + "Incomplete assembled provenance: the frame must use the US schema." + ) + if not isinstance(manifest, SelectionManifest): + raise TypeError( + f"manifest must be a SelectionManifest, got {type(manifest).__name__}." + ) + parent_donors = _tail_donor_set(parent_tail_donor_ids) + declared = _declarations(declared_absences, name="declared_absences") + staging = None if staging_lineage is None else _lineage_rows(staging_lineage) + if register is None: + from microcosm.data.stored_inputs import US_STORED_NON_VARIABLE_COLUMNS + + register = US_STORED_NON_VARIABLE_COLUMNS + + tables = _frame_tables(frame) + origins = _require_provenance(frame, tables, staging) # R1 (P5-P7, P6b) + _require_one_location(tables) # R11 + _require_selected_keys(origins, manifest) # R2 + _require_congressional_districts(tables["household"]) # R12 + _require_acs_household_type(origins[_ACS]["household"]) # T1 + + engine = _engine_columns(tables, variable_index) + if engine.computed: # R3 + raise OnePopulationContractError( + "A column the engine computes at 2024 is stored: " + f"{sorted(engine.computed)}; the engine would overwrite it, so the " + "export must not carry it." + ) + from microcosm.data.stored_inputs import undefined_stored_inputs + + undefined = undefined_stored_inputs( # R9 + _present_columns(tables), + engine_variables=engine.known, + register=register, + ) + if undefined: + raise OnePopulationContractError( + "A stored lower-case column is neither an engine variable nor " + f"registered: {list(undefined)}; the engine would ignore it." + ) + _require_esi_premium(frame) # R4 + _require_classified_adults(frame) # R5 + _require_filled_inputs(tables, engine.inputs) # R6 + _require_tail_columns(tables["tax_unit"]) # R7 + _require_parent_tail_donors(tables["tax_unit"], parent_donors) # R8 + _require_declared_absences(tables, engine, register, declared) # R10 + + +# ------------------------------------------------------- the role record + + +def _plain(value: Any) -> Any: + """``value`` as plain JSON builtins (frame metadata and the files hold these).""" + + if isinstance(value, Mapping): + return {str(key): _plain(item) for key, item in value.items()} + if isinstance(value, list | tuple): + return [_plain(item) for item in value] + if isinstance(value, np.ndarray): + return [_plain(item) for item in value.tolist()] + if isinstance(value, np.generic): + return value.item() + return value + + +def _channel_masks( + table: pd.DataFrame, entity: str, *, rule: str +) -> dict[str, np.ndarray]: + """One row mask per assembled channel, or a refusal naming ``rule``.""" + + column = support_channel_column(entity) + if column not in table: + raise OnePopulationContractError( + f"{rule}: the {entity!r} table lacks {column!r}, so its rows have no " + "origin." + ) + channel = table[column] + unknown = _unexpected(channel, ASSEMBLED_CHANNELS) + if unknown or channel.isna().any(): + raise OnePopulationContractError( + f"{rule}: {column!r} must hold one of {list(ASSEMBLED_CHANNELS)} on " + f"every row; it holds {(unknown or ['null'])[:5]}." + ) + return {name: channel.eq(name).to_numpy() for name in ASSEMBLED_CHANNELS} + + +def _is_count(value: object) -> bool: + # The shared predicate refuses a boolean and a numpy timedelta64, which + # numbers.Integral accepts (PR #1685 review r3, should-fix 2). + return _is_integer(value) + + +def _role_counts( + person: pd.DataFrame, spm_units: int, role: pd.Series +) -> dict[str, object]: + """The role gate's counts and digest over ``person`` (its own expressions).""" + + return { + "persons_joined": len(person), + "table_rows": len(person), + "native_spm_units": int(spm_units), + "true_role_persons": int(role.dropna().sum()), + _ROLE_GATE_DIGEST_KEY: _role_binding_sha256(person), + } + + +def _require_cps_role_record( + cps_record: Mapping[str, Any], recount: Mapping[str, object] +) -> None: + """The CPS role record states the gate's counts and digest of the CPS rows.""" + + rule = "The CPS role record does not match the frame's CPS rows" + keys = (*_ROLE_GATE_COUNT_KEYS, _ROLE_GATE_DIGEST_KEY) + missing = [key for key in keys if key not in cps_record] + if missing: + raise OnePopulationContractError( + f"{rule}: it lacks the role gate's keys {missing} (PR 4 re-derives it " + "with with_us_spm_independence_role on exactly those rows)." + ) + malformed = [key for key in _ROLE_GATE_COUNT_KEYS if not _is_count(cps_record[key])] + if not isinstance(cps_record[_ROLE_GATE_DIGEST_KEY], str): + malformed.append(_ROLE_GATE_DIGEST_KEY) + if malformed: + raise OnePopulationContractError( + f"{rule}: {malformed} must be integer counts and a hex digest." + ) + differs = { + key: {"record": _plain(cps_record[key]), "frame": recount[key]} + for key in keys + if cps_record[key] != recount[key] + } + if differs: + raise OnePopulationContractError( + f"{rule}: {differs}. The record must be derived on the CPS rows in " + "the joined frame's order and dtypes (the digest hashes the ordered " + "person id, SPM unit membership, age and role)." + ) + + +def _require_staging_receipt( + staging_receipt: Mapping[str, Any], acs_counts: Mapping[str, int] +) -> None: + """Staging's ACS role receipt: its keys, its rule, and counts that cover.""" + + missing = sorted(_ACS_ROLE_RECEIPT_KEYS - set(staging_receipt)) + if missing: + raise OnePopulationContractError( + f"Staging's ACS role receipt lacks keys {missing} " + "(acs_inputs.with_acs_spm_independence_role writes them)." + ) + wrong = { + key: _plain(staging_receipt[key]) + for key, expected in _ACS_ROLE_RECEIPT_IDENTITY.items() + if _plain(staging_receipt[key]) != expected + } + if wrong: + raise OnePopulationContractError( + "Staging's ACS role receipt is not the ACS RELSHIPP role rule's: " + f"{wrong} differ from {dict(_ACS_ROLE_RECEIPT_IDENTITY)}." + ) + short = {} + for receipt_key, frame_key in _ACS_ROLE_RECEIPT_COVERAGE: + value = staging_receipt[receipt_key] + if not _is_count(value) or value < acs_counts[frame_key]: + short[receipt_key] = { + "receipt": _plain(value), + "selected": acs_counts[frame_key], + } + if short: + raise OnePopulationContractError( + "Staging's ACS role receipt covers fewer rows than the frame's ACS " + f"rows: {short}. The receipt counts every staged ACS person, so each " + "count must be an integer at least the selected one." + ) + + +def _require_acs_roles_by_rule( + person: pd.DataFrame, acs_rows: np.ndarray, role: pd.Series +) -> None: + """Each ACS person's stored role is staging's ``RELSHIPP`` rule's, row by row. + + Staging's receipt states counts over every staged person, which two + persons trading roles keep, so the receipt alone cannot tie a role to a + person. Re-deriving each selected person's role from the ``RELSHIPP`` + staging kept on the row can (PR #1685 review, should-fix 1). + """ + + if not acs_rows.any(): + return + rule = "The ACS persons' SPM roles are not staging's RELSHIPP rule's" + if _RELSHIPP not in person: + raise OnePopulationContractError( + f"{rule}: the person table lacks {_RELSHIPP!r}, which the rule reads " + "(prepare keeps staging's raw column on ACS rows)." + ) + relshipp = person.loc[acs_rows, _RELSHIPP] + # Before the conversion below, which reads 20+1j as code 20 and a + # timedelta64 of 20 units as 20 (PR #1685 review r2, should-fix 1), and + # an Arrow dictionary of durations as their counts (review r3, + # should-fix 1). + found = _complex_or_temporal(relshipp) + if found is not None: + raise OnePopulationContractError( + f"{rule}: {_RELSHIPP} on ACS rows holds {found}, not integer codes; " + f"{_READ_AS_NUMBERS}" + ) + codes = pd.to_numeric(relshipp, errors="coerce").to_numpy( + dtype=np.float64, na_value=np.nan + ) + off_domain = ~np.isin(codes, sorted(_ACS_RELSHIPP_CODES)) + if off_domain.any(): + raise OnePopulationContractError( + f"{rule}: {int(off_domain.sum())} ACS person(s) hold a blank or " + f"off-domain {_RELSHIPP} (the rule reads the codes 20 to 38)." + ) + derived = np.isin(codes, sorted(_ACS_ROLE_RELSHIPP)) + wrong = derived != role[acs_rows].to_numpy(dtype=bool) + if wrong.any(): + raise OnePopulationContractError( + f"{rule}: {int(wrong.sum())} of {int(acs_rows.sum())} ACS person(s) " + f"hold a role their {_RELSHIPP} does not give ({_ACS_SPM_ROLE_RULE}). " + "Staging's receipt states counts only, so it cannot vouch for which " + "persons hold the role." + ) + + +def combined_spm_role_record( + cps_record: Mapping[str, Any], + staging_receipt: Mapping[str, Any], + frame: Frame, +) -> dict[str, object]: + """The SPM independence role record for the joined frame (F-17, K-6; Q6). + + The parent's release keeps no role record, so each origin brings its own + evidence and the record recounts the frame: + + - ``cps_record`` is a record over exactly the frame's CPS rows (channels + ``asec`` and ``puf_tax_detail``), which the prepare step derives with + ``with_us_spm_independence_role`` from the raw ASEC inputs. Its counts + and ``person_role_binding_sha256`` must equal a recount of those rows + by the gate's rule (the digest is the gate's own + ``_role_binding_sha256``, over the rows in the frame's order and + dtypes). + - ``staging_receipt`` is staging's ACS role receipt + (``acs_inputs.with_acs_spm_independence_role``, :478-511). It counts + every staged ACS person, not the selection, so it is checked for its + keys, for the RELSHIPP rule's identity (column, entity, source column, + the ACS rule and its partition, the ASEC and adult rules, provenance) + and for counts at least the selected ACS rows', never for equality. + Counts cannot tie a role to a person, so each ACS person's role must + also be the one its ``RELSHIPP`` gives under the receipt's rule (a + code from 20 to 38 on every ACS person; the role holders 20, 21, 23, + 37 and 38). + - The frame's role must come from its source column (``role_source == + "source_column"`` under + :func:`~microcosm.build.us_runtime.spm_composition.spm_independence_role`), + non-null and boolean on every person. + + The result holds the gate's keys + (:func:`~microcosm.build.us_runtime.spm_independence_role.us_spm_independence_role_signal_gate`) + recounted over the whole frame, the role source, the counts per support + channel and per origin (with each origin's digest), and both inputs as + plain builtins under ``evidence``. The gate still grades the bands and + the classified-adult rule; this function records, it does not grade. + The H5 writer does not keep frame metadata, so PR 4 writes the record + into the population manifest and PR 5's loader restores it; the loader + must also recompute it after the H5 round trip, since a dtype change + moves the digest. + + Args: + cps_record: The CPS rows' role record in the gate's keys. + staging_receipt: Staging's ACS role receipt. + frame: The joined frame, built by :func:`to_assembled_provenance`. + + Returns: + The record, to store under the frame metadata key + ``spm_independence_role``. + + Raises: + OnePopulationContractError: If the frame's role is not its source + column's, either origin's evidence disagrees with the frame, or + an ACS person's role is not the one its ``RELSHIPP`` gives. + TypeError: If an argument has the wrong type. + """ + + if not isinstance(frame, Frame): + raise TypeError(f"frame must be a Frame, got {type(frame).__name__}.") + for name, value in ( + ("cps_record", cps_record), + ("staging_receipt", staging_receipt), + ): + if not isinstance(value, Mapping): + raise TypeError(f"{name} must be a mapping, got {type(value).__name__}.") + if frame.schema != US_SCHEMA: + raise OnePopulationContractError( + "The SPM role record needs a frame in the US schema." + ) + person = frame.table(US_SCHEMA.person_entity) + spm_unit = frame.table("spm_unit") + _, role_source, _ = spm_independence_role(person) + if role_source != _ROLE_SOURCE_COLUMN: + raise OnePopulationContractError( + f"The SPM role must come from the source column (role_source " + f"{_ROLE_SOURCE_COLUMN!r}); the frame's role source is " + f"{role_source!r}: the person table lacks {NATIVE_SPM_ROLE!r}." + ) + if "age" not in person: + raise OnePopulationContractError( + "The SPM role record needs 'age' on the person table (the role " + "digest binds it)." + ) + role = person[NATIVE_SPM_ROLE] + if role.isna().any() or pd.api.types.infer_dtype(role, skipna=False) != "boolean": + raise OnePopulationContractError( + f"The SPM role record needs a non-null boolean {NATIVE_SPM_ROLE!r} on " + f"every person; {int(role.isna().sum())} null(s), inferred type " + f"{pd.api.types.infer_dtype(role, skipna=False)!r}." + ) + rule = "The SPM role record needs every row's origin" + persons = _channel_masks(person, US_SCHEMA.person_entity, rule=rule) + units = _channel_masks(spm_unit, "spm_unit", rule=rule) + + by_channel = { + channel: { + "persons": int(persons[channel].sum()), + "spm_units": int(units[channel].sum()), + "true_role_persons": int(role[persons[channel]].sum()), + } + for channel in ASSEMBLED_CHANNELS + } + origins: dict[str, dict[str, object]] = {} + for origin, channels in ((_CPS, _CPS_CHANNELS), (_ACS, (ACS_SUPPORT_CHANNEL,))): + rows = np.logical_or.reduce([persons[channel] for channel in channels]) + counts = _role_counts( + person.loc[rows], + sum(by_channel[channel]["spm_units"] for channel in channels), + role[rows], + ) + origins[origin] = { + "channels": list(channels), + "persons": counts["persons_joined"], + "spm_units": counts["native_spm_units"], + "true_role_persons": counts["true_role_persons"], + _ROLE_GATE_DIGEST_KEY: counts[_ROLE_GATE_DIGEST_KEY], + } + if origin == _CPS: + _require_cps_role_record(cps_record, counts) + _require_staging_receipt(staging_receipt, origins[_ACS]) + _require_acs_roles_by_rule(person, persons[ACS_SUPPORT_CHANNEL], role) + + return { + **_role_counts(person, frame.n("spm_unit"), role), + "column": NATIVE_SPM_ROLE, + "role_source": role_source, + "counts_by_channel": by_channel, + "origins": origins, + "evidence": { + "cps_record": _plain(cps_record), + "staging_receipt": _plain(staging_receipt), + }, + "rule": ( + "d2283 one-population role record: the gate's counts and digest " + "recounted over the joined frame; the CPS rows' record matched by " + "recount, staging's ACS receipt matched by keys, rule and coverage." + ), + } + + +# ------------------------------------------------------------- absences + + +def _zero_written_columns(zero_written: object) -> Mapping[str, str]: + if not isinstance(zero_written, Mapping): + raise TypeError( + "zero_written must map each column to the receipt that records its " + f"written zeros, got {type(zero_written).__name__}." + ) + for column, receipt in zero_written.items(): + if not isinstance(column, str) or not isinstance(receipt, str): + raise TypeError( + "zero_written must map str columns to str receipts, got " + f"{column!r}: {receipt!r}." + ) + if not receipt.strip(): + raise OnePopulationContractError( + f"A zero-written column needs its receipt; {column!r} has none." + ) + return zero_written + + +def _fills( + fill_manifest: object, + tables: Mapping[str, pd.DataFrame], +) -> list[Mapping[str, Any]]: + """The fill manifest's fills, checked against the frame they describe.""" + + rule = "The fill manifest does not describe this frame" + if not isinstance(fill_manifest, Mapping): + raise TypeError( + "fill_manifest must be the reviewed default fill's manifest mapping, " + f"got {type(fill_manifest).__name__}." + ) + missing = sorted(_FILL_MANIFEST_KEYS - set(fill_manifest)) + if missing: + raise OnePopulationContractError(f"{rule}: it lacks keys {missing}.") + fills = fill_manifest["fills"] + if isinstance(fills, str | bytes | Mapping) or not isinstance(fills, Collection): + raise OnePopulationContractError(f"{rule}: 'fills' must be a list of fills.") + violations = fill_manifest["unregistered_violations"] + if violations: + raise OnePopulationContractError( + f"{rule}: it records unregistered violations {_plain(violations)!r}; " + "the fill refuses those, so a manifest holding them is not a fill's." + ) + fills = list(fills) + seen: set[tuple[str, str]] = set() + total = 0 + for fill in fills: + if not isinstance(fill, Mapping) or _FILL_KEYS - set(fill): + raise OnePopulationContractError( + f"{rule}: each fill needs the keys {sorted(_FILL_KEYS)}; got " + f"{_plain(fill)!r}." + ) + entity, column = fill["entity"], fill["column"] + if entity not in tables or column not in tables[entity]: + raise OnePopulationContractError( + f"{rule}: it fills {entity!r}.{column!r}, which the frame lacks." + ) + if (entity, column) in seen: + raise OnePopulationContractError( + f"{rule}: it fills {entity!r}.{column!r} twice." + ) + seen.add((entity, column)) + table = tables[entity] + by_spine = fill["missing_rows_by_spine"] + if not _is_count(fill["filled_rows"]) or fill["filled_rows"] < 1: + raise OnePopulationContractError( + f"{rule}: {entity!r}.{column!r} fills {fill['filled_rows']!r} rows." + ) + if not _is_count(fill["rows"]) or fill["rows"] != len(table): + raise OnePopulationContractError( + f"{rule}: its {entity!r} table had {fill['rows']!r} rows; the " + f"frame's has {len(table)} (prepare fills the joined frame)." + ) + # Each count a nonnegative integer before the sum: a negative count + # can balance the sum and would be filed as an entry's rows (PR + # #1685 review, should-fix 5). + if ( + not isinstance(by_spine, Mapping) + or set(by_spine) - {CPS_SPINE_TAG, ACS_SUPPORT_CHANNEL} + or not all(_is_count(value) and value >= 0 for value in by_spine.values()) + or sum(by_spine.values()) != fill["filled_rows"] + ): + raise OnePopulationContractError( + f"{rule}: {entity!r}.{column!r}'s rows by spine " + f"{_plain(by_spine)!r} must count its {fill['filled_rows']!r} " + f"filled rows, in nonnegative integers, under the spine tags " + f"{CPS_SPINE_TAG!r} and {ACS_SUPPORT_CHANNEL!r}." + ) + if table[column].isna().any(): + raise OnePopulationContractError( + f"{rule}: {entity!r}.{column!r} still holds " + f"{int(table[column].isna().sum())} null(s) after its fill." + ) + total += int(fill["filled_rows"]) + if (fill_manifest["columns_filled"], fill_manifest["total_values_filled"]) != ( + len(fills), + total, + ): + raise OnePopulationContractError( + f"{rule}: it says {fill_manifest['columns_filled']!r} columns and " + f"{fill_manifest['total_values_filled']!r} values filled; its fills " + f"are {len(fills)} columns and {total} values." + ) + return fills + + +#: The spine tag each origin's rows carry on the joined frame (Q3). +_ORIGIN_OF_SPINE_TAG = MappingProxyType( + {CPS_SPINE_TAG: _CPS, ACS_SUPPORT_CHANNEL: _ACS} +) +_ORIGIN_CHANNELS = MappingProxyType({_CPS: _CPS_CHANNELS, _ACS: (ACS_SUPPORT_CHANNEL,)}) + + +@dataclass(frozen=True) +class _EntityMass: + """One entity's rows and weights by channel, for the absences file.""" + + channels: Mapping[str, np.ndarray] + weights: np.ndarray + total_weight: float + + def origin_rows(self, origin: str) -> np.ndarray: + return _origin_rows(self.channels, origin) + + def share(self, rows: np.ndarray) -> float | None: + if not self.total_weight > 0: + return None + return float(self.weights[rows].sum() / self.total_weight) + + def counted(self, rows: np.ndarray, origin: str) -> dict[str, object]: + """Rows and entity-weight shares of ``rows`` per channel of ``origin``.""" + + channels = _ORIGIN_CHANNELS[origin] + by_channel = {c: int((rows & self.channels[c]).sum()) for c in channels} + shares = {c: self.share(rows & self.channels[c]) for c in channels} + return { + "rows": int(rows.sum()), + "origin_rows": int(self.origin_rows(origin).sum()), + "rows_by_channel": by_channel, + "entity_weight_share": self.share(rows), + "entity_weight_share_by_channel": ( + None if None in shares.values() else shares + ), + } + + +def _entity_mass(frame: Frame, entity: str, table: pd.DataFrame) -> _EntityMass: + channels = _channel_masks( + table, entity, rule="The absences file needs every row's origin" + ) + weights = np.asarray(frame.resolve_weights(entity).values, dtype=np.float64) + return _EntityMass( + channels=channels, weights=weights, total_weight=float(weights.sum()) + ) + + +def _entry( + entity: str, + column: str, + kind: str, + origin: str, + counted: Mapping[str, object], + *, + rows_rule: str, + evidence: str, + readers: Iterable[str] = (), + detail: Mapping[str, object] | None = None, +) -> dict[str, object]: + return { + "entity": entity, + "column": column, + "kind": kind, + "origin": origin, + **counted, + "rows_rule": rows_rule, + "evidence": evidence, + "readers": list(readers), + "detail": dict(detail or {}), + } + + +def _absence_kind( + entity: str, column: str, origin: str, declared: Mapping[str, str] +) -> tuple[str, str, tuple[str, ...], dict[str, object]] | None: + """The kind of a column ``origin``'s rows lack, or ``None`` if it has none. + + A kind that needs no decision (release-written, raw source column, + origin-native) wins over a declaration, which files only a gap no such + kind covers. + """ + + from microcosm.data.stored_inputs import is_model_named + + if column in RELEASE_WRITTEN_INPUTS: + return (_RELEASE_WRITTEN, RELEASE_WRITTEN_INPUTS[column], (), {}) + if not is_model_named(column): + readers = RAW_COLUMN_READERS.get(column, ()) + evidence = "a raw source column the stored-input rule ignores; " + ( + f"the release reads it: {', '.join(readers)}" + if readers + else "no release reader is listed in RAW_COLUMN_READERS" + ) + return (_RAW_SOURCE, evidence, readers, {}) + native = ACS_NATIVE_AMOUNTS.get(column) + if origin == _CPS and native is not None and native[0] == entity: + return (_ORIGIN_NATIVE, _ORIGIN_NATIVE_EVIDENCE, native[1], {}) + if column in declared: + return ( + _OWNER_DECLARED, + declared[column], + (), + {"decision": declared[column]}, + ) + return None + + +def absences( + frame: Frame, + *, + fill_manifest: Mapping[str, Any], + zero_written: Mapping[str, str], + declared: Mapping[str, str], +) -> dict[str, object]: + """What one origin carries as a default fill, a written zero, or not at all. + + Returns the content of :data:`ABSENCES_FILENAME` (write it with + :func:`write_absences`): one entry per (entity, column, kind, origin) + with the rows it counts, per support channel, and their share of the + entity's total weight on the frame + (:meth:`~microcosm.frame.Frame.resolve_weights`), per channel too. Origins + are keyed by support channel (``asec`` and ``puf_tax_detail`` for CPS, + ``acs_2024_1yr`` for ACS), never by ``_spine``. Each entry + carries one of :data:`ABSENCE_KINDS`: + + - A column null on some row of one origin while the other origin holds a + value somewhere (both directions: what CPS rows fill and ACS rows + lack, and the reverse) is "release-written" if it is in + :data:`RELEASE_WRITTEN_INPUTS`, "raw source column" if it is not + model-named (the entry names the release's readers from + :data:`RAW_COLUMN_READERS`, so the predictor-join columns and #1610's + four household-type columns are never filed as harmless), + "origin-native" if CPS rows lack one of :data:`ACS_NATIVE_AMOUNTS` on + its own entity (the entry names the ACS transfer where it reads the + amount), and "owner-declared" if ``declared`` names it, with the + owner's decision. Those kinds are tried in that order, so a + declaration files only a gap no other kind covers. Any other such + column refuses, all of them in one message: prepare must fill it or + its owner declare it. The gap is :func:`_origin_gap`, the predicate + :func:`require_one_population`'s R10 shares (d2283 lead call L2), so + one declaration answers both. This file is still the stricter of the + two: R10 reads only register entries, and only ACS rows lacking a + column CPS rows hold, where this reads every model-named column in + both directions. + - "reviewed default fill": each fill of ``fill_manifest``, the reviewed + default fill's manifest (``tools/build_us_acs_local_release.py`` + ``fill_reviewed_nulls``, :1151-1165), checked against the frame + (table rows, no null left, per-spine counts nonnegative integers adding + up, spine tags known). The + fill writes in place and the manifest counts rows by spine tag without + naming them, so per-channel rows and weighted shares are given only + when the fill covered every row of that origin; otherwise they are + ``None`` and ``rows_rule`` says why. + - "zero written": each column of ``zero_written``, which maps it to the + receipt recording staging's written zeros. Its rows are the ACS rows + holding zero (a null, in any numeric dtype, is not a zero), an upper + bound: a measured zero is not told apart. + + ``declared`` is the mapping :func:`require_one_population` takes, so a declaration this frame does not use is recorded, never + refused (d2283 lead call (b), 11-18): ``needless_declarations`` lists + each declared column that needs no decision here (release-written, not + model-named, named by ``fill_manifest`` or ``zero_written``, whose + receipt files it, or whose every gap on this frame took a kind that + needs none, such as an origin-native amount), and ``unused_declarations`` + each other declared column no origin lacks on this frame (a stale + declaration; on a frame with no ACS row, every such declaration). Each + list holds ``{"column", "decision"}`` entries sorted by column. A + declaration for an engine input is filed like any other, although + :func:`require_one_population`'s R6 refuses that input's nulls on the + same frame whatever is declared. A column named by both + ``fill_manifest`` and ``zero_written`` refuses: an absence has one kind. + + Args: + frame: The joined frame after prepare's fill. + fill_manifest: The reviewed default fill's manifest for this frame. + zero_written: Column to the receipt recording its written zeros. + declared: Column to its owner's decision, the mapping + :func:`require_one_population` takes as ``declared_absences``. + + Returns: + The absences record: plain builtins, entries and both declaration + lists sorted. + + Raises: + OnePopulationContractError: If an input does not describe the frame, + or a column one origin lacks has no kind. + TypeError: If an argument has the wrong type. + """ + + if not isinstance(frame, Frame): + raise TypeError(f"frame must be a Frame, got {type(frame).__name__}.") + if frame.schema != US_SCHEMA: + raise OnePopulationContractError( + "The absences file needs a frame in the US schema." + ) + declared = _declarations(declared, name="declared") + zero_written = _zero_written_columns(zero_written) + tables = _frame_tables(frame) + fills = _fills(fill_manifest, tables) + + filled_columns = {str(fill["column"]) for fill in fills} + both = sorted(filled_columns & set(zero_written)) + if both: + raise OnePopulationContractError( + f"An absence has one kind: {both} are named by both fill_manifest " + "and zero_written." + ) + # A declared column a receipt also names is needless: the receipt files it. + receipted = filled_columns | set(zero_written) + masses = { + entity: _entity_mass(frame, entity, tables[entity]) + for entity in US_SCHEMA.entities + } + entries: list[dict[str, object]] = [] + used: set[str] = set() + gapped: set[str] = set() + gaps: dict[str, str] = {} + for entity in US_SCHEMA.entities: + table, mass = tables[entity], masses[entity] + for column in table.columns: + if not isinstance(column, str): + continue + null = table[column].isna().to_numpy() + if not null.any(): + continue + for origin, other in ((_CPS, _ACS), (_ACS, _CPS)): + lacking = _origin_gap( + null, mass.origin_rows(origin), mass.origin_rows(other) + ) + if lacking is None: + continue + gapped.add(column) + classified = _absence_kind(entity, column, origin, declared) + if classified is None: + gaps[f"{entity}.{column}"] = ( + f"null on {int(lacking.sum())} {origin} row(s)" + ) + continue + kind, evidence, readers, detail = classified + if kind == _OWNER_DECLARED: + used.add(column) + entries.append( + _entry( + entity, + column, + kind, + origin, + mass.counted(lacking, origin), + rows_rule="null on these rows; the other origin holds values", + evidence=evidence, + readers=readers, + detail=detail, + ) + ) + if gaps: + raise OnePopulationContractError( + f"A column one origin lacks has no absence kind: {gaps}. Each is " + "model-named and not release-written, and the other origin holds " + "values in it, so prepare must fill it or its owner must declare " + "the absence with a decision." + ) + from microcosm.data.stored_inputs import is_model_named + + needless = sorted( + column + for column in set(declared) - used + if column in gapped + or column in receipted + or column in RELEASE_WRITTEN_INPUTS + or not is_model_named(column) + ) + unused = sorted(set(declared) - used - set(needless)) + + for fill in fills: + entity, column = str(fill["entity"]), str(fill["column"]) + mass = masses[entity] + for tag, filled in sorted(fill["missing_rows_by_spine"].items()): + if not filled: + continue + origin = _ORIGIN_OF_SPINE_TAG[tag] + rows = mass.origin_rows(origin) + if filled > int(rows.sum()): + raise OnePopulationContractError( + f"The fill manifest does not describe this frame: it fills " + f"{filled} {origin} rows of {entity!r}.{column!r}; the frame " + f"holds {int(rows.sum())}." + ) + if filled == int(rows.sum()): + counted = mass.counted(rows, origin) + rows_rule = "every row of the origin (the fill's count equals them)" + else: + counted = { + "rows": int(filled), + "origin_rows": int(rows.sum()), + "rows_by_channel": None, + "entity_weight_share": None, + "entity_weight_share_by_channel": None, + } + rows_rule = ( + "the fill manifest's count; it names no rows, so the " + "channels and weighted shares are unknown" + ) + entries.append( + _entry( + entity, + column, + _DEFAULT_FILL, + origin, + counted, + rows_rule=rows_rule, + evidence=( + "prepare's reviewed default fill, reviewed by staging's " + "reviewed_engine_input_nulls register" + ), + detail={ + "fill_value": _plain(fill["fill_value"]), + "fill_kind": _plain(fill["fill_kind"]), + "register_missing_rows": _plain(fill["register_missing_rows"]), + }, + ) + ) + + for column, receipt in sorted(zero_written.items()): + holders = [entity for entity in US_SCHEMA.entities if column in tables[entity]] + if not holders: + raise OnePopulationContractError( + f"A zero-written column the frame lacks: {column!r}." + ) + entity = holders[0] + values = tables[entity][column] + if pd.api.types.is_bool_dtype(values.dtype) or not ( + pd.api.types.is_numeric_dtype(values.dtype) + ): + raise OnePopulationContractError( + f"A zero-written column must be numeric: {entity!r}.{column!r} " + f"is {values.dtype}." + ) + mass = masses[entity] + # A plain boolean mask: on a nullable dtype (Float64, Int64) eq(0) is + # a nullable boolean whose to_numpy() is an object array, which the + # weight lookup cannot index with; a null is not a zero (PR #1685 + # review, should-fix 6). + zero = values.eq(0).to_numpy(dtype=bool, na_value=False) & mass.origin_rows( + _ACS + ) + entries.append( + _entry( + entity, + column, + _ZERO_WRITTEN, + _ACS, + mass.counted(zero, _ACS), + rows_rule=( + "ACS rows holding zero: an upper bound, since a measured " + "zero is not told apart from a written one" + ), + evidence=receipt, + detail={"receipt": receipt}, + ) + ) + + entries.sort( + key=lambda entry: ( + US_SCHEMA.entities.index(entry["entity"]), + entry["column"], + ABSENCE_KINDS.index(entry["kind"]), + entry["origin"], + ) + ) + return { + "schema_version": _ABSENCES_SCHEMA_VERSION, + "file": ABSENCES_FILENAME, + "kinds": list(ABSENCE_KINDS), + "channels": list(ASSEMBLED_CHANNELS), + "share_denominator": ( + "each entity's total weight on the frame (Frame.resolve_weights)" + ), + "rows_by_channel": { + entity: { + channel: int(mask.sum()) + for channel, mask in masses[entity].channels.items() + } + for entity in US_SCHEMA.entities + }, + "fill_manifest_period": _plain(fill_manifest["period"]), + "entries": entries, + "unused_declarations": [ + {"column": column, "decision": declared[column]} for column in unused + ], + "needless_declarations": [ + {"column": column, "decision": declared[column]} for column in needless + ], + } + + +def _absences_json(record: Mapping[str, object]) -> str: + """The absences file's bytes: PR 1's canonical JSON, one trailing newline.""" + + return ( + json.dumps( + _plain(record), + sort_keys=True, + separators=(",", ":"), + ensure_ascii=True, + allow_nan=False, + ) + + "\n" + ) + + +def write_absences(record: Mapping[str, object], directory: str | Path) -> Path: + """Write :func:`absences`' record as ``directory/``:data:`ABSENCES_FILENAME`. + + The JSON is deterministic: sorted keys, no whitespace, ASCII, and + ``allow_nan=False`` (a non-finite share refuses rather than writes). + + Returns: + The written file's path. + """ + + if not isinstance(record, Mapping): + raise TypeError(f"record must be a mapping, got {type(record).__name__}.") + path = Path(directory) / ABSENCES_FILENAME + path.write_text(_absences_json(record), encoding="ascii") + return path + + +def _is_peridnum(value: object) -> bool: + return ( + isinstance(value, str) + and len(value) >= _CPS_UNIT_ID_LENGTH + and value.isascii() + and value.isdigit() + ) + + +def cps_unit_ids(person: pd.DataFrame) -> pd.DataFrame: + """Each CPS household's income year, unit id and selection key. + + The unit id is ``PERIDNUM[:20]`` (H_IDNUM), on which every person of the + household must agree, as the support-mix bake-off reads it + (``tools/bakeoff_us_support_mix.py`` ``_row_index_columns``). It comes + from ``PERIDNUM`` when the column is present, else from + ``source_person_id`` (the ASEC pool writes ``PERIDNUM`` there). Either + way every value must be a string of at least 20 ASCII digits: the ASEC + pool's integer fallback, a number cast to text and a null are refused, + never sliced (unlike the bake-off's ``astype(str)``). The income year is + ``source_year``, an integer on which the household's persons agree. The + key is + :func:`~microcosm.build.us_runtime.one_population_selection.cps_unit_key`, + so the prepare step's selection keys (PR 4 builds them with this + function) and the contract's key check share one rule; digest a key set + with :func:`~microcosm.build.us_runtime.one_population_selection.keys_sha256`. + + Every physical household gets a row: a source household's PUF clone + households carry its PERIDNUM, so they share its key. The selection's + ``cps_keys`` are the clone-0 households' keys. + + Args: + person: CPS person rows with ``person_household_id``, + ``source_year`` and ``PERIDNUM`` or ``source_person_id``. + + Returns: + One row per household id (``person_household_id``), sorted, in an + index named ``household_id``, with columns ``income_year`` (int64), + ``unit_id`` and ``key``. + + Raises: + OnePopulationContractError: If an id or year is missing or malformed, + or a household's persons disagree. + """ + + if not isinstance(person, pd.DataFrame): + raise TypeError(f"person must be a DataFrame, got {type(person).__name__}.") + household_column = US_SCHEMA.membership_column("household") + if _PERIDNUM in person: + column = _PERIDNUM + elif _SOURCE_PERSON_ID in person: + column = _SOURCE_PERSON_ID + else: + raise OnePopulationContractError( + f"CPS unit ids need {_PERIDNUM} or {_SOURCE_PERSON_ID} on the persons." + ) + missing = [c for c in (household_column, _SOURCE_YEAR) if c not in person] + if missing: + raise OnePopulationContractError(f"CPS unit ids need {missing} on the persons.") + values = person[column] + bad = ~values.map(_is_peridnum).astype(bool) + if bad.any(): + raise OnePopulationContractError( + f"CPS unit ids need {column} as a string of at least " + f"{_CPS_UNIT_ID_LENGTH} digits on every person (the ASEC PERIDNUM); " + f"{int(bad.sum())} person(s) hold values such as " + f"{values[bad].head(3).tolist()!r}." + ) + households = _integral_ids( + person[household_column], + refusal=f"CPS unit ids need integral {household_column!r}", + ) + years = _integral_ids( + person[_SOURCE_YEAR], refusal=f"CPS unit ids need an integral {_SOURCE_YEAR}" + ) + per_person = pd.DataFrame( + { + "household_id": households, + "income_year": years, + "unit_id": [value[:_CPS_UNIT_ID_LENGTH] for value in values.tolist()], + } + ) + grouped = per_person.groupby("household_id", sort=True) + for name, label in ( + ("unit_id", f"{column}[:{_CPS_UNIT_ID_LENGTH}] (H_IDNUM)"), + ("income_year", _SOURCE_YEAR), + ): + split = grouped[name].nunique() + if (split != 1).any(): + raise OnePopulationContractError( + f"CPS unit ids: persons of one household disagree on {label} in " + f"household(s) {split.index[split != 1].tolist()[:5]}." + ) + result = grouped[["income_year", "unit_id"]].first() + try: + keys = [ + cps_unit_key(int(year), unit) + for year, unit in zip( + result["income_year"].tolist(), result["unit_id"].tolist(), strict=True + ) + ] + except ValueError as exc: + raise OnePopulationContractError( + f"CPS unit ids: a household's key is malformed: {exc}" + ) from exc + return pd.DataFrame( + { + "income_year": result["income_year"].to_numpy(dtype=np.int64), + "unit_id": pd.Series(result["unit_id"].tolist(), dtype=object).to_numpy(), + "key": pd.Series(keys, dtype=object).to_numpy(), + }, + index=pd.Index(result.index.to_numpy(dtype=np.int64), name="household_id"), + ) diff --git a/packages/microcosm-build/src/microcosm/build/us_runtime/one_population_selection.py b/packages/microcosm-build/src/microcosm/build/us_runtime/one_population_selection.py index 4528941d70..9d531bc9c2 100644 --- a/packages/microcosm-build/src/microcosm/build/us_runtime/one_population_selection.py +++ b/packages/microcosm-build/src/microcosm/build/us_runtime/one_population_selection.py @@ -60,6 +60,7 @@ "acs_unit_key", "cps_unit_key", "group_quarters", + "keys_sha256", "plan_selection", "spm_zero_adult", "starting_weights", @@ -216,8 +217,13 @@ def _refuse_duplicates(keys: Sequence[str], *, side: str) -> None: ) -def _keys_sha256(keys: Iterable[str]) -> str: - """sha256 of the sorted keys joined by newline (keys hold no newline).""" +def keys_sha256(keys: Iterable[str]) -> str: + """sha256 of the sorted keys joined by newline (keys hold no newline). + + The digest :class:`SelectionManifest` records for each selected key set. + It is public so a later check over a frame's keys (the population + contract) digests them by the same rule. + """ return hashlib.sha256("\n".join(sorted(keys)).encode("utf-8")).hexdigest() @@ -940,8 +946,8 @@ def from_plan( n_acs=plan.n_acs, n_cps_by_income_year=plan.n_cps_by_income_year, threshold_draw=plan.threshold_draw, - selected_acs_keys_sha256=_keys_sha256(plan.acs_keys), - cps_keys_sha256=_keys_sha256(plan.cps_keys), + selected_acs_keys_sha256=keys_sha256(plan.acs_keys), + cps_keys_sha256=keys_sha256(plan.cps_keys), input_digests=_check_digests(input_digests), ) diff --git a/packages/microcosm-build/tests/engine_contract/us/test_us_one_population_contract_index.py b/packages/microcosm-build/tests/engine_contract/us/test_us_one_population_contract_index.py new file mode 100644 index 0000000000..6b419858b7 --- /dev/null +++ b/packages/microcosm-build/tests/engine_contract/us/test_us_one_population_contract_index.py @@ -0,0 +1,73 @@ +"""The population contract's stand-in index answers as the installed engine's. + +The contract's engine-free tests inject ``StandInVariableIndex.from_lock()`` +in place of the default :class:`PolicyEngineUSVariableIndex`, which reads the +installed policyengine-us sources. These tests pin the stand-in to that +default: over every name the stand-in classifies, the two give the same +known, computed-at-2024 and input-at-2024 answers, so a passing engine-free +clause test means what it would mean with the engine's metadata behind it. +""" + +from __future__ import annotations + +import pandas as pd + +from microcosm.build.us_runtime.multispine_pool import ( + POOL_ENGINE_INPUT_PROJECTION_CONTRACT, +) +from microcosm.build.us_runtime.one_population_contract import ( + STRUCTURAL_COLUMNS, + PolicyEngineUSVariableIndex, +) +from microcosm.frame.adapters.policyengine_us import ( + PolicyEngineUSVariableMetadataIndex, +) +from test_support.microcosm_build.us_one_population_contract import ( + SPM_ROLE, + STAND_IN_COMPAT_AGGREGATES, + STAND_IN_COMPUTED_AT_2024, + STAND_IN_FORMULA_AFTER_2024, + STAND_IN_STRUCTURAL_FORMULAS, + StandInVariableIndex, + lock_engine_inputs, +) + + +def test_the_lock_inputs_are_the_installed_engine_inputs() -> None: + # The stand-in's inputs are the lock's 926 names; the installed index's + # year-blind input list must be the same names. + installed = frozenset(PolicyEngineUSVariableMetadataIndex().variables()) + assert installed == frozenset(lock_engine_inputs()) + assert len(installed) == POOL_ENGINE_INPUT_PROJECTION_CONTRACT.input_count + + +def _every_classified_name() -> dict[str, pd.DataFrame]: + names = sorted( + frozenset(lock_engine_inputs()) + | STAND_IN_COMPUTED_AT_2024 + | STAND_IN_COMPAT_AGGREGATES + | STAND_IN_FORMULA_AFTER_2024 + | STAND_IN_STRUCTURAL_FORMULAS + | STRUCTURAL_COLUMNS + ) + return {"person": pd.DataFrame(columns=names)} + + +def test_the_stand_in_answers_as_the_default_index() -> None: + tables = _every_classified_name() + names = list(tables["person"].columns) + default = PolicyEngineUSVariableIndex() + stand_in = StandInVariableIndex.from_lock() + + assert default.known_variables(names) == stand_in.known_variables(names) + assert default.computed_at_2024(tables) == stand_in.computed_at_2024(tables) + assert default.inputs_at_2024(tables) == stand_in.inputs_at_2024(tables) + + +def test_a_post_2024_formula_and_the_role_are_inputs_at_2024() -> None: + # weeks_worked has only formula_2025 at the locked policyengine-us, and + # the SPM role is a declared dataset source input despite its fallback + # formula: the contract reads both as inputs at 2024. + tables = {"person": pd.DataFrame(columns=["weeks_worked", SPM_ROLE])} + inputs = PolicyEngineUSVariableIndex().inputs_at_2024(tables) + assert inputs == {"weeks_worked", SPM_ROLE} diff --git a/packages/microcosm-build/tests/engine_free/us/test_us_one_population_contract.py b/packages/microcosm-build/tests/engine_free/us/test_us_one_population_contract.py new file mode 100644 index 0000000000..c83eefb7b0 --- /dev/null +++ b/packages/microcosm-build/tests/engine_free/us/test_us_one_population_contract.py @@ -0,0 +1,7004 @@ +"""d2283 PR 2: the one-population contract library. + +Phase 0 (the foundation) pins the module's surface and engine-free import, +the injected engine variable index (the default adapter's rules over a fake +inner index, and the stand-in built from the engine ABI lock), PR 1's public +key digest, and the generated population every later clause test corrupts: +uncorrupted, it passes the SPM composition check, the SPM role signal gate +(bands included) with a record computed by the gate's rule, and the assembly +validator with a clone-0, three-channel record. + +Phase 1 covers the provenance rewrite (``to_assembled_provenance``: X3, X4, +X6 and one refusal per P5, P6, P6b and P7 rule) and ``cps_unit_ids``. + +Phase 2 covers ``require_one_population``: the valid generated population +passes in both forms; X1 as a table of single-cell corruptions (a few add or +drop a column, where no single cell can break the clause), one or more per +clause, each refusing with its own clause's message; a Hypothesis property +over null cells of the checked columns; the clause order; the exempt list +pinned to its stages' declared outputs; and a ``weeks_worked``-like column +(no formula at 2024) refused under R6. + +Phase 3 covers ``combined_spm_role_record`` (the record passes the real SPM +role gate on the generated population in both forms; one refusal per check, +a digest-only mismatch included), ``absences`` and ``write_absences`` (both +directions, rows and shares by channel, the six kinds, the raw columns' +readers pinned to the predictor join, the fill manifest checked against the +frame, deterministic JSON), X2 (N-2's kinds on a generated population with +an injected register) and X7 (group quarters add nothing to household-type +targets, skipped until PolicyEngine/microcosm#1610's materializer imports). + +The lead's 11-18 calls: (a) the six ACS-native ``acs_*`` amounts CPS rows +lack are "origin-native", with the names pinned to the operator boundary's +contract by reading its source; (b) one declarations mapping passes +``require_one_population`` and ``absences``, which records stale and +needless declarations instead of refusing them; (c) the refusals phase 3 +left untested each have a case. + +Phase 4 covers X5, the whole-frame differential: on an ASEC-only population +(Route A's labels: ``asec`` clone 0, ``puf_tax_detail`` clones), each +provenance-reading gate returns the same verdict and statistics before and +after ``to_assembled_provenance`` with no ACS row, one parametrized case per +reader. The four readers Route A's clone label moves (the weeks UC-rule +scope, Medicare take-up and both retirement families) are strict expected +failures naming PR 3, with a companion check that each moves only its named +fields; ``acs_local_hours`` is left out, its donor prep refusing the +assembled population. Lead call L7 (11-18) adds two more strict expected +failures on verdicts: one clone-only defect each (a clone's ``MCARE`` +mismatch, a clone's weeks with no unemployment compensation) fails Route +A's gate and passes the assembled one, so PR 3 owns six. + +The PR #1685 review (round 1) adds: R6's refusal of ``pd.NA`` in an exempt +column, with None and NaN still passing (blocking 1); staging's lineage +keyed by native ids, so a ``SERIALNO`` or ``SPORDER`` swap that keeps the +set of pairs refuses (blocking 2); P6c, every group unit inside one +household (each of the four group entities on CPS rows) and each ACS +household one SPM unit (blocking 3); each ACS role +re-derived from ``RELSHIPP`` (should-fix 1); nullable lineage values +refused before they are compared (should-fix 2); R2's ids and clone indices +parsed as R1 parses them (should-fix 3); an index whose inputs omit a +known column refused (should-fix 4); a negative per-spine fill count +refused (should-fix 5); written zeros counted on a nullable numeric column +(should-fix 6); a spine assembly record count the validator would coerce +refused at R1 (nit 1); and tests that pin R11 between R1 and R2 in the +clause order, with a real location clone and a repeated ``SERIALNO`` +reporting their earlier clause (nit 2). + +Round 2 adds: complex and temporal ids, lineage values and ``RELSHIPP`` +codes refused before any conversion to real numbers, and a timedelta key +in staging's lineage refused (should-fix 1); R6's release-written nulls +limited to None and a float NaN, a float32 column and a numpy float32 NaN +included, with ``pd.NaT`` and numpy's ``NaT`` refused (nit 1); the lineage +diagnostic ahead of a missing weight (nit 2); an ACS SPM unit merger on +both paths and a CPS crossing at R1 (nit 3); and a lone CPS ``pd.NA`` at +R6 and an ACS ``pd.NA`` beside written zeros (nit 4). + +Round 3 adds: the shared guard as an allowlist, which reads the value type +behind a categorical or an Arrow dictionary and refuses an Arrow dictionary +of times in lineage values and ``RELSHIPP``, with 27 cases that pin dtype +forms it must keep accepting (should-fix 1); numpy timedelta64 refused +wherever the module tests for a number (donor ids, counts, ``TYPEHUGQ``, +the tail flag) and complex or temporal household weights refused +(should-fix 2); membership links of ACS and CPS persons through the same +guard (nit 2); and ``pd.NA`` reported ahead of another null at R6 (nit 3). +""" + +from __future__ import annotations + +import ast +import dataclasses +import datetime +import decimal +import hashlib +import inspect +import json +import math +import re +import tomllib +from pathlib import Path + +import numpy as np +import pandas as pd +import pyarrow as pa +import pytest +from hypothesis import given, settings +from hypothesis import strategies as st + +from microcosm.build.gates import GateResult +from microcosm.build.serialization_dtypes import CANONICAL_STRING_DTYPE +from microcosm.build.us_runtime import one_population_contract as contract +from microcosm.build.us_runtime import one_population_selection as selection +from microcosm.build.us_runtime.acs_local_hours import prepare_acs_local_hours_donor +from microcosm.build.us_runtime.acs_pums import ACS_2024_1YR_SPINE +from microcosm.build.us_runtime.base_pool import ASEC_PUF_SPINE +from microcosm.build.us_runtime.block_location import ( + LOCATION_CLONE_INDEX_COLUMN, + clone_frame_for_location, +) +from microcosm.build.us_runtime.multispine_pool import ( + POOL_ENGINE_INPUT_PROJECTION_CONTRACT, +) +from microcosm.build.us_runtime.one_population_contract import ( + ABSENCE_KINDS, + ABSENCES_FILENAME, + ACS_SUPPORT_CHANNEL, + ASSEMBLED_CHANNELS, + CPS_SPINE_TAG, + ENGINE_PERIOD, + PUF_TAIL_TAX_UNIT_COLUMNS, + RAW_COLUMN_READERS, + RELEASE_WRITTEN_INPUTS, + STRUCTURAL_COLUMNS, + EngineVariableIndex, + OnePopulationContractError, + PolicyEngineUSVariableIndex, + _engine_columns, + absences, + combined_spm_role_record, + cps_unit_ids, + require_one_population, + to_assembled_provenance, + write_absences, +) +from microcosm.build.us_runtime.puf_capital_gains_tail import ( + PUF_CAPITAL_GAINS_TAIL_APPLIED_COLUMN, + PUF_CAPITAL_GAINS_TAIL_DONOR_SOURCE_ID_COLUMN, +) +from microcosm.build.us_runtime.spine_agreement import spine_agreement_gate +from microcosm.build.us_runtime.spm_composition import check_spm_composition +from microcosm.build.us_runtime.spm_independence_role import ( + _role_binding_sha256, + us_spm_independence_role_signal_gate, +) +from microcosm.build.us_runtime.support_provenance import ( + BASE_ASEC_SUPPORT_CHANNEL, + PUF_TAX_DETAIL_SUPPORT_CHANNEL, + SPINE_ASSEMBLY_MANIFEST_KEY, + require_assembled_support_provenance, + spine_source_id_column, + support_channel_column, + support_clone_index_column, + support_copy_rank_series, + support_gate_source_channel_series, + support_role_series, + support_source_id_column, + validate_assembly_provenance, +) +from microcosm.data.stored_inputs import ( + US_STORED_NON_VARIABLE_COLUMNS, + undefined_stored_inputs, +) +from microcosm.frame import US_SCHEMA, Frame, WeightKind +from test_support.microcosm_build.us_one_population_contract import ( + ENGINE_ABI_LOCK, + READER_CLONE_DEFECTS, + READER_GATES, + READER_SOURCE_COLUMNS, + RELEASE_WRITTEN_ON_ACS, + SPM_ROLE, + STAND_IN_COMPAT_AGGREGATES, + STAND_IN_COMPUTED_AT_2024, + STAND_IN_FORMULA_AFTER_2024, + STAND_IN_STRUCTURAL_FORMULAS, + TAIL_PROVENANCE_DEFAULTS, + WIC_SOURCE_TRIPLE, + StandInVariableIndex, + acs_household_weight_series, + assembled_frame, + clone_zero_assembly_record, + cps_household_weight_series, + cps_role_record, + fill_manifest, + generate_population, + joined_frame, + lock_engine_inputs, + reader_population, + role_shares, + selection_manifest, + spm_role_gate_record, + staging_lineage, + staging_role_receipt, + with_spm_role_record, + with_staging_union_columns, +) +from test_support.paths import REPOSITORY_ROOT + +_SEEDS = (0, 1, 2) + + +@pytest.fixture(scope="module") +def population(): + return generate_population(0) + + +@pytest.fixture(scope="module") +def frame(population): + return joined_frame(population) + + +@pytest.fixture(scope="module") +def stand_in(): + return StandInVariableIndex.from_lock() + + +# ----------------------------------------------------------- the surface + + +class TestModuleSurface: + def test_public_names_resolve_and_are_sorted(self) -> None: + assert contract.__all__ == sorted(contract.__all__, key=_all_sort_key) + for name in contract.__all__: + assert hasattr(contract, name), name + + def test_signatures_take_the_injected_inputs_by_keyword(self) -> None: + def keyword_only(function) -> set[str]: + return { + name + for name, parameter in inspect.signature(function).parameters.items() + if parameter.kind is inspect.Parameter.KEYWORD_ONLY + } + + parameters = inspect.signature(contract.to_assembled_provenance).parameters + assert list(parameters)[:2] == ["cps_tables", "acs_tables"] + assert keyword_only(contract.to_assembled_provenance) == { + "cps_household_weights", + "acs_household_weights", + "staging_lineage", + } + assert keyword_only(contract.require_one_population) == { + "parent_tail_donor_ids", + "declared_absences", + "staging_lineage", + "variable_index", + "register", + } + assert list( + inspect.signature(contract.combined_spm_role_record).parameters + ) == ["cps_record", "staging_receipt", "frame"] + assert keyword_only(contract.absences) == { + "fill_manifest", + "zero_written", + "declared", + } + assert list(inspect.signature(contract.cps_unit_ids).parameters) == ["person"] + + def test_constants_match_staging_and_provenance(self) -> None: + # Staging's ACS channel and spine tag, and its donor-row spine tag. + assert ACS_SUPPORT_CHANNEL == ACS_2024_1YR_SPINE + assert CPS_SPINE_TAG == ASEC_PUF_SPINE + assert ASSEMBLED_CHANNELS == ( + BASE_ASEC_SUPPORT_CHANNEL, + PUF_TAX_DETAIL_SUPPORT_CHANNEL, + ACS_2024_1YR_SPINE, + ) + assert ENGINE_PERIOD == 2024 + assert STRUCTURAL_COLUMNS == { + "person_id", + "household_id", + "tax_unit_id", + "spm_unit_id", + "family_id", + "marital_unit_id", + "person_household_id", + "person_tax_unit_id", + "person_spm_unit_id", + "person_family_id", + "person_marital_unit_id", + } + + def test_module_imports_no_engine_at_import_time(self) -> None: + tree = ast.parse(inspect.getsource(contract)) + top_level = [ + node.module if isinstance(node, ast.ImportFrom) else alias.name + for node in tree.body + if isinstance(node, ast.Import | ast.ImportFrom) + for alias in (node.names if isinstance(node, ast.Import) else [None]) + ] + assert not [name for name in top_level if "policyengine" in str(name)] + + def test_error_is_a_value_error(self) -> None: + assert issubclass(OnePopulationContractError, ValueError) + + +def _all_sort_key(name: str) -> tuple[int, str]: + # The repo's __all__ order: constants, then classes, then functions. + if name.isupper(): + return (0, name) + return (1, name) if name[0].isupper() else (2, name) + + +# ------------------------------------------- the default adapter (M2) + + +class _FakeMetadataIndex: + """The three methods the adapter calls, over fixed name sets.""" + + def __init__(self) -> None: + self.inputs = {"age", "household_id", "person_household_id", "tip_income"} + self.formula_owned = {"person_id", "adjusted_gross_income", "weeks_worked"} + self.computed_2024 = {"adjusted_gross_income"} + self.compat = {"social_security"} + self.periods: list[object] = [] + + def variables(self) -> list[str]: + return sorted(self.inputs) + + def formula_owned_outputs(self, names) -> set[str]: + names = set(names) + return (names & self.compat) | (names & self.formula_owned) + + def _engine_computed_columns(self, tables, *, period) -> set[str]: + self.periods.append(period) + present = {column for table in tables.values() for column in table.columns} + return (present & self.compat) | ( + (present & self.computed_2024) - STRUCTURAL_COLUMNS + ) + + +class TestDefaultAdapter: + def test_builds_no_inner_index_until_asked(self, monkeypatch) -> None: + import microcosm.frame.adapters.policyengine_us as adapter_module + + built: list[str] = [] + + class Sentinel: + def __init__(self) -> None: + built.append("built") + raise RuntimeError("inner index built") + + monkeypatch.setattr( + adapter_module, "PolicyEngineUSVariableMetadataIndex", Sentinel + ) + index = PolicyEngineUSVariableIndex() + assert built == [] + assert isinstance(index, EngineVariableIndex) + with pytest.raises(RuntimeError, match="inner index built"): + index.known_variables(["age"]) + assert built == ["built"] + + def test_classes_follow_the_release_guard(self) -> None: + fake = _FakeMetadataIndex() + index = PolicyEngineUSVariableIndex(fake) + tables = { + "person": pd.DataFrame( + columns=[ + "person_id", + "person_household_id", + "age", + "tip_income", + "weeks_worked", + "adjusted_gross_income", + "social_security", + "not_a_variable", + ] + ), + "household": pd.DataFrame(columns=["household_id"]), + } + present = {column for table in tables.values() for column in table} + + assert index.known_variables(present) == present - {"not_a_variable"} + assert index.computed_at_2024(tables) == { + "adjusted_gross_income", + "social_security", + } + # weeks_worked: known, no formula at 2024, so an input at 2024 although + # the year-blind variables() leaves it out. Structural ids never count. + assert index.inputs_at_2024(tables) == {"age", "tip_income", "weeks_worked"} + assert set(fake.periods) == {ENGINE_PERIOD} + + def test_coherent_answers_pass_the_contract_check(self) -> None: + tables = {"person": pd.DataFrame(columns=["person_id", "age", "ssi"])} + classes = _engine_columns(tables, StandInVariableIndex.from_lock()) + assert classes.inputs == {"age"} + assert classes.computed == {"ssi"} + assert classes.known == {"person_id", "age", "ssi"} + + @pytest.mark.parametrize( + ("broken", "message"), + [ + ("computed", "inputs also computed"), + ("structural", "inputs include structural columns"), + ("unknown", "inputs not known"), + ("absent", "names columns no table holds"), + # PR #1685 review, should-fix 4: the other direction. + ("omitted", "inputs omit known columns that are neither computed"), + ], + ) + def test_incoherent_answers_are_refused(self, broken, message) -> None: + class Broken(StandInVariableIndex): + def inputs_at_2024(self, tables): + inputs = set(super().inputs_at_2024(tables)) + if broken == "omitted": + return frozenset(inputs - {"age"}) + extra = { + "computed": "ssi", + "structural": "person_household_id", + "unknown": "not_a_variable", + "absent": "tip_income", + }[broken] + return frozenset(inputs | {extra}) + + tables = { + "person": pd.DataFrame( + columns=["person_household_id", "age", "ssi", "not_a_variable"] + ) + } + index = Broken(inputs=frozenset(lock_engine_inputs())) + with pytest.raises(OnePopulationContractError, match=message): + _engine_columns(tables, index) + + +# --------------------------------------------------- the stand-in (M2) + + +class TestStandInIndex: + def test_lock_projection_is_the_pool_contract(self) -> None: + # lock_engine_inputs checks the lock's own receipt; this pins the + # same names to the pool's installed-engine contract. + inputs = lock_engine_inputs() + payload = [ + {"entity": entity, "variable": variable} + for variable, entity in sorted(inputs.items()) + ] + digest = hashlib.sha256( + json.dumps( + payload, allow_nan=False, separators=(",", ":"), sort_keys=True + ).encode("utf-8") + ).hexdigest() + assert len(inputs) == POOL_ENGINE_INPUT_PROJECTION_CONTRACT.input_count == 926 + assert digest == POOL_ENGINE_INPUT_PROJECTION_CONTRACT.sha256 + + def test_explicit_sets_are_disjoint_from_the_lock(self, stand_in) -> None: + for names in ( + STAND_IN_COMPUTED_AT_2024, + STAND_IN_COMPAT_AGGREGATES, + STAND_IN_FORMULA_AFTER_2024, + STAND_IN_STRUCTURAL_FORMULAS, + ): + assert not names & stand_in.inputs + + def test_a_post_2024_formula_is_an_input_at_2024(self, stand_in) -> None: + # weeks_worked has only formula_2025 at policyengine-us 2.2.1: absent + # from the year-blind 926, not computed at 2024, so an input at 2024. + tables = {"person": pd.DataFrame(columns=["weeks_worked"])} + assert "weeks_worked" not in lock_engine_inputs() + assert stand_in.computed_at_2024(tables) == frozenset() + assert stand_in.inputs_at_2024(tables) == {"weeks_worked"} + + def test_compat_aggregates_are_computed_and_never_inputs(self, stand_in) -> None: + tables = {"person": pd.DataFrame(columns=sorted(STAND_IN_COMPAT_AGGREGATES))} + assert stand_in.computed_at_2024(tables) == STAND_IN_COMPAT_AGGREGATES + assert stand_in.inputs_at_2024(tables) == frozenset() + + def test_structural_columns_are_known_but_neither_class(self, stand_in) -> None: + tables = {"person": pd.DataFrame(columns=sorted(STRUCTURAL_COLUMNS))} + assert stand_in.known_variables(STRUCTURAL_COLUMNS) == STRUCTURAL_COLUMNS + assert stand_in.computed_at_2024(tables) == frozenset() + assert stand_in.inputs_at_2024(tables) == frozenset() + + def test_lock_inputs_the_clauses_read_are_inputs(self, stand_in) -> None: + names = [ + "age", + "employer_sponsored_insurance_premiums", + SPM_ROLE, + "takes_up_ssi_if_eligible", + "congressional_district_geoid", + "tip_income", + ] + tables = {"person": pd.DataFrame(columns=names)} + assert stand_in.inputs_at_2024(tables) == set(names) + + +# ------------------------------------------------ PR 1's key digest (Q7) + + +class TestKeysDigest: + def test_keys_sha256_is_public_and_is_the_manifest_rule(self) -> None: + assert "keys_sha256" in selection.__all__ + assert not hasattr(selection, "_keys_sha256") + keys = ["2024|cps:2", "2023|cps:1", "acs:9"] + assert ( + selection.keys_sha256(keys) + == hashlib.sha256("\n".join(sorted(keys)).encode("utf-8")).hexdigest() + ) + + +# ---------------------------------------------- the generated population + + +class TestGeneratedPopulation: + def test_is_deterministic_in_its_seed(self) -> None: + first, again, other = (generate_population(seed) for seed in (3, 3, 4)) + for entity in US_SCHEMA.entities: + pd.testing.assert_frame_equal( + first.cps_tables[entity], again.cps_tables[entity] + ) + pd.testing.assert_frame_equal( + first.acs_tables[entity], again.acs_tables[entity] + ) + assert first.cps_keys == again.cps_keys + assert first.cps_keys != other.cps_keys + + def test_cps_rows_carry_route_a_labels(self, population) -> None: + multiplier = population.clone_multiplier + for entity in US_SCHEMA.entities: + table = population.cps_tables[entity] + ids = table[US_SCHEMA.entity_id_column(entity)].to_numpy() + channel = table[support_channel_column(entity)].to_numpy() + clone = table[support_clone_index_column(entity)].to_numpy() + source = table[support_source_id_column(entity)].to_numpy() + assert set(clone) == {0, 1, 2} + assert ((channel == BASE_ASEC_SUPPORT_CHANNEL) == (clone == 0)).all() + assert set(channel[clone > 0]) == {PUF_TAX_DETAIL_SUPPORT_CHANNEL} + # puf_support._remap_ids, then the tail's one more multiplier. + assert (ids == source + clone * multiplier).all() + assert set(source[clone > 0]) <= set(ids[clone == 0]) + assert spine_source_id_column(entity) not in table + assert f"{entity}_spine" not in table + + def test_acs_rows_carry_staging_labels(self, population) -> None: + for entity in US_SCHEMA.entities: + table = population.acs_tables[entity] + id_column = US_SCHEMA.entity_id_column(entity) + cps_ids = population.cps_tables[entity][id_column] + assert (table[support_channel_column(entity)] == ACS_2024_1YR_SPINE).all() + assert (table[f"{entity}_spine"] == ACS_2024_1YR_SPINE).all() + assert (table[support_clone_index_column(entity)] == 0).all() + shift = table[id_column] - table[support_source_id_column(entity)] + assert set(shift) == {population.acs_id_offsets[entity]} + assert table[id_column].min() == cps_ids.max() + 1 + assert spine_source_id_column(entity) not in table + person = population.acs_tables["person"] + for group in US_SCHEMA.group_entities: + membership = person[US_SCHEMA.membership_column(group)] + assert set(membership) == set( + population.acs_tables[group][US_SCHEMA.id_column(group)] + ) + + def test_raw_lineage_columns(self, population) -> None: + cps = population.cps_tables["person"] + native = cps[cps[support_clone_index_column("person")] == 0] + peridnum = native["PERIDNUM"] + assert peridnum.str.fullmatch(r"[1-9][0-9]{21}").all() + assert peridnum.is_unique + assert (native["source_person_id"] == peridnum).all() + assert ( + peridnum.str[:20].groupby(native["person_household_id"]).nunique() == 1 + ).all() + assert set(native["source_year"]) == {2023, 2024} + assert ( + len(population.cps_keys) + == len(set(population.cps_keys)) + == len( + population.cps_tables["household"].query( + "household_support_clone_index == 0" + ) + ) + ) + + household = population.acs_tables["household"] + person = population.acs_tables["person"] + assert household["SERIALNO"].is_unique + assert set(household["TYPEHUGQ"]) == {1, 2, 3} + serial = person["person_household_id"].map( + household.set_index("household_id")["SERIALNO"] + ) + assert ( + not pd.DataFrame({"s": serial, "o": person["SPORDER"]}).duplicated().any() + ) + assert (person["source_person_id"] == person["SPORDER"].astype(str)).all() + assert (person["source_year"] == 2024).all() + native_household = person["person_household_id"].map( + household.set_index("household_id")["household_source_id"] + ) + assert (person["source_household_id"] == native_household).all() + assert population.acs_keys == tuple( + f"acs:{value}" for value in household["SERIALNO"] + ) + + def test_districts_carry_their_state_prefix(self, frame) -> None: + household = frame.table("household") + cd = household["congressional_district_geoid"] + assert (cd > 0).all() + assert (cd // 100 == household["state_fips"]).all() + + def test_tail_columns_on_every_tax_unit(self, population, frame) -> None: + tax_unit = frame.table("tax_unit") + for column in TAIL_PROVENANCE_DEFAULTS: + assert tax_unit[column].notna().all(), column + applied = tax_unit[PUF_CAPITAL_GAINS_TAIL_APPLIED_COLUMN].to_numpy() + clone = tax_unit[support_clone_index_column("tax_unit")].to_numpy() + assert applied.any() + assert (clone[applied] == 2).all() + donors = tax_unit.loc[applied, PUF_CAPITAL_GAINS_TAIL_DONOR_SOURCE_ID_COLUMN] + assert set(donors) == population.tail_donor_ids + assert ( + tax_unit.loc[~applied, PUF_CAPITAL_GAINS_TAIL_DONOR_SOURCE_ID_COLUMN] == -1 + ).all() + + def test_every_person_resolves_to_one_row_per_group(self, frame) -> None: + person = frame.table("person") + assert person["person_id"].is_unique + for group in US_SCHEMA.group_entities: + table = frame.table(group) + assert table[US_SCHEMA.id_column(group)].is_unique + joined = person[US_SCHEMA.membership_column(group)].map( + table.set_index(US_SCHEMA.id_column(group))[ + support_channel_column(group) + ] + ) + assert (joined == person[support_channel_column("person")]).all() + + def test_shared_columns_keep_one_dtype(self, population, frame) -> None: + for entity in US_SCHEMA.entities: + cps = population.cps_tables[entity] + acs = population.acs_tables[entity] + for column in set(cps.columns) & set(acs.columns): + assert cps[column].dtype == acs[column].dtype, (entity, column) + assert frame.table("person")[SPM_ROLE].dtype == np.dtype(bool) + + @pytest.mark.parametrize("seed", _SEEDS) + def test_spm_composition_passes(self, seed) -> None: + result = check_spm_composition(joined_frame(generate_population(seed))) + assert result.status == "PASS", result.failures + assert result.details["role_source"] == "source_column" + + def test_a_role_classifies_an_adult_on_its_own(self, frame) -> None: + # The ACS household headed by a 17-year-old passes only through the role. + person = frame.table("person") + minor_heads = person[(person["age"] == 17) & person[SPM_ROLE]] + assert len(minor_heads) == 1 + unit = minor_heads["person_spm_unit_id"].iloc[0] + assert (person.loc[person["person_spm_unit_id"] == unit, "age"] < 18).all() + + @pytest.mark.parametrize("seed", _SEEDS) + def test_role_signal_gate_passes_with_a_record_by_its_rule(self, seed) -> None: + frame = joined_frame(generate_population(seed)) + gated = with_spm_role_record(frame, spm_role_gate_record(frame)) + result = us_spm_independence_role_signal_gate(gated) + assert result.passed, result.failures + share, minor_share = role_shares(frame) + assert result.details["role_share"] == pytest.approx(share) + assert result.details["minor_role_share"] == pytest.approx(minor_share) + lower, upper = result.details["minor_role_share_band"] + assert lower < minor_share < upper + + def test_role_signal_gate_fails_without_the_record(self, frame) -> None: + result = us_spm_independence_role_signal_gate(frame) + assert not result.passed + assert "no source derivation provenance" in " ".join(result.failures) + + def test_assembly_validator_passes_on_a_clone_zero_record(self, frame) -> None: + record = clone_zero_assembly_record(frame) + assembled = Frame( + {entity: frame.table(entity) for entity in frame.entities}, + frame.schema, + {"household": frame.weights_for("household")}, + frame.strata, + mass_log=frame.mass_log, + metadata={**frame.metadata, **record}, + ) + manifest = validate_assembly_provenance(assembled, boundary="phase 0 test") + assert tuple(manifest["channels"]) == ASSEMBLED_CHANNELS + counts = manifest["native_row_counts"] + assert all( + counts[entity][PUF_TAX_DETAIL_SUPPORT_CHANNEL] == 0 + for entity in US_SCHEMA.entities + ) + + def test_stored_columns_are_engine_variables_or_registered( + self, frame, stand_in + ) -> None: + columns = { + column for entity in frame.entities for column in frame.table(entity) + } + assert ( + undefined_stored_inputs( + columns, + engine_variables=stand_in.known_variables(columns), + register=US_STORED_NON_VARIABLE_COLUMNS, + ) + == () + ) + + def test_no_column_is_computed_at_2024(self, frame, stand_in) -> None: + tables = {entity: frame.table(entity) for entity in frame.entities} + assert stand_in.computed_at_2024(tables) == frozenset() + + def test_inputs_are_filled_except_the_release_written( + self, frame, stand_in + ) -> None: + tables = {entity: frame.table(entity) for entity in frame.entities} + inputs = stand_in.inputs_at_2024(tables) + assert {"age", SPM_ROLE, "employer_sponsored_insurance_premiums"} <= inputs + nulls = { + column + for table in tables.values() + for column in inputs & set(table.columns) + if table[column].isna().any() + } + assert nulls == RELEASE_WRITTEN_ON_ACS + person = frame.table("person") + acs = person[support_channel_column("person")] == ACS_2024_1YR_SPINE + for column in RELEASE_WRITTEN_ON_ACS: + assert person.loc[acs, column].isna().all() + assert person.loc[~acs, column].notna().all() + + def test_raw_upper_case_columns_sit_on_one_origin(self, frame) -> None: + person = frame.table("person") + household = frame.table("household") + acs = person[support_channel_column("person")] == ACS_2024_1YR_SPINE + acs_household = ( + household[support_channel_column("household")] == ACS_2024_1YR_SPINE + ) + for column in ("SSI_VAL", "PERIDNUM"): + assert person.loc[acs, column].isna().all() + assert person.loc[~acs, column].notna().all() + assert person.loc[acs, "SPORDER"].notna().all() + assert person.loc[~acs, "SPORDER"].isna().all() + for column in ("SERIALNO", "TYPEHUGQ"): + assert household.loc[acs_household, column].notna().all() + assert household.loc[~acs_household, column].isna().all() + + +class TestStagingUnionForm: + """The ACS tables in staging's pooled form: every CPS column, all null.""" + + def test_acs_rows_gain_every_cps_column_all_null(self, population) -> None: + union = with_staging_union_columns(population) + for entity in US_SCHEMA.entities: + trimmed = population.acs_tables[entity] + pooled = union.acs_tables[entity] + cps_only = set(population.cps_tables[entity]) - set(trimmed) + assert set(pooled) == set(trimmed) | set(population.cps_tables[entity]) + for column in cps_only: + assert pooled[column].isna().all(), (entity, column) + for column in trimmed: + assert ( + pooled[column].astype(object).tolist() + == trimmed[column].astype(object).tolist() + ), (entity, column) + person = union.acs_tables["person"] + assert person["takes_up_ssi_if_eligible"].isna().all() + # An ACS-only integer column comes back as float64 from staging. + assert person["SPORDER"].dtype == np.dtype("float64") + assert union.acs_tables["household"]["TYPEHUGQ"].dtype == np.dtype("float64") + + def test_union_form_passes_the_same_checks(self, population) -> None: + frame = joined_frame(with_staging_union_columns(population)) + assert check_spm_composition(frame).status == "PASS" + gated = with_spm_role_record(frame, spm_role_gate_record(frame)) + assert us_spm_independence_role_signal_gate(gated).passed + assembled = Frame( + {entity: frame.table(entity) for entity in frame.entities}, + frame.schema, + {"household": frame.weights_for("household")}, + frame.strata, + mass_log=frame.mass_log, + metadata={**frame.metadata, **clone_zero_assembly_record(frame)}, + ) + validate_assembly_provenance(assembled, boundary="phase 0 union test") + + +# --------------------------------- phase 1: the provenance rewrite (P1-P8) + +_FORMS = ("trimmed", "union") + + +def _form(population, form: str): + return with_staging_union_columns(population) if form == "union" else population + + +@pytest.fixture(scope="module", params=_FORMS) +def rewritten(request, population): + """(input population, rewritten frame) in the trimmed and union forms.""" + + source = _form(population, request.param) + return source, assembled_frame(source) + + +def _by_id(table: pd.DataFrame, entity: str) -> pd.DataFrame: + return table.set_index(US_SCHEMA.entity_id_column(entity), drop=False) + + +def _acs_rows(table: pd.DataFrame, entity: str) -> pd.DataFrame: + return table[table[support_channel_column(entity)] == ACS_SUPPORT_CHANNEL] + + +def _person_lineage(frame: Frame) -> dict[tuple[int, int], tuple[str, int]]: + """The frame's ACS lineage in staging's keyed form, read off the frame. + + Each ACS person's native (household id, person id), its household's and + its own ``_spine_source_id`` after the rewrite, to its + (``SERIALNO``, ``SPORDER``). + """ + + household = frame.table("household").set_index("household_id") + person = _acs_rows(frame.table("person"), "person") + link = person["person_household_id"] + return { + (int(native_household), int(native_person)): (serial, int(sporder)) + for native_household, native_person, serial, sporder in zip( + link.map(household[spine_source_id_column("household")]).tolist(), + person[spine_source_id_column("person")].tolist(), + link.map(household["SERIALNO"]).tolist(), + person["SPORDER"].tolist(), + strict=True, + ) + } + + +class TestProvenanceRewrite: + def test_returns_a_frame_with_only_the_clone_zero_record(self, rewritten) -> None: + _, frame = rewritten + assert isinstance(frame, Frame) + assert set(frame.metadata) == {SPINE_ASSEMBLY_MANIFEST_KEY} + assert frame.mass_log == () + record = frame.metadata[SPINE_ASSEMBLY_MANIFEST_KEY] + expected = clone_zero_assembly_record(frame)[SPINE_ASSEMBLY_MANIFEST_KEY] + assert tuple(record["channels"]) == ASSEMBLED_CHANNELS + assert { + entity: dict(counts) + for entity, counts in record["native_row_counts"].items() + } == expected["native_row_counts"] + + def test_cps_rows_keep_route_a_labels_and_gain_the_spine_id( + self, rewritten + ) -> None: + population, frame = rewritten + for entity in US_SCHEMA.entities: + before = _by_id(population.cps_tables[entity], entity) + after = _by_id(frame.table(entity), entity).loc[before.index] + for column in ( + support_source_id_column(entity), + support_channel_column(entity), + support_clone_index_column(entity), + ): + assert after[column].tolist() == before[column].tolist(), column + assert ( + after[spine_source_id_column(entity)].tolist() + == before[support_source_id_column(entity)].tolist() + ) + assert (after[f"{entity}_spine"] == CPS_SPINE_TAG).all() + + def test_no_row_is_labelled_acs_and_every_row_has_a_spine_tag( + self, rewritten + ) -> None: + # P3: the predictor join's "acs" channel is never written. + _, frame = rewritten + for entity in US_SCHEMA.entities: + table = frame.table(entity) + assert "acs" not in set(table[support_channel_column(entity)]) + assert table[f"{entity}_spine"].notna().all() + acs = table[support_channel_column(entity)] == ACS_SUPPORT_CHANNEL + assert (table.loc[acs, f"{entity}_spine"] == ACS_SUPPORT_CHANNEL).all() + assert (table.loc[~acs, f"{entity}_spine"] == CPS_SPINE_TAG).all() + + def test_household_weights_follow_their_households(self, rewritten) -> None: + population, frame = rewritten + expected = { + **dict( + zip( + population.cps_tables["household"]["household_id"].tolist(), + population.cps_household_weights.tolist(), + strict=True, + ) + ), + **dict( + zip( + population.acs_tables["household"]["household_id"].tolist(), + population.acs_household_weights.tolist(), + strict=True, + ) + ), + } + weights = frame.weights_for("household") + assert weights.kind is WeightKind.IMPORTANCE + actual = dict( + zip( + frame.table("household")["household_id"].tolist(), + weights.values.tolist(), + strict=True, + ) + ) + assert actual == expected + ids = frame.table("household")["household_id"].to_numpy() + assert (np.diff(ids) > 0).all() + + def test_weights_follow_households_through_a_real_sort(self, population) -> None: + # The generated tables arrive sorted, so the sort above is the + # identity. Here both origins' household rows (with their weights) + # and one other group table come in shuffled. + rng = np.random.default_rng(7) + cps = {entity: table.copy() for entity, table in population.cps_tables.items()} + acs = {entity: table.copy() for entity, table in population.acs_tables.items()} + cps_order = rng.permutation(len(cps["household"])) + acs_order = rng.permutation(len(acs["household"])) + cps["household"] = cps["household"].iloc[cps_order].reset_index(drop=True) + acs["household"] = acs["household"].iloc[acs_order].reset_index(drop=True) + cps["tax_unit"] = cps["tax_unit"].iloc[::-1].reset_index(drop=True) + cps_weights = population.cps_household_weights[cps_order] + acs_weights = population.acs_household_weights[acs_order] + frame = to_assembled_provenance( + cps, + acs, + cps_household_weights=cps_household_weight_series( + cps["household"], cps_weights + ), + acs_household_weights=acs_household_weight_series( + acs["household"], acs_weights + ), + staging_lineage=staging_lineage(population), + ) + given = np.concatenate( + [cps["household"]["household_id"], acs["household"]["household_id"]] + ) + expected = dict( + zip( + given.tolist(), + np.concatenate([cps_weights, acs_weights]).tolist(), + strict=True, + ) + ) + household = frame.table("household")["household_id"].to_numpy() + assert household.tolist() != given.tolist() + assert (np.diff(household) > 0).all() + assert (np.diff(frame.table("tax_unit")["tax_unit_id"].to_numpy()) > 0).all() + actual = dict( + zip( + household.tolist(), + frame.weights_for("household").values.tolist(), + strict=True, + ) + ) + assert actual == expected + # Same frame as the sorted inputs give, row for row. + reference = assembled_frame(population) + for entity in US_SCHEMA.entities: + pd.testing.assert_frame_equal( + frame.table(entity), reference.table(entity), check_like=True + ) + np.testing.assert_array_equal( + frame.weights_for("household").values, + reference.weights_for("household").values, + ) + + @pytest.mark.parametrize("form", ("series", "mapping")) + def test_weights_are_tied_to_households_by_key(self, population, form) -> None: + # d2283 lead call L3's hazard: PR 1's ACS starting weights come in + # selection order and staging's households in id order. Keyed + # weights in another order than the tables' still give each + # household its own weight; by position they would not. + rng = np.random.default_rng(11) + cps = population.keyed_cps_household_weights + acs = population.keyed_acs_household_weights + cps = cps.iloc[rng.permutation(len(cps))] + acs = acs.iloc[::-1] + assert not np.array_equal(acs.to_numpy(), population.acs_household_weights) + assert not np.array_equal(cps.to_numpy(), population.cps_household_weights) + if form == "mapping": + cps, acs = dict(cps.items()), dict(acs.items()) + frame = to_assembled_provenance( + population.cps_tables, + population.acs_tables, + cps_household_weights=cps, + acs_household_weights=acs, + staging_lineage=staging_lineage(population), + ) + np.testing.assert_array_equal( + frame.weights_for("household").values, + assembled_frame(population).weights_for("household").values, + ) + + def test_a_serialno_swap_cannot_trade_weights(self, population) -> None: + # PR #1685 review, blocking 2: two households of equal size, weighted + # 10 and 90, trade SERIALNO. The persons' (SERIALNO, SPORDER) set is + # unchanged, which is all the old set-of-pairs check compared, and + # the weights stay keyed by SERIALNO, so each household would have + # taken the other's weight. Staging's lineage, keyed by native ids, + # refuses the swap before any weight is looked up. + acs = _serialno_swaps_between_households(population)["acs"] + before = population.acs_tables["household"]["SERIALNO"] + swapped = acs["household"]["SERIALNO"].ne(before).to_numpy() + assert int(swapped.sum()) == 2 + weights = population.keyed_acs_household_weights.copy() + low, high = (selection.acs_unit_key(serial) for serial in before[swapped]) + weights.loc[low], weights.loc[high] = 10.0, 90.0 + moved = staging_lineage(dataclasses.replace(population, acs_tables=acs)) + assert set(moved.values()) == set(staging_lineage(population).values()) + assert moved != staging_lineage(population) + with pytest.raises( + OnePopulationContractError, + match=re.escape("0 extra (such as []), 4 moved (such as ["), + ): + to_assembled_provenance( + population.cps_tables, + acs, + cps_household_weights=population.keyed_cps_household_weights, + acs_household_weights=weights, + staging_lineage=staging_lineage(population), + ) + + def test_the_lineage_refusal_precedes_a_missing_weight(self, population) -> None: + # PR #1685 review r2, nit 2: the serial swap plus a keyed weight map + # missing one household. P7 compares the lineage before any weight is + # looked up, so its moved-pair diagnostic comes first; a keyed + # comparison delayed past the weight lookup would report the missing + # weight instead. + acs = _serialno_swaps_between_households(population)["acs"] + before = population.acs_tables["household"]["SERIALNO"] + swapped = acs["household"]["SERIALNO"].ne(before).to_numpy() + traded = {selection.acs_unit_key(serial) for serial in before[swapped]} + weights = population.keyed_acs_household_weights + dropped = next(key for key in weights.index if key not in traded) + weights = weights.drop(dropped) + assert len(weights) == len(acs["household"]) - 1 + with pytest.raises( + OnePopulationContractError, + match=re.escape("0 extra (such as []), 4 moved (such as ["), + ): + _rewrite(population, {"acs": acs, "acs_weights": weights}) + + def test_inputs_are_not_mutated(self, population) -> None: + cps = {entity: table.copy() for entity, table in population.cps_tables.items()} + acs = {entity: table.copy() for entity, table in population.acs_tables.items()} + assembled_frame(population) + for entity in US_SCHEMA.entities: + pd.testing.assert_frame_equal(population.cps_tables[entity], cps[entity]) + pd.testing.assert_frame_equal(population.acs_tables[entity], acs[entity]) + + +class TestRewriteInvariants: + """X3: after the rewrite, across both origins.""" + + def test_source_id_and_rank_are_unique_across_origins(self, rewritten) -> None: + _, frame = rewritten + for entity in US_SCHEMA.entities: + table = frame.table(entity) + pairs = pd.DataFrame( + { + "source": table[support_source_id_column(entity)].to_numpy(), + "rank": support_copy_rank_series(table, entity=entity).to_numpy(), + } + ) + assert not pairs.duplicated().any(), entity + # Both origins are present, so uniqueness is across them. + assert set(table[support_channel_column(entity)]) == set(ASSEMBLED_CHANNELS) + + def test_every_acs_spine_id_is_its_native_id(self, rewritten) -> None: + population, frame = rewritten + for entity in US_SCHEMA.entities: + native = _by_id(population.acs_tables[entity], entity) + after = _by_id(_acs_rows(frame.table(entity), entity), entity) + assert sorted(after.index) == sorted(native.index) + after = after.loc[native.index] + # Native id: staging's source id before the rewrite. + assert ( + after[spine_source_id_column(entity)].tolist() + == native[support_source_id_column(entity)].tolist() + ) + # The new source id is the pooled id. + assert ( + after[support_source_id_column(entity)].tolist() + == after[US_SCHEMA.entity_id_column(entity)].tolist() + ) + assert (after[support_clone_index_column(entity)] == 0).all() + + def test_every_acs_serialno_and_sporder_survives(self, rewritten) -> None: + population, frame = rewritten + assert _person_lineage(frame) == staging_lineage(population) + native = _by_id(population.acs_tables["household"], "household") + after = _by_id(frame.table("household"), "household").loc[native.index] + assert after["SERIALNO"].tolist() == native["SERIALNO"].tolist() + assert after["TYPEHUGQ"].tolist() == native["TYPEHUGQ"].tolist() + + +class TestAssembledValidators: + """X6: the readers that check assembled provenance accept the frame.""" + + @pytest.mark.parametrize("seed", _SEEDS) + @pytest.mark.parametrize("form", _FORMS) + def test_validator_passes_on_three_channels_with_clones(self, seed, form) -> None: + population = _form(generate_population(seed), form) + frame = assembled_frame(population) + manifest = validate_assembly_provenance(frame, boundary="phase 1 test") + assert tuple(manifest["channels"]) == ASSEMBLED_CHANNELS + counts = manifest["native_row_counts"] + for entity in US_SCHEMA.entities: + cps = population.cps_tables[entity] + clone = cps[support_clone_index_column(entity)] + assert dict(counts[entity]) == { + BASE_ASEC_SUPPORT_CHANNEL: int((clone == 0).sum()), + PUF_TAX_DETAIL_SUPPORT_CHANNEL: 0, + ACS_SUPPORT_CHANNEL: len(population.acs_tables[entity]), + } + assert set(clone) == {0, 1, 2} + require_assembled_support_provenance(frame.table(entity), entity=entity) + + def test_spine_agreement_gate_does_not_raise_with_the_record( + self, rewritten + ) -> None: + _, frame = rewritten + result = spine_agreement_gate(frame) + assert isinstance(result, GateResult) + # It fails, but as a result: puf_tax_detail is a clone role to it. + assert not result.passed + assert any("clone role" in failure for failure in result.failures) + + def test_spine_agreement_gate_raises_without_the_record(self, rewritten) -> None: + _, frame = rewritten + bare = Frame( + {entity: frame.table(entity) for entity in frame.entities}, + frame.schema, + {"household": frame.weights_for("household")}, + frame.strata, + ) + with pytest.raises(ValueError, match="has no assembly manifest"): + spine_agreement_gate(bare) + + +# ------------------------------------------------ X4: a Route A fixture + + +@pytest.fixture(scope="module") +def route_a(): + """A Route A base made by the production operators, not by hand. + + ``clone_us_frame_for_puf_support`` clones the release-base ASEC fixture + (``us_release_base_input.asec_frame``) into native rows (clone 0, + ``asec``) and PUF tax-detail copies (clone 1, ``puf_tax_detail``) on all + six entities, and ``with_capital_gains_tail_copies`` adds tail copies + (clone 2) through ``puf_capital_gains_tail._clone_and_transfer``. The + generator's CPS half restates the same rules by hand; this fixture is + used so the differential does not rest on that restatement. + """ + + from microcosm.build.us_runtime.puf_support import clone_us_frame_for_puf_support + from test_support.microcosm_build.us_release_base_input import asec_frame + from test_support.microcosm_build.us_tail_clone_fixtures import ( + with_capital_gains_tail_copies, + ) + + cloned = clone_us_frame_for_puf_support(asec_frame(40, seed=5)) + household = cloned.table("household") + sources = household.loc[ + household["household_support_clone_index"] == 1, "household_source_id" + ].tolist()[::9] + return with_capital_gains_tail_copies(cloned, sources) + + +def test_role_readers_match_route_a_with_no_acs_row(route_a, population) -> None: + """X4: with no ACS row, the role readers return Route A's series. + + The Route A fixture is built by the production clone and tail operators + (see ``route_a``), not from the generator's hand-written CPS half, so the + differential does not rest on the generator restating Route A's labels. + The ACS input is the generator's ACS tables cut to zero rows. + """ + + tables = {entity: route_a.table(entity) for entity in route_a.entities} + empty_acs = { + entity: population.acs_tables[entity].iloc[:0] for entity in US_SCHEMA.entities + } + frame = to_assembled_provenance( + tables, + empty_acs, + cps_household_weights=cps_household_weight_series( + route_a.table("household"), route_a.weights_for("household").values + ), + acs_household_weights={}, + staging_lineage={}, + ) + for entity in US_SCHEMA.entities: + before, after = tables[entity], frame.table(entity) + id_column = US_SCHEMA.entity_id_column(entity) + assert spine_source_id_column(entity) not in before + assert spine_source_id_column(entity) in after + assert set(before[support_clone_index_column(entity)]) == {0, 1, 2} + for column in before: + assert after[column].dtype == before[column].dtype, (entity, column) + for reader in ( + support_role_series, + support_gate_source_channel_series, + support_copy_rank_series, + ): + expected = pd.Series( + reader(before, entity=entity).to_numpy(), + index=before[id_column].to_numpy(), + ).sort_index() + actual = pd.Series( + reader(after, entity=entity).to_numpy(), + index=after[id_column].to_numpy(), + ).sort_index() + pd.testing.assert_series_equal(actual, expected, check_names=False) + validate_assembly_provenance(frame, boundary="phase 1 X4") + assert dict( + zip( + frame.table("household")["household_id"].tolist(), + frame.weights_for("household").values.tolist(), + strict=True, + ) + ) == dict( + zip( + tables["household"]["household_id"].tolist(), + route_a.weights_for("household").values.tolist(), + strict=True, + ) + ) + + +# ------------------------------------ refusals: one per P5, P6, P6b, P7 rule + + +def _copies(population, origin: str) -> dict[str, pd.DataFrame]: + tables = population.cps_tables if origin == "cps" else population.acs_tables + return {entity: table.copy() for entity, table in tables.items()} + + +def _set(table: pd.DataFrame, row: int, column: str, value: object) -> None: + """Set one cell, upcasting the column to object when the dtype refuses.""" + + try: + table.loc[table.index[row], column] = value + except (TypeError, ValueError): + table[column] = table[column].astype(object) + table.loc[table.index[row], column] = value + + +def _first(table: pd.DataFrame, entity: str, clone: int) -> int: + rows = np.flatnonzero(table[support_clone_index_column(entity)].to_numpy() == clone) + return int(rows[0]) + + +def _cps_missing_column(p): + cps = _copies(p, "cps") + cps["household"] = cps["household"].drop(columns=["household_support_channel"]) + return {"cps": cps} + + +def _cps_null_source(p): + cps = _copies(p, "cps") + _set(cps["person"], 0, "person_source_id", None) + return {"cps": cps} + + +def _cps_non_integer_source(p): + cps = _copies(p, "cps") + _set(cps["person"], 0, "person_source_id", 1.5) + return {"cps": cps} + + +def _cps_unknown_channel(p): + cps = _copies(p, "cps") + table = cps["tax_unit"] + _set(table, _first(table, "tax_unit", 1), "tax_unit_support_channel", "acs") + return {"cps": cps} + + +def _cps_asec_on_a_clone(p): + cps = _copies(p, "cps") + table = cps["spm_unit"] + _set(table, _first(table, "spm_unit", 1), "spm_unit_support_channel", "asec") + return {"cps": cps} + + +def _cps_clone_index_three(p): + cps = _copies(p, "cps") + table = cps["family"] + _set(table, _first(table, "family", 2), "family_support_clone_index", 3) + return {"cps": cps} + + +def _cps_spine_source_present(p): + cps = _copies(p, "cps") + table = cps["marital_unit"] + table["marital_unit_spine_source_id"] = table["marital_unit_source_id"] + return {"cps": cps} + + +def _cps_wrong_spine_tag(p): + cps = _copies(p, "cps") + cps["household"]["household_spine"] = ACS_SUPPORT_CHANNEL + return {"cps": cps} + + +def _acs_missing_column(p): + acs = _copies(p, "acs") + acs["tax_unit"] = acs["tax_unit"].drop(columns=["tax_unit_support_clone_index"]) + return {"acs": acs} + + +def _acs_null_channel(p): + acs = _copies(p, "acs") + _set(acs["spm_unit"], 0, "spm_unit_support_channel", None) + return {"acs": acs} + + +def _acs_channel_acs(p): + acs = _copies(p, "acs") + acs["person"]["person_support_channel"] = "acs" + return {"acs": acs} + + +def _acs_clone_index(p): + acs = _copies(p, "acs") + _set(acs["household"], 0, "household_support_clone_index", 1) + return {"acs": acs} + + +def _acs_offset_varies(p): + acs = _copies(p, "acs") + _set( + acs["family"], + 0, + "family_source_id", + int(acs["family"]["family_source_id"].iloc[0]) + 1, + ) + return {"acs": acs} + + +def _acs_spine_source_present(p): + acs = _copies(p, "acs") + table = acs["household"] + table["household_spine_source_id"] = table["household_source_id"] + return {"acs": acs} + + +def _acs_wrong_spine_tag(p): + acs = _copies(p, "acs") + _set(acs["person"], 0, "person_spine", CPS_SPINE_TAG) + return {"acs": acs} + + +def _acs_null_spine_tag(p): + acs = _copies(p, "acs") + _set(acs["tax_unit"], 0, "tax_unit_spine", None) + return {"acs": acs} + + +def _acs_spine_tag_absent(p): + acs = _copies(p, "acs") + acs["household"] = acs["household"].drop(columns=["household_spine"]) + return {"acs": acs} + + +def _acs_weights_by_position(p): + # PR 1's StartingWeights.acs as it comes: an array in selection order. + return {"acs_weights": p.acs_household_weights} + + +def _cps_weights_by_position(p): + return {"cps_weights": p.cps_household_weights.tolist()} + + +def _acs_weight_key_repeats(p): + weights = p.keyed_acs_household_weights + return {"acs_weights": pd.concat([weights, weights.iloc[:1]])} + + +def _acs_household_without_a_weight(p): + return {"acs_weights": p.keyed_acs_household_weights.iloc[1:]} + + +def _serialno_not_a_clean_key(p): + # P7 takes any non-empty, unique SERIALNO; the weight key needs a clean + # one, so staging's own lineage is made to agree with it. + acs = _copies(p, "acs") + serial = acs["household"]["SERIALNO"].iloc[0] + _set(acs["household"], 0, "SERIALNO", f"{serial}|x") + lineage = staging_lineage(dataclasses.replace(p, acs_tables=acs)) + return {"acs": acs, "lineage": lineage} + + +def _cps_weight_names_no_household(p): + weights = p.keyed_cps_household_weights + extra = pd.Series([1.0], index=[int(weights.index.max()) + 1]) + return {"cps_weights": pd.concat([weights, extra])} + + +def _cps_weight_negative(p): + weights = p.keyed_cps_household_weights.copy() + weights.iloc[0] = -1.0 + return {"cps_weights": weights} + + +def _acs_weight_not_finite(p): + weights = dict(p.keyed_acs_household_weights.items()) + weights[next(iter(weights))] = np.nan + return {"acs_weights": weights} + + +def _acs_weight_complex(p): + # Review r3, should-fix 2: the float64 conversion dropped the imaginary + # part, with only a ComplexWarning, and kept the real weight. + weights = p.keyed_acs_household_weights.astype(np.complex128) + weights.iloc[0] += 1j + return {"acs_weights": weights} + + +def _cps_weight_numpy_complex(p): + weights = dict(p.keyed_cps_household_weights.items()) + first = next(iter(weights)) + weights[first] = np.complex128(weights[first] + 1j) + return {"cps_weights": weights} + + +def _cps_weight_timedelta(p): + # The float64 conversion read each weight as its count of nanoseconds. + weights = p.keyed_cps_household_weights + return { + "cps_weights": pd.Series( + pd.to_timedelta(weights.to_numpy(), unit="ns"), index=weights.index + ) + } + + +def _ids_collide_across_origins(p): + # Staged on another donor: staging gave the ACS tax units no offset, so + # their native ids sit on the export's. + acs = _copies(p, "acs") + offset = p.acs_id_offsets["tax_unit"] + acs["tax_unit"]["tax_unit_id"] -= offset + acs["person"]["person_tax_unit_id"] -= offset + return {"acs": acs} + + +def _membership_crosses_origins(p): + acs = _copies(p, "acs") + person = acs["person"] + sizes = person["person_spm_unit_id"].map( + person["person_spm_unit_id"].value_counts() + ) + row = int(np.flatnonzero(sizes.to_numpy() > 1)[0]) + cps_unit = int(p.cps_tables["spm_unit"]["spm_unit_id"].iloc[0]) + _set(person, row, "person_spm_unit_id", cps_unit) + return {"acs": acs} + + +def _group_without_a_person(p): + acs = _copies(p, "acs") + family = acs["family"] + extra = family.iloc[[-1]].copy() + extra["family_id"] += 1 + extra["family_source_id"] += 1 + acs["family"] = pd.concat([family, extra], ignore_index=True) + return {"acs": acs} + + +def _rank_repeats_within_cps(p): + cps = _copies(p, "cps") + table = cps["person"] + _set(table, _first(table, "person", 2), "person_support_clone_index", 1) + return {"cps": cps} + + +def _rank_repeats_across_origins(p): + cps = _copies(p, "cps") + acs_id = int(p.acs_tables["household"]["household_id"].iloc[0]) + table = cps["household"] + _set(table, _first(table, "household", 0), "household_source_id", acs_id) + return {"cps": cps} + + +def _serialno_column_missing(p): + acs = _copies(p, "acs") + acs["household"] = acs["household"].drop(columns=["SERIALNO"]) + return {"acs": acs} + + +def _serialno_null(p): + acs = _copies(p, "acs") + _set(acs["household"], 0, "SERIALNO", None) + return {"acs": acs} + + +def _serialno_repeats(p): + acs = _copies(p, "acs") + _set(acs["household"], 1, "SERIALNO", acs["household"]["SERIALNO"].iloc[0]) + return {"acs": acs} + + +def _sporder_null(p): + acs = _copies(p, "acs") + _set(acs["person"], 0, "SPORDER", None) + return {"acs": acs} + + +def _sporder_repeats(p): + acs = _copies(p, "acs") + person = acs["person"] + second = int(np.flatnonzero(person["SPORDER"].to_numpy() == 2)[0]) + _set(person, second, "SPORDER", 1) + return {"acs": acs} + + +def _source_household_id_moves(p): + acs = _copies(p, "acs") + person = acs["person"] + _set( + person, + 0, + "source_household_id", + int(person["source_household_id"].iloc[0]) + 1000, + ) + return {"acs": acs} + + +def _source_person_id_moves(p): + acs = _copies(p, "acs") + _set(acs["person"], 0, "source_person_id", "99") + return {"acs": acs} + + +def _source_year_moves(p): + acs = _copies(p, "acs") + _set(acs["person"], 0, "source_year", 2023) + return {"acs": acs} + + +def _with_pd_na(table: pd.DataFrame, column: str, dtype: str) -> None: + """``column`` in pandas' nullable ``dtype``, with ``pd.NA`` in its first row.""" + + values = table[column].astype(dtype) + values.iloc[0] = pd.NA + table[column] = values + + +def _source_year_pd_na(p): + # PR #1685 review, should-fix 2: an Int64 pd.NA, which the old year + # check's mismatch sum skipped. + acs = _copies(p, "acs") + _with_pd_na(acs["person"], "source_year", "Int64") + return {"acs": acs} + + +def _source_person_id_pd_na(p): + # Should-fix 2: a nullable string's pd.NA, which the old comparison met + # with a bare TypeError. + acs = _copies(p, "acs") + _with_pd_na(acs["person"], "source_person_id", "string") + return {"acs": acs} + + +def _source_household_id_pd_na(p): + acs = _copies(p, "acs") + _with_pd_na(acs["person"], "source_household_id", "Int64") + return {"acs": acs} + + +def _minor_head_household(tables) -> object: + """The id of the generated ACS household headed by a 17-year-old (two persons).""" + + person = tables["person"] + heads = person.loc[ + person["person_support_channel"].eq(ACS_SUPPORT_CHANNEL).to_numpy() + & person["is_household_head"].to_numpy(dtype=bool) + & person["age"].eq(17).to_numpy(), + "person_household_id", + ] + assert len(heads) == 1 + household = heads.iloc[0] + assert int(person["person_household_id"].eq(household).sum()) == 2 + return household + + +def _swap_serialno(household: pd.DataFrame, first: int, second: int) -> None: + serials = household["SERIALNO"].tolist() + _set(household, first, "SERIALNO", serials[second]) + _set(household, second, "SERIALNO", serials[first]) + + +def _two_person_acs_households(tables) -> tuple[int, int]: + """Rows of the first two ACS households with two persons each. + + Their persons hold SPORDER 1 and 2, so a SERIALNO trade between them + keeps the set of (SERIALNO, SPORDER) pairs. + """ + + person = tables["person"] + acs = person["person_support_channel"].eq(ACS_SUPPORT_CHANNEL).to_numpy() + sizes = person.loc[acs, "person_household_id"].value_counts(sort=False) + pairs = sizes.index[sizes.eq(2).to_numpy()] + rows = np.flatnonzero(tables["household"]["household_id"].isin(pairs).to_numpy()) + first, second = (int(row) for row in rows[:2]) + return first, second + + +def _serialno_swaps_between_households(p): + # PR #1685 review, blocking 2: two households trade SERIALNO. Their + # persons' (SERIALNO, SPORDER) set holds, so the old set check passed + # the frame and each household took the other's weight (weights are + # keyed by SERIALNO). Keyed by native ids, all four persons' pairs + # moved. The review's households hold one person each; two persons each + # keep this case's count apart from the SPORDER swap's. + acs = _copies(p, "acs") + _swap_serialno(acs["household"], *_two_person_acs_households(acs)) + return {"acs": acs} + + +def _sporder_swaps_within_a_household(p): + # Blocking 2's second shape: two persons of one household trade SPORDER + # and, to keep source_person_id = str(SPORDER), source_person_id. + acs = _copies(p, "acs") + person = acs["person"] + first, second = ( + int(row) + for row in np.flatnonzero( + person["person_household_id"].eq(_minor_head_household(acs)).to_numpy() + ) + ) + for column in ("SPORDER", "source_person_id"): + values = person[column].tolist() + _set(person, first, column, values[second]) + _set(person, second, column, values[first]) + return {"acs": acs} + + +def _staging_has_a_person_the_selection_lost(p): + return {"lineage": {**staging_lineage(p), (999_999, 1): ("2024HU9999999", 1)}} + + +def _staging_lacks_a_selected_person(p): + lineage = staging_lineage(p) + first = min(lineage) + return {"lineage": {key: pair for key, pair in lineage.items() if key != first}} + + +def _staging_pair_malformed(p): + return {"lineage": {**staging_lineage(p), (999_999, 1): ("2024HU0000001",)}} + + +def _staging_key_malformed(p): + # A key that is not native ids (here a SERIALNO) cannot tie a pair to + # its person. + return {"lineage": {**staging_lineage(p), "2024HU0000001": ("2024HU0000001", 1)}} + + +def _staging_key_timedelta(p): + # PR #1685 review r2, should-fix 1, on staging's lineage: numpy derives + # timedelta64 from signedinteger, so int() read this key as the native + # ids it replaces and the lineage matched. + lineage = staging_lineage(p) + first = min(lineage) + pair = lineage.pop(first) + lineage[tuple(np.timedelta64(part, "ns") for part in first)] = pair + return {"lineage": lineage} + + +def _acs_tax_unit_spans_households(p): + # PR #1685 review, blocking 3: one ACS person joins a tax unit of another + # household. Its own tax unit keeps a member, so every id resolves (P6b) + # and every channel matches (the validator). + acs = _copies(p, "acs") + person = acs["person"] + row = int(np.flatnonzero(_household_sizes(person, "person_tax_unit_id") > 1)[0]) + household = person["person_household_id"].iloc[row] + elsewhere = person.loc[ + person["person_household_id"].ne(household), "person_tax_unit_id" + ] + _set(person, row, "person_tax_unit_id", elsewhere.iloc[0]) + return {"acs": acs} + + +def _cps_unit_spans_households(p, group: str): + # Blocking 3 on CPS rows: a native person joins another native + # household's ``group`` unit. Its own unit keeps a member, so every id + # resolves (P6b) and every channel matches (the validator). + cps = _copies(p, "cps") + person = cps["person"] + column = f"person_{group}_id" + native = person["person_support_clone_index"].eq(0).to_numpy() + sizes = _household_sizes(person, column) + row = int(np.flatnonzero(native & (sizes > 1))[0]) + household = person["person_household_id"].iloc[row] + elsewhere = native & person["person_household_id"].ne(household).to_numpy() + _set(person, row, column, person[column].iloc[int(np.flatnonzero(elsewhere)[0])]) + return {"cps": cps} + + +def _cps_family_spans_households(p): + return _cps_unit_spans_households(p, "family") + + +def _acs_household_holds_two_spm_units(p): + # Blocking 3's partition: one person of a two-or-more-person ACS + # household moves to an SPM unit of its own, inside the household. + # Staging's ACS role rule is defined only on one SPM unit per household. + acs = _copies(p, "acs") + person, spm_unit = acs["person"], acs["spm_unit"] + row = int(np.flatnonzero(_household_sizes(person, "person_household_id") > 1)[0]) + extra = spm_unit.iloc[[-1]].copy() + shift = int(spm_unit["spm_unit_id"].max()) + 1 - int(extra["spm_unit_id"].iloc[0]) + extra["spm_unit_id"] += shift + extra["spm_unit_source_id"] += shift + acs["spm_unit"] = pd.concat([spm_unit, extra], ignore_index=True) + _set(person, row, "person_spm_unit_id", int(extra["spm_unit_id"].iloc[0])) + return {"acs": acs} + + +def _merge_acs_spm_units( + person: pd.DataFrame, spm_unit: pd.DataFrame, acs: np.ndarray +) -> pd.DataFrame: + """Move every person of the first ACS household into the second's SPM unit. + + Edits ``person`` in place and returns ``spm_unit`` without the emptied + unit's row, so every membership still resolves and every unit holds a + person. Each household still holds one SPM unit, so only the forward + check (no unit holds persons of two households) sees the merger. + """ + + households = person.loc[acs, "person_household_id"].unique() + moved = acs & person["person_household_id"].eq(households[0]).to_numpy() + kept = acs & person["person_household_id"].eq(households[1]).to_numpy() + emptied = person.loc[moved, "person_spm_unit_id"].unique() + assert len(emptied) == 1 + person.loc[moved, "person_spm_unit_id"] = person.loc[ + kept, "person_spm_unit_id" + ].iloc[0] + return spm_unit.loc[spm_unit["spm_unit_id"].ne(emptied[0]).to_numpy()].reset_index( + drop=True + ) + + +def _acs_spm_units_merge(p): + # PR #1685 review r2, nit 3: one ACS household's persons join another + # household's SPM unit; the reverse check (one SPM unit per household) + # passes it. + acs = _copies(p, "acs") + person = acs["person"] + acs["spm_unit"] = _merge_acs_spm_units( + person, acs["spm_unit"], np.ones(len(person), dtype=bool) + ) + return {"acs": acs} + + +_REFUSALS = [ + # P5 on CPS rows (Route A's labels, complete). + ( + _cps_missing_column, + "CPS rows lack complete support metadata: 'household' is missing", + ), + ( + _cps_null_source, + "CPS rows lack complete support metadata: 'person_source_id' has 1 null", + ), + ( + _cps_non_integer_source, + "CPS 'person_source_id' must hold source ids: 1 value(s) are not integers", + ), + (_cps_unknown_channel, "CPS rows must carry channel 'asec' or 'puf_tax_detail'"), + ( + _cps_asec_on_a_clone, + "CPS rows must carry channel 'asec' exactly on clone index 0", + ), + (_cps_clone_index_three, "CPS clone indices must be 0, 1 or 2"), + ( + _cps_spine_source_present, + "CPS rows already carry 'marital_unit_spine_source_id'", + ), + (_cps_wrong_spine_tag, "CPS rows carry a spine tag other than 'asec_puf'"), + # P5 on ACS rows (staging's labels, complete, one offset). + ( + _acs_missing_column, + "ACS rows lack complete support metadata: 'tax_unit' is missing", + ), + ( + _acs_null_channel, + "ACS rows lack complete support metadata: 'spm_unit_support_channel' has 1 null", + ), + (_acs_channel_acs, "ACS rows must carry channel 'acs_2024_1yr'"), + (_acs_clone_index, "ACS rows must carry clone index 0"), + (_acs_offset_varies, "ACS 'family' ids must sit one constant offset"), + (_acs_spine_source_present, "ACS rows already carry 'household_spine_source_id'"), + (_acs_wrong_spine_tag, "ACS rows carry a spine tag other than 'acs_2024_1yr'"), + # Q3: a null spine tag after the rewrite. + (_acs_null_spine_tag, "A null spine tag: 1 ACS 'tax_unit' row(s)"), + (_acs_spine_tag_absent, "A null spine tag: 24 ACS 'household' row(s)"), + # Household weights keyed by household (d2283 lead call L3's check). + ( + _acs_weights_by_position, + "ACS household weights must be keyed by acs_unit_key(SERIALNO) (a pandas " + "Series or a mapping), not a ndarray", + ), + ( + _cps_weights_by_position, + "CPS household weights must be keyed by household_id (a pandas Series or " + "a mapping), not a list", + ), + (_acs_weight_key_repeats, "ACS household weights repeat a key: ['acs:"), + (_cps_weight_negative, "CPS household weights must be finite and non-negative."), + (_acs_weight_not_finite, "ACS household weights must be finite and non-negative."), + ( + _acs_weight_complex, + "ACS household weights must be real numbers; they hold complex128 values", + ), + ( + _cps_weight_numpy_complex, + "CPS household weights must be real numbers; they hold 1 value(s) that are " + "not real numbers or strings, such as [np.complex128(", + ), + ( + _cps_weight_timedelta, + "CPS household weights must be real numbers; they hold timedelta64[ns] values", + ), + # P6b: frame ids and memberships across origins. + ( + _ids_collide_across_origins, + "Frame ids collide: 'tax_unit_id' repeats across origins", + ), + ( + _membership_crosses_origins, + "Memberships do not resolve: 1 ACS person(s)' 'person_spm_unit_id' match no ACS spm_unit row", + ), + ( + _group_without_a_person, + "Memberships do not resolve: 1 ACS family row(s) hold no ACS person", + ), + # P6: a repeated (source id, rank) pair. + (_rank_repeats_within_cps, "A (source id, rank) pair repeats in 'person'"), + (_rank_repeats_across_origins, "A (source id, rank) pair repeats in 'household'"), + # P7: SERIALNO/SPORDER lineage. + ( + _serialno_column_missing, + "ACS lineage does not survive: the ACS household table lacks ['SERIALNO']", + ), + ( + _serialno_null, + "ACS lineage does not survive: every ACS household needs a non-empty string SERIALNO", + ), + ( + _serialno_repeats, + "ACS lineage does not survive: SERIALNO repeats across ACS households", + ), + ( + _sporder_null, + "ACS lineage does not survive: every ACS person needs an integral SPORDER: 1 value(s) are null", + ), + ( + _sporder_repeats, + "ACS lineage does not survive: (SERIALNO, SPORDER) repeats on 2 ACS person(s)", + ), + ( + _source_household_id_moves, + "ACS lineage does not survive: source_household_id differs from the linked household's native id", + ), + ( + _source_person_id_moves, + "ACS lineage does not survive: source_person_id differs from str(SPORDER) on 1", + ), + ( + _source_year_moves, + "ACS lineage does not survive: source_year must be 2024 on every ACS person; 1 differ", + ), + # A pandas nullable dtype's pd.NA in a lineage column (review should-fix 2). + ( + _source_year_pd_na, + "ACS lineage does not survive: every ACS person needs an integral " + "source_year: 1 value(s) are null", + ), + ( + _source_person_id_pd_na, + "ACS lineage does not survive: source_person_id is null on 1 ACS person(s)", + ), + ( + _source_household_id_pd_na, + "ACS lineage does not survive: every ACS person needs an integral " + "source_household_id: 1 value(s) are null", + ), + # Staging's lineage, person by person under native ids (review blocking 2). + ( + _serialno_swaps_between_households, + "keyed by native (household id, person id); 0 missing (such as []), 0 " + "extra (such as []), 4 moved", + ), + ( + _sporder_swaps_within_a_household, + "keyed by native (household id, person id); 0 missing (such as []), 0 " + "extra (such as []), 2 moved", + ), + ( + _staging_has_a_person_the_selection_lost, + "keyed by native (household id, person id); 1 missing (such as [(999999, 1)])", + ), + ( + _staging_lacks_a_selected_person, + "keyed by native (household id, person id); 0 missing (such as []), 1 extra", + ), + ( + _staging_pair_malformed, + "ACS lineage does not survive: staging's lineage maps (999999, 1) to " + "('2024HU0000001',), not a (SERIALNO, SPORDER) pair", + ), + ( + _staging_key_malformed, + "ACS lineage does not survive: staging's lineage has the key " + "'2024HU0000001', not a native (household id, person id) pair of integers", + ), + ( + _staging_key_timedelta, + "ACS lineage does not survive: staging's lineage has the key (np.timedelta64(", + ), + # P6c: group units nest in households; ACS SPM units are the households + # (review blocking 3). + ( + _acs_tax_unit_spans_households, + "Group units do not nest in households: 1 ACS tax_unit unit(s) hold " + "persons of more than one household", + ), + ( + _cps_family_spans_households, + "Group units do not nest in households: 1 CPS family unit(s) hold " + "persons of more than one household", + ), + ( + _acs_household_holds_two_spm_units, + "ACS SPM units must be the households (staging's one-SPM-unit-per-" + "household partition): 1 ACS household(s) hold more than one SPM unit", + ), + ( + _acs_spm_units_merge, + "Group units do not nest in households: 1 ACS spm_unit unit(s) hold " + "persons of more than one household", + ), + # Each household's weight found by its key, after P7 checked SERIALNO. + ( + _acs_household_without_a_weight, + "ACS household weights must name each ACS household by its " + "acs_unit_key(SERIALNO) exactly once: 1 household(s) have no weight", + ), + ( + _serialno_not_a_clean_key, + "ACS household weights need each household's SERIALNO key", + ), + ( + _cps_weight_names_no_household, + "CPS household weights must name each CPS household by its household_id " + "exactly once: 0 household(s) have no weight (such as []) and 1 weight(s) " + "name no household", + ), +] + + +def _rewrite(population, corruption: dict) -> Frame: + return to_assembled_provenance( + corruption.get("cps", population.cps_tables), + corruption.get("acs", population.acs_tables), + cps_household_weights=corruption.get( + "cps_weights", population.keyed_cps_household_weights + ), + acs_household_weights=corruption.get( + "acs_weights", population.keyed_acs_household_weights + ), + staging_lineage=corruption.get("lineage", staging_lineage(population)), + ) + + +@pytest.mark.parametrize( + ("corrupt", "message"), + _REFUSALS, + ids=[corrupt.__name__.lstrip("_") for corrupt, _ in _REFUSALS], +) +def test_each_rule_refuses_with_its_own_message(population, corrupt, message) -> None: + with pytest.raises(OnePopulationContractError, match=re.escape(message)): + _rewrite(population, corrupt(population)) + + +def test_refusal_messages_are_distinct() -> None: + messages = [message for _, message in _REFUSALS] + assert len(set(messages)) == len(messages) + + +@pytest.mark.parametrize("group", ["tax_unit", "spm_unit", "family", "marital_unit"]) +def test_a_cps_group_unit_across_households_refuses(population, group) -> None: + # P6c reads every group entity on CPS rows, not only the family; on ACS + # rows the one-SPM-unit partition would also catch a split SPM unit. + with pytest.raises( + OnePopulationContractError, + match=re.escape( + f"Group units do not nest in households: 1 CPS {group} unit(s) hold " + "persons of more than one household" + ), + ): + _rewrite(population, _cps_unit_spans_households(population, group)) + + +def _complex_membership(person: pd.DataFrame, row: int, column: str) -> None: + """``row``'s ``column`` as a numpy complex, its real part the same id.""" + + _set(person, row, column, np.complex128(int(person[column].iloc[row]) + 0j)) + assert person[column].dtype == np.dtype(object) + + +_GROUPS = ("household", "spm_unit", "tax_unit", "family", "marital_unit") + + +@pytest.mark.parametrize("group", _GROUPS) +@pytest.mark.parametrize("origin", ["acs", "cps"]) +def test_a_complex_membership_refuses(population, origin, group) -> None: + # PR #1685 review r3, nit 2: isin matches a complex 5+0j with the id 5, + # so a person's link held that way resolved and the frame passed. + # P6b, where the five person links resolve, reads each through the + # shared guard first, on both origins' persons. + tables = _copies(population, origin) + column = US_SCHEMA.membership_column(group) + _complex_membership(tables["person"], 0, column) + with pytest.raises( + OnePopulationContractError, + match=re.escape( + f"Memberships do not resolve: {origin.upper()} persons' {column!r} " + "holds 1 value(s) that are not real numbers or strings, such as " + "[np.complex128(" + ), + ): + _rewrite(population, {origin: tables}) + + +def test_union_form_refuses_a_fractional_sporder(population) -> None: + union = with_staging_union_columns(population) + acs = {entity: table.copy() for entity, table in union.acs_tables.items()} + assert acs["person"]["SPORDER"].dtype == np.dtype("float64") + acs["person"].loc[acs["person"].index[0], "SPORDER"] = 1.5 + with pytest.raises( + OnePopulationContractError, + match=re.escape( + "every ACS person needs an integral SPORDER: 1 value(s) are not integers" + ), + ): + _rewrite(union, {"acs": acs, "lineage": staging_lineage(population)}) + + +def _with_source_year(person: pd.DataFrame, form: str) -> None: + """``source_year`` held as complex or temporal data, each value's real part 2024.""" + + years = person["source_year"] + if form == "complex128 column": + values = years.astype(np.complex128) + values.iloc[0] = complex(int(years.iloc[0]), 1) + person["source_year"] = values + elif form == "complex in object": + _set(person, 0, "source_year", complex(int(years.iloc[0]), 1)) + elif form == "timedelta64 column": + person["source_year"] = pd.to_timedelta(years.to_numpy(), unit="ns") + elif form.startswith("Arrow dictionary"): + # Review r3, should-fix 1: the dtype's kind is "O" but it is not an + # object dtype, so the r2 guard skipped it and pd.to_numeric read + # each time as its count of nanoseconds. + unit = pa.timestamp("ns") if "timestamps" in form else pa.duration("ns") + person["source_year"] = _arrow_dictionary(years, unit) + else: + # The last person, not the first: pd.to_numeric reads a leading + # numpy timedelta64 in an object column as NaN but a later one as + # its count of units. + _set(person, -1, "source_year", np.timedelta64(int(years.iloc[-1]), "ns")) + + +def _arrow_dictionary(values: pd.Series, arrow_type) -> pd.Series: + """``values`` (integers, or null) as an Arrow dictionary of ``arrow_type``. + + A timestamp or duration value holds the integer as its count of units, + the encoding review r3's should-fix 1 found read as that integer. + """ + + array = pa.array( + [None if pd.isna(value) else int(value) for value in values], + type=arrow_type, + ).dictionary_encode() + return pd.Series(pd.arrays.ArrowExtensionArray(array), index=values.index) + + +_COMPLEX_OR_TEMPORAL_FORMS = { + "complex128 column": "it holds complex128 values, not integers", + "complex in object": ( + "it holds 1 value(s) that are not real numbers or strings, such as [(2024+1j)]" + ), + "timedelta64 column": "it holds timedelta64[ns] values, not integers", + "numpy timedelta64 in object": ( + "it holds 1 value(s) that are not real numbers or strings, such as " + "[np.timedelta64(2024," + ), + "Arrow dictionary of timestamps": ( + "it holds dictionary" + "[pyarrow] values, not integers" + ), + "Arrow dictionary of durations": ( + "it holds dictionary" + "[pyarrow] values, not integers" + ), +} + + +@pytest.mark.parametrize("form", list(_COMPLEX_OR_TEMPORAL_FORMS)) +def test_a_complex_or_temporal_source_year_refuses(population, form) -> None: + # PR #1685 review r2, should-fix 1: pd.to_numeric keeps 2024+1j complex + # and the float64 conversion after it drops the imaginary part, and it + # reads a timedelta64 of 2024 units as 2024, as a column or as a value + # on a later row of an object column, so P7 saw 2024 and passed the + # frame. On the first row of an object column it read as NaN and + # refused as not an integer, by its position alone. + acs = _copies(population, "acs") + _with_source_year(acs["person"], form) + if "object" in form: + assert acs["person"]["source_year"].dtype == np.dtype(object) + with pytest.raises( + OnePopulationContractError, + match=re.escape( + "ACS lineage does not survive: every ACS person needs an integral " + f"source_year: {_COMPLEX_OR_TEMPORAL_FORMS[form]}" + ), + ): + _rewrite(population, {"acs": acs}) + + +@pytest.mark.parametrize( + "dtype", + [ + "Int64", + "UInt16", + CANONICAL_STRING_DTYPE, + "int64[pyarrow]", + "Arrow dictionary of int64", + "category", + ], + ids=str, +) +def test_a_source_year_in_a_real_dtype_passes(population, dtype) -> None: + # Review r3, should-fix 1: the allowlist reads these as the integer + # 2024, at the public entry as in _integral_ids. + acs = _copies(population, "acs") + years = acs["person"]["source_year"] + if dtype == "Arrow dictionary of int64": + acs["person"]["source_year"] = _arrow_dictionary(years, pa.int64()) + elif dtype is CANONICAL_STRING_DTYPE: + acs["person"]["source_year"] = years.astype(str).astype(dtype) + else: + acs["person"]["source_year"] = years.astype(dtype) + _rewrite(population, {"acs": acs}) + + +@pytest.mark.parametrize( + ("values", "found"), + [ + (pd.Series(np.array([7 + 0j, 7 + 1j])), "complex128 values"), + (pd.Series(np.array([7 + 0j], dtype=np.complex64)), "complex64 values"), + ( + pd.Series([7, complex(7, 0)], dtype=object), + "1 value(s) that are not real numbers or strings", + ), + ( + pd.Series([7, np.complex64(7)], dtype=object), + "1 value(s) that are not real numbers or strings", + ), + (pd.Series(pd.to_datetime(["2024-01-01"])), "datetime64["), + (pd.Series(pd.to_datetime(["2024-01-01"]).tz_localize("UTC")), "datetime64["), + (pd.Series(pd.to_timedelta([7], unit="ns")), "timedelta64[ns] values"), + ( + pd.Series(pd.period_range("2024", periods=1, freq="Y")), + "period[Y-DEC] values", + ), + ( + pd.Series([7, pd.Timestamp(7)], dtype=object), + "1 value(s) that are not real numbers or strings", + ), + ( + pd.Series([7, pd.Timedelta(7)], dtype=object), + "1 value(s) that are not real numbers or strings", + ), + ( + pd.Series([7, np.datetime64(7, "ns")], dtype=object), + "1 value(s) that are not real numbers or strings", + ), + ( + pd.Series([7, np.timedelta64(7, "ns")], dtype=object), + "1 value(s) that are not real numbers or strings", + ), + ( + pd.Series([7, pd.Period("2024", freq="Y")], dtype=object), + "1 value(s) that are not real numbers or strings", + ), + ( + pd.Series([7, datetime.date(2024, 1, 1)], dtype=object), + "1 value(s) that are not real numbers or strings", + ), + (pd.Series([7 + 1j], dtype="category"), "categories of complex128 values"), + ], + ids=lambda value: value if isinstance(value, str) else None, +) +def test_integral_ids_refuse_complex_and_temporal_data(values, found) -> None: + # Review r2, should-fix 1: the shared id parser refuses each before + # pd.to_numeric and the float64 conversion read it. Before the fix the + # complex cases, the datetime64 and timedelta64 columns, the object + # column holding np.timedelta64 and the category passed as numbers; the + # period column and the object columns holding a Timestamp, Timedelta, + # np.datetime64, Period or date refused as "not integers". + with pytest.raises( + OnePopulationContractError, match=re.escape(f"ids: it holds {found}") + ): + contract._integral_ids(values, refusal="ids") + + +@pytest.mark.parametrize( + "values", + [ + pd.Series([7, 8]), + pd.Series([7.0, 8.0]), + pd.Series([7, 8], dtype="Int64"), + pd.Series([7, "8"], dtype=object), + pd.Series([7, 8], dtype="category"), + ], + ids=["int64", "integral float64", "Int64", "object", "category"], +) +def test_integral_ids_still_read_real_ids(values) -> None: + np.testing.assert_array_equal( + contract._integral_ids(values, refusal="ids"), np.array([7, 8]) + ) + + +def _arrow(values: list, arrow_type) -> pd.Series: + return pd.Series(pd.arrays.ArrowExtensionArray(pa.array(values, type=arrow_type))) + + +@pytest.mark.parametrize( + ("values", "found"), + [ + ( + _arrow_dictionary(pd.Series([7, 8]), pa.timestamp("ns")), + "dictionary[pyarrow] " + "values", + ), + ( + _arrow_dictionary(pd.Series([7, 8]), pa.duration("ns")), + "dictionary[pyarrow] values", + ), + ( + pd.Series(pd.Categorical(_arrow([7, 8], pa.duration("ns")))), + "categories of duration[ns][pyarrow] values", + ), + ( + _arrow([decimal.Decimal(7), decimal.Decimal(8)], pa.decimal128(10, 0)), + "decimal128(10, 0)[pyarrow] values", + ), + (_arrow(["7", "8"], pa.string_view()), "string_view[pyarrow] values"), + (pd.Series(pd.interval_range(7, 9)), "interval[int64, right] values"), + ( + pd.Series([7, np.array(8, dtype="m8[ns]")], dtype=object), + "1 value(s) that are not real numbers or strings, such as " + "[array(8, dtype='timedelta64[ns]')]", + ), + ( + pd.Series([7, np.array(8 + 0j)], dtype=object), + "1 value(s) that are not real numbers or strings, such as [array(8.+0.j)]", + ), + ], + ids=[ + "Arrow dictionary of timestamps", + "Arrow dictionary of durations", + "category of Arrow durations", + "Arrow decimal", + "Arrow string_view", + "interval", + "zero-dimensional timedelta64 array in object", + "zero-dimensional complex array in object", + ], +) +def test_integral_ids_refuse_any_data_but_integers_reals_and_strings( + values, found +) -> None: + # Review r3, should-fix 1: the guard is an allowlist. An Arrow + # dictionary's dtype has kind "O" but is not an object dtype, so the r2 + # guard skipped it and pd.to_numeric read each time as its count; it + # also passed an Arrow decimal, raised NotImplementedError on an Arrow + # string_view, and passed a zero-dimensional numpy array in an object + # column, which pd.to_numeric reads as its count or its real part. + with pytest.raises( + OnePopulationContractError, match=re.escape(f"ids: it holds {found}") + ): + contract._integral_ids(values, refusal="ids") + + +@pytest.mark.parametrize( + "values", + [ + pd.Series([7, 8], dtype=np.int32), + pd.Series([7, 8], dtype=np.uint64), + pd.Series([7.0, 8.0], dtype=np.float32), + pd.Series([7, 8], dtype="UInt32"), + pd.Series([7.0, 8.0], dtype="Float64"), + pd.Series(["7", "8"], dtype=CANONICAL_STRING_DTYPE), + pd.Series(["7", "8"]), + pd.Series(["7", "8"], dtype="string[pyarrow]"), + pd.Series(["7", "8"], dtype="category"), + pd.Series([7, np.int64(8)], dtype=object), + _arrow([7, 8], pa.int64()), + _arrow([7, 8], pa.uint8()), + _arrow([7.0, 8.0], pa.float64()), + _arrow(["7", "8"], pa.string()), + _arrow(["7", "8"], pa.large_string()), + _arrow_dictionary(pd.Series([7, 8]), pa.int64()), + pd.Series( + pd.arrays.ArrowExtensionArray(pa.array(["7", "8"]).dictionary_encode()) + ), + ], + ids=[ + "int32", + "uint64", + "float32", + "UInt32", + "Float64", + "canonical string", + "pandas default string", + "string[pyarrow]", + "category of strings", + "object of numpy ints", + "Arrow int64", + "Arrow uint8", + "Arrow float64", + "Arrow string", + "Arrow large_string", + "Arrow dictionary of int64", + "Arrow dictionary of strings", + ], +) +def test_integral_ids_read_the_pinned_id_dtypes(values) -> None: + # Review r3, should-fix 1, the lead's call: the allowlist must not refuse + # a real input. The generator writes int64 ids, staging's pooled form + # float64 (both in the test above); the parent export's H5 load and + # staging's PUMS parse store strings in CANONICAL_STRING_DTYPE + # (serialization_dtypes); the review's probes kept unsigned, nullable, + # categorical and Arrow numeric ids valid. + np.testing.assert_array_equal( + contract._integral_ids(values, refusal="ids"), np.array([7, 8]) + ) + + +def test_a_cross_grain_channel_mismatch_fails_the_validator(population) -> None: + # No P5-P7 rule reads a person's channel against its groups'; the + # assembly validator does, and its ValueError comes back as the + # contract's error. A native CPS person moves into its household's + # PUF tax-detail copy (the native household keeps another member). + cps = _copies(population, "cps") + person = cps["person"] + native = person["person_support_clone_index"] == 0 + sizes = person["person_household_id"].map( + person.loc[native, "person_household_id"].value_counts() + ) + row = int(np.flatnonzero(native.to_numpy() & (sizes.to_numpy() > 1))[0]) + household = int(person["person_household_id"].iloc[row]) + _set(person, row, "person_household_id", household + population.clone_multiplier) + with pytest.raises( + OnePopulationContractError, + match=re.escape("The joined one-population frame is not valid") + + ".*cross-grain provenance disagrees", + ): + _rewrite(population, {"cps": cps}) + + +# ------------------------------------------------------------ cps_unit_ids + + +class TestCpsUnitIds: + def test_keys_are_the_selection_keys(self, population) -> None: + person = population.cps_tables["person"] + household = population.cps_tables["household"].set_index("household_id") + ids = cps_unit_ids(person) + assert ids.index.name == "household_id" + assert ids.index.tolist() == sorted(household.index) + assert ids["income_year"].dtype == np.dtype("int64") + native = household["household_support_clone_index"] == 0 + native_keys = ids.loc[native[native].index, "key"].tolist() + assert sorted(native_keys) == sorted(population.cps_keys) + assert selection.keys_sha256(native_keys) == selection.keys_sha256( + population.cps_keys + ) + # A clone household shares its source household's key. + source = household["household_source_id"] + assert (ids["key"] == ids["key"].loc[source.loc[ids.index]].to_numpy()).all() + assert (ids["unit_id"].str.len() == 20).all() + assert ( + ids["key"] + == [ + selection.cps_unit_key(year, unit) + for year, unit in zip(ids["income_year"], ids["unit_id"], strict=True) + ] + ).all() + + def test_reads_source_person_id_when_peridnum_is_absent(self, population) -> None: + person = population.cps_tables["person"] + pd.testing.assert_frame_equal( + cps_unit_ids(person.drop(columns=["PERIDNUM"])), cps_unit_ids(person) + ) + + @pytest.mark.parametrize( + ("corrupt", "message"), + [ + ( + lambda person: person.drop(columns=["PERIDNUM"]).assign( + source_person_id=np.arange(len(person)) + ), + "need source_person_id as a string of at least 20 digits", + ), + ( + lambda person: person.assign(PERIDNUM=person["PERIDNUM"].astype(float)), + "need PERIDNUM as a string of at least 20 digits", + ), + ( + lambda person: person.assign(PERIDNUM=person["PERIDNUM"].str[:19]), + "need PERIDNUM as a string of at least 20 digits", + ), + ( + lambda person: person.assign( + PERIDNUM=person["PERIDNUM"].where(person.index != 0, None) + ), + "need PERIDNUM as a string of at least 20 digits", + ), + ( + lambda person: person.drop(columns=["PERIDNUM", "source_person_id"]), + "need PERIDNUM or source_person_id", + ), + ( + lambda person: person.assign( + source_year=person["source_year"] + .astype(float) + .where(person.index != 0, np.nan) + ), + "need an integral source_year", + ), + ], + ids=["integer_fallback", "float", "short", "null", "absent", "null_year"], + ) + def test_refuses_a_malformed_id(self, population, corrupt, message) -> None: + person = population.cps_tables["person"].copy() + with pytest.raises(OnePopulationContractError, match=re.escape(message)): + cps_unit_ids(corrupt(person)) + + def test_refuses_acs_rows(self, frame) -> None: + with pytest.raises( + OnePopulationContractError, match="as a string of at least 20 digits" + ): + cps_unit_ids(frame.table("person")) + + @pytest.mark.parametrize( + ("column", "message"), + [ + ("PERIDNUM", "disagree on PERIDNUM[:20] (H_IDNUM)"), + ("source_year", "disagree on source_year"), + ], + ) + def test_refuses_a_household_whose_persons_disagree( + self, population, column, message + ) -> None: + person = population.cps_tables["person"].copy() + sizes = person["person_household_id"].map( + person["person_household_id"].value_counts() + ) + row = person.index[int(np.flatnonzero(sizes.to_numpy() > 1)[0])] + if column == "PERIDNUM": + value = person.loc[row, "PERIDNUM"] + person.loc[row, "PERIDNUM"] = ("1" if value[0] != "1" else "2") + value[1:] + else: + person.loc[row, "source_year"] = person.loc[row, "source_year"] - 1 + with pytest.raises(OnePopulationContractError, match=re.escape(message)): + cps_unit_ids(person) + + +# ------------------------------- phase 2: require_one_population (R1-R12, T1) + + +@pytest.fixture(scope="module") +def assembled(population): + return assembled_frame(population) + + +def _require(population, frame: Frame, **overrides) -> None: + kwargs = { + "parent_tail_donor_ids": population.tail_donor_ids, + "variable_index": StandInVariableIndex.from_lock(), + } + kwargs.update(overrides) + manifest = kwargs.pop("manifest", None) or selection_manifest(population) + require_one_population(frame, manifest, **kwargs) + + +def _tables(frame: Frame) -> dict[str, pd.DataFrame]: + return {entity: frame.table(entity).copy() for entity in frame.entities} + + +def _rebuild( + frame: Frame, + tables: dict[str, pd.DataFrame], + *, + metadata=None, +) -> Frame: + return 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 if metadata is None else metadata, + ) + + +def _origin_mask(table: pd.DataFrame, entity: str, origin: str) -> np.ndarray: + channel = table[support_channel_column(entity)] + if origin == "acs": + return channel.eq(ACS_2024_1YR_SPINE).to_numpy() + return channel.ne(ACS_2024_1YR_SPINE).to_numpy() + + +def _row(table: pd.DataFrame, entity: str, origin: str, *, clone=None, where=None): + """Position of the first row of ``origin`` (and clone index, predicate).""" + + mask = np.array(_origin_mask(table, entity, origin), dtype=bool) + if clone is not None: + mask &= table[support_clone_index_column(entity)].to_numpy() == clone + if where is not None: + mask &= np.asarray(where, dtype=bool) + return int(np.flatnonzero(mask)[0]) + + +def _cell(frame: Frame, entity: str, column: str, value, *, origin, **row): + tables = _tables(frame) + table = tables[entity] + _set(table, _row(table, entity, origin, **row), column, value) + return _rebuild(frame, tables) + + +def _with_column(frame: Frame, entity: str, column: str, values) -> Frame: + tables = _tables(frame) + tables[entity][column] = values + return _rebuild(frame, tables) + + +def _without_column(frame: Frame, entity: str, column: str) -> Frame: + tables = _tables(frame) + tables[entity] = tables[entity].drop(columns=[column]) + return _rebuild(frame, tables) + + +def _household_sizes(person: pd.DataFrame, column: str) -> np.ndarray: + return person[column].map(person[column].value_counts()).to_numpy() + + +def _acs_null_on_cps(frame: Frame, entity: str, column: str, value) -> Frame: + """``column`` filled with ``value`` on CPS rows and null on ACS rows.""" + + table = frame.table(entity) + acs = _origin_mask(table, entity, "acs") + return _with_column( + frame, + entity, + column, + pd.Series(np.where(acs, None, value), index=table.index, dtype=object), + ) + + +#: The engine inputs d2283 lead call L1 (11-18) moved off the exempt list: +#: the release's first engine pass refuses a null in each float or integer +#: one at load, and later passes compute from is_self_employed, before their +#: producers write them, so prepare fills each on ACS rows and R6 refuses its +#: null. The +#: three integer recodes are the ones staging writes natively. The ACA pass +#: computes from takes_up_medicaid_if_eligible before Medicaid writes it, +#: masked today; it moved with the lead-call review (fail closed). +_MOVED_OFF_THE_EXEMPT_LIST = ( + "cps_race", + "hourly_wage", + "fsla_overtime_premium", + "selected_marketplace_plan_benchmark_ratio", + "other_health_insurance_premiums", + "health_insurance_premiums", + "is_self_employed", + "detailed_occupation_recode", + "detailed_industry_recode", + "major_industry_recode", + "takes_up_medicaid_if_eligible", +) +#: The moved inputs the engine holds as booleans. +_MOVED_BOOLEANS = frozenset({"is_self_employed", "takes_up_medicaid_if_eligible"}) + + +class TestRequireOnePopulation: + @pytest.mark.parametrize("form", _FORMS) + @pytest.mark.parametrize("seed", _SEEDS) + def test_a_valid_population_passes(self, seed, form) -> None: + population = _form(generate_population(seed), form) + frame = assembled_frame(population) + _require(population, frame) + _require(population, frame, staging_lineage=staging_lineage(population)) + + def test_a_frame_with_no_acs_row_passes(self, population) -> None: + # T1 and P7 are vacuous, R2's ACS half is the empty key set and + # R10 has no ACS row to read. + empty_acs = { + entity: population.acs_tables[entity].iloc[:0] + for entity in US_SCHEMA.entities + } + frame = to_assembled_provenance( + population.cps_tables, + empty_acs, + cps_household_weights=population.keyed_cps_household_weights, + acs_household_weights={}, + staging_lineage={}, + ) + manifest = dataclasses.replace( + selection_manifest(population), + n_acs=0, + selected_acs_keys_sha256=selection.keys_sha256(()), + ) + assert "SERIALNO" not in frame.table("household") + _require(population, frame, manifest=manifest, staging_lineage={}) + + def test_a_frame_with_no_acs_row_still_checks_staging_lineage( + self, population + ) -> None: + empty_acs = { + entity: population.acs_tables[entity].iloc[:0] + for entity in US_SCHEMA.entities + } + frame = to_assembled_provenance( + population.cps_tables, + empty_acs, + cps_household_weights=population.keyed_cps_household_weights, + acs_household_weights={}, + staging_lineage={}, + ) + manifest = dataclasses.replace( + selection_manifest(population), + n_acs=0, + selected_acs_keys_sha256=selection.keys_sha256(()), + ) + lineage = staging_lineage(population) + with pytest.raises( + OnePopulationContractError, + match=re.escape( + "ACS lineage does not survive: the selected ACS persons' (SERIALNO, " + "SPORDER) lineage differs from staging's, keyed by native " + f"(household id, person id); {len(lineage)} missing" + ), + ): + _require(population, frame, manifest=manifest, staging_lineage=lineage) + + def test_the_default_index_is_built_at_call_time( + self, population, assembled, monkeypatch + ) -> None: + built: list[object] = [] + + def fake_default(): + built.append(None) + return StandInVariableIndex.from_lock() + + monkeypatch.setattr(contract, "PolicyEngineUSVariableIndex", fake_default) + assert built == [] + _require(population, assembled, variable_index=None) + assert len(built) == 1 + + def test_the_default_register_is_the_stored_inputs_register( + self, population, assembled + ) -> None: + frame = _with_column( + assembled, "person", "cps_employment_income_last_year", 0.0 + ) + with pytest.raises( + OnePopulationContractError, + match=re.escape("['cps_employment_income_last_year']"), + ): + _require(population, frame) + register = { + **US_STORED_NON_VARIABLE_COLUMNS, + "cps_employment_income_last_year": "test auxiliary column", + } + _require(population, frame, register=register) + + def test_tail_donors_are_compared_without_weights( + self, population, assembled + ) -> None: + tables = _tables(assembled) + tables["tax_unit"]["puf_capital_gains_tail_transfer_weight"] *= 3.0 + weights = assembled.weights_for("household") + frame = Frame( + tables, + assembled.schema, + {"household": type(weights)(weights.values * 2.0, weights.kind)}, + assembled.strata, + mass_log=assembled.mass_log, + metadata=assembled.metadata, + ) + _require(population, frame) + + def test_a_post_2024_formula_column_with_nulls_refuses_under_r6( + self, population, assembled, stand_in + ) -> None: + # weeks_worked has only a 2025 formula at policyengine-us 2.2.1: the + # year-blind input list (the lock) lacks it and R3 does not refuse + # it, so R6's year-aware input rule is what catches a null. + assert "weeks_worked" not in lock_engine_inputs() + frame = _acs_null_on_cps(assembled, "person", "weeks_worked", 52.0) + tables = {entity: frame.table(entity) for entity in frame.entities} + assert "weeks_worked" not in stand_in.computed_at_2024(tables) + assert "weeks_worked" in stand_in.inputs_at_2024(tables) + n_acs = int(_origin_mask(frame.table("person"), "person", "acs").sum()) + with pytest.raises( + OnePopulationContractError, + match=re.escape( + f"A null in an engine input at 2024: {{'person.weeks_worked': {n_acs}}}" + ), + ): + _require(population, frame) + _require(population, _with_column(assembled, "person", "weeks_worked", 52.0)) + + def test_a_register_column_absent_on_acs_rows_needs_a_declaration( + self, population, assembled + ) -> None: + register = { + **US_STORED_NON_VARIABLE_COLUMNS, + "cps_employment_income_last_year": "test auxiliary column", + } + frame = _acs_null_on_cps( + assembled, "person", "cps_employment_income_last_year", 1.0 + ) + with pytest.raises( + OnePopulationContractError, + match=re.escape("'person.cps_employment_income_last_year'"), + ): + _require(population, frame, register=register) + _require( + population, + frame, + register=register, + declared_absences={ + "cps_employment_income_last_year": "owner: ACS has no prior year" + }, + ) + with pytest.raises( + OnePopulationContractError, + match=re.escape("A declared absence needs its owner's decision"), + ): + _require( + population, + frame, + register=register, + declared_absences={"cps_employment_income_last_year": " "}, + ) + + def test_a_stage_output_outside_the_exempt_list_is_not_exempt( + self, population, assembled + ) -> None: + # scf_wealth declares the education-debt columns, but only an opt-in + # stage writes them: R10 does not exempt a stage's outputs whole. + assert "federal_student_loan_balance" in US_STORED_NON_VARIABLE_COLUMNS + assert "federal_student_loan_balance" not in RELEASE_WRITTEN_INPUTS + frame = _acs_null_on_cps( + assembled, "person", "federal_student_loan_balance", 0.0 + ) + with pytest.raises( + OnePopulationContractError, + match=re.escape( + "A model-named column held on some CPS row is null on ACS rows " + "without a declared absence: {'person.federal_student_loan_balance'" + ), + ): + _require(population, frame) + + def test_a_release_written_input_may_be_null_on_acs_rows( + self, population, assembled + ) -> None: + frame = _acs_null_on_cps( + assembled, "person", "takes_up_head_start_if_eligible", True + ) + _require(population, frame) + not_exempt = _acs_null_on_cps( + assembled, "spm_unit", "takes_up_snap_if_eligible", True + ) + with pytest.raises( + OnePopulationContractError, + match=re.escape("'spm_unit.takes_up_snap_if_eligible'"), + ): + _require(population, not_exempt) + + @pytest.mark.parametrize( + ("null", "dtype", "filled"), + [ + (None, object, True), + (np.nan, object, True), + (np.nan, "float64", 1.0), + (np.nan, "float32", 1.0), + (np.float32("nan"), object, True), + ], + ids=[ + "none", + "nan in object", + "nan in float64", + "nan in float32", + "numpy float32 nan in object", + ], + ) + def test_a_release_written_null_may_be_none_or_nan( + self, population, assembled, null, dtype, filled + ) -> None: + # PR #1685 review, blocking 1: the release's first engine pass loads + # a boolean None as False and a NaN as True (numpy's casts), so both + # stay allowed in an exempt column; pd.NA and every other null refuse + # (the tests below). Review r2: a float32 column's NaN passes by its + # dtype, and a numpy float32 NaN in an object column, which is not a + # Python float, passes as a float NaN. + person = assembled.table("person") + acs = _origin_mask(person, "person", "acs") + values = pd.Series( + [null if row else filled for row in acs], index=person.index, dtype=dtype + ) + if dtype is object: + assert type(values[acs].iloc[0]) is type(null) + _require( + population, + _with_column(assembled, "person", "takes_up_ssi_if_eligible", values), + ) + + @pytest.mark.parametrize("dtype", ["Float32", "Float64"]) + def test_a_nullable_float_nan_that_is_not_pd_na_passes( + self, population, assembled, dtype + ) -> None: + # Review r2, the lead's call on nit 1: a nullable Float column can + # hold a NaN unmasked, which pandas does not count as null, so R6 + # passes it; only the column's masked null, pd.NA, refuses. + person = assembled.table("person") + acs = _origin_mask(person, "person", "acs") + values = pd.Series( + pd.arrays.FloatingArray( + np.where(acs, np.nan, 1.0).astype(dtype.lower()), + np.zeros(len(acs), dtype=bool), + ), + index=person.index, + ) + assert str(values.dtype) == dtype + assert not values.isna().any() and np.isnan(values.to_numpy()[acs]).all() + _require( + population, + _with_column(assembled, "person", "takes_up_ssi_if_eligible", values), + ) + + @pytest.mark.parametrize( + ("null", "origin", "dtype", "filled"), + [ + (pd.NaT, "acs", object, True), + (np.datetime64("NaT"), "cps", object, True), + (np.timedelta64("NaT"), "acs", object, True), + ( + np.datetime64("NaT", "ns"), + "acs", + "datetime64[ns]", + np.datetime64(1, "ns"), + ), + ( + np.timedelta64("NaT", "ns"), + "acs", + "timedelta64[ns]", + np.timedelta64(1, "ns"), + ), + ], + ids=[ + "pd.NaT on ACS rows", + "numpy NaT on a CPS row", + "timedelta NaT on ACS rows", + "datetime64 column", + "timedelta64 column", + ], + ) + def test_a_null_other_than_none_or_nan_refuses( + self, population, assembled, null, origin, dtype, filled + ) -> None: + # Review r2, nit 1: R6 lets a release-written column be null only as + # None or a float NaN. Pandas also counts pd.NaT and numpy's NaT as + # null; R6 used to refuse only pd.NA, so they passed. They refuse on + # either origin, in an object column or in a datetime64 or + # timedelta64 column, whose only null is NaT. + person = assembled.table("person") + rows = _origin_mask(person, "person", origin) + if origin == "cps": + rows = np.arange(len(person)) == int(np.flatnonzero(rows)[0]) + values = pd.Series( + [null if row else filled for row in rows], index=person.index, dtype=dtype + ) + assert values.dtype == np.dtype(dtype) + assert int(values.isna().sum()) == int(rows.sum()) > 0 + with pytest.raises( + OnePopulationContractError, + match=re.escape( + "A null other than None or NaN in a release-written input: " + f"{{'person.takes_up_ssi_if_eligible': {int(rows.sum())}}}" + ), + ): + _require( + population, + _with_column(assembled, "person", "takes_up_ssi_if_eligible", values), + ) + + def test_a_lone_pd_na_on_a_cps_row_refuses(self, population, assembled) -> None: + # Review r2, nit 4: R6 reads every row of a release-written column, + # not only ACS rows; an ACS-only scan would pass this frame. + person = assembled.table("person") + row = _row(person, "person", "cps") + values = pd.array([True] * len(person), dtype="boolean") + values[row] = pd.NA + frame = _with_column( + assembled, + "person", + "takes_up_ssi_if_eligible", + pd.Series(values, index=person.index), + ) + with pytest.raises( + OnePopulationContractError, + match=re.escape( + "A pd.NA in a release-written input: " + "{'person.takes_up_ssi_if_eligible': 1}" + ), + ): + _require(population, frame) + + def test_a_pd_na_is_reported_before_another_null( + self, population, assembled + ) -> None: + # Review r3, nit 3: R6 refuses a pd.NA in any release-written column + # before any other null, so a pd.NaT on an ACS row of one column + # cannot take the diagnostic from a pd.NA on a CPS row of another. + person = assembled.table("person") + nat_row = _row(person, "person", "acs") + frame = _with_column( + assembled, + "person", + "takes_up_ssi_if_eligible", + pd.Series( + [pd.NaT if row == nat_row else True for row in range(len(person))], + index=person.index, + dtype=object, + ), + ) + column = "would_file_taxes_voluntarily" + entity = lock_engine_inputs()[column] + table = frame.table(entity) + values = pd.array([True] * len(table), dtype="boolean") + values[_row(table, entity, "cps")] = pd.NA + frame = _with_column( + frame, entity, column, pd.Series(values, index=table.index) + ) + with pytest.raises( + OnePopulationContractError, + match=re.escape( + f"A pd.NA in a release-written input: {{'{entity}.{column}': 1}}" + ), + ): + _require(population, frame) + + @pytest.mark.parametrize( + ("column", "dtype", "filled"), + [ + ("takes_up_ssi_if_eligible", "boolean", True), + ("would_file_taxes_voluntarily", "boolean", True), + ("bank_account_assets", "Float64", 1_000.0), + ], + ) + def test_a_pd_na_in_a_release_written_input_refuses( + self, population, assembled, column, dtype, filled + ) -> None: + # Blocking 1: a pandas nullable dtype holds its null as pd.NA, which + # the H5 codec keeps and the first engine pass cannot cast to bool + # (bool(pd.NA) raises TypeError). The SSI December pass loads the + # twelve booleans before their producers write them; R6 refuses a + # pd.NA in every exempt column, the SCF wealth amounts included, + # fail closed. Before the fix R6 left exempt columns unread. + entity = lock_engine_inputs()[column] + table = assembled.table(entity) + acs = _origin_mask(table, entity, "acs") + values = pd.array([pd.NA if row else filled for row in acs], dtype=dtype) + frame = _with_column( + assembled, entity, column, pd.Series(values, index=table.index) + ) + with pytest.raises( + OnePopulationContractError, + match=re.escape( + "A pd.NA in a release-written input: " + f"{{'{entity}.{column}': {int(acs.sum())}}}" + ), + ): + _require(population, frame) + + def test_r2_parses_cps_clone_indices_as_r1_does( + self, population, assembled + ) -> None: + # PR #1685 review, should-fix 3: R1 and the assembly validator take + # digit-string clone indices through the integral parser (lead call + # L5's leniency). R2 compared the raw values with 0, found no clone-0 + # household and refused every CPS key as orphaned. + tables = _tables(assembled) + household = tables["household"] + column = support_clone_index_column("household") + household[column] = [str(int(value)) for value in household[column]] + assert not pd.api.types.is_numeric_dtype(household[column].dtype) + _require(population, _rebuild(assembled, tables)) + + def test_r2_parses_string_household_ids(self, population) -> None: + # Should-fix 3's second shape, on R2 itself: string household ids + # with matching string memberships on a frame with no ACS row. + # cps_unit_ids keys households by int64, which a raw string index + # joined to nothing. + empty_acs = { + entity: population.acs_tables[entity].iloc[:0] + for entity in US_SCHEMA.entities + } + frame = to_assembled_provenance( + population.cps_tables, + empty_acs, + cps_household_weights=population.keyed_cps_household_weights, + acs_household_weights={}, + staging_lineage={}, + ) + manifest = dataclasses.replace( + selection_manifest(population), + n_acs=0, + selected_acs_keys_sha256=selection.keys_sha256(()), + ) + tables = _tables(frame) + for entity, column in ( + ("household", "household_id"), + ("person", "person_household_id"), + ): + tables[entity][column] = [ + str(int(value)) for value in tables[entity][column] + ] + contract._require_selected_keys(contract._split_origins(tables), manifest) + + def test_an_index_that_omits_an_input_cannot_hide_its_null( + self, population, assembled + ) -> None: + # PR #1685 review, should-fix 4: an index that leaves a known, + # non-computed column out of its inputs hid that column's null from + # R6 (which reads only the inputs) and R10 (which skips every known + # column). The coherence check now refuses the index itself. + class OmitsTipIncome(StandInVariableIndex): + def inputs_at_2024(self, tables): + return frozenset(super().inputs_at_2024(tables) - {"tip_income"}) + + frame = _cell(assembled, "person", "tip_income", None, origin="acs") + with pytest.raises( + OnePopulationContractError, + match=re.escape( + "The engine variable index answers do not cohere (the inputs must " + "be exactly the known columns not computed at 2024 and not " + "structural): inputs omit known columns that are neither computed " + "at 2024 nor structural: ['tip_income']" + ), + ): + _require( + population, + frame, + variable_index=OmitsTipIncome(inputs=frozenset(lock_engine_inputs())), + ) + + @pytest.mark.parametrize("column", _MOVED_OFF_THE_EXEMPT_LIST) + def test_a_moved_input_null_on_an_acs_row_refuses( + self, population, assembled, column + ) -> None: + # d2283 lead call L1: each moved input is R6's on every row. The + # generator carries none of them, so each is added on its entity. + entity = lock_engine_inputs()[column] + value = True if column in _MOVED_BOOLEANS else 1.0 + filled = _with_column(assembled, entity, column, value) + _require(population, filled) + with pytest.raises( + OnePopulationContractError, + match=re.escape( + f"A null in an engine input at 2024: {{'{entity}.{column}': 1}}" + ), + ): + _require(population, _cell(filled, entity, column, None, origin="acs")) + + def test_arguments_are_type_checked(self, population, assembled) -> None: + with pytest.raises(TypeError, match="frame must be a Frame"): + _require(population, assembled.table("person")) + with pytest.raises(TypeError, match="manifest must be a SelectionManifest"): + require_one_population( + assembled, {}, parent_tail_donor_ids=population.tail_donor_ids + ) + with pytest.raises(TypeError, match="parent_tail_donor_ids must hold int"): + _require(population, assembled, parent_tail_donor_ids={True}) + with pytest.raises(TypeError, match="declared_absences must map"): + _require(population, assembled, declared_absences=["x"]) + + def test_timedelta_parent_donor_ids_refuse(self, population, assembled) -> None: + # PR #1685 review r3, should-fix 2: numpy registers timedelta64 as + # numbers.Integral and int() reads a nanosecond one as its count, so + # these ids read as the parent's own and R8 passed the frame. + donors = { + np.timedelta64(int(donor), "ns") for donor in population.tail_donor_ids + } + with pytest.raises( + TypeError, + match=re.escape("parent_tail_donor_ids must hold int donor ids only."), + ): + _require(population, assembled, parent_tail_donor_ids=donors) + + +class TestExemptList: + """RELEASE_WRITTEN_INPUTS: d2283 Q1 (a), re-read at the module's commit.""" + + @staticmethod + def _stage_outputs() -> dict[str, list[str]]: + from importlib.resources import files + + payload = json.loads( + files("microcosm.build.us") + .joinpath("source_stages.json") + .read_text(encoding="utf-8") + ) + return {stage["stage"]: stage["outputs"] for stage in payload["stages"]} + + def test_each_entry_names_a_stage_that_declares_it(self) -> None: + outputs = self._stage_outputs() + for column, evidence in RELEASE_WRITTEN_INPUTS.items(): + match = re.match(r"(\w+) stage: ", evidence) + assert match, (column, evidence) + stage = match.group(1) + assert stage in outputs, (column, stage) + assert column in outputs[stage], (column, stage) + + def test_each_entry_cites_its_lines(self) -> None: + for column, evidence in RELEASE_WRITTEN_INPUTS.items(): + assert re.search(r"\w+\.py:\d+", evidence), column + # d2283 lead call L1: each entry states its earlier readers. + assert "Earlier readers: " in evidence, column + + def test_the_list_is_the_decided_list(self) -> None: + outputs = self._stage_outputs() + org_bools = { + "is_hispanic", + "worked_last_year", + "has_never_worked", + "is_military", + "is_computer_scientist", + "is_executive_administrative_professional", + "is_farmer_fisher", + "is_paid_hourly", + "is_union_member_or_covered", + } + assert set(RELEASE_WRITTEN_INPUTS) == { + "bank_account_assets", + "bond_assets", + "stock_assets", + "net_worth", + "meets_ssi_disability_criteria", + "takes_up_head_start_if_eligible", + "takes_up_ssi_if_eligible", + "would_file_taxes_voluntarily", + *org_bools, + "takes_up_aca_if_eligible", + } + assert len(RELEASE_WRITTEN_INPUTS) == 18 + assert len(outputs["org_wages"]) == 15 + moved = set(_MOVED_OFF_THE_EXEMPT_LIST) + assert set(outputs["org_wages"]) == org_bools | ( + moved & set(outputs["org_wages"]) + ) + assert len(moved & set(outputs["org_wages"])) == 6 + assert moved - set(outputs["org_wages"]) <= set( + outputs["aca_marketplace_inputs"] + ) | set(outputs["other_health_insurance_premiums"]) | set( + outputs["medicaid_take_up"] + ) + not_exempt = { + # d2283 lead call L1: the first engine pass refuses each null + # float or integer at load, and later passes compute from + # is_self_employed, before the producers write them. + *_MOVED_OFF_THE_EXEMPT_LIST, + # SNAP take-up passes ACS nulls to a gate that misgrades them. + "takes_up_snap_if_eligible", + # Pass-through producers. + "is_snap_abawd_discretionary_exempt", + "auto_loan_balance", + "auto_loan_interest", + "qualified_passenger_vehicle_loan_interest", + *outputs["vehicle_assets"], + *outputs["sipp_tips"], + # A stage's source column. + "health_insurance_premiums_without_medicare_part_b", + # The hours stage is skipped on the pool branch. + *outputs["hours_worked"], + } + assert not_exempt.isdisjoint(RELEASE_WRITTEN_INPUTS) + assert not any( + column.startswith("scf_") or "student_loan" in column + for column in RELEASE_WRITTEN_INPUTS + ) + + def test_every_entry_is_an_engine_input_in_the_lock(self) -> None: + # So R10 (register entries only) never sees one: each is R6's. + assert set(RELEASE_WRITTEN_INPUTS) <= set(lock_engine_inputs()) + + def test_module_constants_match_their_sources(self) -> None: + assert contract._LOCATION_CLONE_INDEX_SUFFIX == ( + "_" + LOCATION_CLONE_INDEX_COLUMN + ) + assert set(PUF_TAIL_TAX_UNIT_COLUMNS) == set(TAIL_PROVENANCE_DEFAULTS) + assert "unrecaptured_section_1250_gain" not in PUF_TAIL_TAX_UNIT_COLUMNS + + +# ---- what the exempt list's verdicts rest on (d2283 lead-call review, 11-19) + +#: The release tool whose pool arm d2283 lead call L1's trace read. +_RELEASE_TOOL = REPOSITORY_ROOT / "tools" / "build_us_fiscal_refresh_release.py" +#: The calls whose order the exempt list's verdicts read, in the release's +#: order: the three producers no engine pass precedes, the first engine +#: pass (the SSI December pass), the producers whose outputs only that pass +#: loads first, and the passes that compute from the moved premiums and +#: self-employment flag before their producer, other health insurance. +_TRACED_STAGE_ORDER = ( + "with_us_scf_wealth_inputs", + "with_us_ssi_disability_criteria", + "with_us_sipp_head_start_input", + "_ssi_person_uncapped_amount", + "with_us_ssi_take_up", + "with_us_voluntary_filing_input", + "with_us_org_wages_inputs", + "_with_aca_marketplace_source_outputs", + "_with_medicaid_take_up_outputs", + "_with_snap_state_take_up_outputs", + "with_us_other_health_insurance_inputs", +) +#: The release's engine passes built from the frame, up to and including +#: the other-health-insurance stage's own (L1's trace: E1 to E5). +_TRACED_FRAME_PASSES = ( + "_ssi_person_uncapped_amount", + "_with_aca_marketplace_source_outputs", + "_with_medicaid_take_up_outputs", + "_with_snap_state_take_up_outputs", + "with_us_other_health_insurance_inputs", +) +#: The calls that build an engine pass from a frame. An engine made only to +#: read variable metadata (``PolicyEngineUSEngine()``) and a dataset read +#: from a file (``_load_frame``'s ``USSingleYearDataset``) are not passes. +_FRAME_PASS_CALLS = frozenset({"_dataset_from_frame", "Microsimulation", "materialize"}) +#: The engine releases L1's trace read statically: policyengine-us's +#: variables and policyengine-core's null handling at load. +_L1_TRACED_ENGINE = {"policyengine-us": "2.2.1", "policyengine-core": "3.32.5"} +_RETRACE = ( + "re-run d2283 lead call L1's earlier-reader trace over " + "RELEASE_WRITTEN_INPUTS and the inputs moved off it before this changes, " + "then update their evidence and this test" +) + + +class _SourceCalls: + """Which functions build a frame engine pass, read from source text. + + Nothing is imported. A function builds a pass when it calls a name in + :data:`_FRAME_PASS_CALLS`, or a function that does, followed by name + through its own module (methods and nested functions included) and its + ``microcosm`` imports. Following by name over-approximates, which errs + toward a failure; a call through a variable or a class is not followed. + """ + + def __init__(self) -> None: + self._parsed: dict[Path, tuple[dict, dict]] = {} + self._builds: dict[tuple[Path, str], bool] = {} + + @staticmethod + def calls(node: ast.AST) -> list[tuple[int, str]]: + found = [] + for sub in ast.walk(node): + if isinstance(sub, ast.Call): + func = sub.func + name = ( + func.id + if isinstance(func, ast.Name) + else getattr(func, "attr", None) + ) + if name: + found.append((sub.lineno, name)) + return sorted(found) + + @staticmethod + def module_path(module: str) -> Path | None: + if not module.startswith("microcosm"): + return None + for src in sorted((REPOSITORY_ROOT / "packages").glob("*/src")): + base = src.joinpath(*module.split(".")) + for candidate in (base / "__init__.py", base.with_suffix(".py")): + if candidate.is_file(): + return candidate + return None + + @staticmethod + def _absolute(path: Path, node: ast.ImportFrom) -> str: + if not node.level: + return node.module or "" + package = path.parent + for _ in range(node.level - 1): + package = package.parent + src = next(parent for parent in package.parents if parent.name == "src") + parts = package.relative_to(src).parts + return ".".join((*parts, *([node.module] if node.module else []))) + + def parsed(self, path: Path) -> tuple[dict, dict]: + if path not in self._parsed: + tree = ast.parse(path.read_text(encoding="utf-8")) + functions: dict[str, list[ast.AST]] = {} + for node in ast.walk(tree): + if isinstance(node, ast.FunctionDef | ast.AsyncFunctionDef): + functions.setdefault(node.name, []).append(node) + imports = { + alias.asname or alias.name: (self._absolute(path, node), alias.name) + for node in tree.body + if isinstance(node, ast.ImportFrom) + for alias in node.names + } + self._parsed[path] = (functions, imports) + return self._parsed[path] + + def resolve(self, module: str, name: str, depth: int = 0): + path = self.module_path(module) + if path is None or depth > 8: + return None + functions, imports = self.parsed(path) + if name in functions: + return path, name + if name in imports: + return self.resolve(*imports[name], depth + 1) + return None + + def builds(self, path: Path, name: str, *, seen=frozenset()) -> bool: + key = (path, name) + if key in self._builds: + return self._builds[key] + if key in seen: + return False + functions, imports = self.parsed(path) + result = False + for node in functions.get(name, ()): + for _, called in self.calls(node): + if called in _FRAME_PASS_CALLS: + result = True + elif called in functions: + result = self.builds(path, called, seen=seen | {key}) + elif called in imports: + target = self.resolve(*imports[called]) + result = target is not None and self.builds( + *target, seen=seen | {key} + ) + if result: + break + if result: + break + # A False found under a cut cycle may be wrong from elsewhere: keep + # only what holds whatever the path. + if result or not seen: + self._builds[key] = result + return result + + def main_calls(self, path: Path) -> list[tuple[int, str, bool]]: + """``_main``'s calls in source order, each marked if it builds a pass.""" + + functions, imports = self.parsed(path) + (main,) = functions["_main"] + marked = [] + for line, name in self.calls(main): + if name in _FRAME_PASS_CALLS: + builds = True + elif name in functions: + builds = self.builds(path, name) + elif name in imports: + target = self.resolve(*imports[name]) + builds = target is not None and self.builds(*target) + else: + builds = False + marked.append((line, name, builds)) + return marked + + +class TestWhatTheExemptListRestsOn: + """The release order and engine pins L1's verdicts read (lead-call review). + + Every exempt entry's "Earlier readers" verdict, and the moved inputs' + fill notes, are static reads of the release tool's stage order and of + the pinned engine. These fail when either moves, so the trace is re-run. + """ + + @pytest.fixture(scope="class") + def release_calls(self) -> list[tuple[int, str, bool]]: + return _SourceCalls().main_calls(_RELEASE_TOOL) + + def test_the_stages_run_in_the_traced_order(self, release_calls) -> None: + first: dict[str, int] = {} + for line, name, _ in release_calls: + first.setdefault(name, line) + missing = [name for name in _TRACED_STAGE_ORDER if name not in first] + assert not missing, f"The release no longer calls {missing}: {_RETRACE}." + lines = {name: first[name] for name in _TRACED_STAGE_ORDER} + assert list(lines.values()) == sorted(lines.values()), ( + f"The release's stage order moved: {lines}; {_RETRACE}." + ) + + def test_the_frame_engine_passes_are_the_traced_ones(self, release_calls) -> None: + last = next( + line for line, name, _ in release_calls if name == _TRACED_FRAME_PASSES[-1] + ) + passes = [ + name for line, name, builds in release_calls if builds and line <= last + ] + assert passes == list(_TRACED_FRAME_PASSES), ( + "The release's engine passes through other health insurance are " + f"{passes}; {_RETRACE}." + ) + + def test_an_untraced_pass_would_be_seen(self, tmp_path) -> None: + # The reader, fed a tool as data: a tool-local helper that builds a + # dataset from the frame, a call it cannot resolve, and a stage + # imported through us_runtime's package that materializes a pass. + tool = tmp_path / "tool.py" + tool.write_text( + "from microcosm.build.us_runtime import (\n" + " with_us_other_health_insurance_inputs,\n" + ")\n" + "def _early(frame):\n" + " return _dataset_from_frame(frame)\n" + "def _main(frame):\n" + " frame = _early(frame)\n" + " frame = with_us_scf_wealth_inputs(frame)\n" + " return with_us_other_health_insurance_inputs(frame)\n", + encoding="utf-8", + ) + marked = [(name, builds) for _, name, builds in _SourceCalls().main_calls(tool)] + assert marked == [ + ("_early", True), + ("with_us_scf_wealth_inputs", False), + ("with_us_other_health_insurance_inputs", True), + ] + + def test_the_engine_pins_are_the_ones_l1_traced(self) -> None: + engine = json.loads(ENGINE_ABI_LOCK.read_text(encoding="utf-8"))["engine"] + lock = tomllib.loads((REPOSITORY_ROOT / "uv.lock").read_text(encoding="utf-8")) + build = next(p for p in lock["package"] if p["name"] == "microcosm-build") + core = [ + requirement["specifier"] + for requirement in build["metadata"]["requires-dist"] + if requirement["name"] == "policyengine-core" + and requirement.get("marker") == "extra == 'us'" + ] + locked_us = { + p["version"] for p in lock["package"] if p["name"] == "policyengine-us" + } + traced_us = _L1_TRACED_ENGINE["policyengine-us"] + pins = { + "policyengine-us": (engine["package"], engine["version"], locked_us), + "policyengine-core": core, + } + assert pins == { + "policyengine-us": ("policyengine-us", traced_us, {traced_us}), + "policyengine-core": [f"=={_L1_TRACED_ENGINE['policyengine-core']}"], + }, f"The engine pins moved: {pins}; {_RETRACE}." + for package, version in _L1_TRACED_ENGINE.items(): + assert f"{package} {version}" in contract._LOADED_NOT_COMPUTED + + +# X1: one or more corruptions per clause. Each takes the population and its +# valid assembled frame and returns the corrupted frame and any argument +# overrides. All but a few change one cell; the exceptions add or drop a +# column or the record, or change a household's key on every row, where no +# single cell can break the clause (R1's assembled form, R2's digest and +# orphaned clone key, R3, R9, R11, T1's presence, R4's presence, R5's age, +# R6's moved input, R7's presence, R8's twice-applied and moved donors, +# R10's column beside a CPS null). + + +def _r1_not_assembled(p, f): + return joined_frame(p, metadata=f.metadata), {} + + +def _r1_mixed(p, f): + return _without_column(f, "tax_unit", "tax_unit_spine_source_id"), {} + + +def _r1_null_source(p, f): + return _cell(f, "person", "person_source_id", None, origin="cps", clone=1), {} + + +def _r1_null_clone(p, f): + return _cell( + f, "household", "household_support_clone_index", None, origin="acs" + ), {} + + +def _r1_null_spine_source(p, f): + return _cell(f, "spm_unit", "spm_unit_spine_source_id", None, origin="cps"), {} + + +def _r1_unknown_channel(p, f): + return _cell(f, "family", "family_support_channel", "acs", origin="acs"), {} + + +def _r1_record_missing(p, f): + return _rebuild(f, _tables(f), metadata={}), {} + + +def _r1_record_two_channels(p, f): + record = clone_zero_assembly_record(f)[SPINE_ASSEMBLY_MANIFEST_KEY] + counts = { + entity: { + channel: count + for channel, count in by_channel.items() + if channel != PUF_TAX_DETAIL_SUPPORT_CHANNEL + } + for entity, by_channel in record["native_row_counts"].items() + } + metadata = { + SPINE_ASSEMBLY_MANIFEST_KEY: { + **record, + "channels": (BASE_ASEC_SUPPORT_CHANNEL, ACS_2024_1YR_SPINE), + "native_row_counts": counts, + } + } + return _rebuild(f, _tables(f), metadata=metadata), {} + + +def _record_with_count(f, value_of): + """``f`` whose record's ACS household count is ``value_of(count)``.""" + + record = clone_zero_assembly_record(f)[SPINE_ASSEMBLY_MANIFEST_KEY] + counts = { + entity: dict(by_channel) + for entity, by_channel in record["native_row_counts"].items() + } + counts["household"][ACS_2024_1YR_SPINE] = value_of( + counts["household"][ACS_2024_1YR_SPINE] + ) + metadata = {SPINE_ASSEMBLY_MANIFEST_KEY: {**record, "native_row_counts": counts}} + return _rebuild(f, _tables(f), metadata=metadata) + + +def _r1_record_fractional_count(p, f): + # Review nit 1: the validator reads a count through int(), so N + 0.5 + # passed for N live rows. + return _record_with_count(f, lambda count: count + 0.5), {} + + +def _r1_cross_grain(p, f): + # A clone-1 person moves into its clone-0 household (the clone-1 + # household keeps another member): only the validator's cross-grain + # check reads a person's channel against its household's. + tables = _tables(f) + person = tables["person"] + where = _household_sizes(person, "person_household_id") > 1 + row = _row(person, "person", "cps", clone=1, where=where) + household = int(person["person_household_id"].iloc[row]) + _set(person, row, "person_household_id", household - p.clone_multiplier) + return _rebuild(f, tables), {} + + +def _p5_cps_clone_three(p, f): + return _cell( + f, "household", "household_support_clone_index", 3, origin="cps", clone=1 + ), {} + + +def _p5_cps_asec_on_a_clone(p, f): + return _cell( + f, "tax_unit", "tax_unit_support_channel", "asec", origin="cps", clone=1 + ), {} + + +def _p5_cps_spine_source_moves(p, f): + table = f.table("spm_unit") + value = int(table["spm_unit_spine_source_id"].iloc[_row(table, "spm_unit", "cps")]) + return _cell(f, "spm_unit", "spm_unit_spine_source_id", value + 1, origin="cps"), {} + + +def _p5_cps_wrong_spine_tag(p, f): + return _cell(f, "family", "family_spine", ACS_2024_1YR_SPINE, origin="cps"), {} + + +def _p5_cps_non_integer_source(p, f): + return _cell(f, "person", "person_source_id", 1.5, origin="cps", clone=0), {} + + +def _p5_acs_clone_index(p, f): + return _cell( + f, "marital_unit", "marital_unit_support_clone_index", 1, origin="acs" + ), {} + + +def _p5_acs_source_not_pooled(p, f): + table = f.table("person") + value = int(table["person_source_id"].iloc[_row(table, "person", "acs")]) + return _cell(f, "person", "person_source_id", value + 10**6, origin="acs"), {} + + +def _p5_acs_offset_varies(p, f): + table = f.table("family") + value = int(table["family_spine_source_id"].iloc[_row(table, "family", "acs")]) + return _cell(f, "family", "family_spine_source_id", value + 1000, origin="acs"), {} + + +def _p5_acs_wrong_spine_tag(p, f): + return _cell(f, "household", "household_spine", ASEC_PUF_SPINE, origin="acs"), {} + + +def _q3_null_spine_tag(p, f): + return _cell(f, "tax_unit", "tax_unit_spine", None, origin="acs"), {} + + +def _p6b_acs_person_in_a_cps_group(p, f): + tables = _tables(f) + person = tables["person"] + where = _household_sizes(person, "person_spm_unit_id") > 1 + row = _row(person, "person", "acs", where=where) + spm_unit = tables["spm_unit"] + cps_unit = int(spm_unit["spm_unit_id"].iloc[_row(spm_unit, "spm_unit", "cps")]) + _set(person, row, "person_spm_unit_id", cps_unit) + return _rebuild(f, tables), {} + + +def _p6_tail_copy_relabelled(p, f): + return _cell( + f, "household", "household_support_clone_index", 1, origin="cps", clone=2 + ), {} + + +def _acs_person_in_a_household_of_two(f) -> tuple[dict, int, int]: + tables = _tables(f) + person = tables["person"] + where = _household_sizes(person, "person_household_id") > 1 + row = _row(person, "person", "acs", where=where) + household = person["person_household_id"].iloc[row] + other = int( + np.flatnonzero( + (person["person_household_id"] == household).to_numpy() + & (np.arange(len(person)) != row) + )[0] + ) + return tables, row, other + + +def _p7_sporder_repeats(p, f): + tables, row, other = _acs_person_in_a_household_of_two(f) + person = tables["person"] + _set(person, row, "SPORDER", person["SPORDER"].iloc[other]) + return _rebuild(f, tables), {} + + +def _p7_source_person_id_moves(p, f): + return _cell(f, "person", "source_person_id", "99", origin="acs"), {} + + +def _p7_serialno_null(p, f): + return _cell(f, "household", "SERIALNO", None, origin="acs"), {} + + +def _p7_staging_lacks_a_person(p, f): + lineage = staging_lineage(p) + first = min(lineage) + return f, { + "staging_lineage": {key: pair for key, pair in lineage.items() if key != first} + } + + +def _p7_serialno_swapped(p, f): + # Review blocking 2 on the frame R1 reads: see + # _serialno_swaps_between_households. + tables = _tables(f) + household = tables["household"] + _swap_serialno(household, *_two_person_acs_households(tables)) + return _rebuild(f, tables), {"staging_lineage": staging_lineage(p)} + + +def _p7_source_year_pd_na(p, f): + # Review should-fix 2 on the frame R1 reads: an Int64 pd.NA on one ACS + # person, which R10 would otherwise let a declaration cover. + tables = _tables(f) + person = tables["person"] + values = person["source_year"].astype("Int64") + values.iloc[_row(person, "person", "acs")] = pd.NA + person["source_year"] = values + return _rebuild(f, tables), {} + + +def _source_year_as_arrow_times(f, arrow_type) -> Frame: + """Review r3, should-fix 1, on the frame R1 reads: every ``source_year`` + as an Arrow dictionary of times, each holding the year as its count.""" + + tables = _tables(f) + person = tables["person"] + person["source_year"] = _arrow_dictionary(person["source_year"], arrow_type) + return _rebuild(f, tables) + + +def _p7_source_year_arrow_timestamps(p, f): + return _source_year_as_arrow_times(f, pa.timestamp("ns")), {} + + +def _p7_source_year_arrow_durations(p, f): + return _source_year_as_arrow_times(f, pa.duration("ns")), {} + + +def _p6c_tax_unit_spans_households(p, f): + # Review blocking 3 on the frame R1 reads: see + # _acs_tax_unit_spans_households. + tables = _tables(f) + person = tables["person"] + acs = _origin_mask(person, "person", "acs") + row = int( + np.flatnonzero(acs & (_household_sizes(person, "person_tax_unit_id") > 1))[0] + ) + household = person["person_household_id"].iloc[row] + elsewhere = acs & person["person_household_id"].ne(household).to_numpy() + _set( + person, + row, + "person_tax_unit_id", + person["person_tax_unit_id"].iloc[int(np.flatnonzero(elsewhere)[0])], + ) + return _rebuild(f, tables), {} + + +def _p6c_acs_household_holds_two_spm_units(p, f): + # Review blocking 3's partition on the frame R1 reads, with the clone-0 + # record recounted so the validator passes the extra unit. + tables = _tables(f) + person, spm_unit = tables["person"], tables["spm_unit"] + acs = _origin_mask(person, "person", "acs") + row = int( + np.flatnonzero(acs & (_household_sizes(person, "person_household_id") > 1))[0] + ) + extra = spm_unit.iloc[[-1]].copy() + assert extra["spm_unit_support_channel"].iloc[0] == ACS_SUPPORT_CHANNEL + for column in ("spm_unit_id", "spm_unit_source_id", "spm_unit_spine_source_id"): + extra[column] += 1 + tables["spm_unit"] = pd.concat([spm_unit, extra], ignore_index=True) + _set(person, row, "person_spm_unit_id", int(extra["spm_unit_id"].iloc[0])) + frame = _rebuild(f, tables) + return ( + _rebuild(frame, _tables(frame), metadata=clone_zero_assembly_record(frame)), + {}, + ) + + +def _p6c_acs_spm_units_merge(p, f): + # Review r2, nit 3, on the frame R1 reads: see _acs_spm_units_merge, with + # the clone-0 record recounted so the validator passes the lost unit. + tables = _tables(f) + person = tables["person"] + tables["spm_unit"] = _merge_acs_spm_units( + person, tables["spm_unit"], _origin_mask(person, "person", "acs") + ) + frame = _rebuild(f, tables) + return ( + _rebuild(frame, _tables(frame), metadata=clone_zero_assembly_record(frame)), + {}, + ) + + +def _r11_location_clone_column(p, f): + return _with_column(f, "household", "household_location_clone_index", 0), {} + + +def _r2_peridnum_disagrees(p, f): + tables = _tables(f) + person = tables["person"] + where = _household_sizes(person, "person_household_id") > 1 + row = _row(person, "person", "cps", clone=0, where=where) + value = person["PERIDNUM"].iloc[row] + _set(person, row, "PERIDNUM", ("1" if value[0] != "1" else "2") + value[1:]) + return _rebuild(f, tables), {} + + +def _r2_two_native_rows_share_a_key(p, f): + # A one-person native household takes another native household's + # H_IDNUM (its own clone keeps the old one). + tables = _tables(f) + person = tables["person"] + sizes = _household_sizes(person, "person_household_id") + row = _row(person, "person", "cps", clone=0, where=sizes == 1) + other = _row( + person, + "person", + "cps", + clone=0, + where=person["person_household_id"].to_numpy() + != person["person_household_id"].iloc[row], + ) + _set(person, row, "PERIDNUM", person["PERIDNUM"].iloc[other][:20] + "01") + return _rebuild(f, tables), {} + + +def _r2_cps_key_substituted(p, f): + # A native household and its clones take a new, unused H_IDNUM: the + # counts by income year hold, only the digest moves. + tables = _tables(f) + person = tables["person"] + old = person["PERIDNUM"].iloc[_row(person, "person", "cps", clone=0)][:20] + new = ("1" if old[0] != "1" else "2") + old[1:] + assert not person["PERIDNUM"].str.startswith(new, na=False).any() + hit = person["PERIDNUM"].str.startswith(old, na=False).to_numpy(dtype=bool) + person.loc[hit, "PERIDNUM"] = [new + v[20:] for v in person.loc[hit, "PERIDNUM"]] + return _rebuild(f, tables), {} + + +def _r2_orphaned_clone_key(p, f): + # A clone-1 household's persons take a key no clone-0 household has. + tables = _tables(f) + person = tables["person"] + row = _row(person, "person", "cps", clone=1) + hit = ( + person["person_household_id"] == person["person_household_id"].iloc[row] + ).to_numpy() + old = person["PERIDNUM"].iloc[row][:20] + new = ("1" if old[0] != "1" else "2") + old[1:] + person.loc[hit, "PERIDNUM"] = [new + v[20:] for v in person.loc[hit, "PERIDNUM"]] + return _rebuild(f, tables), {} + + +def _r2_acs_household_not_selected(p, f): + return _cell(f, "household", "SERIALNO", "2024HU9999999", origin="acs"), {} + + +def _r2_manifest_counts_differ(p, f): + manifest = dataclasses.replace(selection_manifest(p), n_cps=len(p.cps_keys) - 1) + return f, {"manifest": manifest} + + +def _r12_null_district(p, f): + return _cell(f, "household", "congressional_district_geoid", None, origin="cps"), {} + + +def _r12_wrong_state_prefix(p, f): + table = f.table("household") + state = int(table["state_fips"].iloc[_row(table, "household", "acs")]) + return _cell( + f, + "household", + "congressional_district_geoid", + (state + 1) * 100 + 1, + origin="acs", + ), {} + + +def _r12_non_positive_district(p, f): + return _cell(f, "household", "congressional_district_geoid", -601, origin="cps"), {} + + +def _t1_typehugq_out_of_domain(p, f): + return _cell(f, "household", "TYPEHUGQ", 4, origin="acs"), {} + + +def _t1_typehugq_null(p, f): + return _cell(f, "household", "TYPEHUGQ", None, origin="acs"), {} + + +def _t1_typehugq_missing(p, f): + return _without_column(f, "household", "TYPEHUGQ"), {} + + +def _t1_typehugq_boolean(p, f): + return _cell(f, "household", "TYPEHUGQ", True, origin="acs"), {} + + +def _t1_typehugq_timedelta(p, f): + # Review r3, should-fix 2: numpy registers timedelta64 as a number, and + # np.timedelta64(1, "ns") in (1, 2, 3) holds, so T1 passed this code. + table = f.table("household") + code = int(table["TYPEHUGQ"].iloc[_row(table, "household", "acs")]) + return _cell( + f, "household", "TYPEHUGQ", np.timedelta64(code, "ns"), origin="acs" + ), {} + + +def _r3_computed_column(p, f): + return _with_column(f, "spm_unit", "snap", 0.0), {} + + +def _r3_compat_aggregate(p, f): + return _with_column(f, "person", "social_security", 0.0), {} + + +def _r9_unregistered_column(p, f): + return _with_column(f, "person", "would_claim_wic", True), {} + + +def _r4_null_premium(p, f): + return _cell( + f, "person", "employer_sponsored_insurance_premiums", None, origin="acs" + ), {} + + +def _r4_premium_missing(p, f): + return _without_column(f, "person", "employer_sponsored_insurance_premiums"), {} + + +def _r5_minor_head_loses_role(p, f): + person = f.table("person") + where = (person["age"] == 17).to_numpy() & person["is_household_head"].to_numpy( + dtype=bool + ) + return _cell(f, "person", SPM_ROLE, False, origin="acs", where=where), {} + + +def _r5_no_age(p, f): + return _without_column(f, "person", "age"), {} + + +def _r6_null_tip_income(p, f): + return _cell(f, "person", "tip_income", None, origin="acs"), {} + + +def _r6_null_is_female_on_a_tail_copy(p, f): + return _cell(f, "person", "is_female", None, origin="cps", clone=2), {} + + +def _r6_null_moved_premiums_on_acs(p, f): + # d2283 lead call L1 moved health_insurance_premiums off the exempt list + # (the ACA, Medicaid and SNAP-state passes read it before its producer). + filled = _with_column(f, "person", "health_insurance_premiums", 1.0) + return _cell(filled, "person", "health_insurance_premiums", None, origin="acs"), {} + + +def _r7_null_tail_column(p, f): + return _cell( + f, + "tax_unit", + "puf_capital_gains_tail_donor_agi_band_index", + None, + origin="acs", + ), {} + + +def _r7_tail_column_missing(p, f): + return _without_column(f, "tax_unit", "puf_capital_gains_tail_transfer_weight"), {} + + +def _r8_donor_moves(p, f): + applied = f.table("tax_unit")[PUF_CAPITAL_GAINS_TAIL_APPLIED_COLUMN].to_numpy( + dtype=bool + ) + return _cell( + f, + "tax_unit", + PUF_CAPITAL_GAINS_TAIL_DONOR_SOURCE_ID_COLUMN, + 1, + origin="cps", + where=applied, + ), {} + + +def _r8_unapplied_unit_applies(p, f): + applied = f.table("tax_unit")[PUF_CAPITAL_GAINS_TAIL_APPLIED_COLUMN].to_numpy( + dtype=bool + ) + return _cell( + f, + "tax_unit", + PUF_CAPITAL_GAINS_TAIL_APPLIED_COLUMN, + True, + origin="cps", + where=~applied, + ), {} + + +def _r8_parent_donor_unapplied(p, f): + applied = f.table("tax_unit")[PUF_CAPITAL_GAINS_TAIL_APPLIED_COLUMN].to_numpy( + dtype=bool + ) + return _cell( + f, + "tax_unit", + PUF_CAPITAL_GAINS_TAIL_APPLIED_COLUMN, + False, + origin="cps", + where=applied, + ), {} + + +def _r8_donor_applied_twice(p, f): + # A second CPS tax unit applies a parent donor: the id set holds. + tables = _tables(f) + tax_unit = tables["tax_unit"] + applied = tax_unit[PUF_CAPITAL_GAINS_TAIL_APPLIED_COLUMN].to_numpy(dtype=bool) + donor = tax_unit[PUF_CAPITAL_GAINS_TAIL_DONOR_SOURCE_ID_COLUMN].iloc[ + int(np.flatnonzero(applied)[0]) + ] + row = _row(tax_unit, "tax_unit", "cps", where=~applied) + _set(tax_unit, row, PUF_CAPITAL_GAINS_TAIL_APPLIED_COLUMN, True) + _set(tax_unit, row, PUF_CAPITAL_GAINS_TAIL_DONOR_SOURCE_ID_COLUMN, donor) + return _rebuild(f, tables), {} + + +def _r8_applied_not_a_flag(p, f): + return _cell( + f, "tax_unit", PUF_CAPITAL_GAINS_TAIL_APPLIED_COLUMN, 2, origin="acs" + ), {} + + +def _r8_applied_flag_timedelta(p, f): + # Review r3, should-fix 2: an applied CPS unit's flag held as + # np.timedelta64(1, "ns"), which numbers.Real accepts and which equals 1, + # so R8 read it as True and passed the frame. + applied = f.table("tax_unit")[PUF_CAPITAL_GAINS_TAIL_APPLIED_COLUMN].to_numpy( + dtype=bool + ) + return _cell( + f, + "tax_unit", + PUF_CAPITAL_GAINS_TAIL_APPLIED_COLUMN, + np.timedelta64(1, "ns"), + origin="cps", + where=applied, + ), {} + + +def _r8_donor_moved_to_an_acs_unit(p, f): + # d2283 lead call L4: a parent donor moves from its CPS tax unit to an + # ACS one, so the id set and the one-to-one rule both still hold. + tables = _tables(f) + tax_unit = tables["tax_unit"] + applied = tax_unit[PUF_CAPITAL_GAINS_TAIL_APPLIED_COLUMN].to_numpy(dtype=bool) + cps_row = int(np.flatnonzero(applied)[0]) + donor = tax_unit[PUF_CAPITAL_GAINS_TAIL_DONOR_SOURCE_ID_COLUMN].iloc[cps_row] + _set(tax_unit, cps_row, PUF_CAPITAL_GAINS_TAIL_APPLIED_COLUMN, False) + _set(tax_unit, cps_row, PUF_CAPITAL_GAINS_TAIL_DONOR_SOURCE_ID_COLUMN, -1) + acs_row = _row(tax_unit, "tax_unit", "acs") + _set(tax_unit, acs_row, PUF_CAPITAL_GAINS_TAIL_APPLIED_COLUMN, True) + _set(tax_unit, acs_row, PUF_CAPITAL_GAINS_TAIL_DONOR_SOURCE_ID_COLUMN, donor) + return _rebuild(f, tables), {} + + +def _r10_register_column_null_on_acs(p, f): + return _cell(f, "person", "source_row_id", None, origin="acs"), {} + + +def _r10_register_column_null_beside_a_cps_null(p, f): + # d2283 lead call L2: R10 shares absences' gap predicate, so one null on a + # CPS row no longer switches it off for a column ACS rows lack. + column = "cps_employment_income_last_year" + frame = _acs_null_on_cps(f, "person", column, 1.0) + frame = _cell(frame, "person", column, None, origin="cps") + register = {**US_STORED_NON_VARIABLE_COLUMNS, column: "test auxiliary column"} + return frame, {"register": register} + + +_FRAME_REFUSALS = [ + # R1: incomplete assembled provenance (form, completeness, record). + (_r1_not_assembled, "Incomplete assembled provenance: the frame is not assembled"), + (_r1_mixed, "Mixed assembled and unassembled provenance: ['tax_unit'] lack"), + ( + _r1_null_source, + "Incomplete assembled provenance: assembled support metadata requires " + "complete non-null 'person_source_id'", + ), + ( + _r1_null_clone, + "Incomplete assembled provenance: 'household_support_clone_index' has 1 null", + ), + ( + _r1_null_spine_source, + "Incomplete assembled provenance: 'spm_unit_spine_source_id' has 1 null", + ), + ( + _r1_unknown_channel, + "Incomplete assembled provenance: rows must carry one of the assembled " + "channels", + ), + ( + _r1_record_missing, + "Incomplete assembled provenance: one-population provenance: " + "receipt-validated support provenance has no assembly manifest", + ), + ( + _r1_record_two_channels, + "Incomplete assembled provenance: the spine assembly record must declare", + ), + ( + _r1_record_fractional_count, + "Incomplete assembled provenance: the spine assembly record's native row " + "counts must be nonnegative integers; ['household.acs_2024_1yr=", + ), + (_r1_cross_grain, "cross-grain provenance disagrees with the assembly manifest"), + # P5: each origin's value rules on the assembled frame. + (_p5_cps_clone_three, "CPS clone indices must be 0, 1 or 2"), + ( + _p5_cps_asec_on_a_clone, + "CPS rows must carry channel 'asec' exactly on clone index 0; 1 'tax_unit'", + ), + ( + _p5_cps_spine_source_moves, + "CPS rows' spine source id must equal their source id", + ), + (_p5_cps_wrong_spine_tag, "CPS rows carry a spine tag other than 'asec_puf'"), + ( + _p5_cps_non_integer_source, + "CPS 'person_source_id' must hold source ids: 1 value(s) are not integers", + ), + (_p5_acs_clone_index, "ACS rows must carry clone index 0"), + (_p5_acs_source_not_pooled, "ACS rows' source id must equal their pooled id"), + (_p5_acs_offset_varies, "ACS 'family' ids must sit one constant offset"), + ( + _p5_acs_wrong_spine_tag, + "ACS rows carry a spine tag other than 'acs_2024_1yr'", + ), + (_q3_null_spine_tag, "A null spine tag: 1 ACS 'tax_unit' row(s)"), + # P6b and P6. + ( + _p6b_acs_person_in_a_cps_group, + "Memberships do not resolve: 1 ACS person(s)' 'person_spm_unit_id' match " + "no ACS spm_unit row", + ), + ( + _p6_tail_copy_relabelled, + "A (source id, rank) pair repeats in 'household'", + ), + # P7: SERIALNO/SPORDER lineage. + ( + _p7_sporder_repeats, + "ACS lineage does not survive: (SERIALNO, SPORDER) repeats on 2 ACS", + ), + ( + _p7_source_person_id_moves, + "ACS lineage does not survive: source_person_id differs from str(SPORDER)", + ), + ( + _p7_serialno_null, + "ACS lineage does not survive: every ACS household needs a non-empty " + "string SERIALNO", + ), + ( + _p7_staging_lacks_a_person, + "keyed by native (household id, person id); 0 missing (such as []), 1 extra", + ), + ( + _p7_serialno_swapped, + "keyed by native (household id, person id); 0 missing (such as []), 0 " + "extra (such as []), 4 moved", + ), + ( + _p7_source_year_pd_na, + "ACS lineage does not survive: every ACS person needs an integral " + "source_year: 1 value(s) are null", + ), + ( + _p7_source_year_arrow_timestamps, + "ACS lineage does not survive: every ACS person needs an integral " + "source_year: it holds dictionary[pyarrow] values, not integers", + ), + ( + _p7_source_year_arrow_durations, + "ACS lineage does not survive: every ACS person needs an integral " + "source_year: it holds dictionary[pyarrow] values, not integers", + ), + # P6c, after the assembly validator: groups nest in households, and ACS + # SPM units are the households. + ( + _p6c_tax_unit_spans_households, + "Group units do not nest in households: 1 ACS tax_unit unit(s) hold " + "persons of more than one household", + ), + ( + _p6c_acs_household_holds_two_spm_units, + "ACS SPM units must be the households (staging's one-SPM-unit-per-" + "household partition): 1 ACS household(s) hold more than one SPM unit", + ), + ( + _p6c_acs_spm_units_merge, + "Group units do not nest in households: 1 ACS spm_unit unit(s) hold " + "persons of more than one household", + ), + # R11. + (_r11_location_clone_column, "A household with more than one location"), + # R2. + ( + _r2_peridnum_disagrees, + "A CPS key without exactly one native row: CPS unit ids: persons of one " + "household disagree", + ), + ( + _r2_two_native_rows_share_a_key, + "A CPS key without exactly one native row: 1 key(s) have more than one " + "clone-0 household", + ), + ( + _r2_orphaned_clone_key, + "A CPS key without exactly one native row: 1 clone household key(s) have " + "no clone-0 household", + ), + ( + _r2_cps_key_substituted, + "CPS keys do not match the selection manifest: the frame's clone-0 " + "households give (count, by income year, digest) (24, ((2023, 12), " + "(2024, 12)), '", + ), + ( + _r2_acs_household_not_selected, + "ACS keys do not match the selection manifest", + ), + (_r2_manifest_counts_differ, "CPS keys do not match the selection manifest"), + # R12. + ( + _r12_null_district, + "A household without a congressional district: " + "'congressional_district_geoid' must be an integral geoid on every " + "household: 1 value(s) are null", + ), + ( + _r12_wrong_state_prefix, + "A household without a congressional district: 1 household(s) hold a " + "'congressional_district_geoid' whose state prefix", + ), + ( + _r12_non_positive_district, + "A household without a congressional district: 1 household(s) hold a " + "non-positive", + ), + # T1. + ( + _t1_typehugq_out_of_domain, + "TYPEHUGQ must be 1, 2 or 3 on every ACS household", + ), + (_t1_typehugq_null, "1 ACS household(s) hold [nan]"), + ( + _t1_typehugq_missing, + "on every ACS household (#1610's household materializer " + "reads it to leave group quarters out); the household table lacks it.", + ), + (_t1_typehugq_boolean, "1 ACS household(s) hold [True]"), + (_t1_typehugq_timedelta, "1 ACS household(s) hold [np.timedelta64("), + # R3. + (_r3_computed_column, "A column the engine computes at 2024 is stored: ['snap']"), + ( + _r3_compat_aggregate, + "A column the engine computes at 2024 is stored: ['social_security']", + ), + # R9. + ( + _r9_unregistered_column, + "A stored lower-case column is neither an engine variable nor registered: " + "['would_claim_wic']", + ), + # R4. + (_r4_null_premium, "A null ESI premium: d2283 one-population contract: ESI"), + (_r4_premium_missing, "A null ESI premium: the person table lacks"), + # R5. + (_r5_minor_head_loses_role, "An SPM unit has no classified adult: 1 of"), + ( + _r5_no_age, + "An SPM unit has no classified adult: the composition check cannot run", + ), + # R6. + ( + _r6_null_tip_income, + "A null in an engine input at 2024: {'person.tip_income': 1}", + ), + ( + _r6_null_is_female_on_a_tail_copy, + "A null in an engine input at 2024: {'person.is_female': 1}", + ), + ( + _r6_null_moved_premiums_on_acs, + "A null in an engine input at 2024: {'person.health_insurance_premiums': 1}", + ), + # R7. + ( + _r7_null_tail_column, + "A null PUF tail column on a tax unit: " + "{'tax_unit.puf_capital_gains_tail_donor_agi_band_index': 1}", + ), + ( + _r7_tail_column_missing, + "A null PUF tail column on a tax unit: the tax-unit table lacks", + ), + # R8. + ( + _r8_donor_moves, + "The tail donor set differs from the parent's: 1 parent donor(s) missing", + ), + ( + _r8_unapplied_unit_applies, + "The tail donor set differs from the parent's: 0 parent donor(s) missing " + "(such as []) and 1 donor(s) the parent never applied (such as [-1])", + ), + ( + _r8_parent_donor_unapplied, + "The tail donor set differs from the parent's: 1 parent donor(s) missing " + "(such as [7000000]) and 0 donor(s) the parent never applied", + ), + ( + _r8_donor_applied_twice, + "The tail donor set differs from the parent's: donor id(s) [7000000] are " + "applied on more than one tax unit", + ), + ( + _r8_applied_not_a_flag, + "The tail donor set differs from the parent's: " + "'puf_capital_gains_tail_transfer_applied' holds non-flag values [2]", + ), + ( + _r8_applied_flag_timedelta, + "The tail donor set differs from the parent's: " + "'puf_capital_gains_tail_transfer_applied' holds non-flag values " + "[np.timedelta64(1,'ns')]", + ), + ( + _r8_donor_moved_to_an_acs_unit, + "The tail donor set differs from the parent's: 1 ACS tax unit(s) apply a " + "tail donor", + ), + # R10. + ( + _r10_register_column_null_on_acs, + "A model-named column held on some CPS row is null on ACS rows without a " + "declared absence: {'person.source_row_id': '1 of", + ), + ( + _r10_register_column_null_beside_a_cps_null, + "A model-named column held on some CPS row is null on ACS rows without a " + "declared absence: {'person.cps_employment_income_last_year': '", + ), +] + + +@pytest.mark.parametrize( + ("corrupt", "message"), + _FRAME_REFUSALS, + ids=[corrupt.__name__.lstrip("_") for corrupt, _ in _FRAME_REFUSALS], +) +def test_each_clause_refuses_with_its_own_message( + population, assembled, corrupt, message +) -> None: + frame, overrides = corrupt(population, assembled) + with pytest.raises(OnePopulationContractError, match=re.escape(message)): + _require(population, frame, **overrides) + + +def test_frame_refusal_messages_are_distinct() -> None: + messages = [message for _, message in _FRAME_REFUSALS] + assert len(set(messages)) == len(messages) + + +@pytest.mark.parametrize("group", ["tax_unit", "spm_unit", "family", "marital_unit"]) +def test_a_cps_group_unit_across_households_refuses_at_r1( + population, assembled, group +) -> None: + # PR #1685 review r2, nit 3: R1 runs P6c on both origins. Its other P6c + # fixtures are all ACS, so a call on the ACS rows alone would pass a CPS + # crossing made after assembly. As _cps_unit_spans_households, on the + # frame R1 reads. + tables = _tables(assembled) + person = tables["person"] + column = f"person_{group}_id" + native = _origin_mask(person, "person", "cps") & ( + person["person_support_clone_index"].to_numpy() == 0 + ) + row = int(np.flatnonzero(native & (_household_sizes(person, column) > 1))[0]) + household = person["person_household_id"].iloc[row] + elsewhere = native & person["person_household_id"].ne(household).to_numpy() + _set(person, row, column, person[column].iloc[int(np.flatnonzero(elsewhere)[0])]) + with pytest.raises( + OnePopulationContractError, + match=re.escape( + f"Group units do not nest in households: 1 CPS {group} unit(s) hold " + "persons of more than one household" + ), + ): + _require(population, _rebuild(assembled, tables)) + + +@pytest.mark.parametrize("group", _GROUPS) +@pytest.mark.parametrize("origin", ["acs", "cps"]) +def test_a_complex_membership_refuses_at_r1( + population, assembled, origin, group +) -> None: + # Review r3, nit 2, on the frame R1 reads: as test_a_complex_membership_ + # refuses, one person's link held as a numpy complex, on either origin. + tables = _tables(assembled) + person = tables["person"] + column = US_SCHEMA.membership_column(group) + _complex_membership(person, _row(person, "person", origin), column) + with pytest.raises( + OnePopulationContractError, + match=re.escape( + f"Memberships do not resolve: {origin.upper()} persons' {column!r} " + "holds 1 value(s) that are not real numbers or strings, such as " + "[np.complex128(" + ), + ): + _require(population, _rebuild(assembled, tables)) + + +def test_every_clause_has_a_corruption() -> None: + prefixes = {corrupt.__name__.split("_")[1] for corrupt, _ in _FRAME_REFUSALS} + assert prefixes >= { + "p5", + "p6", + "p6b", + "p7", + "q3", + *(f"r{number}" for number in range(1, 13)), + "t1", + } + + +@pytest.mark.parametrize( + ("corruptions", "message"), + [ + # Within R1, the assembly validator before P6c (nesting): a person + # moved across households is a cross-grain move first. + ( + (_p6c_tax_unit_spans_households, _r1_cross_grain), + "cross-grain provenance disagrees", + ), + # R1 (P5) before R2, R6 and R12. + ( + (_p5_acs_clone_index, _r2_peridnum_disagrees, _r12_null_district), + "ACS rows must carry clone index 0", + ), + # R1 before R11, and R11 before R2 (review nit 2: no case held R11). + ( + (_r11_location_clone_column, _p5_acs_clone_index), + "ACS rows must carry clone index 0", + ), + ( + (_r2_peridnum_disagrees, _r11_location_clone_column), + "A household with more than one location", + ), + # R2 before R12 and T1. + ( + (_r12_null_district, _t1_typehugq_null, _r2_peridnum_disagrees), + "CPS unit ids: persons of one household disagree", + ), + # R3 before R9. + ((_r9_unregistered_column, _r3_computed_column), "computes at 2024"), + # R4 before R5 and R6. + ((_r6_null_tip_income, _r5_minor_head_loses_role, _r4_null_premium), "ESI"), + # R6 and R7 before R8 and R10. + ( + (_r10_register_column_null_on_acs, _r8_donor_moves, _r7_null_tail_column), + "A null PUF tail column", + ), + ( + (_r10_register_column_null_on_acs, _r6_null_tip_income), + "A null in an engine input at 2024", + ), + ], +) +def test_clauses_run_in_their_fixed_order( + population, assembled, corruptions, message +) -> None: + frame = assembled + for corrupt in corruptions: + frame, overrides = corrupt(population, frame) + assert overrides == {} + with pytest.raises(OnePopulationContractError, match=re.escape(message)): + _require(population, frame) + + +def _acs_serialno_repeats(frame: Frame) -> Frame: + """The second ACS household takes the first's ``SERIALNO``.""" + + tables = _tables(frame) + household = tables["household"] + acs = np.flatnonzero(_origin_mask(household, "household", "acs")) + _set(household, int(acs[1]), "SERIALNO", household["SERIALNO"].iloc[int(acs[0])]) + return _rebuild(frame, tables) + + +def test_a_real_location_clone_refuses_at_r1_first(population, assembled) -> None: + # Review nit 2: block_location's own cloning remaps every pooled id and + # keeps the provenance ids, so P5 (R1) reads the clone before R11 reads + # the location-clone columns it also adds. The documented precedence. + frame = clone_frame_for_location(assembled, 2) + marked = [ + entity + for entity in US_SCHEMA.entities + if f"{entity}_location_clone_index" in frame.table(entity) + ] + assert marked == list(US_SCHEMA.entities) + with pytest.raises( + OnePopulationContractError, + match=re.escape("ACS rows' source id must equal their pooled id"), + ): + _require(population, frame) + + +def test_a_repeated_serialno_refuses_at_r1_before_r2(population, assembled) -> None: + # Review nit 2: P7 (R1) reads a repeated SERIALNO before R2's + # repeated-key branch, which stays as a guard; called on its own, R2 + # refuses the same households. + frame = _acs_serialno_repeats(assembled) + with pytest.raises( + OnePopulationContractError, + match=re.escape( + "ACS lineage does not survive: SERIALNO repeats across ACS households" + ), + ): + _require(population, frame) + tables = _tables(frame) + with pytest.raises( + OnePopulationContractError, + match=re.escape("An ACS household with more than one row"), + ): + contract._require_selected_keys( + contract._split_origins(tables), selection_manifest(population) + ) + + +@pytest.mark.parametrize( + "value_of", + [str, float, lambda count: -1], + ids=["digit string", "integral float", "negative"], +) +def test_r1_refuses_a_record_count_the_validator_would_coerce( + population, assembled, value_of +) -> None: + # Review nit 1, the other forms: the validator's int() reads "N" and + # N.0 as N; a negative count it refuses itself, but R1's check reads + # every count first, so the message is one. + with pytest.raises( + OnePopulationContractError, + match=re.escape( + "the spine assembly record's native row counts must be nonnegative integers" + ), + ): + _require(population, _record_with_count(assembled, value_of)) + + +# Property: a null in any checked cell refuses. "Checked" means some clause +# reads every value of the column on those rows; an exempt column, or a +# register column on a CPS row (R10 reads it only on ACS rows), is not. +def _checked_cells(population, frame: Frame) -> list[tuple[str, str, str]]: + tables = {entity: frame.table(entity) for entity in frame.entities} + inputs = StandInVariableIndex.from_lock().inputs_at_2024(tables) + cells = [ + (entity, column, "any") + for entity in US_SCHEMA.entities + for column in ( + support_source_id_column(entity), + support_channel_column(entity), + support_clone_index_column(entity), + spine_source_id_column(entity), + f"{entity}_spine", + ) + ] + cells += [ + ("household", "congressional_district_geoid", "any"), + ("household", "state_fips", "any"), + ("household", "SERIALNO", "acs"), + ("household", "TYPEHUGQ", "acs"), + ("person", "SPORDER", "acs"), + ("person", "source_household_id", "acs"), + ("person", "source_person_id", "acs"), + ("person", "source_row_id", "acs"), + ("person", "source_year", "any"), + ("person", "PERIDNUM", "cps"), + *(("tax_unit", column, "any") for column in PUF_TAIL_TAX_UNIT_COLUMNS), + ] + cells += [ + (entity, column, "any") + for entity in US_SCHEMA.entities + for column in sorted(inputs - set(RELEASE_WRITTEN_INPUTS)) + if column in tables[entity] + ] + return sorted(set(cells)) + + +@pytest.fixture(scope="module") +def checked_cells(population, assembled): + return _checked_cells(population, assembled) + + +def test_the_checked_cells_cover_the_engine_inputs(checked_cells) -> None: + columns = {column for _, column, _ in checked_cells} + assert {"age", SPM_ROLE, "tip_income", "employer_sponsored_insurance_premiums"} <= ( + columns + ) + assert "takes_up_ssi_if_eligible" not in columns + + +@settings(max_examples=60, deadline=None, database=None) +@given(data=st.data()) +def test_a_null_in_any_checked_cell_refuses( + population, assembled, checked_cells, data +) -> None: + entity, column, origin = data.draw(st.sampled_from(checked_cells)) + table = assembled.table(entity) + if origin == "any": + rows = np.arange(len(table)) + else: + rows = np.flatnonzero(_origin_mask(table, entity, origin)) + row = int(data.draw(st.sampled_from(rows.tolist()))) + tables = _tables(assembled) + _set(tables[entity], row, column, None) + frame = _rebuild(assembled, tables) + with pytest.raises(OnePopulationContractError): + _require(population, frame) + + +# --------------------------- phase 3: the combined SPM role record (S1, Q6) + + +def _role_inputs(frame: Frame) -> tuple[dict, dict]: + return cps_role_record(frame), staging_role_receipt(frame) + + +def _swap_cps_roles(frame: Frame) -> Frame: + """Two CPS persons trade roles: every count holds, the digest moves.""" + + tables = _tables(frame) + person = tables["person"] + cps = _origin_mask(person, "person", "cps") + role = person[SPM_ROLE].to_numpy(dtype=bool) + holder = int(np.flatnonzero(cps & role)[0]) + other = int(np.flatnonzero(cps & ~role)[0]) + values = role.copy() + values[[holder, other]] = values[[other, holder]] + person[SPM_ROLE] = values + return _rebuild(frame, tables) + + +def _swap_acs_roles(frame: Frame) -> Frame: + """An adult ACS role holder and an adult of its household without it trade. + + PR #1685 review, should-fix 1 (its example: a 40-year-old reference + person and a 25-year-old adult child): every count holds, so staging's + receipt still covers the rows and the role gate's counts are unchanged; + only the persons' ``RELSHIPP`` says which of them holds the role. + """ + + tables = _tables(frame) + person = tables["person"] + adult_acs = _origin_mask(person, "person", "acs") & person["age"].ge(18).to_numpy() + role = person[SPM_ROLE].to_numpy(dtype=bool) + household = person["person_household_id"].to_numpy() + holder = next( + int(row) + for row in np.flatnonzero(adult_acs & role) + if (adult_acs & ~role & (household == household[row])).any() + ) + other = int(np.flatnonzero(adult_acs & ~role & (household == household[holder]))[0]) + values = role.copy() + values[[holder, other]] = values[[other, holder]] + person[SPM_ROLE] = values + return _rebuild(frame, tables) + + +def _relshipp_as(frame: Frame, form: str) -> Frame: + """The first ACS person's ``RELSHIPP`` as complex or temporal data. + + Each value keeps its code as the real part (or the count of time units), + so a conversion to real numbers reads the person's own code and role + (PR #1685 review r2, should-fix 1). + """ + + tables = _tables(frame) + person = tables["person"] + row = _row(person, "person", "acs") + code = int(person["RELSHIPP"].iloc[row]) + if form == "complex128 column": + values = person["RELSHIPP"].astype(np.complex128) + values.iloc[row] = complex(code, 1) + person["RELSHIPP"] = values + elif form == "complex in object": + _set(person, row, "RELSHIPP", complex(code, 1)) + elif form == "timedelta64 column": + person["RELSHIPP"] = pd.to_timedelta(person["RELSHIPP"].to_numpy(), unit="ns") + elif form.startswith("Arrow dictionary"): + # Review r3, should-fix 1: every code as an Arrow dictionary of + # times (CPS rows null), each holding the code as its count. + unit = pa.timestamp("ns") if "timestamps" in form else pa.duration("ns") + person["RELSHIPP"] = _arrow_dictionary(person["RELSHIPP"], unit) + else: + _set(person, row, "RELSHIPP", np.timedelta64(code, "ns")) + return _rebuild(frame, tables) + + +class TestCombinedSpmRoleRecord: + @pytest.mark.parametrize("form", _FORMS) + @pytest.mark.parametrize("seed", _SEEDS) + def test_the_record_passes_the_real_role_gate(self, seed, form) -> None: + frame = assembled_frame(_form(generate_population(seed), form)) + record = combined_spm_role_record(*_role_inputs(frame), frame) + result = us_spm_independence_role_signal_gate( + with_spm_role_record(frame, record) + ) + assert result.passed, result.failures + # Plain builtins: the record survives canonical JSON as it is. + assert json.loads(json.dumps(record, allow_nan=False)) == record + + def test_the_gate_keys_recount_the_whole_frame(self, assembled) -> None: + record = combined_spm_role_record(*_role_inputs(assembled), assembled) + expected = spm_role_gate_record(assembled) + assert {key: record[key] for key in expected} == expected + assert record["role_source"] == "source_column" + assert record["column"] == SPM_ROLE + + def test_the_digest_is_the_gates_own_rule(self, assembled) -> None: + person = assembled.table("person") + record = combined_spm_role_record(*_role_inputs(assembled), assembled) + assert record["person_role_binding_sha256"] == _role_binding_sha256(person) + cps = _origin_mask(person, "person", "cps") + assert record["origins"]["CPS"][ + "person_role_binding_sha256" + ] == _role_binding_sha256(person.loc[cps]) + + def test_counts_by_channel_and_origin(self, assembled) -> None: + record = combined_spm_role_record(*_role_inputs(assembled), assembled) + person = assembled.table("person") + spm_unit = assembled.table("spm_unit") + for channel in ASSEMBLED_CHANNELS: + rows = person["person_support_channel"].eq(channel) + assert record["counts_by_channel"][channel] == { + "persons": int(rows.sum()), + "spm_units": int( + spm_unit["spm_unit_support_channel"].eq(channel).sum() + ), + "true_role_persons": int(person.loc[rows, SPM_ROLE].sum()), + } + assert all( + record["counts_by_channel"][channel]["persons"] > 0 + for channel in ASSEMBLED_CHANNELS + ) + cps, acs = record["origins"]["CPS"], record["origins"]["ACS"] + assert cps["channels"] == [ + BASE_ASEC_SUPPORT_CHANNEL, + PUF_TAX_DETAIL_SUPPORT_CHANNEL, + ] + assert acs["channels"] == [ACS_2024_1YR_SPINE] + for key, gate_key in ( + ("persons", "persons_joined"), + ("spm_units", "native_spm_units"), + ("true_role_persons", "true_role_persons"), + ): + assert cps[key] + acs[key] == record[gate_key] + assert cps["persons"] == cps_role_record(assembled)["persons_joined"] + + def test_both_inputs_are_cited(self, assembled) -> None: + cps_record, receipt = _role_inputs(assembled) + record = combined_spm_role_record(cps_record, receipt, assembled) + assert record["evidence"] == { + "cps_record": cps_record, + "staging_receipt": receipt, + } + + def test_numpy_scalars_in_the_inputs_become_builtins(self, assembled) -> None: + cps_record, receipt = _role_inputs(assembled) + cps_record = { + **cps_record, + "persons_joined": np.int64(cps_record["persons_joined"]), + } + receipt = {**receipt, "weighted_role_share": np.float64(0.6)} + record = combined_spm_role_record(cps_record, receipt, assembled) + assert type(record["evidence"]["cps_record"]["persons_joined"]) is int + assert type(record["evidence"]["staging_receipt"]["weighted_role_share"]) is ( + float + ) + + def test_the_inputs_are_not_mutated(self, assembled) -> None: + cps_record, receipt = _role_inputs(assembled) + before = (json.dumps(cps_record), json.dumps(receipt)) + person = assembled.table("person").copy() + combined_spm_role_record(cps_record, receipt, assembled) + assert (json.dumps(cps_record), json.dumps(receipt)) == before + pd.testing.assert_frame_equal(assembled.table("person"), person) + + def test_a_frame_with_no_acs_row(self, population) -> None: + empty_acs = { + entity: population.acs_tables[entity].iloc[:0] + for entity in US_SCHEMA.entities + } + frame = to_assembled_provenance( + population.cps_tables, + empty_acs, + cps_household_weights=population.keyed_cps_household_weights, + acs_household_weights={}, + staging_lineage={}, + ) + record = combined_spm_role_record(*_role_inputs(frame), frame) + assert record["origins"]["ACS"]["persons"] == 0 + assert record["persons_joined"] == record["origins"]["CPS"]["persons"] + + def test_the_receipt_rule_and_partition_are_staging_constants(self) -> None: + # Read from acs_inputs' source: importing it loads the ACS transfer. + source = _U / "acs_inputs.py" + for constant, key in ( + ("ACS_SPM_ROLE_RULE", "rule"), + ("ACS_SPM_ROLE_PARTITION", "partition"), + ): + value = ast.literal_eval(_module_assignment(source, constant)) + assert contract._ACS_ROLE_RECEIPT_IDENTITY[key] == value, constant + + def test_the_relshipp_codes_are_staging_constants(self) -> None: + # The codes the row-level ACS role check reads (review should-fix 1) + # are copies of the rule's own constants (d2283 lead call L8). + from microcosm.build.us_runtime import acs_inputs + + assert contract._ACS_ROLE_RELSHIPP == { + acs_inputs._ACS_REFERENCE_PERSON, + *acs_inputs._ACS_SPOUSE_OF_REFERENCE, + *acs_inputs._ACS_GROUP_QUARTERS_PERSON, + } + assert contract._ACS_RELSHIPP_CODES == acs_inputs._ACS_RELSHIPP_CODES + + def test_a_swap_of_acs_roles_keeps_every_count(self, assembled) -> None: + # Why the receipt and the counts cannot catch should-fix 1's swap: + # the gate's counts and the receipt's coverage are unchanged. + swapped = _swap_acs_roles(assembled) + before, after = (spm_role_gate_record(frame) for frame in (assembled, swapped)) + assert { + key: before[key] for key in before if key != "person_role_binding_sha256" + } == {key: after[key] for key in after if key != "person_role_binding_sha256"} + assert staging_role_receipt(swapped) == staging_role_receipt(assembled) + + def test_the_receipt_keys_are_staging_receipts(self) -> None: + # The dict acs_inputs.with_acs_spm_independence_role assigns to + # ``provenance`` (U/acs_inputs.py:478-511). + from microcosm.build.us_runtime import acs_inputs + + tree = ast.parse( + inspect.getsource(acs_inputs.with_acs_spm_independence_role).strip() + ) + receipts = [ + node.value + for node in ast.walk(tree) + if isinstance(node, ast.Assign) + and [getattr(target, "id", None) for target in node.targets] + == ["provenance"] + and isinstance(node.value, ast.Dict) + ] + assert len(receipts) == 1 + keys = {key.value for key in receipts[0].keys} + assert keys == contract._ACS_ROLE_RECEIPT_KEYS + assert set(staging_role_receipt(joined_frame(generate_population(0)))) == keys + + +_ROLE_RECORD_REFUSALS = [ + ( + "persons", + lambda f: ( + {**cps_role_record(f), "persons_joined": 1}, + staging_role_receipt(f), + f, + ), + "The CPS role record does not match the frame's CPS rows: {'persons_joined': " + "{'record': 1, 'frame': ", + ), + ( + "units", + lambda f: ( + {**cps_role_record(f), "native_spm_units": 0}, + staging_role_receipt(f), + f, + ), + "The CPS role record does not match the frame's CPS rows: {'native_spm_units'", + ), + ( + "digest only", + lambda f: (cps_role_record(_swap_cps_roles(f)), staging_role_receipt(f), f), + "The CPS role record does not match the frame's CPS rows: " + "{'person_role_binding_sha256'", + ), + ( + "whole-frame record", + lambda f: (spm_role_gate_record(f), staging_role_receipt(f), f), + "The CPS role record does not match the frame's CPS rows: {'persons_joined'", + ), + ( + "missing key", + lambda f: ( + { + key: value + for key, value in cps_role_record(f).items() + if key != "true_role_persons" + }, + staging_role_receipt(f), + f, + ), + "The CPS role record does not match the frame's CPS rows: it lacks the " + "role gate's keys ['true_role_persons']", + ), + ( + "boolean count", + lambda f: ( + {**cps_role_record(f), "table_rows": True}, + staging_role_receipt(f), + f, + ), + "The CPS role record does not match the frame's CPS rows: ['table_rows'] " + "must be integer counts", + ), + ( + # Review r3, should-fix 2: numpy registers timedelta64 as an integer, + # and it compares equal to its count, so the record matched. + "timedelta count", + lambda f: ( + { + **cps_role_record(f), + "persons_joined": np.timedelta64( + cps_role_record(f)["persons_joined"], "ns" + ), + }, + staging_role_receipt(f), + f, + ), + "The CPS role record does not match the frame's CPS rows: " + "['persons_joined'] must be integer counts", + ), + ( + "role source", + lambda f: ( + cps_role_record(f), + staging_role_receipt(f), + _without_column(f, "person", SPM_ROLE), + ), + "The SPM role must come from the source column (role_source " + "'source_column'); the frame's role source is 'household_structure_fallback'", + ), + ( + "null role", + lambda f: ( + cps_role_record(f), + staging_role_receipt(f), + _cell(f, "person", SPM_ROLE, None, origin="acs"), + ), + "The SPM role record needs a non-null boolean 'is_spm_independent_minor_role'", + ), + ( + "missing age", + lambda f: ( + cps_role_record(f), + staging_role_receipt(f), + _without_column(f, "person", "age"), + ), + "The SPM role record needs 'age' on the person table", + ), + ( + "integer role", + lambda f: ( + cps_role_record(f), + staging_role_receipt(f), + _with_column( + f, "person", SPM_ROLE, f.table("person")[SPM_ROLE].astype(np.int64) + ), + ), + "The SPM role record needs a non-null boolean 'is_spm_independent_minor_role' " + "on every person; 0 null(s), inferred type 'integer'", + ), + ( + "unknown person channel", + lambda f: ( + cps_role_record(f), + staging_role_receipt(f), + _cell(f, "person", "person_support_channel", "acs", origin="acs"), + ), + "The SPM role record needs every row's origin: 'person_support_channel' " + "must hold one of ['asec', 'puf_tax_detail', 'acs_2024_1yr'] on every row; " + "it holds [\"'acs'\"]", + ), + ( + "null spm unit channel", + lambda f: ( + cps_role_record(f), + staging_role_receipt(f), + _cell(f, "spm_unit", "spm_unit_support_channel", None, origin="acs"), + ), + "The SPM role record needs every row's origin: 'spm_unit_support_channel' " + "must hold one of", + ), + ( + "channel column missing", + lambda f: ( + cps_role_record(f), + staging_role_receipt(f), + _without_column(f, "spm_unit", "spm_unit_support_channel"), + ), + "The SPM role record needs every row's origin: the 'spm_unit' table lacks " + "'spm_unit_support_channel'", + ), + ( + "receipt keys", + lambda f: ( + cps_role_record(f), + {k: v for k, v in staging_role_receipt(f).items() if k != "rule"}, + f, + ), + "Staging's ACS role receipt lacks keys ['rule']", + ), + ( + "receipt identity", + lambda f: ( + cps_role_record(f), + {**staging_role_receipt(f), "provenance": "asec"}, + f, + ), + "Staging's ACS role receipt is not the ACS RELSHIPP role rule's: " + "{'provenance': 'asec'}", + ), + ( + "receipt rule", + lambda f: ( + cps_role_record(f), + { + **staging_role_receipt(f), + "rule": staging_role_receipt(f)["rule"] + " OR RELSHIPP == 22", + }, + f, + ), + "Staging's ACS role receipt is not the ACS RELSHIPP role rule's: {'rule': ", + ), + ( + "receipt partition", + lambda f: ( + cps_role_record(f), + {**staging_role_receipt(f), "partition": "spm_unit"}, + f, + ), + "Staging's ACS role receipt is not the ACS RELSHIPP role rule's: " + "{'partition': 'spm_unit'}", + ), + ( + "receipt coverage", + lambda f: (cps_role_record(f), staging_role_receipt(f, staged_beyond=-1), f), + "Staging's ACS role receipt covers fewer rows than the frame's ACS rows: " + "{'persons'", + ), + ( + # Review r3, should-fix 2: a numpy timedelta64 count passed as an + # integer at least the selected one. + "receipt timedelta count", + lambda f: ( + cps_role_record(f), + { + **staging_role_receipt(f), + "spm_units": np.timedelta64(staging_role_receipt(f)["spm_units"], "ns"), + }, + f, + ), + "Staging's ACS role receipt covers fewer rows than the frame's ACS rows: " + "{'spm_units'", + ), + # Each ACS person's role is the one its RELSHIPP gives (review + # should-fix 1): the receipt states counts only. + ( + "acs roles traded", + lambda f: (cps_role_record(f), staging_role_receipt(f), _swap_acs_roles(f)), + "The ACS persons' SPM roles are not staging's RELSHIPP rule's: 2 of ", + ), + ( + "relshipp missing", + lambda f: ( + cps_role_record(f), + staging_role_receipt(f), + _without_column(f, "person", "RELSHIPP"), + ), + "The ACS persons' SPM roles are not staging's RELSHIPP rule's: the person " + "table lacks 'RELSHIPP'", + ), + ( + "relshipp off-domain", + lambda f: ( + cps_role_record(f), + staging_role_receipt(f), + _cell(f, "person", "RELSHIPP", 19, origin="acs"), + ), + "The ACS persons' SPM roles are not staging's RELSHIPP rule's: 1 ACS " + "person(s) hold a blank or off-domain RELSHIPP", + ), + # Review r2, should-fix 1: each keeps the person's code as its real part + # or count of units. The complex forms and the timedelta64 column passed, + # read as the person's own code; one numpy timedelta64 in an object + # column already refused as off-domain, and now gets this message. + # Review r3, should-fix 1: the Arrow dictionaries of times passed too. + *( + ( + f"relshipp {form}", + lambda f, form=form: ( + cps_role_record(f), + staging_role_receipt(f), + _relshipp_as(f, form), + ), + "The ACS persons' SPM roles are not staging's RELSHIPP rule's: RELSHIPP " + f"on ACS rows holds {found}", + ) + for form, found in ( + ("complex128 column", "complex128 values, not integer codes"), + ( + "complex in object", + "1 value(s) that are not real numbers or strings, such as [(", + ), + ("timedelta64 column", "timedelta64[ns] values, not integer codes"), + ( + "numpy timedelta64 in object", + "1 value(s) that are not real numbers or strings, such as " + "[np.timedelta64(", + ), + ( + "Arrow dictionary of durations", + "dictionary" + "[pyarrow] values, not integer codes", + ), + ( + "Arrow dictionary of timestamps", + "dictionary" + "[pyarrow] values, not integer codes", + ), + ) + ), +] + + +@pytest.mark.parametrize( + ("case", "inputs", "message"), + _ROLE_RECORD_REFUSALS, + ids=[case for case, _, _ in _ROLE_RECORD_REFUSALS], +) +def test_the_role_record_refuses_with_its_own_message( + assembled, case, inputs, message +) -> None: + with pytest.raises(OnePopulationContractError, match=re.escape(message)): + combined_spm_role_record(*inputs(assembled)) + + +def test_the_role_record_refusal_messages_are_distinct() -> None: + messages = [message for _, _, message in _ROLE_RECORD_REFUSALS] + assert len(set(messages)) == len(messages) + + +@pytest.mark.parametrize( + "form", ["Int64", "object", "int64[pyarrow]", "Arrow dictionary of int64"] +) +def test_relshipp_in_a_real_dtype_passes(assembled, form) -> None: + # Review r3, should-fix 1: the allowlist reads these codes. The frame + # holds RELSHIPP as float64, null on CPS rows (test_the_record_passes_ + # the_real_role_gate covers it); staging's PUMS parse reads it as a + # number, and the review's probes kept nullable and object codes valid. + tables = _tables(assembled) + person = tables["person"] + codes = person["RELSHIPP"] + if form == "Arrow dictionary of int64": + person["RELSHIPP"] = _arrow_dictionary(codes, pa.int64()) + elif form == "int64[pyarrow]": + person["RELSHIPP"] = pd.Series( + pd.arrays.ArrowExtensionArray( + pa.array([None if pd.isna(code) else int(code) for code in codes]) + ), + index=codes.index, + ) + assert str(person["RELSHIPP"].dtype) == form + elif form == "object": + person["RELSHIPP"] = pd.Series( + [None if pd.isna(code) else int(code) for code in codes], + index=codes.index, + dtype=object, + ) + else: + person["RELSHIPP"] = codes.astype(form) + frame = _rebuild(assembled, tables) + combined_spm_role_record(*_role_inputs(frame), frame) + + +def test_the_role_records_refusals_are_live_against_the_gate(assembled) -> None: + # The digest-only corruption is one the gate itself would catch on a + # frame whose roles moved: the record of the swapped frame fails the + # gate on the original frame. + swapped = _swap_cps_roles(assembled) + stale = spm_role_gate_record(swapped) + result = us_spm_independence_role_signal_gate( + with_spm_role_record(assembled, stale) + ) + assert not result.passed + assert stale["persons_joined"] == spm_role_gate_record(assembled)["persons_joined"] + + +@pytest.mark.parametrize("form", _FORMS) +@pytest.mark.parametrize("seed", _SEEDS) +def test_a_cps_record_derived_before_the_join_is_accepted(seed, form) -> None: + # PR 4 derives the CPS record on the selected CPS rows before they meet + # the ACS rows: the join must keep their order and the digest's dtypes. + population = _form(generate_population(seed), form) + frame = assembled_frame(population) + person = population.cps_tables["person"] + record = { + "persons_joined": len(person), + "table_rows": len(person), + "native_spm_units": len(population.cps_tables["spm_unit"]), + "true_role_persons": int(person[SPM_ROLE].sum()), + "person_role_binding_sha256": _role_binding_sha256(person), + } + combined = combined_spm_role_record(record, staging_role_receipt(frame), frame) + assert ( + combined["origins"]["CPS"]["person_role_binding_sha256"] + == (record["person_role_binding_sha256"]) + ) + + +# -------------------------------------------- phase 3: absences (A1, Q2) + + +def _absences(frame: Frame, *, fills=(), zero_written=None, declared=None) -> dict: + return absences( + frame, + fill_manifest=fill_manifest(fills), + zero_written=zero_written or {}, + declared=declared or {}, + ) + + +def _keyed(record: dict) -> dict[tuple[str, str, str, str], dict]: + keyed = { + (entry["entity"], entry["column"], entry["kind"], entry["origin"]): entry + for entry in record["entries"] + } + assert len(keyed) == len(record["entries"]) + return keyed + + +def _share(frame: Frame, entity: str, mask: np.ndarray) -> float: + weights = np.asarray(frame.resolve_weights(entity).values, dtype=np.float64) + return float(weights[mask].sum() / weights.sum()) + + +_GENERATED_ABSENCES = { + ("household", "SERIALNO", "raw source column", "CPS"), + ("household", "TYPEHUGQ", "raw source column", "CPS"), + ("person", "PERIDNUM", "raw source column", "ACS"), + # The ACS role rule's source column, kept on ACS rows (review should-fix 1). + ("person", "RELSHIPP", "raw source column", "CPS"), + ("person", "SPORDER", "raw source column", "CPS"), + ("person", "SSI_VAL", "raw source column", "ACS"), + ("person", "takes_up_ssi_if_eligible", "release-written", "ACS"), +} + + +def _acs_fill(frame: Frame, column: str, *, rows: int | None = None) -> dict: + table = frame.table("person") + acs = int(_origin_mask(table, "person", "acs").sum()) + filled = acs if rows is None else rows + return { + "entity": "person", + "column": column, + "filled_rows": filled, + "rows": len(table), + "fill_value": "0.0", + "fill_kind": "variable default_value", + "register_missing_rows": filled, + "missing_rows_by_spine": {ACS_2024_1YR_SPINE: filled}, + } + + +class TestAbsences: + @pytest.mark.parametrize("form", _FORMS) + def test_both_directions_on_the_generated_population(self, form) -> None: + frame = assembled_frame(_form(generate_population(0), form)) + record = _absences(frame) + assert set(_keyed(record)) == _GENERATED_ABSENCES + + def test_rows_and_shares_are_keyed_by_channel(self, assembled) -> None: + keyed = _keyed(_absences(assembled)) + person = assembled.table("person") + acs = _origin_mask(person, "person", "acs") + ssi = keyed[("person", "takes_up_ssi_if_eligible", "release-written", "ACS")] + assert ssi["rows"] == ssi["origin_rows"] == int(acs.sum()) + assert ssi["rows_by_channel"] == {ACS_2024_1YR_SPINE: int(acs.sum())} + assert ssi["entity_weight_share"] == pytest.approx( + _share(assembled, "person", acs) + ) + assert ssi["evidence"] == RELEASE_WRITTEN_INPUTS["takes_up_ssi_if_eligible"] + sporder = keyed[("person", "SPORDER", "raw source column", "CPS")] + channel = person["person_support_channel"] + assert sporder["rows_by_channel"] == { + BASE_ASEC_SUPPORT_CHANNEL: int(channel.eq(BASE_ASEC_SUPPORT_CHANNEL).sum()), + PUF_TAX_DETAIL_SUPPORT_CHANNEL: int( + channel.eq(PUF_TAX_DETAIL_SUPPORT_CHANNEL).sum() + ), + } + by_channel = sporder["entity_weight_share_by_channel"] + assert by_channel[BASE_ASEC_SUPPORT_CHANNEL] == pytest.approx( + _share( + assembled, "person", channel.eq(BASE_ASEC_SUPPORT_CHANNEL).to_numpy() + ) + ) + assert sum(by_channel.values()) == pytest.approx(sporder["entity_weight_share"]) + assert sporder["entity_weight_share"] + ssi["entity_weight_share"] == ( + pytest.approx(1.0) + ) + + def test_every_entity_resolves_weights(self, assembled) -> None: + record = _absences(assembled) + for entity in US_SCHEMA.entities: + rows = record["rows_by_channel"][entity] + assert sum(rows.values()) == assembled.n(entity) + weights = assembled.resolve_weights(entity).values + assert len(weights) == assembled.n(entity) + assert np.isfinite(weights).all() and weights.sum() > 0 + + def test_a_column_null_on_every_row_is_no_absence(self, assembled) -> None: + # Neither origin holds a value, so neither lacks it relative to the + # other: no entry and no refusal, although parent_1_id is model-named. + frame = _with_column( + assembled, + "person", + "parent_1_id", + pd.Series(None, index=assembled.table("person").index, dtype=object), + ) + assert set(_keyed(_absences(frame))) == _GENERATED_ABSENCES + + def test_typehugq_is_not_filed_as_harmless(self, assembled) -> None: + typehugq = _keyed(_absences(assembled))[ + ("household", "TYPEHUGQ", "raw source column", "CPS") + ] + assert typehugq["readers"] == list(RAW_COLUMN_READERS["TYPEHUGQ"]) + assert "#1610" in typehugq["readers"][0] + assert "the release reads it" in typehugq["evidence"] + + def test_the_household_type_and_predictor_columns_name_their_readers( + self, assembled + ) -> None: + frame = _acs_null_on_cps(assembled, "household", "HRHTYPE", 1) + for column, value in ( + ("A_EXPRRP", 1), + ("A_MARITL", 7), + ("WKSWORK", 52), + ("PRDTRACE", 1), + ("PEDISDRS", 2), + ): + frame = _acs_null_on_cps(frame, "person", column, value) + keyed = _keyed(_absences(frame)) + for entity, column in ( + ("household", "HRHTYPE"), + ("person", "A_EXPRRP"), + ("person", "A_MARITL"), + ): + entry = keyed[(entity, column, "raw source column", "ACS")] + assert entry["readers"] == [contract._HOUSEHOLD_TYPE_READER] + assert keyed[("person", "WKSWORK", "raw source column", "ACS")]["readers"] == [ + "org_wages" + ] + assert keyed[("person", "PRDTRACE", "raw source column", "ACS")]["readers"] == [ + "org_wages", + "scf_auto_loans", + "scf_wealth", + ] + assert keyed[("person", "PEDISDRS", "raw source column", "ACS")]["readers"] == [ + "ssi_disability_criteria" + ] + # A raw column no release reader is listed for says so. + ssi_val = keyed[("person", "SSI_VAL", "raw source column", "ACS")] + assert ssi_val["readers"] == [] + assert "no release reader is listed" in ssi_val["evidence"] + + def test_raw_readers_are_the_predictor_joins_producers(self) -> None: + from microcosm.build.us_runtime import acs_release_predictors + + inverted: dict[str, set[str]] = {} + for producer, columns in acs_release_predictors._MODEL_PREDICTORS.items(): + for column in columns: + inverted.setdefault(column, set()).add(producer) + household_type = {"TYPEHUGQ", "HRHTYPE", "A_EXPRRP", "A_MARITL"} + assert set(RAW_COLUMN_READERS) == set(inverted) | household_type + assert set(acs_release_predictors._OUTPUT_COLUMNS) == set(inverted) + for column, producers in inverted.items(): + assert RAW_COLUMN_READERS[column] == tuple(sorted(producers)), column + for column in household_type: + assert RAW_COLUMN_READERS[column] == (contract._HOUSEHOLD_TYPE_READER,) + assert ABSENCE_KINDS == ( + "owner-declared", + "release-written", + "raw source column", + "reviewed default fill", + "zero written", + "origin-native", + ) + + def test_a_reviewed_default_fill_over_every_acs_row(self, assembled) -> None: + record = _absences(assembled, fills=[_acs_fill(assembled, "tip_income")]) + entry = _keyed(record)[("person", "tip_income", "reviewed default fill", "ACS")] + acs = _origin_mask(assembled.table("person"), "person", "acs") + assert entry["rows_by_channel"] == {ACS_2024_1YR_SPINE: int(acs.sum())} + assert entry["entity_weight_share"] == pytest.approx( + _share(assembled, "person", acs) + ) + assert entry["detail"] == { + "fill_value": "0.0", + "fill_kind": "variable default_value", + "register_missing_rows": int(acs.sum()), + } + assert "reviewed_engine_input_nulls" in entry["evidence"] + + def test_a_partial_fill_names_no_rows_or_share(self, assembled) -> None: + cps_fill = { + **_acs_fill(assembled, "employer_sponsored_insurance_premiums", rows=3), + "missing_rows_by_spine": {CPS_SPINE_TAG: 2, ACS_2024_1YR_SPINE: 1}, + } + keyed = _keyed(_absences(assembled, fills=[cps_fill])) + for origin, rows in (("CPS", 2), ("ACS", 1)): + entry = keyed[ + ( + "person", + "employer_sponsored_insurance_premiums", + "reviewed default fill", + origin, + ) + ] + assert entry["rows"] == rows + assert entry["rows_by_channel"] is None + assert entry["entity_weight_share"] is None + assert "names no rows" in entry["rows_rule"] + + def test_a_zero_spine_count_files_no_entry(self, assembled) -> None: + # Review should-fix 5's bound is nonnegative, not positive: a spine + # the fill did not touch may count zero, and files nothing. + fill = { + **_acs_fill(assembled, "tip_income", rows=3), + "missing_rows_by_spine": {CPS_SPINE_TAG: 0, ACS_2024_1YR_SPINE: 3}, + } + keyed = _keyed(_absences(assembled, fills=[fill])) + assert ( + keyed[("person", "tip_income", "reviewed default fill", "ACS")]["rows"] == 3 + ) + assert ("person", "tip_income", "reviewed default fill", "CPS") not in keyed + + def test_zero_written_on_a_nullable_numeric_column(self, assembled) -> None: + # Review should-fix 6: a Float64 origin-native amount, pd.NA on CPS + # rows and zeros on two ACS rows. eq(0) on it is a nullable boolean, + # which used to reach the weight lookup as an object array. Review r2, + # nit 4: a third ACS row holds pd.NA, so a mask that read a null as a + # zero would count three ACS rows, not two. + column = "acs_social_security_income" + frame = _acs_only(assembled, "person", column, 120.0) + tables = _tables(frame) + person = tables["person"] + acs = _origin_mask(person, "person", "acs") + values = person[column].astype("Float64") + zeros, null = np.flatnonzero(acs)[:2], np.flatnonzero(acs)[2] + values.iloc[zeros] = 0.0 + values.iloc[null] = pd.NA + person[column] = values + frame = _rebuild(frame, tables) + assert str(frame.table("person")[column].dtype) == "Float64" + assert int(frame.table("person")[column].isna().sum()) == int((~acs).sum()) + 1 + record = _absences(frame, zero_written={column: "receipt"}) + entry = _keyed(record)[("person", column, "zero written", "ACS")] + mask = np.zeros(len(person), dtype=bool) + mask[zeros] = True + assert entry["rows"] == 2 + assert entry["rows_by_channel"] == {ACS_2024_1YR_SPINE: 2} + assert entry["entity_weight_share"] == pytest.approx( + _share(frame, "person", mask) + ) + + def test_zero_written_counts_acs_zeros_as_an_upper_bound(self, assembled) -> None: + receipt = "acs_transfer cells_kept_at_zero (U/acs_transfer.py:2440-2468)" + record = _absences(assembled, zero_written={"tip_income": receipt}) + entry = _keyed(record)[("person", "tip_income", "zero written", "ACS")] + person = assembled.table("person") + zeros = _origin_mask(person, "person", "acs") & person["tip_income"].eq(0) + assert entry["rows"] == int(zeros.sum()) > 0 + assert entry["entity_weight_share"] == pytest.approx( + _share(assembled, "person", zeros.to_numpy()) + ) + assert entry["detail"] == {"receipt": receipt} + assert "upper bound" in entry["rows_rule"] + + def test_an_owner_declared_absence(self, assembled) -> None: + frame = _acs_null_on_cps(assembled, "person", "parent_1_id", 3) + with pytest.raises( + OnePopulationContractError, + match=re.escape( + "A column one origin lacks has no absence kind: " + "{'person.parent_1_id': 'null on" + ), + ): + _absences(frame) + decision = "US data owner: ACS rows carry no parent link (d2283 Q2)" + entry = _keyed(_absences(frame, declared={"parent_1_id": decision}))[ + ("person", "parent_1_id", "owner-declared", "ACS") + ] + assert entry["detail"] == {"decision": decision} + assert entry["evidence"] == decision + + def test_a_frame_with_no_acs_row(self, population) -> None: + empty_acs = { + entity: population.acs_tables[entity].iloc[:0] + for entity in US_SCHEMA.entities + } + frame = to_assembled_provenance( + population.cps_tables, + empty_acs, + cps_household_weights=population.keyed_cps_household_weights, + acs_household_weights={}, + staging_lineage={}, + ) + record = _absences(frame) + assert record["entries"] == [] + assert record["rows_by_channel"]["person"][ACS_2024_1YR_SPINE] == 0 + contract._absences_json(record) # allow_nan=False holds + + def test_the_json_is_deterministic(self, population, tmp_path) -> None: + records = [ + _absences( + assembled_frame(_form(population, form)), + zero_written={"tip_income": "receipt"}, + ) + for form in _FORMS + ] + texts = [contract._absences_json(record) for record in records] + assert texts[0] == texts[1] + path = write_absences(records[0], tmp_path) + assert path == tmp_path / ABSENCES_FILENAME + assert path.read_text(encoding="ascii") == texts[0] + assert json.loads(texts[0]) == records[0] + assert ( + texts[0] + == json.dumps(json.loads(texts[0]), sort_keys=True, separators=(",", ":")) + + "\n" + ) + with pytest.raises(ValueError): + contract._absences_json({**records[0], "bad": float("nan")}) + + +_ABSENCE_REFUSALS = [ + ( + "fill on a missing column", + lambda f: {"fills": [{**_acs_fill(f, "tip_income"), "column": "no_such"}]}, + "The fill manifest does not describe this frame: it fills 'person'.'no_such'", + ), + ( + "fill rows", + lambda f: {"fills": [{**_acs_fill(f, "tip_income"), "rows": 1}]}, + "The fill manifest does not describe this frame: its 'person' table had 1 rows", + ), + ( + # Review r3, should-fix 2: a numpy timedelta64 count equals its count + # of units, so it passed as the table's row count. + "fill rows timedelta", + lambda f: { + "fills": [ + { + **_acs_fill(f, "tip_income"), + "rows": np.timedelta64(len(f.table("person")), "ns"), + } + ] + }, + "The fill manifest does not describe this frame: its 'person' table had " + "np.timedelta64(", + ), + ( + "fill spine tag", + lambda f: { + "fills": [ + { + **_acs_fill(f, "tip_income", rows=2), + "missing_rows_by_spine": {"acs": 2}, + } + ] + }, + "The fill manifest does not describe this frame: 'person'.'tip_income''s rows " + "by spine {'acs': 2}", + ), + ( + "fill count", + lambda f: { + "fills": [ + { + **_acs_fill(f, "tip_income", rows=2), + "missing_rows_by_spine": {ACS_2024_1YR_SPINE: 3}, + } + ] + }, + "The fill manifest does not describe this frame: 'person'.'tip_income''s rows " + "by spine {'acs_2024_1yr': 3}", + ), + ( + # Review should-fix 5: the sum matches, and the origin-capacity check + # rejects only counts above capacity, so -1 became a CPS entry's rows. + "fill negative count", + lambda f: { + "fills": [ + { + **_acs_fill(f, "tip_income", rows=3), + "missing_rows_by_spine": { + CPS_SPINE_TAG: -1, + ACS_2024_1YR_SPINE: 4, + }, + } + ] + }, + "The fill manifest does not describe this frame: 'person'.'tip_income''s rows " + "by spine {'asec_puf': -1, 'acs_2024_1yr': 4} must count its 3 filled rows, " + "in nonnegative integers", + ), + ( + "fill beyond the origin", + lambda f: { + "fills": [ + { + **_acs_fill(f, "tip_income", rows=10_000), + "rows": len(f.table("person")), + } + ] + }, + "The fill manifest does not describe this frame: it fills 10000 ACS rows", + ), + ( + "fill leaves a null", + lambda f: { + "frame": _cell(f, "person", "tip_income", None, origin="acs"), + "fills": [_acs_fill(f, "tip_income")], + }, + "The fill manifest does not describe this frame: 'person'.'tip_income' still " + "holds 1 null(s)", + ), + ( + "fill twice", + lambda f: {"fills": [_acs_fill(f, "tip_income")] * 2}, + "The fill manifest does not describe this frame: it fills 'person'.'tip_income' " + "twice", + ), + ( + "manifest totals", + lambda f: { + "manifest": { + **fill_manifest([_acs_fill(f, "tip_income")]), + "columns_filled": 2, + } + }, + "The fill manifest does not describe this frame: it says 2 columns", + ), + ( + "manifest keys", + lambda f: {"manifest": {"fills": []}}, + "The fill manifest does not describe this frame: it lacks keys", + ), + ( + "manifest violations", + lambda f: { + "manifest": { + **fill_manifest(), + "unregistered_violations": [{"column": "tip_income"}], + } + }, + "The fill manifest does not describe this frame: it records unregistered " + "violations", + ), + ( + "zero written absent", + lambda f: {"zero_written": {"no_such": "receipt"}}, + "A zero-written column the frame lacks: 'no_such'", + ), + ( + "zero written text", + lambda f: {"zero_written": {"SERIALNO": "receipt"}}, + "A zero-written column must be numeric: 'household'.'SERIALNO'", + ), + ( + "zero written receipt", + lambda f: {"zero_written": {"tip_income": " "}}, + "A zero-written column needs its receipt; 'tip_income' has none", + ), + ( + "two kinds", + lambda f: { + "fills": [_acs_fill(f, "tip_income")], + "zero_written": {"tip_income": "receipt"}, + }, + "An absence has one kind: ['tip_income'] are named by both fill_manifest and " + "zero_written", + ), + ( + "declared empty", + lambda f: {"declared": {"parent_1_id": " "}}, + "A declared absence needs its owner's decision; 'parent_1_id' has none", + ), + ( + "unknown channel", + lambda f: { + "frame": _cell(f, "family", "family_support_channel", "acs", origin="acs") + }, + "The absences file needs every row's origin: 'family_support_channel' must " + "hold one of", + ), + ( + "null channel", + lambda f: { + "frame": _cell(f, "person", "person_support_channel", None, origin="cps") + }, + "The absences file needs every row's origin: 'person_support_channel' must " + "hold one of ['asec', 'puf_tax_detail', 'acs_2024_1yr'] on every row; it " + "holds ['None']", + ), + ( + "channel column missing", + lambda f: {"frame": _without_column(f, "tax_unit", "tax_unit_support_channel")}, + "The absences file needs every row's origin: the 'tax_unit' table lacks " + "'tax_unit_support_channel'", + ), + ( + "undeclared", + lambda f: {"frame": _acs_null_on_cps(f, "tax_unit", "filing_status_input", 1)}, + "A column one origin lacks has no absence kind: " + "{'tax_unit.filing_status_input': 'null on", + ), + ( + # ACS rows carry a PUMA, CPS rows none: not one of the six + # origin-native amounts, so it refuses until filled or declared. + "undeclared reverse", + lambda f: {"frame": _acs_only(f, "household", "puma_geoid", "0600101")}, + "A column one origin lacks has no absence kind: " + "{'household.puma_geoid': 'null on", + ), +] + + +@pytest.mark.parametrize( + ("case", "corrupt", "message"), + _ABSENCE_REFUSALS, + ids=[case for case, _, _ in _ABSENCE_REFUSALS], +) +def test_absences_refuse_with_their_own_message( + assembled, case, corrupt, message +) -> None: + inputs = corrupt(assembled) + frame = inputs.get("frame", assembled) + manifest = inputs.get("manifest") or fill_manifest(inputs.get("fills", ())) + with pytest.raises(OnePopulationContractError, match=re.escape(message)): + absences( + frame, + fill_manifest=manifest, + zero_written=inputs.get("zero_written", {}), + declared=inputs.get("declared", {}), + ) + + +def test_absence_refusal_messages_are_distinct() -> None: + messages = [message for _, _, message in _ABSENCE_REFUSALS] + assert len(set(messages)) == len(messages) + + +def test_every_kindless_column_is_listed_in_one_refusal(assembled) -> None: + # One refusal names every gap, in both directions, so a first live run + # lists them all at once. + frame = _acs_null_on_cps(assembled, "person", "parent_1_id", 3) + acs = _origin_mask(frame.table("person"), "person", "acs") + frame = _acs_only(frame, "household", "puma_geoid", "0600101") + cps_households = int( + (~_origin_mask(frame.table("household"), "household", "acs")).sum() + ) + with pytest.raises(OnePopulationContractError) as raised: + _absences(frame) + message = str(raised.value) + assert f"'person.parent_1_id': 'null on {int(acs.sum())} ACS row(s)'" in message + assert (f"'household.puma_geoid': 'null on {cps_households} CPS row(s)'") in message + + +# ---- the moved inputs on a whole population (lead-call review, 11-19) + + +def _with_moved_inputs(frame: Frame, *, acs_null: bool) -> Frame: + """Every moved input on its entity: on every row, or null on ACS rows. + + PR 4's genuine input carries each on CPS rows (the parent export's + release values) and fills each on ACS rows; the generator carries none. + """ + + entities = lock_engine_inputs() + tables = _tables(frame) + for column in _MOVED_OFF_THE_EXEMPT_LIST: + entity = entities[column] + table = tables[entity] + value = True if column in _MOVED_BOOLEANS else 1.0 + if acs_null: + acs = _origin_mask(table, entity, "acs") + table[column] = pd.Series( + np.where(acs, None, value), index=table.index, dtype=object + ) + else: + table[column] = value + return _rebuild(frame, tables) + + +class TestMovedInputs: + @pytest.mark.parametrize("seed", _SEEDS) + def test_filled_on_every_row_they_pass_and_add_no_absence(self, seed) -> None: + population = generate_population(seed) + frame = assembled_frame(population) + filled = _with_moved_inputs(frame, acs_null=False) + _require(population, filled, staging_lineage=staging_lineage(population)) + assert set(_keyed(_absences(filled))) == set(_keyed(_absences(frame))) + + def test_null_on_acs_rows_both_checks_name_every_one( + self, population, assembled + ) -> None: + frame = _with_moved_inputs(assembled, acs_null=True) + with pytest.raises(OnePopulationContractError) as refused: + _require(population, frame) + message = str(refused.value) + assert message.startswith("A null in an engine input at 2024: "), message + missing = [c for c in _MOVED_OFF_THE_EXEMPT_LIST if f".{c}'" not in message] + assert not missing, message + with pytest.raises( + OnePopulationContractError, + match=re.escape("A column one origin lacks has no absence kind"), + ) as gap: + _absences(frame) + missing = [ + c for c in _MOVED_OFF_THE_EXEMPT_LIST if f".{c}'" not in str(gap.value) + ] + assert not missing, str(gap.value) + + +# ------- lead call (a), 11-18: ACS-native amounts CPS rows lack by origin + + +def _acs_only(frame: Frame, entity: str, column: str, value) -> Frame: + """``column`` holding ``value`` on ACS rows and null on CPS rows.""" + + table = frame.table(entity) + acs = _origin_mask(table, entity, "acs") + return _with_column( + frame, + entity, + column, + pd.Series(np.where(acs, value, None), index=table.index, dtype=object), + ) + + +def _with_acs_native_amounts(frame: Frame) -> Frame: + for column, (entity, _) in contract.ACS_NATIVE_AMOUNTS.items(): + frame = _acs_only(frame, entity, column, 120.0) + return frame + + +def _module_assignment(path: Path, name: str) -> ast.expr: + """The value assigned to ``name`` at the top level of ``path``'s source.""" + + for node in ast.parse(path.read_text(encoding="utf-8")).body: + targets = ( + [node.target] + if isinstance(node, ast.AnnAssign) + else node.targets + if isinstance(node, ast.Assign) + else [] + ) + if [getattr(target, "id", None) for target in targets] == [name]: + return node.value + raise AssertionError(f"{path.name} assigns no {name}.") + + +_U = Path(contract.__file__).parent + + +class TestOriginNativeAmounts: + """The six ACS-native ``acs_*`` amounts CPS rows lack need no decision.""" + + def test_they_are_origin_native_on_cps_rows(self, population, assembled) -> None: + frame = _with_acs_native_amounts(assembled) + record = _absences(frame) + keyed = _keyed(record) + assert "origin-native" in record["kinds"] + for column, (entity, readers) in contract.ACS_NATIVE_AMOUNTS.items(): + entry = keyed[(entity, column, "origin-native", "CPS")] + cps = ~_origin_mask(frame.table(entity), entity, "acs") + assert entry["rows"] == entry["origin_rows"] == int(cps.sum()) + assert entry["entity_weight_share"] == pytest.approx( + _share(frame, entity, cps) + ) + assert "_ACS_NATIVE_INPUT_CONTRACTS" in entry["evidence"] + assert entry["readers"] == list(readers) + assert entry["detail"] == {} + # No declaration is needed, and the contract passes the same frame. + assert record["needless_declarations"] == [] + _require(population, frame) + + def test_the_transfer_reads_the_three_combined_amounts(self) -> None: + # acs_transfer._RECIPIENT_COMBINED_SOURCES, read from its source. + sources = _module_assignment( + _U / "acs_transfer.py", "_RECIPIENT_COMBINED_SOURCES" + ) + assert isinstance(sources, ast.Dict) + read = {value.value for value in sources.values} + assert read == { + column + for column, (_, readers) in contract.ACS_NATIVE_AMOUNTS.items() + if readers + } + assert all( + "acs_transfer" in reader + for _, readers in contract.ACS_NATIVE_AMOUNTS.values() + for reader in readers + ) + + def test_the_names_are_the_operator_boundary_contracts(self) -> None: + # Read from operator_boundary's source: importing it loads the ACS + # transfer, and with it microcosm.fit. + contracts = _module_assignment( + _U / "operator_boundary.py", "_ACS_NATIVE_INPUT_CONTRACTS" + ) + assert isinstance(contracts, ast.Dict) + literal = { + key.value: value.elts[0].value + for key, value in zip(contracts.keys, contracts.values, strict=True) + if key is not None + } + spreads = [ + value + for key, value in zip(contracts.keys, contracts.values, strict=True) + if key is None + ] + spread_sources = { + generator.iter.func.value.id + if isinstance(generator.iter, ast.Call) + else generator.iter.id + for spread in spreads + for generator in spread.generators + } + assert spread_sources == { + "ACS_WORK_EXPERIENCE_NATIVE_MAPPINGS", + "ACS_UNRESOLVED_PARENT_ID_MAPPINGS", + } + work = ast.literal_eval( + _module_assignment( + _U / "acs_inputs.py", "ACS_WORK_EXPERIENCE_NATIVE_MAPPINGS" + ) + ) + parents = ast.literal_eval( + _module_assignment( + _U / "acs_inputs.py", "ACS_UNRESOLVED_PARENT_ID_MAPPINGS" + ) + ) + spread_outputs = set(work) | {output for output, _ in parents} + assert not {name for name in spread_outputs if name.startswith("acs_")} + amounts = { + column: entity + for column, entity in literal.items() + if column.startswith("acs_") + } + assert len(amounts) == 6 + assert { + column: entity + for column, (entity, _) in contract.ACS_NATIVE_AMOUNTS.items() + } == amounts + # The register files each as an ACS-native amount, not a model input. + for column in amounts: + assert "not a model input" in US_STORED_NON_VARIABLE_COLUMNS[column] + + def test_the_reverse_direction_still_refuses(self, assembled) -> None: + frame = _acs_null_on_cps(assembled, "person", "acs_social_security_income", 1.0) + n_acs = int(_origin_mask(frame.table("person"), "person", "acs").sum()) + with pytest.raises( + OnePopulationContractError, + match=re.escape( + "A column one origin lacks has no absence kind: " + f"{{'person.acs_social_security_income': 'null on {n_acs} ACS row(s)'}}" + ), + ): + _absences(frame) + decision = "US data owner: decided for this test" + record = _absences(frame, declared={"acs_social_security_income": decision}) + entry = _keyed(record)[ + ("person", "acs_social_security_income", "owner-declared", "ACS") + ] + assert entry["detail"] == {"decision": decision} + + @pytest.mark.parametrize( + ("entity", "column"), + [ + # A model-named column outside the six. + ("person", "parent_1_id"), + # One of the six, on an entity its contract does not name. + ("person", "acs_monthly_gross_rent"), + ], + ) + def test_any_other_column_cps_rows_lack_refuses( + self, assembled, entity, column + ) -> None: + frame = _acs_only(assembled, entity, column, 3.0) + n_cps = int((~_origin_mask(frame.table(entity), entity, "acs")).sum()) + with pytest.raises( + OnePopulationContractError, + match=re.escape( + "A column one origin lacks has no absence kind: " + f"{{'{entity}.{column}': 'null on {n_cps} CPS row(s)'}}" + ), + ): + _absences(frame) + + +# --------- lead call (b), 11-18: one declarations mapping for R10 and absences + + +_DECISION = "US data owner: decided for this test" + + +class TestOneDeclarationsMapping: + def test_stale_and_needless_declarations_are_recorded( + self, population, assembled + ) -> None: + register = {**US_STORED_NON_VARIABLE_COLUMNS, _AUXILIARY: "auxiliary"} + frame = _acs_null_on_cps(assembled, "person", _AUXILIARY, 41_000.0) + declared = { + _AUXILIARY: f"{_DECISION} (used)", + # Stale: no origin lacks it (staging filled it, say). + "parent_1_id": f"{_DECISION} (stale)", + # Needless: release-written, and a raw source column. + "takes_up_ssi_if_eligible": f"{_DECISION} (release-written)", + "SSI_VAL": f"{_DECISION} (raw)", + } + _require(population, frame, register=register, declared_absences=declared) + record = _absences(frame, declared=declared) + assert record["unused_declarations"] == [ + {"column": "parent_1_id", "decision": declared["parent_1_id"]} + ] + assert record["needless_declarations"] == [ + {"column": "SSI_VAL", "decision": declared["SSI_VAL"]}, + { + "column": "takes_up_ssi_if_eligible", + "decision": declared["takes_up_ssi_if_eligible"], + }, + ] + keyed = _keyed(record) + assert ("person", _AUXILIARY, "owner-declared", "ACS") in keyed + # The needless ones keep the kinds they need no decision for. + assert ("person", "SSI_VAL", "raw source column", "ACS") in keyed + assert ("person", "takes_up_ssi_if_eligible", "release-written", "ACS") in ( + keyed + ) + assert "owner-declared" not in { + kind for (_, column, kind, _) in keyed if column != _AUXILIARY + } + + def test_a_declaration_an_origin_native_gap_needs_not_is_needless( + self, assembled + ) -> None: + frame = _with_acs_native_amounts(assembled) + declared = {"acs_social_security_income": _DECISION} + record = _absences(frame, declared=declared) + assert record["needless_declarations"] == [ + {"column": "acs_social_security_income", "decision": _DECISION} + ] + assert record["unused_declarations"] == [] + assert ( + "person", + "acs_social_security_income", + "origin-native", + "CPS", + ) in _keyed(record) + + @pytest.mark.parametrize("receipt", ["fill_manifest", "zero_written"]) + def test_a_declaration_a_receipt_covers_is_needless( + self, population, assembled, receipt + ) -> None: + # The owner declared a gap that prepare later filled (or staging wrote + # as zero): the receipt files the entry and the declaration is + # recorded as needless, on the mapping R10 also accepts. + declared = {"tip_income": f"{_DECISION} (before the fill)"} + inputs = ( + {"fills": [_acs_fill(assembled, "tip_income")]} + if receipt == "fill_manifest" + else {"zero_written": {"tip_income": "staging receipt"}} + ) + _require(population, assembled, declared_absences=declared) + record = _absences(assembled, declared=declared, **inputs) + assert record["needless_declarations"] == [ + {"column": "tip_income", "decision": declared["tip_income"]} + ] + assert record["unused_declarations"] == [] + kinds = { + kind for (_, column, kind, _) in _keyed(record) if column == "tip_income" + } + assert kinds == { + "reviewed default fill" if receipt == "fill_manifest" else "zero written" + } + + def test_one_declaration_answers_r10_and_absences( + self, population, assembled + ) -> None: + # d2283 lead call L2: R10 and absences share one gap predicate, so a + # register column null on every ACS row and on one CPS row refuses + # both undeclared, and one declaration passes both. + register = {**US_STORED_NON_VARIABLE_COLUMNS, _AUXILIARY: "auxiliary"} + frame = _acs_null_on_cps(assembled, "person", _AUXILIARY, 41_000.0) + frame = _cell(frame, "person", _AUXILIARY, None, origin="cps") + with pytest.raises( + OnePopulationContractError, + match=re.escape( + "A model-named column held on some CPS row is null on ACS rows " + f"without a declared absence: {{'person.{_AUXILIARY}': " + ), + ): + _require(population, frame, register=register) + with pytest.raises( + OnePopulationContractError, + match=re.escape( + "A column one origin lacks has no absence kind: " + f"{{'person.{_AUXILIARY}': " + ), + ): + _absences(frame) + declared = {_AUXILIARY: _DECISION} + _require(population, frame, register=register, declared_absences=declared) + record = _absences(frame, declared=declared) + keyed = _keyed(record) + assert ("person", _AUXILIARY, "owner-declared", "ACS") in keyed + # The CPS null is no gap: no ACS row holds a value. + assert ("person", _AUXILIARY, "owner-declared", "CPS") not in keyed + assert record["unused_declarations"] == [] + assert record["needless_declarations"] == [] + + def test_a_register_column_null_on_every_row_is_no_gap( + self, population, assembled + ) -> None: + # The shared predicate's other half: with no value on a CPS row there + # is no gap, so R10 and absences both pass it undeclared. + register = {**US_STORED_NON_VARIABLE_COLUMNS, _AUXILIARY: "auxiliary"} + index = assembled.table("person").index + frame = _with_column( + assembled, "person", _AUXILIARY, pd.Series(None, index=index, dtype=object) + ) + _require(population, frame, register=register) + record = _absences(frame) + assert _AUXILIARY not in {column for (_, column, _, _) in _keyed(record)} + + def test_a_frame_with_no_acs_row_lists_every_declaration_as_unused( + self, population + ) -> None: + empty_acs = { + entity: population.acs_tables[entity].iloc[:0] + for entity in US_SCHEMA.entities + } + frame = to_assembled_provenance( + population.cps_tables, + empty_acs, + cps_household_weights=population.keyed_cps_household_weights, + acs_household_weights={}, + staging_lineage={}, + ) + manifest = dataclasses.replace( + selection_manifest(population), + n_acs=0, + selected_acs_keys_sha256=selection.keys_sha256(()), + ) + declared = { + column: f"{_DECISION} ({column})" + for column in ("parent_2_id", "parent_1_id", _AUXILIARY) + } + _require( + population, + frame, + manifest=manifest, + staging_lineage={}, + declared_absences=declared, + ) + record = _absences(frame, declared=declared) + assert record["unused_declarations"] == [ + {"column": column, "decision": declared[column]} + for column in sorted(declared) + ] + assert record["needless_declarations"] == [] + assert record["entries"] == [] + + +# ------ lead call (c), 11-18: each public function's type and schema refusals + + +def _foreign_schema_frame() -> Frame: + """A valid frame in a schema other than the US one.""" + + from microcosm.frame import EntitySchema, Weights + + return Frame( + { + "person": pd.DataFrame( + {"person_id": [0, 1], "person_household_id": [1, 1]} + ), + "household": pd.DataFrame({"household_id": [1]}), + }, + EntitySchema(group_entities=("household",)), + {"household": Weights(np.array([1.0]), WeightKind.DESIGN)}, + ) + + +def _rewrite_with(p, **overrides) -> Frame: + kwargs = { + "cps_tables": p.cps_tables, + "acs_tables": p.acs_tables, + "cps_household_weights": p.keyed_cps_household_weights, + "acs_household_weights": p.keyed_acs_household_weights, + "staging_lineage": staging_lineage(p), + **overrides, + } + return to_assembled_provenance( + kwargs.pop("cps_tables"), kwargs.pop("acs_tables"), **kwargs + ) + + +def _absences_with(f, **overrides) -> dict: + kwargs = { + "fill_manifest": fill_manifest(), + "zero_written": {}, + "declared": {}, + **overrides, + } + return absences(kwargs.pop("frame", f), **kwargs) + + +_TYPE_REFUSALS = [ + ( + "rewrite cps tables", + lambda p, f: _rewrite_with(p, cps_tables=list(p.cps_tables.values())), + "CPS tables must be a mapping of entity to table, got list.", + ), + ( + "rewrite acs table", + lambda p, f: _rewrite_with( + p, acs_tables={**p.acs_tables, "person": p.acs_tables["person"].to_dict()} + ), + "ACS 'person' table must be a DataFrame, got dict.", + ), + ( + "rewrite staging lineage", + lambda p, f: _rewrite_with(p, staging_lineage="2024HU0000001"), + "staging_lineage must map each staged ACS person's native (household id, " + "person id) to its (SERIALNO, SPORDER), got str.", + ), + ( + "require staging lineage", + lambda p, f: _require(p, f, staging_lineage=5), + "staging_lineage must map each staged ACS person's native (household id, " + "person id) to its (SERIALNO, SPORDER), got int.", + ), + ( + # PR #1685 review, blocking 2: the old set of (SERIALNO, SPORDER) + # pairs cannot tie a SERIALNO to its household, so it is refused. + "rewrite staging lineage as a set of pairs", + lambda p, f: _rewrite_with( + p, staging_lineage=frozenset(staging_lineage(p).values()) + ), + "staging_lineage must map each staged ACS person's native (household id, " + "person id) to its (SERIALNO, SPORDER), got frozenset.", + ), + ( + "role record frame", + lambda p, f: combined_spm_role_record( + cps_role_record(f), staging_role_receipt(f), f.table("person") + ), + "frame must be a Frame, got DataFrame.", + ), + ( + "role record cps record", + lambda p, f: combined_spm_role_record( + list(cps_role_record(f)), staging_role_receipt(f), f + ), + "cps_record must be a mapping, got list.", + ), + ( + "role record receipt", + lambda p, f: combined_spm_role_record(cps_role_record(f), None, f), + "staging_receipt must be a mapping, got NoneType.", + ), + ( + "absences frame", + lambda p, f: _absences_with(f, frame=f.table("person")), + "frame must be a Frame, got DataFrame.", + ), + ( + "absences fill manifest", + lambda p, f: _absences_with(f, fill_manifest=[]), + "fill_manifest must be the reviewed default fill's manifest mapping, got list.", + ), + ( + "absences zero written", + lambda p, f: _absences_with(f, zero_written=["tip_income"]), + "zero_written must map each column to the receipt that records its written " + "zeros, got list.", + ), + ( + "absences zero written receipt", + lambda p, f: _absences_with(f, zero_written={"tip_income": 1}), + "zero_written must map str columns to str receipts, got 'tip_income': 1.", + ), + ( + "absences declared", + lambda p, f: _absences_with(f, declared=["parent_1_id"]), + "declared must map each column to its owner's decision, got list.", + ), + ( + "absences declared decision", + lambda p, f: _absences_with(f, declared={"parent_1_id": 1}), + "declared must map str columns to str decisions, got 'parent_1_id': 1.", + ), + ( + "write absences", + lambda p, f: write_absences(list(_absences(f)), Path("no-such-directory")), + "record must be a mapping, got list.", + ), + ( + "cps unit ids", + lambda p, f: cps_unit_ids(p.cps_tables["person"].to_dict()), + "person must be a DataFrame, got dict.", + ), +] + + +@pytest.mark.parametrize( + ("case", "call", "message"), + _TYPE_REFUSALS, + ids=[case for case, _, _ in _TYPE_REFUSALS], +) +def test_each_public_function_refuses_a_wrong_type( + population, assembled, case, call, message +) -> None: + with pytest.raises(TypeError, match=re.escape(message)): + call(population, assembled) + + +@pytest.mark.parametrize( + ("case", "call", "message"), + [ + ( + "require", + lambda p: require_one_population( + _foreign_schema_frame(), + selection_manifest(p), + parent_tail_donor_ids=frozenset(), + ), + "Incomplete assembled provenance: the frame must use the US schema.", + ), + ( + "role record", + lambda p: combined_spm_role_record({}, {}, _foreign_schema_frame()), + "The SPM role record needs a frame in the US schema.", + ), + ( + "absences", + lambda p: _absences_with(None, frame=_foreign_schema_frame()), + "The absences file needs a frame in the US schema.", + ), + ], + ids=["require", "role record", "absences"], +) +def test_a_frame_in_another_schema_refuses(population, case, call, message) -> None: + with pytest.raises(OnePopulationContractError, match=re.escape(message)): + call(population) + + +# ------------------------- phase 3: X2, N-2's kinds on a generated population + + +_AUXILIARY = "cps_employment_income_last_year" + + +def test_n2_kinds_on_a_generated_population(population, assembled) -> None: + """A registered auxiliary null on every ACS row refuses until declared. + + The SSI take-up column (a Q1-exempt producer output) and ``SSI_VAL`` (an + upper-case raw column), both null on every ACS row, pass the contract + and appear in the absences file with their kinds; so do a reviewed + default fill, a written zero and an ACS-native amount CPS rows lack + (origin-native). + """ + + register = { + **US_STORED_NON_VARIABLE_COLUMNS, + _AUXILIARY: "registered auxiliary person column (#1575's shape)", + } + frame = _acs_null_on_cps(assembled, "person", _AUXILIARY, 41_000.0) + person = frame.table("person") + acs = _origin_mask(person, "person", "acs") + for column in (_AUXILIARY, "takes_up_ssi_if_eligible", "SSI_VAL"): + assert person.loc[acs, column].isna().all() + assert person.loc[~acs, column].notna().all() + + with pytest.raises( + OnePopulationContractError, + match=re.escape( + "A model-named column held on some CPS row is null on ACS rows without " + f"a declared absence: {{'person.{_AUXILIARY}'" + ), + ): + _require(population, frame, register=register) + with pytest.raises( + OnePopulationContractError, + match=re.escape("A column one origin lacks has no absence kind"), + ): + _absences(frame) + + declared = {_AUXILIARY: "US data owner: ACS rows carry no prior-year wage"} + frame = _acs_only(frame, "person", "acs_social_security_income", 900.0) + _require(population, frame, register=register, declared_absences=declared) + record = _absences( + frame, + fills=[_acs_fill(frame, "tip_income")], + zero_written={"employer_sponsored_insurance_premiums": "staging receipt"}, + declared=declared, + ) + keyed = _keyed(record) + kinds = {(column, kind) for (_, column, kind, origin) in keyed if origin == "ACS"} + assert { + (_AUXILIARY, "owner-declared"), + ("takes_up_ssi_if_eligible", "release-written"), + ("SSI_VAL", "raw source column"), + ("tip_income", "reviewed default fill"), + ("employer_sponsored_insurance_premiums", "zero written"), + } <= kinds + assert ("person", "acs_social_security_income", "origin-native", "CPS") in keyed + assert {kind for (_, _, kind, _) in keyed} == set(ABSENCE_KINDS) + for column in (_AUXILIARY, "takes_up_ssi_if_eligible", "SSI_VAL"): + entry = next( + entry + for key, entry in keyed.items() + if key[1] == column and key[3] == "ACS" + ) + assert entry["rows"] == entry["origin_rows"] == int(acs.sum()) + assert entry["entity_weight_share"] == pytest.approx( + _share(frame, "person", acs) + ) + owner = keyed[("person", _AUXILIARY, "owner-declared", "ACS")] + assert owner["detail"] == {"decision": declared[_AUXILIARY]} + + +# ------------- phase 3: X7, group quarters add nothing to household types + + +def _with_household_type_codes(frame: Frame) -> Frame: + """CPS ``A_EXPRRP`` and ``A_MARITL`` on every person, from the roster. + + Household heads are 1 (with relatives) or 2; a role holder sharing the + head's tax unit is the spouse (3); other role holders are housemates + (13); persons without the role are children (5). Group-quarters persons + get 14, as the ACS loader writes. Couples are married (1), everyone else + never married (7). + """ + + tables = _tables(frame) + person = tables["person"] + household = tables["household"].set_index("household_id") + kind = person["person_household_id"].map(household["TYPEHUGQ"]) + head = person["is_household_head"].to_numpy(dtype=bool) + role = person[SPM_ROLE].to_numpy(dtype=bool) + head_unit = person.loc[head].set_index("person_household_id")["person_tax_unit_id"] + shares_unit = ( + person["person_household_id"].map(head_unit).to_numpy() + == person["person_tax_unit_id"].to_numpy() + ) + spouse = role & ~head & shares_unit + child = ~role + relatives = ( + pd.Series(spouse | child) + .groupby(person["person_household_id"].to_numpy()) + .transform("any") + .to_numpy() + ) + relationship = np.select( + [head & relatives, head, spouse, child], [1, 2, 3, 5], default=13 + ) + group_quarters = kind.isin([2, 3]).to_numpy() + relationship[group_quarters] = 14 + couple = ( + pd.Series(spouse) + .groupby(person["person_household_id"].to_numpy()) + .transform("any") + .to_numpy() + ) + person["A_EXPRRP"] = relationship.astype(np.int64) + person["A_MARITL"] = np.where((head & couple) | spouse, 1, 7).astype(np.int64) + return _rebuild(frame, tables) + + +_HOUSEHOLD_TYPES = ( + "all", + "family", + "married_couple_family", + "other_family", + "male_householder_no_spouse", + "female_householder_no_spouse", + "nonfamily", + "householder_living_alone", + "householder_not_living_alone", +) + + +def test_the_household_type_codes_give_one_householder_per_housing_unit( + assembled, +) -> None: + # Runs today, so X7's input is checked before #1610 can run on it. + frame = _with_household_type_codes(assembled) + person = frame.table("person") + kind = person["person_household_id"].map( + frame.table("household").set_index("household_id")["TYPEHUGQ"] + ) + housing = ~kind.isin([2, 3]).to_numpy() + relationship = person["A_EXPRRP"].to_numpy() + householders = ( + pd.Series(np.isin(relationship, [1, 2]) & housing) + .groupby(person["person_household_id"].to_numpy()) + .sum() + ) + housing_households = np.unique(person["person_household_id"].to_numpy()[housing]) + assert (householders.loc[housing_households] == 1).all() + assert (relationship[~housing] == 14).all() + assert set(relationship.tolist()) <= {1, 2, 3, 5, 13, 14} + assert set(person["A_MARITL"].tolist()) <= {1, 7} + assert (person.loc[relationship == 3, "A_MARITL"] == 1).all() + + +def test_group_quarters_add_nothing_to_household_type_targets(assembled) -> None: + """Unexecuted until PolicyEngine/microcosm#1610 lands its materializer.""" + + targets = pytest.importorskip( + "microcosm.build.us_runtime.household_type_targets", + reason=( + "PolicyEngine/microcosm#1610's household-type materializer " + "(household_type_household_values) is not on main yet" + ), + ) + import warnings + + frame = _with_household_type_codes(assembled) + household = frame.table("household") + group_quarters = household["TYPEHUGQ"].isin([2, 3]).to_numpy() + assert group_quarters.sum() == 2 + weights = np.asarray(frame.weights_for("household").values, dtype=np.float64) + with warnings.catch_warnings(): + warnings.simplefilter("ignore", targets.HouseholdUniverseFallbackWarning) + for household_type in _HOUSEHOLD_TYPES: + for own_children in ( + "all", + "with_own_children_under_18", + "no_own_children_under_18", + ): + values = targets.household_type_household_values( + frame, + {"household_type": household_type, "own_children": own_children}, + ) + assert len(values) == len(household) + assert (values[group_quarters] == 0).all() + assert float((weights * values)[group_quarters].sum()) == 0.0 + housing = targets.household_type_household_values( + frame, {"household_type": "all"} + ) + assert (housing[~group_quarters] == 1).all() + + +# ------------- phase 4: X5, the whole-frame differential (BP, K-21, Q4) + +#: The fields each moved reader's statistics change in (d2283 Q4: CPS clones +#: keep Route A's ``puf_tax_detail`` label once assembled), keyed by reader, +#: and, keyed by defect, the detail fields each clone-only defect of +#: :data:`READER_CLONE_DEFECTS` moves besides the verdict (lead call L7). +#: PR 3 owns all six. +_X5_MOVED_FIELDS: dict[str, frozenset[str]] = { + "medicare_clone_mcare_mismatch": frozenset( + {"source_mismatch_count", "source_rows"} + ), + "medicare_take_up": frozenset({"source_rows"}), + "retirement_contributions": frozenset( + { + "allocation_mismatch_rows", + "source_positive_rows", + "source_reconciliation_rows", + "source_rows", + "source_total", + } + ), + "retirement_distributions": frozenset({"source_rows"}), + "weeks_clone_uc_mismatch": frozenset( + {"uc_constraint_mismatch_count", "uc_constraint_rows"} + ), + "weeks_unemployed": frozenset({"uc_constraint_rows"}), +} + +_X5_PR3_REASONS: dict[str, str] = { + "medicare_clone_mcare_mismatch": ( + "d2283 PR 3 flips this. Medicare take-up, fail to pass: one clone row's " + "MCARE disagrees with its take-up flag. Route A reconciles every row " + "and fails (medicare_take_up.py:306-308); once assembled, " + "_asec_source_mask keeps only stored-asec rows (:134-146), so the " + "clone's mismatch is not counted and the gate passes." + ), + "medicare_take_up": ( + "d2283 PR 3 flips this. Medicare take-up: once assembled, " + "_asec_source_mask keeps only rows whose stored channel is asec " + "(medicare_take_up.py:134-146), so MCARE reconciliation leaves out the " + "clone rows Route A checks; source_mismatch_count can only fall, which " + "can move the gate from fail to pass (:306-308)." + ), + "retirement_contributions": ( + "d2283 PR 3 flips this. Retirement contributions: once assembled, the " + "source and reconciliation masks keep only stored-asec rows " + "(retirement_contributions.py:172-193) where Route A takes every row, " + "so five source fields move; the verdict does not." + ), + "retirement_distributions": ( + "d2283 PR 3 flips this. Retirement distributions: once assembled, the " + "source mask keeps only stored-asec rows " + "(retirement_distributions.py:274-295) where Route A takes every row, " + "so source_rows moves and clone-row DST codes go unvalidated; " + "reconciliation does not move." + ), + "weeks_clone_uc_mismatch": ( + "d2283 PR 3 flips this. Weeks unemployed, fail to pass: one clone row " + "has weeks unemployed and no unemployment compensation. Route A puts " + "every clone in the UC rule (weeks_unemployed.py:1351) and fails " + "(:1422-1426); once assembled the rule's scope is (asec & clone) | " + "(non-asec & native) (:1366-1373), which a puf_tax_detail clone is " + "not in, so the gate passes." + ), + "weeks_unemployed": ( + "d2283 PR 3 flips this. Weeks unemployed, the UC-rule scope: once " + "assembled it is (asec & clone) | (non-asec & native) " + "(weeks_unemployed.py:1366-1373), so CPS clones labelled " + "puf_tax_detail leave it, where Route A puts every clone in it (:1351)." + ), +} + +#: Runtime modules that test the assembled discriminator only as writers or +#: provenance owners, not as gate readers. +_X5_WRITERS = frozenset( + { + "__init__", + "one_population_contract", + "puf_support", + "spine_agreement", + "spine_assembly", + "stacked_spine", + "support_provenance", + } +) + + +@pytest.fixture(scope="module") +def readers(): + # pytest counts a fixture's error as a marked test's expected failure + # when its type matches ``raises``; the builder's self-checks raise + # AssertionError, so re-raise them as an error the strict xfails + # (raises=AssertionError) report rather than absorb. + try: + return reader_population() + except AssertionError as exc: + raise RuntimeError(f"The X5 reader frame is broken: {exc}") from exc + + +@pytest.fixture(scope="module") +def defect_readers(): + # As ``readers``: a broken defect frame is an error, never an xfail. + try: + return { + defect: reader_population(clone_defect=defect) + for defect in READER_CLONE_DEFECTS + } + except AssertionError as exc: + raise RuntimeError(f"An X5 clone-defect frame is broken: {exc}") from exc + + +def _x5_statistics(result: object) -> object: + """A reader's verdict and summary statistics, as plain data.""" + + if isinstance(result, GateResult): + return { + "name": result.name, + "passed": result.passed, + "failures": list(result.failures), + "details": result.details, + } + if isinstance(result, frozenset): + return sorted(result) + raise TypeError(f"Unexpected reader result {type(result).__name__}.") + + +def _x5_differences(route_a: object, assembled: object, path=()) -> list[tuple]: + """Every path at which two readers' statistics differ. + + Exact: both frames hold the same person rows in the same order with the + same weights (see the fixture test), so equal statistics are the same + sums, bit for bit. NaN equals NaN. + """ + + if isinstance(route_a, dict) and isinstance(assembled, dict): + differences: list[tuple] = [] + for key in sorted(set(route_a) | set(assembled), key=str): + if key not in route_a or key not in assembled: + differences.append((*path, key)) + else: + differences.extend( + _x5_differences(route_a[key], assembled[key], (*path, key)) + ) + return differences + if isinstance(route_a, (list, tuple)) and isinstance(assembled, (list, tuple)): + if len(route_a) != len(assembled): + return [path] + differences = [] + for index, (left, right) in enumerate(zip(route_a, assembled, strict=True)): + differences.extend(_x5_differences(left, right, (*path, index))) + return differences + if ( + isinstance(route_a, float) + and isinstance(assembled, float) + and math.isnan(route_a) + and math.isnan(assembled) + ): + return [] + return [] if route_a == assembled else [path] + + +def _x5_run(readers, reader: str) -> tuple[object, object]: + gate = READER_GATES[reader] + return ( + _x5_statistics(gate(readers.route_a)), + _x5_statistics(gate(readers.assembled)), + ) + + +def test_x5_covers_every_assembled_form_reader() -> None: + """The readers are F-19's: every runtime module that tests the assembled + discriminator itself, less writers and owners, plus every caller of the + physical-channel accessor. + + ``acs_local_hours`` is the one such module with no release gate; its + case is the donor-prep refusal below. + """ + + runtime = Path(inspect.getfile(contract)).parent + sources = { + path.stem: path.read_text(encoding="utf-8") for path in runtime.glob("*.py") + } + discriminator = re.compile( + r"has_assembled_support_metadata|spine_source_id_column\(" + ) + testing = {name for name, text in sources.items() if discriminator.search(text)} + callers = { + name + for name, text in sources.items() + if "support_gate_source_channel_series(" in text + } - {"support_provenance"} + modules = {gate.__module__.rsplit(".", 1)[1] for gate in READER_GATES.values()} + assert testing - _X5_WRITERS == (modules - {"ssi_take_up"}) | {"acs_local_hours"} + assert callers <= modules + assert set(READER_SOURCE_COLUMNS) == set(READER_GATES) + assert set(_X5_MOVED_FIELDS) == set(_X5_PR3_REASONS) + assert set(READER_GATES).isdisjoint(READER_CLONE_DEFECTS) + assert set(_X5_MOVED_FIELDS) <= set(READER_GATES) | set(READER_CLONE_DEFECTS) + assert set(READER_CLONE_DEFECTS) <= set(_X5_MOVED_FIELDS) + assert {reader for reader, _ in READER_CLONE_DEFECTS.values()} <= set( + _X5_MOVED_FIELDS + ) + + +def test_the_reader_frame_exercises_every_reader(readers) -> None: + """X5's preconditions, outside every expected failure. + + A strict xfail cannot pass for want of data, and an equal pair of + statistics is not two failing gates: the frame has clone rows (indices + 0, 1 and 2) on every entity and each reader's raw source columns; every + Route A gate passes and takes its source branch; clone rows differ from + the source wherever Route A does not reconcile them, so a reader whose + assembled mask took clone rows would show; and the WIC gate's two + clone keys (the source triple on Route A, ``person_source_id`` once + assembled) partition the rows alike. + """ + + route_a, assembled = readers.route_a, readers.assembled + person = route_a.table("person") + for entity in US_SCHEMA.entities: + table = route_a.table(entity) + assert set(table[support_clone_index_column(entity)]) == {0, 1, 2}, entity + assert spine_source_id_column(entity) not in table + assert spine_source_id_column(entity) in assembled.table(entity) + for reader, columns in READER_SOURCE_COLUMNS.items(): + assert set(columns) <= set(person.columns), reader + assert set(columns) <= set(assembled.table("person").columns), reader + assert ( + person["person_id"].tolist() == assembled.table("person")["person_id"].tolist() + ) + np.testing.assert_array_equal( + route_a.resolve_weights("person").values, + assembled.resolve_weights("person").values, + ) + + results = {name: gate(route_a) for name, gate in READER_GATES.items()} + for name, result in results.items(): + if isinstance(result, GateResult): + assert result.passed, (name, result.failures) + assert results["ssi_take_up_reporters"] == readers.reporters + assert readers.clone_only_ssi not in results["ssi_take_up_reporters"] + clone = person["person_support_clone_index"].to_numpy() > 0 + assert int(results["alimony"].details["asec_source_rows"]) == int((~clone).sum()) + for name in ("medicare_take_up", "workers_compensation"): + assert "source_rows" in results[name].details, name + for name in ("retirement_contributions", "retirement_distributions"): + assert int(results[name].details["source_rows"]) == len(person), name + weeks = results["weeks_unemployed"].details + assert not weeks["source_missing"] + assert int(weeks["source_reconciliation_rows"]) == int((~clone).sum()) + assert int(weeks["uc_constraint_rows"]) == int(clone.sum()) + assert int(results["wic_claim"].details["clone_group_count"]) == int((~clone).sum()) + + def differs(column: str, expected) -> bool: + return bool((clone & (person[column].to_numpy() != expected)).any()) + + oi_off = person["OI_OFF"].to_numpy() + oi_val = person["OI_VAL"].to_numpy(dtype=np.float64) + assert differs("workers_compensation", person["WC_VAL"].to_numpy()) + assert differs("alimony_income", np.where(oi_off == 20, oi_val, 0.0)) + lkweeks = person["LKWEEKS"].to_numpy() + assert differs("weeks_unemployed", np.where(lkweeks == -1, 0, lkweeks)) + weeks_positive = person["weeks_unemployed"].to_numpy() > 0 + uc_positive = person["unemployment_compensation"].to_numpy() > 0 + assert (clone & weeks_positive).any() + assert not (clone & weeks_positive & ~uc_positive).any() + native_values = person.loc[~clone].set_index("person_source_id") + for column in ( + "traditional_401k_contributions_desired", + "taxable_401k_distributions", + ): + expected = person["person_source_id"].map(native_values[column]).to_numpy() + assert differs(column, expected), column + ssi_clone = clone & ( + person["person_source_id"].astype(str).eq(readers.clone_only_ssi).to_numpy() + ) + assert (person.loc[ssi_clone, "SSI_VAL"] > 0).all() and ssi_clone.any() + + triple = person[list(WIC_SOURCE_TRIPLE)].astype(str).agg(":".join, axis=1) + source = person["person_source_id"] + assert triple.groupby(source).nunique().max() == 1 + assert source.groupby(triple).nunique().max() == 1 + + +_X5_CASES = [ + pytest.param( + name, + id=name, + marks=pytest.mark.xfail( + strict=True, raises=AssertionError, reason=_X5_PR3_REASONS[name] + ), + ) + if name in _X5_PR3_REASONS + else pytest.param(name, id=name) + for name in sorted(READER_GATES) +] + + +@pytest.mark.parametrize("reader", _X5_CASES) +def test_assembled_readers_return_route_a_statistics(readers, reader) -> None: + """X5 (BP): on an ASEC-only population every provenance-reading gate + returns Route A's verdict and statistics after the rewrite. + + Run once on the Route A frame and once on its + ``to_assembled_provenance`` with no ACS row. The four readers whose + assembled branch moves under Route A's clone label are strict expected + failures, each naming PR 3 (two more, on verdicts, follow below); the + WIC frame's two clone partitions agree + (see the fixture test), so the WIC case compares one partition. + """ + + route_a, assembled = _x5_run(readers, reader) + assert _x5_differences(route_a, assembled) == [] + + +@pytest.mark.parametrize("reader", sorted(set(_X5_MOVED_FIELDS) & set(READER_GATES))) +def test_a_moved_reader_moves_only_its_named_fields(readers, reader) -> None: + """Outside the expected failure, a moved reader keeps its verdict and + every statistic but the fields named for it, and Route A's value of + those fields counts the clone rows (true before and after PR 3).""" + + route_a, assembled = _x5_run(readers, reader) + moved = {("details", field) for field in _X5_MOVED_FIELDS[reader]} + assert set(_x5_differences(route_a, assembled)) <= moved + assert route_a["passed"] and assembled["passed"] + person = readers.route_a.table("person") + clones = int((person["person_support_clone_index"] > 0).sum()) + details = route_a["details"] + if reader == "weeks_unemployed": + assert details["uc_constraint_rows"] == clones > 0 + else: + assert details["source_rows"] == len(person) > clones + if reader == "retirement_contributions": + assert details["source_reconciliation_rows"] == len(person) + source = person["RETCB_VAL"].to_numpy() > 0 + assert details["source_positive_rows"] == int(source.sum()) + assert details["allocation_mismatch_rows"] > 0 + + +def test_each_clone_defect_changes_one_clone_cell(readers, defect_readers) -> None: + """L7's preconditions, outside the expected failures: each defect frame + differs from the reader frame in one cell, on a clone row, on both + forms; the builder has already checked that Route A's gate for the + defect's reader fails with exactly its one failure and every other + reader passes.""" + + for defect, population in defect_readers.items(): + reader, failure = READER_CLONE_DEFECTS[defect] + for form in ("route_a", "assembled"): + base = getattr(readers, form).table("person") + changed = getattr(population, form).table("person") + assert list(base.columns) == list(changed.columns), (defect, form) + differs = [ + (row, column) + for column in base.columns + for row in np.flatnonzero( + (base[column] != changed[column]).to_numpy() + & ~(base[column].isna() & changed[column].isna()).to_numpy() + ) + ] + assert len(differs) == 1, (defect, form, differs) + row, column = differs[0] + assert base["person_support_clone_index"].iloc[row] > 0, (defect, form) + assert column in READER_SOURCE_COLUMNS[reader], (defect, column) + result = READER_GATES[reader](population.route_a) + assert list(result.failures) == [failure], defect + + +_X5_DEFECT_CASES = [ + pytest.param( + defect, + id=defect, + marks=pytest.mark.xfail( + strict=True, raises=AssertionError, reason=_X5_PR3_REASONS[defect] + ), + ) + for defect in sorted(READER_CLONE_DEFECTS) +] + + +@pytest.mark.parametrize("defect", _X5_DEFECT_CASES) +def test_a_clone_only_defect_keeps_route_a_verdict(defect_readers, defect) -> None: + """X5 on verdicts (lead call L7): a defect on one clone row fails Route + A's gate, so the assembled gate must fail with the same failures. + + Today the assembled reader leaves the clone row out and passes: a strict + expected failure naming PR 3. A defect that did nothing would leave both + gates passing and turn this into a strict unexpected pass. + """ + + route_a, assembled = _x5_run( + defect_readers[defect], READER_CLONE_DEFECTS[defect][0] + ) + assert (assembled["passed"], assembled["failures"]) == ( + route_a["passed"], + route_a["failures"], + ) + + +@pytest.mark.parametrize("defect", sorted(READER_CLONE_DEFECTS)) +def test_a_clone_only_defect_moves_only_its_named_fields( + defect_readers, defect +) -> None: + """Outside the expected failure, a defect moves only the verdict and its + named fields, and Route A counts the one clone mismatch (true before + and after PR 3).""" + + reader, failure = READER_CLONE_DEFECTS[defect] + population = defect_readers[defect] + route_a, assembled = _x5_run(population, reader) + moved = {("passed",), ("failures",)} | { + ("details", field) for field in _X5_MOVED_FIELDS[defect] + } + assert set(_x5_differences(route_a, assembled)) <= moved + assert not route_a["passed"] + assert route_a["failures"] == [failure] + # The assembled gate fails for no other reason (true before and after). + assert set(assembled["failures"]) <= {failure} + person = population.route_a.table("person") + clones = int((person["person_support_clone_index"] > 0).sum()) + details = route_a["details"] + if reader == "weeks_unemployed": + assert details["uc_constraint_mismatch_count"] == 1 + assert details["uc_constraint_rows"] == clones + else: + assert details["source_mismatch_count"] == 1 + assert details["source_rows"] == len(person) + + +def test_the_local_hours_donor_refuses_the_assembled_population(readers) -> None: + """X5 leaves ``acs_local_hours`` out: it has no release gate, and its + donor prep refuses an assembled frame (``acs_local_hours.py:227-237``). + + The Route A frame passes that check and stops later, at the raw hours + columns this fixture does not carry. + """ + + with pytest.raises(ValueError, match="explicit legacy ASEC observation roles"): + prepare_acs_local_hours_donor(readers.assembled, seed=0, period=2024) + with pytest.raises(ValueError, match="requires complete raw ASEC"): + prepare_acs_local_hours_donor(readers.route_a, seed=0, period=2024) 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..03b3c9a825 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 @@ -136,6 +136,11 @@ "puf_support.py", # Validates provenance at the clone boundary. "spine_agreement.py", # Pre-calibration distribution comparison. "spine_assembly.py", # New pre-operator assembly seam. + # d2283's one-population contract: rewrites the parent export's CPS + # rows and staging's ACS rows into the assembled provenance form, tags + # each row's spine, and refuses a joined frame by origin. Reads and + # writes provenance by charter; treats no population otherwise. + "one_population_contract.py", # Declares the SPM measurement universe per source arm. The ACS and # ASEC rulings differ by construction, so the provenance tag is the # producer's input rather than something it must be blind to. @@ -459,6 +464,10 @@ # keys, eligibility flags, the nested plan, starting weights and a # manifest. Reads no frame and treats no population itself. "one_population_selection.py", + # d2283's one-population contract (provenance owner above): the + # assembled rewrite, the contract's refusals, the role record and the + # absences file. A check and a relabelling, not a population operator. + "one_population_contract.py", "support_provenance.py", "take_up.py", "take_up_contract.py", diff --git a/test_support/microcosm_build/us_one_population_contract.py b/test_support/microcosm_build/us_one_population_contract.py new file mode 100644 index 0000000000..9ee500f86a --- /dev/null +++ b/test_support/microcosm_build/us_one_population_contract.py @@ -0,0 +1,1731 @@ +"""A generated d2283 one-population input and a stand-in engine variable index. + +d2283's population contract (``us_runtime/one_population_contract.py``) takes +two inputs: the parent Route A export's CPS rows and a staging run's ACS rows. +:func:`generate_population` builds one small, valid pair from a seed: + +- CPS tables in the export's form: six entities; native ASEC rows at clone + index 0 (channel ``asec``), every household's PUF tax-detail copy at clone + index 1 and, for a few households, the capital-gains tail copy at clone + index 2 (both ``puf_tax_detail``), with ids shifted by + ``puf_support._remap_ids``'s multiplier and the tail's extra multiplier; + ``_source_id``, ``_support_channel`` and + ``_support_clone_index`` on every entity and no spine source id or + spine tag; ``PERIDNUM`` (22 digits, the first 20 shared by a household), + ``source_year`` and the other ASEC lineage columns; the six tail + provenance columns on every tax unit, with applied donors on the tail + copies. +- ACS tables in staging's form (``base_pool._prepared_source_view``): channel + and ``_spine`` ``acs_2024_1yr``, clone index 0, native ids in + ``_source_id`` and pooled ids offset past the CPS maximum by + ``base_pool._id_remap_offsets``'s rule; household ``SERIALNO`` and + ``TYPEHUGQ``; person ``SPORDER`` and the PUMS lineage columns. They also + carry what the prepare step fills before the contract runs: the ESI + premium (PR 0) and the six tail columns at the transfer's defaults. + +The ACS tables :func:`generate_population` returns hold only the ACS rows' +own columns: the SSI take-up column (which the release writes) and the raw +ASEC columns are absent. Staging pools the union of both origins' columns +(``base_pool._aligned_column_orders`` and the concat in +``base_pool._combined_tables``), so on its output those columns are present +and all null on ACS rows, and an ACS-only integer column (``SPORDER``, +``TYPEHUGQ``) comes back as float64. :func:`with_staging_union_columns` +gives that form; a clause that reads "absent" and "all null" differently +should be tested on both. + +Both origins come from one column spec, so a shared column keeps one dtype +after the two are joined. Every SPM unit has a classified adult, and the +weighted SPM role shares sit inside the role gate's bands by construction. + +:func:`cps_role_record`, :func:`staging_role_receipt` and +:func:`fill_manifest` give the role record's and the absences file's inputs +in the shapes the prepare step will pass: a CPS-rows record in the role +gate's keys, staging's ACS role receipt, and the reviewed default fill's +manifest. + +:class:`StandInVariableIndex` answers the contract's engine questions without +an engine: its input list is the engine ABI lock's committed projection (the +926 names ``variables()`` returned at policyengine-us 2.2.1), plus explicit +small sets of names computed at 2024 and of names whose only formula starts +after 2024. + +:func:`reader_population` is the whole-frame differential's (X5) ASEC-only +population: a Route A frame made by the production clone and tail operators, +carrying every :data:`READER_GATES` reader's raw source columns, on which +each of those gates passes, and its provenance rewrite with no ACS row. +""" + +from __future__ import annotations + +import hashlib +import json +from collections.abc import Callable, Iterable, Mapping +from dataclasses import dataclass, replace +from functools import cache +from importlib.resources import files +from types import MappingProxyType + +import numpy as np +import pandas as pd + +from microcosm.build.us_runtime.alimony import us_alimony_signal_gate +from microcosm.build.us_runtime.medicare_take_up import ( + US_MEDICARE_TAKE_UP_REQUIRED_SOURCE_COLUMNS, + us_medicare_take_up_signal_gate, +) +from microcosm.build.us_runtime.one_population_contract import ( + ACS_SUPPORT_CHANNEL, + ASSEMBLED_CHANNELS, + CPS_SPINE_TAG, + STRUCTURAL_COLUMNS, + to_assembled_provenance, +) +from microcosm.build.us_runtime.one_population_selection import ( + RULE_VERSION, + SelectionManifest, + acs_unit_key, + cps_unit_key, + keys_sha256, +) +from microcosm.build.us_runtime.puf_capital_gains_tail import ( + PUF_CAPITAL_GAINS_TAIL_APPLIED_COLUMN, + PUF_CAPITAL_GAINS_TAIL_DONOR_AGI_BAND_COLUMN, + PUF_CAPITAL_GAINS_TAIL_DONOR_FILING_STATUS_COLUMN, + PUF_CAPITAL_GAINS_TAIL_DONOR_SOURCE_ID_COLUMN, + PUF_CAPITAL_GAINS_TAIL_DONOR_SYNTHETIC_COLUMN, + PUF_CAPITAL_GAINS_TAIL_TRANSFER_WEIGHT_COLUMN, +) +from microcosm.build.us_runtime.puf_support import clone_us_frame_for_puf_support +from microcosm.build.us_runtime.retirement_contributions import ( + US_RETIREMENT_CONTRIBUTION_OUTPUT_COLUMNS, + US_RETIREMENT_CONTRIBUTION_REQUIRED_SOURCE_COLUMNS, + us_retirement_contributions_signal_gate, +) +from microcosm.build.us_runtime.retirement_distributions import ( + US_RETIREMENT_DISTRIBUTION_OUTPUT_COLUMNS, + US_RETIREMENT_DISTRIBUTION_REQUIRED_SOURCE_COLUMNS, + us_retirement_distributions_signal_gate, +) +from microcosm.build.us_runtime.spm_independence_role import ( + US_SPM_INDEPENDENCE_ROLE_PROVENANCE_KEY, +) +from microcosm.build.us_runtime.ssi_take_up import ( + US_SSI_TAKE_UP_ANCHOR, + us_ssi_take_up_reporter_source_ids, +) +from microcosm.build.us_runtime.support_provenance import ( + BASE_ASEC_SUPPORT_CHANNEL, + PUF_TAX_DETAIL_SUPPORT_CHANNEL, + spine_assembly_manifest, + support_channel_column, + support_clone_index_column, + support_source_id_column, +) +from microcosm.build.us_runtime.weeks_unemployed import us_weeks_unemployed_signal_gate +from microcosm.build.us_runtime.wic_claim import ( + US_WIC_CLAIM_REQUIRED_SOURCE_COLUMNS, + us_wic_claim_signal_gate, +) +from microcosm.build.us_runtime.workers_compensation import ( + US_WORKERS_COMPENSATION_REQUIRED_SOURCE_COLUMNS, + us_workers_compensation_signal_gate, +) +from microcosm.frame import US_SCHEMA, Frame, WeightKind, Weights +from test_support.microcosm_build.us_tail_clone_fixtures import ( + with_capital_gains_tail_copies, +) + +# ------------------------------------------------------ stand-in index + +ENGINE_ABI_LOCK = files("microcosm.build.us").joinpath("engine_abi.lock.json") +_PROJECTION_CONSUMER = "_simulation_projection" + +#: Formula variables the stand-in computes at 2024 (none is in the lock). +STAND_IN_COMPUTED_AT_2024 = frozenset( + {"adjusted_gross_income", "employment_income", "income_tax", "snap", "ssi"} +) +#: The aggregates the release's guard refuses at any period +#: (``policyengine_us._FORMULA_OWNED_COMPAT_COLUMNS`` in microcosm-frame). +STAND_IN_COMPAT_AGGREGATES = frozenset( + { + "dividend_income", + "ordinary_dividend_income", + "partnership_s_corp_income", + "social_security", + } +) +#: Known variables whose only formula starts after 2024: policyengine-us +#: 2.2.1 gives ``weeks_worked`` a ``formula_2025`` and no other. +STAND_IN_FORMULA_AFTER_2024 = frozenset({"weeks_worked"}) +#: Structural variables with a formula, so absent from the year-blind input +#: list: policyengine-us's ``person_id`` is ``np.arange``. +STAND_IN_STRUCTURAL_FORMULAS = frozenset({"person_id"}) + +#: The always-on output prepare leaves null on ACS rows and the release +#: writes on both origins (d2283 K-2; on the contract's exempt list). +RELEASE_WRITTEN_ON_ACS = frozenset({"takes_up_ssi_if_eligible"}) + + +@cache +def lock_engine_inputs() -> Mapping[str, str]: + """The ABI lock's engine-input projection: variable name to entity. + + Read as package data, so no engine is imported. The count and digest + are checked against the lock's own receipt, computed as + ``multispine_pool._pool_engine_input_projection`` computes them. + """ + + payload = json.loads(ENGINE_ABI_LOCK.read_text(encoding="utf-8")) + manifest = payload["remaining_stage_input_manifest"] + rows = [row for row in manifest["rows"] if row["consumer"] == _PROJECTION_CONSUMER] + projection = {row["variable"]: row["entity"] for row in rows} + if len(projection) != len(rows): + raise AssertionError("The lock's engine-input projection repeats a variable.") + digest = hashlib.sha256( + json.dumps( + [ + {"entity": entity, "variable": variable} + for variable, entity in sorted(projection.items()) + ], + allow_nan=False, + separators=(",", ":"), + sort_keys=True, + ).encode("utf-8") + ).hexdigest() + contract = manifest["receipt"]["engine_input_projection_contract"] + if (len(projection), digest) != (contract["input_count"], contract["sha256"]): + raise AssertionError( + "The lock's engine-input projection does not match its receipt: " + f"{len(projection)} names, digest {digest}; receipt {contract}." + ) + return MappingProxyType(projection) + + +def _present(tables: Mapping[str, pd.DataFrame]) -> frozenset[str]: + return frozenset( + column + for table in tables.values() + for column in table.columns + if isinstance(column, str) + ) + + +@dataclass(frozen=True) +class StandInVariableIndex: + """An :class:`EngineVariableIndex` with no engine behind it. + + ``inputs`` is the year-blind input list (``variables()``); ``computed`` + holds what the engine computes at 2024, compatibility aggregates + included; ``formula_after_2024`` holds known names with no formula at + 2024; ``structural_formulas`` holds structural names that only a formula + defines. Answers follow + :class:`~microcosm.build.us_runtime.one_population_contract.PolicyEngineUSVariableIndex`'s + rules: computed never counts a structural column, and an input at 2024 is + known, not structural and not computed. + """ + + inputs: frozenset[str] + computed: frozenset[str] = STAND_IN_COMPUTED_AT_2024 | STAND_IN_COMPAT_AGGREGATES + formula_after_2024: frozenset[str] = STAND_IN_FORMULA_AFTER_2024 + structural_formulas: frozenset[str] = STAND_IN_STRUCTURAL_FORMULAS + + @classmethod + def from_lock(cls) -> StandInVariableIndex: + return cls(inputs=frozenset(lock_engine_inputs())) + + @property + def known(self) -> frozenset[str]: + return ( + self.inputs + | self.computed + | self.formula_after_2024 + | self.structural_formulas + ) + + def known_variables(self, columns: Iterable[str]) -> frozenset[str]: + return frozenset(set(columns) & self.known) + + def computed_at_2024(self, tables: Mapping[str, pd.DataFrame]) -> frozenset[str]: + return frozenset((_present(tables) & self.computed) - STRUCTURAL_COLUMNS) + + def inputs_at_2024(self, tables: Mapping[str, pd.DataFrame]) -> frozenset[str]: + known = self.known_variables(_present(tables)) + return frozenset(known - STRUCTURAL_COLUMNS - self.computed_at_2024(tables)) + + +# --------------------------------------------------------- the generator + +CPS_INCOME_YEARS = (2023, 2024) +ACS_SOURCE_YEAR = 2024 +SPM_ROLE = "is_spm_independent_minor_role" +TAIL_DONOR_ID_BASE = 7_000_000 + +TAIL_PROVENANCE_DEFAULTS: Mapping[str, object] = MappingProxyType( + { + PUF_CAPITAL_GAINS_TAIL_APPLIED_COLUMN: False, + PUF_CAPITAL_GAINS_TAIL_DONOR_SOURCE_ID_COLUMN: -1, + PUF_CAPITAL_GAINS_TAIL_DONOR_SYNTHETIC_COLUMN: False, + PUF_CAPITAL_GAINS_TAIL_DONOR_FILING_STATUS_COLUMN: 0, + PUF_CAPITAL_GAINS_TAIL_DONOR_AGI_BAND_COLUMN: -1, + PUF_CAPITAL_GAINS_TAIL_TRANSFER_WEIGHT_COLUMN: 0.0, + } +) + +#: (state FIPS, districts): states with numbered districts only. +_STATES = ((6, 52), (12, 28), (36, 26), (42, 17), (48, 38)) +_ROLE_SHARE_BAND = (0.40, 0.75) +_MINOR_ROLE_SHARE_BAND = (0.003, 0.06) + +#: One dtype per column, shared by both origins. +_DTYPES: Mapping[str, object] = MappingProxyType( + { + "age": "int64", + "is_female": "bool", + "is_household_head": "bool", + SPM_ROLE: "bool", + "employer_sponsored_insurance_premiums": "float64", + "tip_income": "float64", + "takes_up_ssi_if_eligible": "bool", + "SSI_VAL": "float64", + "PERIDNUM": object, + "SERIALNO": object, + "TYPEHUGQ": "int64", + "SPORDER": "int64", + "RELSHIPP": "int64", + "source_year": "int64", + "source_household_id": "int64", + "source_person_id": object, + "source_row_id": "int64", + "state_fips": "int64", + "congressional_district_geoid": "int64", + PUF_CAPITAL_GAINS_TAIL_APPLIED_COLUMN: "bool", + PUF_CAPITAL_GAINS_TAIL_DONOR_SOURCE_ID_COLUMN: "int64", + PUF_CAPITAL_GAINS_TAIL_DONOR_SYNTHETIC_COLUMN: "bool", + PUF_CAPITAL_GAINS_TAIL_DONOR_FILING_STATUS_COLUMN: "int64", + PUF_CAPITAL_GAINS_TAIL_DONOR_AGI_BAND_COLUMN: "int64", + PUF_CAPITAL_GAINS_TAIL_TRANSFER_WEIGHT_COLUMN: "float64", + **{ + column: "int64" + for entity in US_SCHEMA.entities + for column in ( + US_SCHEMA.entity_id_column(entity), + support_source_id_column(entity), + support_clone_index_column(entity), + ) + }, + **{ + US_SCHEMA.membership_column(group): "int64" + for group in US_SCHEMA.group_entities + }, + **{ + column: object + for entity in US_SCHEMA.entities + for column in (support_channel_column(entity), f"{entity}_spine") + }, + } +) + + +def _typed(table: pd.DataFrame) -> pd.DataFrame: + unknown = sorted(set(table.columns) - set(_DTYPES)) + if unknown: + raise AssertionError(f"Generator columns without a dtype: {unknown}.") + return table.astype({column: _DTYPES[column] for column in table.columns}) + + +@dataclass(frozen=True) +class _Member: + kind: str # head, spouse, child, adult_child, roommate, minor_head, gq + age: int + female: bool + + +@dataclass(frozen=True) +class _Household: + members: tuple[_Member, ...] + state_fips: int + district: int + weight: float + typehugq: int = 1 + + +_ROLE_KINDS = frozenset({"head", "spouse", "roommate", "minor_head", "gq"}) +_HEAD_KINDS = frozenset({"head", "minor_head", "gq"}) +#: ACS persons' RELSHIPP by kind (20 reference person, 21 spouse, 25 child, +#: 34 roommate; a group-quarters person is 37 or 38 by TYPEHUGQ). The ACS +#: role is staging's RELSHIPP rule, so an ACS roommate holds none: it is a +#: member of the household's one SPM unit, not the head of its own. +_ACS_RELSHIPP = MappingProxyType( + { + "head": 20, + "spouse": 21, + "child": 25, + "adult_child": 25, + "roommate": 34, + "minor_head": 20, + } +) +_ACS_ROLE_RELSHIPP = frozenset({20, 21, 23, 37, 38}) +_PATTERN = ("couple", "single_parent", "single", "couple_adult_child", "roommates") + + +def _household( + rng: np.random.Generator, index: int, *, weight: float, kind: str | None = None +) -> _Household: + kind = kind or _PATTERN[index % len(_PATTERN)] + head_female = bool(rng.random() < 0.5) + members = [_Member("head", int(rng.integers(25, 81)), head_female)] + n_children = 0 + if kind in ("couple", "couple_adult_child"): + members.append(_Member("spouse", int(rng.integers(25, 81)), not head_female)) + if kind == "couple": + n_children = int(rng.integers(0, 4)) + elif kind == "single_parent": + n_children = int(rng.integers(1, 4)) + for child in range(n_children): + # The first child of every other family is 15 to 17, so the weighted + # share of role holders among 15-to-17-year-olds stays small. + teen = child == 0 and index % 2 == 0 + age = int(rng.integers(15, 18)) if teen else int(rng.integers(0, 18)) + members.append(_Member("child", age, bool(rng.random() < 0.5))) + if kind == "couple_adult_child": + members.append( + _Member("adult_child", int(rng.integers(18, 31)), bool(rng.random() < 0.5)) + ) + if kind == "roommates": + members.append( + _Member("roommate", int(rng.integers(20, 70)), bool(rng.random() < 0.5)) + ) + state, districts = _STATES[int(rng.integers(0, len(_STATES)))] + return _Household( + members=tuple(members), + state_fips=state, + district=int(rng.integers(1, districts + 1)), + weight=weight, + ) + + +def _unit_groups( + members: tuple[_Member, ...], *, acs: bool = False +) -> dict[str, list[list[int]]]: + """Member positions per unit, for each group entity but the household. + + ACS households are one SPM unit each, staging's partition (ACS PUMS + carries no SPM_ID); CPS roommates head SPM units of their own. + """ + + if members[0].kind in ("minor_head", "gq"): + everyone = [list(range(len(members)))] + return { + "tax_unit": everyone, + "spm_unit": everyone, + "family": everyone, + "marital_unit": [[position] for position in range(len(members))], + } + core = [ + position + for position, member in enumerate(members) + if member.kind in ("head", "spouse", "child") + ] + family = core + [ + position + for position, member in enumerate(members) + if member.kind == "adult_child" + ] + outsiders = [ + [position] + for position, member in enumerate(members) + if member.kind not in ("head", "spouse", "child") + ] + roommates = [ + [position] + for position, member in enumerate(members) + if member.kind == "roommate" + ] + couple = [ + position + for position, member in enumerate(members) + if member.kind in ("head", "spouse") + ] + singles = [ + [position] + for position, member in enumerate(members) + if member.kind not in ("head", "spouse") + ] + return { + "tax_unit": [core, *outsiders], + "spm_unit": [list(range(len(members)))] if acs else [family, *roommates], + "family": [family, *roommates], + "marital_unit": [couple, *singles], + } + + +def _native_tables( + households: list[_Household], + rng: np.random.Generator, + *, + first_person_id: int, + acs: bool = False, +) -> tuple[dict[str, pd.DataFrame], list[list[int]]]: + """Native tables (ids from 1, persons from ``first_person_id``). + + ACS persons also carry ``RELSHIPP``, and their SPM role is staging's + RELSHIPP rule's. Returns the tables and, per household, its persons' + row positions. + """ + + person_rows: list[dict[str, object]] = [] + household_rows: list[dict[str, object]] = [] + groups: dict[str, list[dict[str, object]]] = { + group: [] for group in US_SCHEMA.group_entities if group != "household" + } + positions: list[list[int]] = [] + for household_index, household in enumerate(households): + household_id = household_index + 1 + household_rows.append( + { + "household_id": household_id, + "state_fips": household.state_fips, + "congressional_district_geoid": household.state_fips * 100 + + household.district, + } + ) + unit_ids: dict[str, list[int]] = {} + for group, units in _unit_groups(household.members, acs=acs).items(): + ids = [0] * len(household.members) + for unit in units: + unit_id = len(groups[group]) + 1 + groups[group].append({f"{group}_id": unit_id}) + for position in unit: + ids[position] = unit_id + unit_ids[group] = ids + mine = [] + for position, member in enumerate(household.members): + adult = member.age >= 22 + mine.append(len(person_rows)) + if acs: + relationship = ( + (37 if household.typehugq == 2 else 38) + if member.kind == "gq" + else _ACS_RELSHIPP[member.kind] + ) + origin_columns: dict[str, object] = { + "RELSHIPP": relationship, + SPM_ROLE: relationship in _ACS_ROLE_RELSHIPP, + } + else: + origin_columns = {SPM_ROLE: member.kind in _ROLE_KINDS} + person_rows.append( + { + "person_id": first_person_id + len(person_rows), + "person_household_id": household_id, + **{ + US_SCHEMA.membership_column(group): unit_ids[group][position] + for group in unit_ids + }, + "age": member.age, + "is_female": member.female, + "is_household_head": member.kind in _HEAD_KINDS, + **origin_columns, + "employer_sponsored_insurance_premiums": ( + float(rng.integers(10, 80) * 100) + if adult and member.age < 65 and rng.random() < 0.5 + else 0.0 + ), + "tip_income": ( + float(rng.integers(5, 50) * 100) + if adult and rng.random() < 0.1 + else 0.0 + ), + } + ) + positions.append(mine) + tables = { + "person": pd.DataFrame(person_rows), + "household": pd.DataFrame(household_rows), + **{group: pd.DataFrame(rows) for group, rows in groups.items()}, + } + return tables, positions + + +def _clone_multiplier(tables: Mapping[str, pd.DataFrame]) -> int: + """``puf_support._id_multiplier_for_values`` over every entity's ids.""" + + max_id = max( + int(tables[entity][US_SCHEMA.entity_id_column(entity)].abs().max()) + for entity in US_SCHEMA.entities + ) + return 10 ** max(1, len(str(max_id))) + + +def _shift_ids(table: pd.DataFrame, entity: str, shift: int) -> pd.DataFrame: + table = table.copy() + table[US_SCHEMA.entity_id_column(entity)] += shift + if entity == US_SCHEMA.person_entity: + for group in US_SCHEMA.group_entities: + table[US_SCHEMA.membership_column(group)] += shift + return table + + +def _cps_tables( + households: list[_Household], + rng: np.random.Generator, + *, + tail_every: int, +) -> tuple[dict[str, pd.DataFrame], np.ndarray, int, frozenset[int], tuple[str, ...]]: + native, positions = _native_tables(households, rng, first_person_id=1) + person = native["person"] + + # ASEC lineage: each household gets an income year, H_IDNUM and PH_SEQ. + peridnum = [""] * len(person) + source_year = [0] * len(person) + source_household_id = [0] * len(person) + source_row_id = [0] * len(person) + seen: set[str] = set() + keys: list[str] = [] + rows_by_year = dict.fromkeys(CPS_INCOME_YEARS, 0) + households_by_year = dict.fromkeys(CPS_INCOME_YEARS, 0) + for household_index, rows in enumerate(positions): + year = CPS_INCOME_YEARS[household_index % len(CPS_INCOME_YEARS)] + h_idnum = ( + f"{int(rng.integers(1, 10))}{int(rng.integers(0, 10**9)):09d}" + f"{int(rng.integers(0, 10**10)):010d}" + ) + if h_idnum in seen: # pragma: no cover - 1 in 10**19 + raise AssertionError("Generated H_IDNUM repeats.") + seen.add(h_idnum) + keys.append(cps_unit_key(year, h_idnum)) + households_by_year[year] += 1 + for line, row in enumerate(rows, start=1): + peridnum[row] = f"{h_idnum}{line:02d}" + source_year[row] = year + source_household_id[row] = households_by_year[year] + source_row_id[row] = rows_by_year[year] + rows_by_year[year] += 1 + person["PERIDNUM"] = peridnum + person["source_year"] = source_year + person["source_household_id"] = source_household_id + person["source_person_id"] = peridnum + person["source_row_id"] = source_row_id + adult = person["age"].to_numpy() >= 18 + person["SSI_VAL"] = np.where( + adult & (rng.random(len(person)) < 0.08), + rng.integers(20, 90, len(person)) * 100.0, + 0.0, + ) + person["takes_up_ssi_if_eligible"] = rng.random(len(person)) < 0.6 + for column, default in TAIL_PROVENANCE_DEFAULTS.items(): + native["tax_unit"][column] = default + + # puf_support._clone_entity_table: clone 0 keeps its ids, clone 1 moves + # every id (memberships too) by the multiplier; both keep the native id + # as the source id. + multiplier = _clone_multiplier(native) + cloned: dict[str, pd.DataFrame] = {} + for entity in US_SCHEMA.entities: + copies = [] + for clone_index, channel in enumerate( + (BASE_ASEC_SUPPORT_CHANNEL, PUF_TAX_DETAIL_SUPPORT_CHANNEL) + ): + copy = _shift_ids(native[entity], entity, clone_index * multiplier) + copy[support_source_id_column(entity)] = native[entity][ + US_SCHEMA.entity_id_column(entity) + ].to_numpy() + copy[support_channel_column(entity)] = channel + copy[support_clone_index_column(entity)] = clone_index + copies.append(copy) + cloned[entity] = pd.concat(copies, ignore_index=True) + + # puf_capital_gains_tail._clone_and_transfer: copy the selected + # households' clone-1 rows on every entity, move their ids by one more + # multiplier, set clone index 2, keep channel and source id; stamp the + # recipient tax unit's tail provenance. + selected = [index + 1 for index in range(0, len(households), tail_every)] + person = cloned["person"] + clone_one = person[support_clone_index_column("person")] == 1 + tail_people = person.loc[ + clone_one & person["person_household_id"].isin(np.add(selected, multiplier)) + ] + tail_ids = { + "person": set(tail_people["person_id"]), + **{ + group: set(tail_people[US_SCHEMA.membership_column(group)]) + for group in US_SCHEMA.group_entities + }, + } + weights = np.array([household.weight for household in households]) + household_weights = np.concatenate([weights / 2.0, weights / 2.0]) + tail_weights = [] + for entity in US_SCHEMA.entities: + table = cloned[entity] + rows = table.loc[ + table[US_SCHEMA.entity_id_column(entity)].isin(tail_ids[entity]) + ] + tail = _shift_ids(rows, entity, multiplier) + tail[support_clone_index_column(entity)] = 2 + cloned[entity] = pd.concat([table, tail], ignore_index=True) + tax_unit = cloned["tax_unit"] + donors: list[int] = [] + for number, household_id in enumerate(selected): + weight = households[household_id - 1].weight / 2.0 + household_weights[len(households) + household_id - 1] = weight * 0.75 + tail_weights.append(weight * 0.25) + head = person.loc[ + clone_one & (person["person_household_id"] == household_id + multiplier) + ].iloc[0] + target = tax_unit["tax_unit_id"] == int(head["person_tax_unit_id"]) + multiplier + donor = TAIL_DONOR_ID_BASE + 17 * number + donors.append(donor) + tax_unit.loc[target, PUF_CAPITAL_GAINS_TAIL_APPLIED_COLUMN] = True + tax_unit.loc[target, PUF_CAPITAL_GAINS_TAIL_DONOR_SOURCE_ID_COLUMN] = donor + tax_unit.loc[target, PUF_CAPITAL_GAINS_TAIL_DONOR_SYNTHETIC_COLUMN] = bool( + number % 2 + ) + tax_unit.loc[target, PUF_CAPITAL_GAINS_TAIL_DONOR_FILING_STATUS_COLUMN] = ( + 1 + number % 2 + ) + tax_unit.loc[target, PUF_CAPITAL_GAINS_TAIL_DONOR_AGI_BAND_COLUMN] = number % 3 + tax_unit.loc[target, PUF_CAPITAL_GAINS_TAIL_TRANSFER_WEIGHT_COLUMN] = ( + weight * 0.25 + ) + household_weights = np.concatenate([household_weights, tail_weights]) + tables = {entity: _typed(table) for entity, table in cloned.items()} + return tables, household_weights, multiplier, frozenset(donors), tuple(keys) + + +def _acs_tables( + households: list[_Household], + rng: np.random.Generator, + cps_tables: Mapping[str, pd.DataFrame], +) -> tuple[dict[str, pd.DataFrame], np.ndarray, dict[str, int], tuple[str, ...]]: + # acs_pums: households sorted by SERIALNO and numbered 1..N in that + # order; persons by (SERIALNO, SPORDER), person ids 0..N-1. + serials = [ + f"{ACS_SOURCE_YEAR}{'GQ' if household.typehugq != 1 else 'HU'}" + f"{int(rng.integers(0, 10**7)):07d}" + for household in households + ] + if len(set(serials)) != len(serials): # pragma: no cover - seeded + raise AssertionError("Generated SERIALNO repeats.") + order = sorted(range(len(households)), key=serials.__getitem__) + households = [households[index] for index in order] + serials = [serials[index] for index in order] + native, positions = _native_tables(households, rng, first_person_id=0, acs=True) + native["household"]["SERIALNO"] = serials + native["household"]["TYPEHUGQ"] = [household.typehugq for household in households] + person = native["person"] + sporder = np.zeros(len(person), dtype=np.int64) + for rows in positions: + sporder[rows] = np.arange(1, len(rows) + 1) + person["SPORDER"] = sporder + person["source_year"] = ACS_SOURCE_YEAR + person["source_household_id"] = person["person_household_id"].to_numpy() + person["source_person_id"] = [str(int(value)) for value in sporder] + person["source_row_id"] = np.arange(len(person), dtype=np.int64) + for column, default in TAIL_PROVENANCE_DEFAULTS.items(): + native["tax_unit"][column] = default + + # base_pool._prepared_source_view with the export as donor: tag the + # spine, copy the native id into the source id, then offset each entity's + # ids (memberships by their group's offset) past the donor's maximum + # when the id sets overlap (_id_remap_offsets). + offsets: dict[str, int] = {} + for entity in US_SCHEMA.entities: + id_column = US_SCHEMA.entity_id_column(entity) + mine = cps_tables[entity][id_column].to_numpy() + theirs = native[entity][id_column].to_numpy() + if np.intersect1d(mine, theirs).size: + offsets[entity] = int(mine.max()) + 1 - int(theirs.min()) + tables: dict[str, pd.DataFrame] = {} + for entity in US_SCHEMA.entities: + source = native[entity] + table = source.copy() + table[f"{entity}_spine"] = ACS_SUPPORT_CHANNEL + table[support_source_id_column(entity)] = source[ + US_SCHEMA.entity_id_column(entity) + ].to_numpy() + table[support_channel_column(entity)] = ACS_SUPPORT_CHANNEL + table[support_clone_index_column(entity)] = 0 + table[US_SCHEMA.entity_id_column(entity)] += offsets.get(entity, 0) + if entity == US_SCHEMA.person_entity: + for group in US_SCHEMA.group_entities: + table[US_SCHEMA.membership_column(group)] += offsets.get(group, 0) + tables[entity] = _typed(table) + weights = np.array([household.weight for household in households]) + keys = tuple(acs_unit_key(serial) for serial in serials) + return tables, weights, offsets, keys + + +@dataclass(frozen=True, eq=False) +class GeneratedPopulation: + """One valid input pair for the contract, with what a test needs to know. + + ``cps_household_weights`` and ``acs_household_weights`` align with each + origin's household table; :attr:`keyed_cps_household_weights` and + :attr:`keyed_acs_household_weights` key them as the contract takes them. + ``clone_multiplier`` is the CPS clone id shift, ``acs_id_offsets`` + staging's per-entity ACS offsets, ``tail_donor_ids`` the applied tail + donors, and ``cps_keys``/``acs_keys`` the selection keys of the native + CPS households and the ACS households. + """ + + seed: int + cps_tables: Mapping[str, pd.DataFrame] + acs_tables: Mapping[str, pd.DataFrame] + cps_household_weights: np.ndarray + acs_household_weights: np.ndarray + clone_multiplier: int + acs_id_offsets: Mapping[str, int] + tail_donor_ids: frozenset[int] + cps_keys: tuple[str, ...] + acs_keys: tuple[str, ...] + + @property + def keyed_cps_household_weights(self) -> pd.Series: + """The CPS household weights keyed by ``household_id``.""" + + return cps_household_weight_series( + self.cps_tables["household"], self.cps_household_weights + ) + + @property + def keyed_acs_household_weights(self) -> pd.Series: + """The ACS household weights keyed by ``acs_unit_key(SERIALNO)``.""" + + return acs_household_weight_series( + self.acs_tables["household"], self.acs_household_weights + ) + + +def cps_household_weight_series(household: pd.DataFrame, weights: object) -> pd.Series: + """CPS household weights keyed as the contract takes them, by household id. + + ``weights`` align with ``household``'s rows. + """ + + return pd.Series( + np.asarray(weights, dtype=np.float64), + index=pd.Index(household["household_id"].to_numpy(), name="household_id"), + ) + + +def acs_household_weight_series(household: pd.DataFrame, weights: object) -> pd.Series: + """ACS household weights keyed as the contract takes them. + + The key is ``acs_unit_key(SERIALNO)``, the key PR 1's selection keeps its + ACS starting weights in order of. ``weights`` align with ``household``'s + rows. + """ + + return pd.Series( + np.asarray(weights, dtype=np.float64), + index=pd.Index( + [acs_unit_key(serial) for serial in household["SERIALNO"]], + dtype=object, + name="acs_unit_key", + ), + ) + + +def generate_population( + seed: int = 0, + *, + n_cps_households: int = 24, + n_acs_households: int = 24, + tail_every: int = 4, +) -> GeneratedPopulation: + """Generate one valid CPS-and-ACS population input from ``seed``. + + The ACS side always holds one household whose only member at least 15 is + a 17-year-old head with the SPM role (so the role, not age alone, + classifies its SPM unit's adult) and two group-quarters households + (``TYPEHUGQ`` 2 and 3). + """ + + rng = np.random.default_rng(seed) + cps_households = [ + _household(rng, index, weight=float(rng.integers(800, 1201))) + for index in range(n_cps_households) + ] + acs_households = [ + _household(rng, index, weight=float(rng.integers(80, 121))) + for index in range(n_acs_households - 3) + ] + state, districts = _STATES[0] + acs_households.append( + _Household( + members=( + _Member("minor_head", 17, bool(rng.random() < 0.5)), + _Member("child", 12, bool(rng.random() < 0.5)), + ), + state_fips=state, + district=1, + weight=100.0, + ) + ) + for typehugq, age in ((2, 82), (3, 19)): + acs_households.append( + _Household( + members=(_Member("gq", age, bool(rng.random() < 0.5)),), + state_fips=state, + district=districts, + weight=100.0, + typehugq=typehugq, + ) + ) + cps, cps_weights, multiplier, donors, cps_keys = _cps_tables( + cps_households, rng, tail_every=tail_every + ) + acs, acs_weights, offsets, acs_keys = _acs_tables(acs_households, rng, cps) + population = GeneratedPopulation( + seed=seed, + cps_tables=MappingProxyType(cps), + acs_tables=MappingProxyType(acs), + cps_household_weights=cps_weights, + acs_household_weights=acs_weights, + clone_multiplier=multiplier, + acs_id_offsets=MappingProxyType(offsets), + tail_donor_ids=donors, + cps_keys=cps_keys, + acs_keys=acs_keys, + ) + _check_role_bands(joined_frame(population)) + return population + + +def with_staging_union_columns(population: GeneratedPopulation) -> GeneratedPopulation: + """``population`` with its ACS tables in staging's pooled column union. + + Staging concatenates the donor's rows (here, the CPS tables, tagged + ``asec_puf``) and the ACS rows over the union of their columns, donor + columns first. Its ACS rows therefore carry every CPS-only column all + null, in the dtype the concat gives it, and their own integer-only + columns come back as float64. The CPS tables and weights are unchanged. + """ + + acs: dict[str, pd.DataFrame] = {} + for entity in US_SCHEMA.entities: + donor = population.cps_tables[entity].assign( + **{f"{entity}_spine": CPS_SPINE_TAG} + ) + pooled = pd.concat( + [donor, population.acs_tables[entity]], ignore_index=True, sort=False + ) + acs[entity] = pooled.iloc[len(donor) :].reset_index(drop=True) + return replace(population, acs_tables=MappingProxyType(acs)) + + +# ------------------------------------------------------ joined frame + + +def staging_lineage( + population: GeneratedPopulation, +) -> dict[tuple[int, int], tuple[str, int]]: + """The ACS persons' (``SERIALNO``, ``SPORDER``) lineage, as staging holds it. + + Keyed by each person's native (household id, person id), staging's + ``_source_id`` before the rewrite, so a ``SERIALNO`` cannot move + between households without the key's pair changing. The generated ACS + tables are staging's rows for the selected households, so this is what + the prepare step would read from staging. + """ + + household = population.acs_tables["household"] + person = population.acs_tables["person"] + by_household = household.set_index("household_id") + link = person["person_household_id"] + serial = link.map(by_household["SERIALNO"]) + native_household = link.map(by_household[support_source_id_column("household")]) + return { + (int(household_id), int(person_id)): (str(serial_number), int(sporder)) + for household_id, person_id, serial_number, sporder in zip( + native_household.tolist(), + person[support_source_id_column("person")].tolist(), + serial.tolist(), + person["SPORDER"].tolist(), + strict=True, + ) + } + + +def assembled_frame(population: GeneratedPopulation) -> Frame: + """The contract's provenance rewrite of ``population``.""" + + return to_assembled_provenance( + population.cps_tables, + population.acs_tables, + cps_household_weights=population.keyed_cps_household_weights, + acs_household_weights=population.keyed_acs_household_weights, + staging_lineage=staging_lineage(population), + ) + + +def joined_frame( + population: GeneratedPopulation, + *, + metadata: Mapping[str, object] | None = None, +) -> Frame: + """CPS and ACS rows in one frame, as given (no provenance rewrite). + + Group tables are sorted by id and the household weights follow them. + """ + + tables: dict[str, pd.DataFrame] = {} + weights = np.concatenate( + [population.cps_household_weights, population.acs_household_weights] + ) + for entity in US_SCHEMA.entities: + table = pd.concat( + [population.cps_tables[entity], population.acs_tables[entity]], + ignore_index=True, + sort=False, + ) + if entity in US_SCHEMA.group_entities: + order = np.argsort( + table[US_SCHEMA.id_column(entity)].to_numpy(), kind="stable" + ) + table = table.iloc[order].reset_index(drop=True) + if entity == "household": + weights = weights[order] + tables[entity] = table + return Frame( + tables, + US_SCHEMA, + {"household": Weights(weights, WeightKind.IMPORTANCE)}, + metadata=metadata, + ) + + +def selection_manifest(population: GeneratedPopulation) -> SelectionManifest: + """PR 1's selection manifest for selecting every generated household. + + The key digests and counts are the generated keys'; the other fields + are coherent placeholders (the contract reads only the keys' digests and + counts). + """ + + by_year: dict[int, int] = {} + for key in population.cps_keys: + year = int(key.split("|", 1)[0]) + by_year[year] = by_year.get(year, 0) + 1 + group_quarters = int( + (population.acs_tables["household"]["TYPEHUGQ"] != 1).sum() + if len(population.acs_tables["household"]) + else 0 + ) + return SelectionManifest( + rule_version=RULE_VERSION, + salt="d2283-generated-population", + replicate=0, + budget=len(population.cps_keys) + len(population.acs_keys), + include_group_quarters=True, + drop_spm_zero_adult=True, + acs_households=len(population.acs_keys), + acs_eligible=len(population.acs_keys), + acs_spm_zero_adult=0, + acs_group_quarters=group_quarters, + cps_income_years=tuple(sorted(by_year)), + n_cps=len(population.cps_keys), + n_acs=len(population.acs_keys), + n_cps_by_income_year=tuple(sorted(by_year.items())), + threshold_draw=None, + selected_acs_keys_sha256=keys_sha256(population.acs_keys), + cps_keys_sha256=keys_sha256(population.cps_keys), + ) + + +def clone_zero_assembly_record(frame: Frame) -> dict[str, object]: + """The three-channel spine assembly record over the clone-0 rows.""" + + return spine_assembly_manifest( + { + entity: frame.table(entity).loc[ + frame.table(entity)[support_clone_index_column(entity)] == 0 + ] + for entity in frame.entities + }, + channels=ASSEMBLED_CHANNELS, + ) + + +def _gate_record(person: pd.DataFrame, spm_units: int) -> dict[str, object]: + """The role gate's counts and digest over ``person``, by its rule. + + The digest restates ``spm_independence_role._role_binding_sha256``: the + sha256 of the uint64 row hashes of the ordered person id, SPM unit + membership, age and role columns. + """ + + columns = ["person_id", "person_spm_unit_id", "age", SPM_ROLE] + hashes = pd.util.hash_pandas_object(person[columns], index=False) + return { + "persons_joined": len(person), + "table_rows": len(person), + "native_spm_units": int(spm_units), + "true_role_persons": int(person[SPM_ROLE].sum()), + "person_role_binding_sha256": hashlib.sha256( + hashes.to_numpy(dtype=" dict[str, object]: + """A record in the role gate's keys, computed by its rule over ``frame``.""" + + return _gate_record(frame.table("person"), frame.n("spm_unit")) + + +def _cps_rows(table: pd.DataFrame, entity: str) -> np.ndarray: + return table[support_channel_column(entity)].ne(ACS_SUPPORT_CHANNEL).to_numpy() + + +def cps_role_record(frame: Frame) -> dict[str, object]: + """The CPS half's role record PR 4 would derive, over the frame's CPS rows. + + The gate's keys over the CPS person rows in the frame's order and dtypes + (by the gate's rule, restated), plus the provenance keys + ``with_us_spm_independence_role`` writes that the contract reads as + evidence only. + """ + + person = frame.table("person") + spm_unit = frame.table("spm_unit") + return { + **_gate_record( + person.loc[_cps_rows(person, "person")], + int(_cps_rows(spm_unit, "spm_unit").sum()), + ), + "primitive_column": SPM_ROLE, + "source_join": [ + "source_year (income year)", + "PERIDNUM (exact 22-digit string)", + ], + "unmatched_persons": 0, + } + + +def staging_role_receipt(frame: Frame, *, staged_beyond: int = 5) -> dict[str, object]: + """Staging's ACS role receipt for a staging run that held ``frame``'s ACS rows. + + The keys and identity are ``acs_inputs.with_acs_spm_independence_role``'s; + the counts cover ``staged_beyond`` more persons (and one more SPM unit and + role holder per five) than the selection keeps, as a pre-selection + receipt does. + """ + + from microcosm.build.us_runtime.acs_inputs import ( + ACS_SPM_ROLE_PARTITION, + ACS_SPM_ROLE_RULE, + ) + from microcosm.build.us_runtime.spm_role_source import ( + SPM_ADULT_RULE, + SPM_ROLE_RULE, + ) + + person = frame.table("person") + acs = ~_cps_rows(person, "person") + role = person.loc[acs, SPM_ROLE].to_numpy(dtype=bool) + age = person.loc[acs, "age"].to_numpy() + minor = (age >= 15) & (age < 18) + extra = staged_beyond // 5 + return { + "column": SPM_ROLE, + "entity": "person", + "source_columns": ["RELSHIPP"], + "rule": ACS_SPM_ROLE_RULE, + "partition": ACS_SPM_ROLE_PARTITION, + "asec_rule": SPM_ROLE_RULE, + "adult_rule": SPM_ADULT_RULE, + "provenance": "acs_2024_1yr_native", + "persons": int(acs.sum()) + staged_beyond, + "spm_units": int((~_cps_rows(frame.table("spm_unit"), "spm_unit")).sum()) + + extra, + "role_true_persons": int(role.sum()) + extra, + "role_branches": { + "reference_person": int(role.sum()), + "spouse_of_reference_person": 0, + "group_quarters_sole_person": 2, + }, + "persons_aged_15_to_17": int(minor.sum()), + "independent_minor_persons": int((role & minor).sum()), + "housing_units_classified_only_by_role": 1, + "group_quarters_units_without_classified_adult": 0, + "weighted_role_share": 0.6, + "weighted_minor_role_share": 0.02, + } + + +def fill_manifest(fills: Iterable[Mapping[str, object]] = (), *, period: int = 2024): + """A reviewed default fill's manifest (``fill_reviewed_nulls``'s shape).""" + + fills = [dict(fill) for fill in fills] + return { + "period": period, + "register_entries": len(fills), + "columns_filled": len(fills), + "total_values_filled": sum(int(fill["filled_rows"]) for fill in fills), + "count_mismatch_warnings": [], + "unregistered_violations": [], + "fills": fills, + } + + +def with_spm_role_record(frame: Frame, record: Mapping[str, object]) -> Frame: + """``frame`` with ``record`` under the role gate's metadata key.""" + + return Frame( + {entity: frame.table(entity) for entity in frame.entities}, + frame.schema, + {entity: frame.weights_for(entity) for entity in frame.weighted_entities}, + frame.strata, + mass_log=frame.mass_log, + metadata={ + **frame.metadata, + US_SPM_INDEPENDENCE_ROLE_PROVENANCE_KEY: dict(record), + }, + ) + + +def role_shares(frame: Frame) -> tuple[float, float]: + """Weighted SPM role share overall and among 15-to-17-year-olds.""" + + person = frame.table("person") + weights = np.asarray(frame.resolve_weights("person").values, dtype=np.float64) + role = person[SPM_ROLE].to_numpy(dtype=bool) + age = person["age"].to_numpy(dtype=np.float64) + minor = (age >= 15) & (age < 18) + return ( + float(weights[role].sum() / weights.sum()), + float(weights[role & minor].sum() / weights[minor].sum()), + ) + + +def _check_role_bands(frame: Frame) -> None: + share, minor_share = role_shares(frame) + for label, value, (lower, upper) in ( + ("role share", share, _ROLE_SHARE_BAND), + ("minor role share", minor_share, _MINOR_ROLE_SHARE_BAND), + ): + if not lower <= value <= upper: + raise AssertionError( + f"Generated {label} {value:.4f} is outside [{lower}, {upper}]." + ) + + +# ------------------------------------- X5: a Route A frame for the readers + +#: The provenance-reading gates d2283's whole-frame differential (X5) runs: +#: six of the seven assembled-form readers F-19 lists (alimony, Medicare +#: take-up, both retirement families, WIC, workers' compensation; the +#: seventh, ``acs_local_hours``, has no release gate), the weeks-unemployed +#: gate (in F-19's first count of nine; PR 3 owns its UC-rule scope) and +#: the SSI take-up reporter lineage (a reviewed caller of +#: ``support_gate_source_channel_series``; the SSI gate itself grades +#: diagnostics built from an engine-computed ``uncapped_ssi``). +READER_GATES: Mapping[str, Callable[[Frame], object]] = MappingProxyType( + { + "alimony": us_alimony_signal_gate, + "medicare_take_up": us_medicare_take_up_signal_gate, + "retirement_contributions": us_retirement_contributions_signal_gate, + "retirement_distributions": us_retirement_distributions_signal_gate, + "ssi_take_up_reporters": us_ssi_take_up_reporter_source_ids, + "weeks_unemployed": us_weeks_unemployed_signal_gate, + "wic_claim": us_wic_claim_signal_gate, + "workers_compensation": us_workers_compensation_signal_gate, + } +) + +#: Each reader's raw ASEC source columns, all on the reader frame. +READER_SOURCE_COLUMNS: Mapping[str, tuple[str, ...]] = MappingProxyType( + { + "alimony": ("OI_VAL", "OI_OFF"), + "medicare_take_up": US_MEDICARE_TAKE_UP_REQUIRED_SOURCE_COLUMNS, + "retirement_contributions": US_RETIREMENT_CONTRIBUTION_REQUIRED_SOURCE_COLUMNS, + "retirement_distributions": US_RETIREMENT_DISTRIBUTION_REQUIRED_SOURCE_COLUMNS, + "ssi_take_up_reporters": (US_SSI_TAKE_UP_ANCHOR,), + "weeks_unemployed": ("LKWEEKS", "unemployment_compensation"), + "wic_claim": US_WIC_CLAIM_REQUIRED_SOURCE_COLUMNS, + "workers_compensation": US_WORKERS_COMPENSATION_REQUIRED_SOURCE_COLUMNS, + } +) + +#: The WIC gate's source-local identity on a frame without spine ids. +WIC_SOURCE_TRIPLE = ("source_year", "source_household_id", "source_person_id") + +#: The two clone-only defects d2283 lead call L7 adds to X5. Each changes +#: one cell on one clone row so the row breaks its reader's Route A +#: reconciliation, which the assembled readers leave out: Medicare's +#: assembled source mask keeps stored-``asec`` rows, and the assembled weeks +#: UC rule keys on the stored channel and clone index. Each maps to its +#: reader and the one failure Route A's gate then reports. +READER_CLONE_DEFECTS: Mapping[str, tuple[str, str]] = MappingProxyType( + { + "medicare_clone_mcare_mismatch": ( + "medicare_take_up", + "takes_up_medicare_if_eligible: 1 MCARE reconciliation mismatch(es)", + ), + "weeks_clone_uc_mismatch": ( + "weeks_unemployed", + "weeks_unemployed has 1 row(s) positive outside the " + "unemployment-compensation constraint.", + ), + } +) + +#: Each defect's cell: the native person (group, index) whose one clone row +#: changes, the column and the new value. Elder 0 is enrolled (``MCARE`` +#: 1, take-up True) and its clone now reports code 2; worker 5 receives +#: unemployment compensation, so its clone carries 10 weeks, and the clone's +#: compensation is now 0. Neither sits in a tail-source household, so each +#: has exactly one clone row. +_CLONE_DEFECT_CELLS: Mapping[str, tuple[tuple[str, int], str, object]] = ( + MappingProxyType( + { + "medicare_clone_mcare_mismatch": (("elder", 0), "MCARE", 2), + "weeks_clone_uc_mismatch": ( + ("worker", 5), + "unemployment_compensation", + 0.0, + ), + } + ) +) + +_READER_WEIGHT = 1_000.0 +#: One single's household weighs a tenth of the rest, so the Keogh +#: distribution it carries sits inside the gate's 0.5% share bound. +_READER_LIGHT_WEIGHT = 100.0 +#: A distribution slot: (code column, amount column). +_DST_SLOTS = tuple( + (f"DST_SC{suffix}", f"DST_VAL{suffix}") for suffix in ("1", "2", "1_YNG", "2_YNG") +) +_DST_OUTPUT_BY_CODE = dict(enumerate(US_RETIREMENT_DISTRIBUTION_OUTPUT_COLUMNS, 1)) + + +@dataclass(frozen=True) +class ReaderPopulation: + """The X5 reader population in both provenance forms. + + ``route_a`` is the Route A (unassembled) frame; ``assembled`` is + :func:`~microcosm.build.us_runtime.one_population_contract.to_assembled_provenance` + of its tables with no ACS row. ``reporters`` are the native persons with + a direct ``SSI_VAL`` report (as ``person_source_id`` strings) and + ``clone_only_ssi`` the person whose clone rows alone carry one. + """ + + route_a: Frame + assembled: Frame + reporters: frozenset[str] + clone_only_ssi: str + + +def _reader_households() -> list[tuple[float, list[dict[str, object]]]]: + """200 native persons in 120 households; ``group`` names each role.""" + + households: list[tuple[float, list[dict[str, object]]]] = [] + + def person(group: str, age: int, female: bool, **extra: object) -> dict: + return {"group": group, "age": age, "is_female": female, **extra} + + # WIC: postpartum mothers with infants, pregnant women, young children. + # Claims by category: postpartum 2 of 4, infant 3 of 4, pregnant 1 of 2, + # child 2 of 4, so every category share sits inside its band. + for index in range(4): + households.append( + ( + _READER_WEIGHT, + [ + person("mother", 24 + 2 * index, True, children=1, wic=index < 2), + person("infant", 0, index % 2 == 0, wic=index < 3), + ], + ) + ) + for index in range(2): + households.append( + ( + _READER_WEIGHT, + [ + person( + "pregnant", 25 + 5 * index, True, pregnant=True, wic=index == 0 + ), + person("partner", 27 + 5 * index, False), + ], + ) + ) + for index in range(4): + households.append( + ( + _READER_WEIGHT, + [ + person("parent", 30 + 2 * index, index % 2 == 0, children=1), + person("child", 1 + index, index % 2 == 1, wic=index < 2), + ], + ) + ) + # Medicare: 40 enrolled persons, a fifth of the person weight. + for index in range(20): + households.append( + ( + _READER_WEIGHT, + [ + person("elder", 66 + index % 14, False), + person("elder", 65 + index % 14, True), + ], + ) + ) + for index in range(50): + households.append( + ( + _READER_WEIGHT, + [ + person("worker", 25 + index % 38, False), + person("worker", 24 + index % 38, True), + ], + ) + ) + for index in range(39): + households.append( + (_READER_WEIGHT, [person("single", 22 + index % 40, index % 2 == 0)]) + ) + households.append((_READER_LIGHT_WEIGHT, [person("light", 60, False)])) + return households + + +def _reader_native_frame() -> tuple[Frame, dict[str, np.ndarray]]: + """The native ASEC rows, each producer's direct-source output written. + + Returns the frame and, by group, the person positions in its person + table (for choosing who carries a rare measure). + """ + + rows: list[dict[str, object]] = [] + household_ids: list[int] = [] + weights: list[float] = [] + marital_unit = 0 + for household_index, (weight, members) in enumerate(_reader_households()): + household_id = household_index + 1 + household_ids.append(household_id) + weights.append(weight) + couple = len(members) == 2 and all(member["age"] >= 18 for member in members) + for line, member in enumerate(members, 1): + if line == 1 or not couple: + marital_unit += 1 + rows.append( + { + **member, + "person_household_id": household_id, + "person_marital_unit_id": marital_unit, + "line": line, + } + ) + table = pd.DataFrame(rows) + count = len(table) + group = table["group"].to_numpy(dtype=object) + positions = { + name: np.flatnonzero(group == name) for name in sorted(set(group.tolist())) + } + age = table["age"].to_numpy(dtype=np.int64) + adult = age >= 15 + + def zeros() -> np.ndarray: + return np.zeros(count, dtype=np.float64) + + workers, elders, singles = ( + positions["worker"], + positions["elder"], + positions["single"], + ) + # Weeks unemployed: five LKWEEKS reports; unemployment compensation on + # two of them and on one person with none (the clones' UC scope). + lkweeks = np.where(adult, 0, -1).astype(np.int64) + lkweeks[workers[:5]] = 20 + unemployment = zeros() + unemployment[workers[[0, 1, 5]]] = 4_000.0 + # Workers' compensation: one direct report. + wc = zeros() + wc[workers[6]] = 12_000.0 + # Other income: alimony (code 20), strike benefits (12), another code. + oi_off = np.zeros(count, dtype=np.int64) + oi_val = zeros() + for position, code, amount in ( + (singles[0], 20, 6_000.0), + (singles[1], 12, 800.0), + (singles[2], 7, 400.0), + ): + oi_off[position], oi_val[position] = code, amount + alimony_expense = zeros() + alimony_expense[singles[3]] = 3_000.0 + # Retirement contributions: one leaf per contributor. + wages = np.where(np.isin(np.arange(count), workers), 40_000.0, 0.0) + self_employment = zeros() + self_employment[workers[12]] = 20_000.0 + retcb = zeros() + contributions = { + column: zeros() for column in US_RETIREMENT_CONTRIBUTION_OUTPUT_COLUMNS + } + for offset, column in enumerate(US_RETIREMENT_CONTRIBUTION_OUTPUT_COLUMNS): + amount = 5_000.0 - 1_000.0 * offset + retcb[workers[8 + offset]] = amount + contributions[column][workers[8 + offset]] = amount + # Retirement distributions: every account code, a two-slot sum, an + # "other" code (7) with no leaf, and Keogh on the light household. + dst_codes = {code: np.zeros(count, dtype=np.int64) for code, _ in _DST_SLOTS} + dst_amounts = {amount: zeros() for _, amount in _DST_SLOTS} + for position, slot, code, amount in ( + (elders[0], 0, 1, 8_000.0), + (elders[1], 0, 2, 5_000.0), + (elders[2], 0, 3, 4_000.0), + (elders[2], 1, 4, 3_000.0), + (positions["light"][0], 2, 5, 2_000.0), + (elders[3], 3, 6, 1_500.0), + (elders[4], 0, 7, 900.0), + (elders[5], 0, 4, 2_500.0), + (elders[5], 1, 4, 500.0), + ): + code_column, amount_column = _DST_SLOTS[slot] + dst_codes[code_column][position] = code + dst_amounts[amount_column][position] = amount + distributions = { + column: zeros() for column in US_RETIREMENT_DISTRIBUTION_OUTPUT_COLUMNS + } + for code_column, amount_column in _DST_SLOTS: + for code, column in _DST_OUTPUT_BY_CODE.items(): + hit = dst_codes[code_column] == code + distributions[column][hit] += dst_amounts[amount_column][hit] + # SSI: two direct reports. + ssi = zeros() + ssi[elders[6]] = 9_000.0 + ssi[singles[5]] = 4_000.0 + # Medicare: every elder enrolled; other adults not; children NIU. + mcare = np.where(np.isin(np.arange(count), elders), 1, np.where(adult, 2, 0)) + + household_of = table["person_household_id"].to_numpy(dtype=np.int64) + person = pd.DataFrame( + { + "person_id": np.arange(1, count + 1, dtype=np.int64), + "person_household_id": household_of, + "person_tax_unit_id": household_of, + "person_spm_unit_id": household_of, + "person_family_id": household_of, + "person_marital_unit_id": table["person_marital_unit_id"].astype("int64"), + "age": age, + "is_female": table["is_female"].astype(bool), + "is_pregnant": table.get("pregnant", pd.Series(False, index=table.index)) + .fillna(False) + .astype(bool), + "own_children_in_household": table.get( + "children", pd.Series(0, index=table.index) + ) + .fillna(0) + .astype("int64"), + "source_year": np.full(count, 2024, dtype=np.int64), + "source_household_id": household_of, + "source_person_id": table["line"].astype(str).astype(object), + "LKWEEKS": lkweeks, + "unemployment_compensation": unemployment, + "weeks_unemployed": np.where(lkweeks == -1, 0, lkweeks).astype(np.float64), + "MCARE": mcare.astype(np.int64), + "takes_up_medicare_if_eligible": mcare == 1, + "WC_VAL": wc, + "workers_compensation": wc.copy(), + "OI_OFF": oi_off, + "OI_VAL": oi_val, + "alimony_income": np.where(oi_off == 20, oi_val, 0.0), + "strike_benefits": np.where(oi_off == 12, oi_val, 0.0), + "miscellaneous_income": np.where(np.isin(oi_off, (12, 20)), 0.0, oi_val), + "alimony_expense": alimony_expense, + "WSAL_VAL": wages, + "SEMP_VAL": self_employment, + "RETCB_VAL": retcb, + **contributions, + **dst_codes, + **dst_amounts, + **distributions, + US_SSI_TAKE_UP_ANCHOR: ssi, + "takes_up_wic_if_eligible": table.get( + "wic", pd.Series(False, index=table.index) + ) + .fillna(False) + .astype(bool), + } + ) + ids = np.asarray(household_ids, dtype=np.int64) + tables = { + "person": person, + "household": pd.DataFrame({"household_id": ids}), + "tax_unit": pd.DataFrame({"tax_unit_id": ids}), + "spm_unit": pd.DataFrame({"spm_unit_id": ids}), + "family": pd.DataFrame({"family_id": ids}), + "marital_unit": pd.DataFrame( + {"marital_unit_id": np.arange(1, marital_unit + 1, dtype=np.int64)} + ), + } + frame = Frame( + tables, + US_SCHEMA, + {"household": Weights(np.asarray(weights), WeightKind.DESIGN)}, + ) + return frame, positions + + +def _on_clones(person: pd.DataFrame, column: str, values: Mapping[int, float]) -> None: + """Write ``values`` (by native person id) on every clone row, in place.""" + + clone = person["person_support_clone_index"].to_numpy() > 0 + source = person["person_source_id"].to_numpy(dtype=np.int64) + for native_id, value in values.items(): + person.loc[clone & (source == native_id), column] = value + + +def reader_population(*, clone_defect: str | None = None) -> ReaderPopulation: + """An ASEC-only population for the whole-frame differential (d2283 X5). + + The native rows (:func:`_reader_native_frame`) carry every reader's raw + ASEC source columns and each producer's direct-source output. The + production operators then make Route A's labels, as X4's fixture does: + ``clone_us_frame_for_puf_support`` adds a PUF tax-detail copy (clone 1, + ``puf_tax_detail``) of every household on all six entities, writing + ``_source_id`` and halving the weights, and + ``with_capital_gains_tail_copies`` adds tail copies (clone 2) of three + households: a WIC infant's, a UC recipient's and a contributor's. + + Clone rows then take stand-ins for the PUF imputations where Route A's + gates do not reconcile clones against the source, so a reader whose + assembled mask wrongly took clone rows would show it: weeks positive + only where unemployment compensation is (the clones' UC rule), a + workers' compensation amount unlike ``WC_VAL`` and one with none, an + alimony amount unlike the ``OI_VAL`` split and one with none, every + contribution and distribution leaf scaled, and an ``SSI_VAL`` report on + a person whose native row has none. Medicare and WIC clones copy their + natives: Route A's Medicare gate reconciles every row against ``MCARE``, + and its WIC gate refuses a clone whose claim differs from its source + person's. + + The WIC gate keys clones by the source triple (``source_year``, + ``source_household_id``, ``source_person_id``) on Route A and by + ``person_source_id`` once assembled. The triple is unique per native + person and both columns are copied to every clone, so the two keys + partition the rows alike. + + Args: + clone_defect: A key of :data:`READER_CLONE_DEFECTS`, to change that + defect's one clone cell (d2283 lead call L7), or ``None``. + + Raises: + AssertionError: If any reader's gate fails on the Route A frame (or, + with ``clone_defect``, if the defect's reader does not fail with + exactly its one failure while every other reader passes), so a + differential never compares two gates failing for another + reason. + """ + + native, positions = _reader_native_frame() + cloned = clone_us_frame_for_puf_support(native) + household = cloned.table("household") + clone_one = household["household_support_clone_index"].to_numpy() == 1 + sources = household.loc[clone_one, "household_source_id"].to_numpy(dtype=np.int64) + native_person = native.table("person") + + def household_of(position: int) -> int: + return int(native_person["person_household_id"].iloc[position]) + + tail_sources = [ + household_of(positions["infant"][0]), + household_of(positions["worker"][0]), + household_of(positions["worker"][8]), + ] + if not set(tail_sources) <= set(sources.tolist()): + raise AssertionError("A tail source household has no PUF tax-detail copy.") + route_a = with_capital_gains_tail_copies(cloned, tail_sources) + + def native_id(group: str, index: int) -> int: + return int(native_person["person_id"].iloc[positions[group][index]]) + + tables = {entity: route_a.table(entity).copy() for entity in route_a.entities} + person = tables["person"] + clone = person["person_support_clone_index"].to_numpy() > 0 + uc = person["unemployment_compensation"].to_numpy(dtype=np.float64) + person.loc[clone, "weeks_unemployed"] = np.where(uc[clone] > 0.0, 10.0, 0.0) + _on_clones( + person, + "workers_compensation", + {native_id("worker", 6): 15_000.0, native_id("worker", 7): 3_000.0}, + ) + _on_clones( + person, + "alimony_income", + {native_id("single", 0): 7_500.0, native_id("single", 4): 2_000.0}, + ) + for column in ( + *US_RETIREMENT_CONTRIBUTION_OUTPUT_COLUMNS, + *US_RETIREMENT_DISTRIBUTION_OUTPUT_COLUMNS, + ): + factor = 1.2 if column in US_RETIREMENT_CONTRIBUTION_OUTPUT_COLUMNS else 0.9 + person.loc[clone, column] = person.loc[clone, column] * factor + clone_only_ssi = native_id("single", 6) + _on_clones(person, US_SSI_TAKE_UP_ANCHOR, {clone_only_ssi: 2_000.0}) + if clone_defect is not None: + (group, index), column, value = _CLONE_DEFECT_CELLS[clone_defect] + source = person["person_source_id"].to_numpy(dtype=np.int64) + rows = np.flatnonzero(clone & (source == native_id(group, index))) + if len(rows) != 1: + raise AssertionError( + f"The {clone_defect} defect needs one clone row; found {len(rows)}." + ) + person.loc[person.index[rows[0]], column] = value + route_a = Frame( + tables, + route_a.schema, + {entity: route_a.weights_for(entity) for entity in route_a.weighted_entities}, + route_a.strata, + mass_log=route_a.mass_log, + metadata=route_a.metadata, + ) + reporters = frozenset( + str(native_id(group, index)) for group, index in (("elder", 6), ("single", 5)) + ) + _check_reader_gates(route_a, reporters=reporters, clone_defect=clone_defect) + + empty_acs = { + entity: table.iloc[:0] + for entity, table in generate_population(0).acs_tables.items() + } + assembled = to_assembled_provenance( + tables, + empty_acs, + cps_household_weights=cps_household_weight_series( + route_a.table("household"), route_a.weights_for("household").values + ), + acs_household_weights={}, + staging_lineage={}, + ) + return ReaderPopulation( + route_a=route_a, + assembled=assembled, + reporters=reporters, + clone_only_ssi=str(clone_only_ssi), + ) + + +def _check_reader_gates( + frame: Frame, *, reporters: frozenset[str], clone_defect: str | None = None +) -> None: + expected: dict[str, list[str]] = {} + if clone_defect is not None: + defect_reader, failure = READER_CLONE_DEFECTS[clone_defect] + expected[defect_reader] = [failure] + failures: dict[str, object] = {} + for name, reader in READER_GATES.items(): + result = reader(frame) + if isinstance(result, frozenset): + if result != reporters: + failures[name] = sorted(result) + elif result.passed == (name in expected) or list(result.failures) != ( + expected.get(name, []) + ): + failures[name] = list(result.failures) + if failures: + raise AssertionError( + f"Route A reader gates fail on the reader frame: {failures} " + f"(expected failures: {expected})." + )