From 9a6893d645d6f13d105abae30453c4b825508620 Mon Sep 17 00:00:00 2001 From: Max Ghenis Date: Sat, 14 Nov 2026 19:52:52 -0500 Subject: [PATCH 1/3] Keep ACS partnership_income at zero where SEMP already holds it (#1387) ACS SEMP includes a respondent's own partnership income (2024 ACS Subject Definitions p. 94), and the form tells respondents to report jointly received income under one person (2024 questionnaire item 43). The ACS-local transfer still drew the PUF donor's nonpassive partnership_income onto those rows, so the release could count it twice. transfer_acs_inputs, acs_transfer_execution_contract_identity and build_optional_acs_multispine take a keyword-only semp_covers_partnership_income (default False). With it on, after adult care and before the passive reconciliation, newly drawn partnership_income (where the transfer did not draw self_employment_income_before_lsr) is set to 0.0 on: - rows with finite nonzero SEMP; - HEAD/SPOUSE rows of a tax unit whose HEAD/SPOUSE has finite nonzero SEMP; - rows with blank SEMP. s_corp_income is kept (ACS counts incorporated owners as wage workers). The rule refuses a plan with partnership_income but no s_corp_income; a recipient without SEMP, person_tax_unit_id or tax_unit_role_input, before any fit; and a tax-unit role outside HEAD/SPOUSE/DEPENDENT. The flag-on execution contract binds the rule. The partnership_income provenance record carries a per-set receipt: cells kept at zero, nonzero draws discarded, and the discarded draws in whole dollars, unweighted and household-weighted. acs_self_employment_identity_gate adds the matching clauses over selected ACS rows, a passive-without-line-32 clause on the person and tax-unit totals, infinite-value and malformed-role checks, and the columns they read. The gate is not behind the flag, so ACS-local staging and checkpoints built before this change must be rebuilt (changelog.d fragment; the release tool's refusal now says so). Only the legacy ACS base builder turns the flag on. Off the flag every contract payload and draw is unchanged. acs_transfer.py is an attested kernel module, so seed_map, seed_protocol, the US bundle spec_sha256 and the loader golden vector move; they are repinned with the five-step repin and each pin's comment names #1387. Co-Authored-By: Claude Opus 5.5 --- ...acs-semp-partnership-double-count.fixed.md | 1 + docs/evidence/spec-engine/us-f0-coverage.json | 16 +- .../build/spec_engine/inventory_coverage.py | 7 +- .../microcosm/build/us_runtime/acs_inputs.py | 118 ++- .../build/us_runtime/acs_multispine.py | 13 + .../build/us_runtime/acs_transfer.py | 316 +++++- .../shared/test_spec_engine_loader.py | 4 +- .../us/test_us_acs_block_location.py | 1 + .../us/test_us_acs_local_release_tool.py | 43 +- .../engine_free/us/test_us_acs_multispine.py | 6 + .../us/test_us_acs_multispine_base_builder.py | 11 + .../test_us_acs_multispine_legacy_builder.py | 12 + .../test_us_acs_self_employment_identity.py | 28 +- .../us/test_us_acs_semp_partnership.py | 938 ++++++++++++++++++ .../us/test_us_multispine_pool_tool.py | 4 +- tools/_legacy/build_us_acs_multispine_base.py | 4 +- tools/build_us_acs_local_release.py | 24 +- 17 files changed, 1518 insertions(+), 28 deletions(-) create mode 100644 changelog.d/1387-acs-semp-partnership-double-count.fixed.md create mode 100644 packages/microcosm-build/tests/engine_free/us/test_us_acs_semp_partnership.py diff --git a/changelog.d/1387-acs-semp-partnership-double-count.fixed.md b/changelog.d/1387-acs-semp-partnership-double-count.fixed.md new file mode 100644 index 0000000000..c79ac24ccd --- /dev/null +++ b/changelog.d/1387-acs-semp-partnership-double-count.fixed.md @@ -0,0 +1 @@ +The ACS local lane no longer counts a respondent's partnership income twice (microcosm#1387). ACS SEMP already includes income from one's own partnership, and the 2024 ACS form tells respondents to report jointly received income wholly under one person, yet the transfer drew the PUF donor's nonpassive `partnership_income` onto those rows. A new keyword-only `semp_covers_partnership_income` on `transfer_acs_inputs`, `acs_transfer_execution_contract_identity` and `build_optional_acs_multispine` (off by default; only the legacy ACS base builder turns it on) keeps a newly drawn `partnership_income` at zero on rows with a finite nonzero SEMP, on tax-unit heads and spouses whose head or spouse reports one, and on rows with blank SEMP, before the passive partnership/S-corp subset is reconciled to line 32. `s_corp_income` is kept: ACS counts incorporated owners as wage workers. The rule refuses a plan that transfers `partnership_income` without `s_corp_income`, a recipient without `SEMP`, `person_tax_unit_id` or `tax_unit_role_input` (before any fit), and a tax-unit role outside HEAD/SPOUSE/DEPENDENT. The partnership provenance record carries a receipt: per row set, the cells kept at zero, the nonzero draws discarded, and the discarded draws in whole dollars, unweighted and household-weighted. Off the flag every contract payload and draw is unchanged; the US spec-engine attestation pins move because `acs_transfer.py` is an attested kernel module. The `acs_self_employment_identity` gate now also requires `partnership_income` to be zero on those three row sets, the passive subset to be zero wherever the person's or tax unit's line 32 is zero, finite line-32 values and well-formed tax-unit roles, and it needs the line-32, tax-unit and role columns. The gate is not behind the flag, so ACS local staging and calibrated checkpoints built before this fix fail materialize, consumer export and package and must be rebuilt. diff --git a/docs/evidence/spec-engine/us-f0-coverage.json b/docs/evidence/spec-engine/us-f0-coverage.json index 3856451e3a..019061e72a 100644 --- a/docs/evidence/spec-engine/us-f0-coverage.json +++ b/docs/evidence/spec-engine/us-f0-coverage.json @@ -1642,13 +1642,13 @@ "compiler_ir.node_slices" ], "expected": { - "map_sha256": "270cf6498f8a2977993f969d0703be88fb930499dab42741a2111f57ffec4266", - "protocol_sha256": "a696ad74bfa5743b63c65499e6f5a41ea913a96ca38a5e3b9882069284bfca47" + "map_sha256": "dc4e5675d73adb4ac385a86e9f8bd4dafbd6cf3f7adffaf570fd27932bd5361b", + "protocol_sha256": "deaa56165bd46eb61b814abed73e9033d761db20a2aa4ea01337c43a5c76be69" }, "failures": [], "observed": { - "map_sha256": "270cf6498f8a2977993f969d0703be88fb930499dab42741a2111f57ffec4266", - "protocol_sha256": "a696ad74bfa5743b63c65499e6f5a41ea913a96ca38a5e3b9882069284bfca47" + "map_sha256": "dc4e5675d73adb4ac385a86e9f8bd4dafbd6cf3f7adffaf570fd27932bd5361b", + "protocol_sha256": "deaa56165bd46eb61b814abed73e9033d761db20a2aa4ea01337c43a5c76be69" }, "status": "covered" }, @@ -1663,7 +1663,7 @@ "compiler_ir.seed_stream_map" ], "expected": { - "implementation_sha256": "a696ad74bfa5743b63c65499e6f5a41ea913a96ca38a5e3b9882069284bfca47", + "implementation_sha256": "deaa56165bd46eb61b814abed73e9033d761db20a2aa4ea01337c43a5c76be69", "protocol": "legacy-v1", "streams": [ "build_model", @@ -1684,7 +1684,7 @@ }, "failures": [], "observed": { - "implementation_sha256": "a696ad74bfa5743b63c65499e6f5a41ea913a96ca38a5e3b9882069284bfca47", + "implementation_sha256": "deaa56165bd46eb61b814abed73e9033d761db20a2aa4ea01337c43a5c76be69", "protocol": "legacy-v1", "streams": [ "build_model", @@ -2585,7 +2585,7 @@ "country": "us", "schema_id": "country_spec", "schema_version": 1, - "spec_sha256": "bd526d8cf819e9f97fa46c5fe279c7b9ef4458b3e2d3498f823602f45e6a7575" + "spec_sha256": "3c21db4468d0c92f91cc03a21c8afa7dedf21863fa0cef0429238ee63d7d4896" } }, "report_schema_version": 3, @@ -2595,7 +2595,7 @@ "country": "us", "schema_id": "country_spec", "schema_version": 1, - "spec_sha256": "bd526d8cf819e9f97fa46c5fe279c7b9ef4458b3e2d3498f823602f45e6a7575" + "spec_sha256": "3c21db4468d0c92f91cc03a21c8afa7dedf21863fa0cef0429238ee63d7d4896" }, "status": "pass" } diff --git a/packages/microcosm-build/src/microcosm/build/spec_engine/inventory_coverage.py b/packages/microcosm-build/src/microcosm/build/spec_engine/inventory_coverage.py index 8121f4a3cb..ceab6cbfd2 100644 --- a/packages/microcosm-build/src/microcosm/build/spec_engine/inventory_coverage.py +++ b/packages/microcosm-build/src/microcosm/build/spec_engine/inventory_coverage.py @@ -389,8 +389,11 @@ # calibrate's shared option checks move both again; no US solve changes. # Its TANF ledger fix moves the protocol again: the site's recorded salt # becomes the takes_up_tanf_if_eligible its draw always used. - "seed_map": "270cf6498f8a2977993f969d0703be88fb930499dab42741a2111f57ffec4266", - "seed_protocol": "a696ad74bfa5743b63c65499e6f5a41ea913a96ca38a5e3b9882069284bfca47", + # microcosm#1387 moves both again: the ACS transfer's opt-in SEMP-covered + # partnership step changes acs_transfer's attested bytes. Off its flag no + # draw, RNG rule or QRF target changes. + "seed_map": "dc4e5675d73adb4ac385a86e9f8bd4dafbd6cf3f7adffaf570fd27932bd5361b", + "seed_protocol": "deaa56165bd46eb61b814abed73e9033d761db20a2aa4ea01337c43a5c76be69", "source_manifest": "dc3879886d2a69f20fb982a675d7fb322c0e4017afef6471be54b0ee3cbd2af6", "take_up": "9522ce40f7dea569312dd7a7beb474e5a5afadd2f1e10cb5876534c3ef623d35", "tail": "565f0ceeadab69d3e96a886a00dd0305f7425fa3acde24d12ba48db2b37d5fc0", diff --git a/packages/microcosm-build/src/microcosm/build/us_runtime/acs_inputs.py b/packages/microcosm-build/src/microcosm/build/us_runtime/acs_inputs.py index 238e865afd..59a7cb6824 100644 --- a/packages/microcosm-build/src/microcosm/build/us_runtime/acs_inputs.py +++ b/packages/microcosm-build/src/microcosm/build/us_runtime/acs_inputs.py @@ -24,6 +24,8 @@ ) from microcosm.build.us_runtime.acs_transfer import ( ACS_SELF_EMPLOYMENT_COMPONENT_INPUTS, + ACS_TAX_UNIT_ROLES, + acs_tax_unit_head_or_spouse, ) from microcosm.build.us_runtime.spm_role_source import ( NATIVE_SPM_ROLE, @@ -671,6 +673,16 @@ def without_acs_group_quarters_children( for column in ACS_SELF_EMPLOYMENT_COMPONENT_INPUTS if column not in _SEMP_ROUTED_LEAVES ) +#: microcosm#1387: the line-32 leaves and the passive subset the gate grades, +#: and the tax-unit columns its spouse clause reads. ACS SEMP includes +#: own-partnership income but not S-corp profit, so only partnership_income +#: must be zero where SEMP accounts for it. +_PARTNERSHIP = "partnership_income" +_S_CORP = "s_corp_income" +_PASSIVE = "passive_partnership_s_corp_income" +_TAX_UNIT = "person_tax_unit_id" +_TAX_UNIT_ROLE = "tax_unit_role_input" +_LINE_32_GATE_COLUMNS = (_PARTNERSHIP, _S_CORP, _PASSIVE, _TAX_UNIT, _TAX_UNIT_ROLE) def acs_self_employment_identity_gate( @@ -695,6 +707,19 @@ def acs_self_employment_identity_gate( or infinite leaf or ``ADJINC`` on a row that reports SEMP fails, because the identity cannot be checked there, and so does an infinite SEMP, which is not a blank. + + The gate also grades the line-32 leaves (microcosm#1387). ACS SEMP + includes own-partnership income, so ``partnership_income`` must be + exactly zero on a row that reports a finite nonzero SEMP, on a tax-unit + HEAD or SPOUSE row when a HEAD or SPOUSE of the same tax unit reports one + (the form puts jointly received income under one person), and on a row + with blank SEMP. ``s_corp_income`` is not constrained: ACS counts + incorporated owners as wage workers. The passive subset must be zero + wherever the person's or the tax unit's line 32 (partnership plus S-corp + income) is zero, and an infinite line-32 or passive value fails. A + tax-unit role outside HEAD/SPOUSE/DEPENDENT, or a missing role on a row + with a tax unit, fails rather than exempting its unit. Every column the + gate reads must be present; none is read as zero. """ name = "acs_self_employment_identity" @@ -703,7 +728,12 @@ def acs_self_employment_identity_gate( raise ValueError("rows must be a one-dimensional mask aligned to person.") missing = [ column - for column in ("SEMP", "ADJINC", *_SELF_EMPLOYMENT_LEAVES) + for column in ( + "SEMP", + "ADJINC", + *_SELF_EMPLOYMENT_LEAVES, + *_LINE_32_GATE_COLUMNS, + ) if column not in person.columns ] if missing: @@ -749,6 +779,44 @@ def numeric(column: str) -> np.ndarray: [filled[:, position[column]] != 0.0 for column in _SEMP_ROUTED_LEAVES] ).all(axis=1) + # microcosm#1387: partnership income that SEMP already accounts for. + partnership = numeric(_PARTNERSHIP) + s_corp = numeric(_S_CORP) + passive = numeric(_PASSIVE) + partnership_zero = np.isfinite(partnership) & (partnership == 0.0) + own_semp = np.isfinite(semp) & (semp != 0.0) + units = subset[_TAX_UNIT] + head_or_spouse, malformed_role = acs_tax_unit_head_or_spouse( + subset[_TAX_UNIT_ROLE], units + ) + unit_reports = ( + pd.Series(own_semp & head_or_spouse, index=subset.index) + .groupby(units, sort=False) + .transform("any") + .astype("boolean") + .fillna(False) + .to_numpy(dtype=bool) + ) + partnership_on_semp = own_semp & ~partnership_zero + partnership_on_spouse = ( + head_or_spouse & unit_reports & ~own_semp & ~blank_semp & ~partnership_zero + ) + partnership_on_blank = blank_semp & ~partnership_zero + line_32_values = np.column_stack([partnership, s_corp, passive]) + infinite_line_32 = np.isinf(line_32_values).any(axis=1) + person_line_32 = pd.Series( + np.where(np.isnan(partnership), 0.0, partnership) + + np.where(np.isnan(s_corp), 0.0, s_corp), + index=subset.index, + ) + unit_line_32 = person_line_32.groupby(units, sort=False).transform("sum") + no_line_32 = (person_line_32 == 0.0).to_numpy() | (unit_line_32 == 0.0).to_numpy( + dtype=bool, na_value=False + ) + passive_without_line_32 = no_line_32 & ( + np.where(np.isnan(passive), 0.0, passive) != 0.0 + ) + failures: list[str] = [] if not selected.any(): failures.append("No ACS person rows were selected for the check.") @@ -777,6 +845,42 @@ def numeric(column: str) -> np.ndarray: "carry both base and SSTB self-employment; QBI reconciliation " "routes SEMP wholly to one of them." ) + if partnership_on_semp.any(): + failures.append( + f"{int(partnership_on_semp.sum())} ACS person row(s) reporting a " + "nonzero SEMP carry partnership_income that is not exactly zero; " + "ACS SEMP already includes own-partnership income." + ) + if partnership_on_spouse.any(): + failures.append( + f"{int(partnership_on_spouse.sum())} ACS tax-unit head or spouse " + "row(s) carry partnership_income that is not exactly zero while " + "their tax unit's head or spouse reports a nonzero SEMP, which " + "may hold the couple's jointly received partnership income." + ) + if partnership_on_blank.any(): + failures.append( + f"{int(partnership_on_blank.sum())} ACS person row(s) with blank " + "SEMP carry partnership_income that is not exactly zero." + ) + if passive_without_line_32.any(): + failures.append( + f"{int(passive_without_line_32.sum())} ACS person row(s) carry " + "passive_partnership_s_corp_income where the person's or the tax " + "unit's partnership plus S-corp income is zero." + ) + if malformed_role.any(): + failures.append( + f"{int(malformed_role.sum())} ACS person row(s) have a " + f"tax_unit_role_input outside {list(ACS_TAX_UNIT_ROLES)}, or none " + "while in a tax unit, so their tax unit's partnership check " + "cannot run." + ) + if infinite_line_32.any(): + failures.append( + f"{int(infinite_line_32.sum())} ACS person row(s) have an infinite " + "partnership, S-corp or passive partnership/S-corp income." + ) if infinite_semp.any(): failures.append( f"{int(infinite_semp.sum())} ACS person row(s) have an infinite SEMP." @@ -809,6 +913,18 @@ def numeric(column: str) -> np.ndarray: "infinite_semp_rows": int(infinite_semp.sum()), "nonfinite_leaf_rows": int(nonfinite_leaf.sum()), "nonfinite_adjinc_rows": int(nonfinite_adjinc.sum()), + "partnership_on_semp_rows": int(partnership_on_semp.sum()), + "partnership_on_positive_semp_rows": int( + (partnership_on_semp & (semp > 0.0)).sum() + ), + "partnership_on_negative_semp_rows": int( + (partnership_on_semp & (semp < 0.0)).sum() + ), + "partnership_on_spouse_rows": int(partnership_on_spouse.sum()), + "partnership_on_blank_semp_rows": int(partnership_on_blank.sum()), + "passive_without_line_32_rows": int(passive_without_line_32.sum()), + "infinite_line_32_rows": int(infinite_line_32.sum()), + "malformed_tax_unit_role_rows": int(malformed_role.sum()), "nonzero_rows_by_leaf": { column: int((filled[:, index] != 0.0).sum()) for index, column in enumerate(_SELF_EMPLOYMENT_LEAVES) diff --git a/packages/microcosm-build/src/microcosm/build/us_runtime/acs_multispine.py b/packages/microcosm-build/src/microcosm/build/us_runtime/acs_multispine.py index df325fb301..5bae4819e1 100644 --- a/packages/microcosm-build/src/microcosm/build/us_runtime/acs_multispine.py +++ b/packages/microcosm-build/src/microcosm/build/us_runtime/acs_multispine.py @@ -121,6 +121,7 @@ def build_optional_acs_multispine( work_disability_inputs: bool = False, income_transfer: bool = False, native_receipt_anchors: bool = False, + semp_covers_partnership_income: bool = False, donor_spine: str = ASEC_PUF_DONOR_SPINE, donor_channel: str | None = ACS_DONOR_CHANNEL_AUTO, seed: int = 0, @@ -164,6 +165,13 @@ def build_optional_acs_multispine( public-assistance counts it records against ``receives_tanf``) is ``provenance["acs_local_receipt_anchors"]``. The source is checked before any fit. + ``semp_covers_partnership_income`` (the ACS local lane, microcosm#1387) + tells the shared transfer that ACS ``SEMP`` already includes + own-partnership income, so a ``partnership_income`` draw is kept at zero + where the row's or its tax unit's SEMP accounts for it (see + :func:`~microcosm.build.us_runtime.acs_transfer.keep_semp_covered_partnership_income`). + Only the shared call receives it; the hours and income passes do not + draw ``partnership_income``. Large intermediate frames are released as soon as the next stage has materialized its own frame. This cannot make the final dense pool small, @@ -363,6 +371,11 @@ def build_optional_acs_multispine( seed=seed, n_estimators=n_estimators, max_targets_per_fit=max_targets_per_fit, + **( + {"semp_covers_partnership_income": True} + if semp_covers_partnership_income + else {} + ), ) del mapped_frame adult_care_gate = _require_recipient_adult_care_structure(transferred.frame) diff --git a/packages/microcosm-build/src/microcosm/build/us_runtime/acs_transfer.py b/packages/microcosm-build/src/microcosm/build/us_runtime/acs_transfer.py index 0706cf02ec..4a464141a4 100644 --- a/packages/microcosm-build/src/microcosm/build/us_runtime/acs_transfer.py +++ b/packages/microcosm-build/src/microcosm/build/us_runtime/acs_transfer.py @@ -59,6 +59,7 @@ "ACS_OPTIONAL_PERSON_TRANSFER_PREDICTORS", "ACS_PERSON_TRANSFER_PREDICTORS", "ACS_SELF_EMPLOYMENT_COMPONENT_INPUTS", + "ACS_SEMP_COVERED_LINE_32_INPUTS", "ASEC_PUF_DONOR_SPINE", "AcsImputedInput", "AcsPersonPredictorExtension", @@ -71,15 +72,19 @@ "acs_transfer_donor_requirements", "acs_transfer_execution_contract_identity", "acs_adult_care_qualifying_rows", + "acs_tax_unit_head_or_spouse", "assert_acs_transfer_targets_are_input_leaves", "declared_acs_transfer_target_families", "default_acs_transfer_target_families", "ACS_DERIVED_TRANSFER_INPUTS", + "ACS_TAX_UNIT_ROLES", "derive_acs_schedule_d_capital_gain_distributions", "keep_measured_self_employment_totals", + "keep_semp_covered_partnership_income", "reconcile_acs_adult_care", "required_acs_transfer_inputs", "resolve_acs_donor_channel", + "semp_covered_partnership_cells", "transfer_acs_inputs", ] @@ -415,13 +420,15 @@ def acs_transfer_execution_contract_identity( targets: Sequence[str] | None = None, derive_schedule_d: bool = True, person_predictor_extensions: Sequence[AcsPersonPredictorExtension] | None = None, + semp_covers_partnership_income: bool = False, ) -> dict[str, object]: """Bind the complete runtime predictor and target-codec contract. ``person_predictor_extensions`` enters the payload only when it is non-empty, so every caller that uses none (the shared plan, the pool lane, banked checkpoints and the spec projection) keeps the same payload and - SHA-256. + SHA-256. ``semp_covers_partnership_income`` (the ACS local lane, + microcosm#1387) likewise enters only when True. """ extensions = _normalize_person_predictor_extensions(person_predictor_extensions) @@ -509,6 +516,26 @@ def acs_transfer_execution_contract_identity( payload["person_predictor_extensions"] = [ extension.identity() for extension in extensions ] + if semp_covers_partnership_income: + # Opt-in only: the key is absent, not False, when the lane is off, so + # every national and default digest stays the same. + post_transfer = payload["post_transfer_structure"] + assert isinstance(post_transfer, dict) + post_transfer["semp_covered_partnership_income"] = { + "enabled": _SEMP_COVERED_PARTNERSHIP in requested_targets, + "covered": list(ACS_SEMP_COVERED_LINE_32_INPUTS), + "measured_column": _ACS_SEMP, + "tax_unit_link": _ADULT_CARE_UNIT, + "tax_unit_role": _ADULT_CARE_ROLE, + "rows": [ + "own_semp_finite_nonzero", + "head_or_spouse_of_unit_with_head_or_spouse_semp_finite_nonzero", + "semp_blank", + ], + "operation": "set_to_zero", + "order": "before_passive_partnership_s_corp", + "mutable_rows": ("newly_imputed_cells_where_recipient_total_not_imputed"), + } payload["sha256"] = hashlib.sha256( json.dumps( payload, @@ -845,6 +872,86 @@ def acs_derived_transfer_expectations( _LINE_32_COMPONENTS = ("partnership_income", "s_corp_income") _ADULT_CARE_ROLE = "tax_unit_role_input" _ADULT_CARE_UNIT = "person_tax_unit_id" +# microcosm#1387: the raw ACS self-employment column, and the one line-32 leaf +# it already contains. ACS SEMP includes own-partnership income (2024 ACS +# Subject Definitions p. 94) and excludes incorporated-business profit, whose +# owners ACS counts as wage workers (p. 65), so s_corp_income is not covered. +_ACS_SEMP = "SEMP" +_SEMP_COVERED_PARTNERSHIP = "partnership_income" +ACS_SEMP_COVERED_LINE_32_INPUTS: tuple[str, ...] = (_SEMP_COVERED_PARTNERSHIP,) +_SEMP_COVERED_REQUIRED = (_ACS_SEMP, _ADULT_CARE_UNIT, _ADULT_CARE_ROLE) +#: The tax-unit roles microunit emits (microcosm-frame units.py). +ACS_TAX_UNIT_ROLES: tuple[str, ...] = ("HEAD", "SPOUSE", "DEPENDENT") + + +def acs_tax_unit_head_or_spouse( + roles: pd.Series, + units: pd.Series, +) -> tuple[np.ndarray, np.ndarray]: + """Return ``(head_or_spouse, malformed)`` masks for tax-unit roles. + + Bytes decode and case folds to upper, as the PUF tax-unit demographics + read roles. ``malformed`` marks a role outside HEAD/SPOUSE/DEPENDENT and a + missing role on a row that has a tax unit. The SEMP-covered partnership + rule and its gate refuse those rows rather than read them as neither head + nor spouse, which would skip their tax unit silently (microcosm#1387). + """ + + decoded = ( + roles.map(lambda value: value.decode() if isinstance(value, bytes) else value) + .astype("object") + .astype("string") + .str.upper() + ) + present = decoded.notna().to_numpy(dtype=bool) + known = decoded.isin(ACS_TAX_UNIT_ROLES).to_numpy(dtype=bool, na_value=False) + has_unit = units.notna().to_numpy(dtype=bool) + head_or_spouse = decoded.isin(("HEAD", "SPOUSE")).to_numpy( + dtype=bool, na_value=False + ) + malformed = (present & ~known) | (~present & has_unit) + return head_or_spouse, malformed + + +def _require_semp_covered_columns(columns: Sequence[str]) -> None: + missing = [column for column in _SEMP_COVERED_REQUIRED if column not in columns] + if missing: + raise ValueError( + "The SEMP-covered partnership rule needs person column(s) " + f"{missing}; refusing to treat them as zero." + ) + + +def _acs_person_design_weights(recipient: Frame) -> np.ndarray | None: + """Return each person's household design weight, or None without one. + + PolicyEngine weights a person by their household, so the SEMP-covered + partnership receipt sums discarded draws with these weights. A frame + without household weights, ids or a unique weight per household gives + None, and the receipt then carries unweighted sums only. + """ + + if "household" not in recipient.weighted_entities: + return None + person = recipient.table(recipient.schema.person_entity) + household = recipient.table("household") + if ( + "household_id" not in household.columns + or "person_household_id" not in person.columns + ): + return None + by_household = pd.Series( + np.asarray(recipient.weights_for("household").values, dtype=np.float64), + index=household["household_id"].to_numpy(), + ) + if not by_household.index.is_unique: + return None + weights = ( + pd.Series(person["person_household_id"].to_numpy()) + .map(by_household) + .to_numpy(dtype=np.float64, na_value=np.nan) + ) + return None if np.isnan(weights).any() else weights def derive_acs_schedule_d_capital_gain_distributions( @@ -1534,6 +1641,7 @@ def transfer_acs_inputs( execution_contract: Mapping[str, object] | None = None, regime_evidence_targets: Iterable[tuple[str, str]] = (), person_predictor_extensions: Sequence[AcsPersonPredictorExtension] | None = None, + semp_covers_partnership_income: bool = False, ) -> AcsTransferResult: """Impute requested missing leaves from ``donor`` onto ``recipient``. @@ -1575,6 +1683,21 @@ def transfer_acs_inputs( family, on a family outside the plan, on a feature name that clashes with a shared predictor or another extension, when the donor lacks a component and when the recipient lacks the source column. + + ``semp_covers_partnership_income`` (the ACS local lane, microcosm#1387) + declares that the recipient's raw ``SEMP`` already includes + own-partnership income. A ``partnership_income`` draw is then kept at zero + on the rows :func:`semp_covered_partnership_cells` names, before the + passive subset is reconciled to line 32. A plan that draws + ``partnership_income`` without ``s_corp_income`` is refused, because the + rule covers only the partnership leaf; that guard reads the plan, so a + caller whose donor might carry the combined column in + ``partnership_income`` with an all-zero ``s_corp_income`` must refuse + that donor itself (the legacy builder's dense-donor gate does). A + recipient without ``SEMP``, ``person_tax_unit_id`` or + ``tax_unit_role_input`` is refused before any fit when + ``partnership_income`` has cells to draw. Off by default: every other + caller keeps its draws and execution-contract SHA-256. """ _validate_frames(recipient, donor) @@ -1625,10 +1748,22 @@ def transfer_acs_inputs( all_targets = [ target for _entity, _family, targets in requested for target in targets ] + if ( + semp_covers_partnership_income + and _SEMP_COVERED_PARTNERSHIP in all_targets + and not set(_LINE_32_COMPONENTS) <= set(all_targets) + ): + raise ValueError( + "The SEMP-covered partnership rule needs a plan that transfers " + "partnership_income and s_corp_income as separate leaves; this " + "plan transfers partnership_income without s_corp_income, so a " + "combined partnership and S-corp column could be zeroed whole." + ) resolved_execution_contract = acs_transfer_execution_contract_identity( targets=all_targets, derive_schedule_d=derive_schedule_d, person_predictor_extensions=extensions, + semp_covers_partnership_income=semp_covers_partnership_income, ) if execution_contract is not None and dict(execution_contract) != ( resolved_execution_contract @@ -1639,6 +1774,15 @@ def transfer_acs_inputs( assert_acs_transfer_targets_are_input_leaves(all_targets) active = _missing_target_families(requested, recipient=recipient) + if semp_covers_partnership_income and any( + entity == "person" and _SEMP_COVERED_PARTNERSHIP in targets + for entity, _family, targets in active + ): + # Before any fit: partnership_income has cells to draw, so the rule + # will need these columns. + _require_semp_covered_columns( + recipient.table(recipient.schema.person_entity).columns + ) if selected_regime_evidence: requested_families = { (entity, family): targets for entity, family, targets in requested @@ -1901,6 +2045,11 @@ def transfer_acs_inputs( donor_spine=donor_spine, resolved_channel=resolved_channel, execution_contract=resolved_execution_contract, + person_weights=( + _acs_person_design_weights(recipient) + if semp_covers_partnership_income + else None + ), ) tables: dict[str, pd.DataFrame] = dict(output_tables) @@ -1938,6 +2087,7 @@ def _apply_post_transfer_structure( donor_spine: str, resolved_channel: str | None, execution_contract: Mapping[str, object], + person_weights: np.ndarray | None = None, ) -> None: """Apply the deterministic post-fit steps the base's construction implies. @@ -1948,6 +2098,9 @@ def _apply_post_transfer_structure( capital-gain parents at the packaged share with route exclusivity. - The adult-care expense surface is reconciled to the statute structure (qualifying carriers only, at most one per tax unit). + - On the ACS local lane only, partnership_income draws that the row's or + its tax unit's SEMP already accounts for are kept at zero (see + :func:`keep_semp_covered_partnership_income`, microcosm#1387). - The passive partnership/S-corp subset is zeroed where it has no line-32 total under it (microcosm#1239). - Self-employment components drawn onto rows whose self-employment total @@ -2064,6 +2217,21 @@ def _apply_post_transfer_structure( provenance[index] = replace(item, reconciliation=counts) break + # microcosm#1387: before the passive block, so a partnership draw this + # step zeroes also clears the passive subset that rested on it. + semp_contract = post_transfer_contract.get("semp_covered_partnership_income") + if isinstance(semp_contract, Mapping) and semp_contract["enabled"] is True: + semp_counts = keep_semp_covered_partnership_income( + person, + imputed_masks=imputed_masks, + person_weights=person_weights, + ) + if semp_counts is not None: + for index, item in enumerate(provenance): + if item.column == _SEMP_COVERED_PARTNERSHIP and item.entity == "person": + provenance[index] = replace(item, reconciliation=semp_counts) + break + passive_contract = post_transfer_contract.get("passive_partnership_s_corp") passive_mask = imputed_masks.get(("person", _PASSIVE_PARTNERSHIP_S_CORP)) if ( @@ -2141,6 +2309,152 @@ def keep_measured_self_employment_totals( return counts +def semp_covered_partnership_cells(person: pd.DataFrame) -> dict[str, np.ndarray]: + """Return the person rows whose ACS SEMP already accounts for partnership income. + + ACS SEMP includes own-partnership income (2024 ACS Subject Definitions + p. 94) but not incorporated-business profit (p. 65), so these masks cover + ``partnership_income`` and never ``s_corp_income``. Three row sets, each + reported separately so a build can measure it: + + - ``own_semp``: the row's raw ``SEMP`` is finite and nonzero. + - ``tax_unit``: the row is a tax-unit HEAD or SPOUSE whose own ``SEMP`` is + not finite and nonzero, and a HEAD or SPOUSE row of the same + ``person_tax_unit_id`` has finite nonzero ``SEMP``. The 2024 form tells + respondents to report jointly received income wholly under one person + (questionnaire item 43), so a spouse's zero there is not a measurement. + - ``blank_semp``: ``SEMP`` is blank, which places the row outside the ACS + income universe (under 15). + + The masks are disjoint. A missing ``SEMP``, ``person_tax_unit_id`` or + ``tax_unit_role_input`` column raises ``ValueError``: none is read as zero. + So does a role outside HEAD/SPOUSE/DEPENDENT, or a missing role on a row + with a tax unit (:func:`acs_tax_unit_head_or_spouse`). + """ + + _require_semp_covered_columns(person.columns) + semp = pd.to_numeric(person[_ACS_SEMP], errors="coerce").to_numpy( + dtype=np.float64, na_value=np.nan + ) + own = np.isfinite(semp) & (semp != 0.0) + blank = np.isnan(semp) + head_or_spouse, malformed = acs_tax_unit_head_or_spouse( + person[_ADULT_CARE_ROLE], person[_ADULT_CARE_UNIT] + ) + if malformed.any(): + examples = sorted( + {str(value) for value in person[_ADULT_CARE_ROLE].to_numpy()[malformed]} + )[:5] + raise ValueError( + "The SEMP-covered partnership rule found " + f"{int(malformed.sum())} person row(s) whose tax_unit_role_input is " + f"not one of {list(ACS_TAX_UNIT_ROLES)} (examples {examples}); " + "refusing to read them as neither head nor spouse." + ) + reporter = pd.Series(own & head_or_spouse, index=person.index) + # A row without a tax unit has no spouse to extend from. + unit_reports = ( + reporter.groupby(person[_ADULT_CARE_UNIT], sort=False) + .transform("any") + .astype("boolean") + .fillna(False) + .to_numpy(dtype=bool) + ) + return { + "own_semp": own, + "tax_unit": head_or_spouse & unit_reports & ~own & ~blank, + "blank_semp": blank, + } + + +def keep_semp_covered_partnership_income( + person: pd.DataFrame, + *, + imputed_masks: Mapping[tuple[str, str], np.ndarray], + person_weights: np.ndarray | None = None, +) -> dict[str, int] | None: + """Zero partnership_income draws that ACS SEMP already accounts for. + + A ``partnership_income`` cell this transfer filled is set to zero on the + rows of :func:`semp_covered_partnership_cells`, unless the same transfer + also drew the row's ``self_employment_income_before_lsr`` (then the row's + self-employment is a draw, not its own SEMP; the declared plan never + draws it, because it is ACS-native). Every other cell and column, + ``s_corp_income`` included, keeps its value. ``person`` is updated in + place. + + Returns the receipt, or ``None`` when the transfer drew no + ``partnership_income`` cell. Per row set it counts the cells kept at zero + and the nonzero draws discarded, and sums the discarded draws' positive + and negative parts in whole dollars, unweighted and, when + ``person_weights`` is given, weighted by them. The discarded draws never + reach the output, so these sums are the only measure of what the rule + removed. + """ + + drawn = imputed_masks.get(("person", _SEMP_COVERED_PARTNERSHIP)) + if drawn is None or _SEMP_COVERED_PARTNERSHIP not in person.columns: + return None + drawn = np.asarray(drawn, dtype=bool) + total_drawn = np.asarray( + imputed_masks.get( + ("person", _SELF_EMPLOYMENT_TOTAL), np.zeros(len(person), bool) + ), + dtype=bool, + ) + if drawn.shape != (len(person),) or total_drawn.shape != (len(person),): + raise ValueError("imputed masks must be aligned to person.") + if person_weights is not None: + person_weights = np.asarray(person_weights, dtype=np.float64) + if person_weights.shape != (len(person),): + raise ValueError("person_weights must be aligned to person.") + if not drawn.any(): + return None + mutable = drawn & ~total_drawn + cells = semp_covered_partnership_cells(person) + semp = pd.to_numeric(person[_ACS_SEMP], errors="coerce").to_numpy( + dtype=np.float64, na_value=np.nan + ) + values = pd.to_numeric(person[_SEMP_COVERED_PARTNERSHIP], errors="coerce").to_numpy( + dtype=np.float64, na_value=np.nan + ) + nonzero = np.isfinite(values) & (values != 0.0) + positive = np.where(nonzero & (values > 0.0), values, 0.0) + negative = np.where(nonzero & (values < 0.0), values, 0.0) + + def dollars(prefix: str, rows: np.ndarray, into: dict[str, int]) -> None: + into[f"{prefix}discarded_positive_dollars"] = int( + np.round(positive[rows].sum()) + ) + into[f"{prefix}discarded_negative_dollars"] = int( + np.round(negative[rows].sum()) + ) + if person_weights is not None: + into[f"{prefix}household_weighted_discarded_positive_dollars"] = int( + np.round((positive[rows] * person_weights[rows]).sum()) + ) + into[f"{prefix}household_weighted_discarded_negative_dollars"] = int( + np.round((negative[rows] * person_weights[rows]).sum()) + ) + + covered = np.zeros(len(person), dtype=bool) + counts: dict[str, int] = {} + for name, rows in cells.items(): + cleared = mutable & rows + covered |= cleared + counts[f"{name}_cells"] = int(cleared.sum()) + counts[f"{name}_nonzero_draws_discarded"] = int((cleared & nonzero).sum()) + dollars(f"{name}_", cleared, counts) + own = mutable & cells["own_semp"] + counts["own_semp_positive_cells"] = int((own & (semp > 0.0)).sum()) + counts["own_semp_negative_cells"] = int((own & (semp < 0.0)).sum()) + counts["cells_kept_at_zero"] = int(covered.sum()) + counts["nonzero_draws_discarded"] = int((covered & nonzero).sum()) + dollars("", covered, counts) + person.loc[covered, _SEMP_COVERED_PARTNERSHIP] = 0.0 + return counts + + def _model_target_names(targets: Sequence[str]) -> tuple[str, ...]: """Return the exact chained-QRF target order for exported leaves.""" diff --git a/packages/microcosm-build/tests/engine_free/shared/test_spec_engine_loader.py b/packages/microcosm-build/tests/engine_free/shared/test_spec_engine_loader.py index 3228fa1517..538981c4c3 100644 --- a/packages/microcosm-build/tests/engine_free/shared/test_spec_engine_loader.py +++ b/packages/microcosm-build/tests/engine_free/shared/test_spec_engine_loader.py @@ -25,8 +25,10 @@ def test_semantic_hash_has_golden_vector_and_surface_separation(tmp_path) -> Non # ssi_disability_criteria's attested bytes. # The opt-in cross-fitted gate calibration moves the fit kernels' bytes. # The hierarchy value ranks move medicaid_take_up's attested bytes. + # microcosm#1387's SEMP-covered partnership step moves acs_transfer's + # attested bytes. assert first.spec_sha256 == ( - "1ff3b42c42250c734fdf1b5cf4c03e28a582ee5b448e2a8363c77a59a3932bdc" + "bf67d5d913958b6b7c7ba81ca6c59fd208ea09f8f9ac9209f2b65218eb4cf09a" ) second_root = _rich_minimal(tmp_path / "xy", note="second", store="local:b") diff --git a/packages/microcosm-build/tests/engine_free/us/test_us_acs_block_location.py b/packages/microcosm-build/tests/engine_free/us/test_us_acs_block_location.py index da8571e4e7..901a878f31 100644 --- a/packages/microcosm-build/tests/engine_free/us/test_us_acs_block_location.py +++ b/packages/microcosm-build/tests/engine_free/us/test_us_acs_block_location.py @@ -990,6 +990,7 @@ def test__legacy_tool__block_v1_main_records_rule_seed_gate_and_attributes( "location_seed": 5, "location_clones": 1, "donor_location_rule": "block_v1", + "semp_covers_partnership_income": True, } location = summary["household_location"] diff --git a/packages/microcosm-build/tests/engine_free/us/test_us_acs_local_release_tool.py b/packages/microcosm-build/tests/engine_free/us/test_us_acs_local_release_tool.py index 1abf078c76..b50a4293b1 100644 --- a/packages/microcosm-build/tests/engine_free/us/test_us_acs_local_release_tool.py +++ b/packages/microcosm-build/tests/engine_free/us/test_us_acs_local_release_tool.py @@ -74,6 +74,10 @@ "sstb_self_employment_income_before_lsr", "farm_operations_income", "partnership_self_employment_net_earnings", + # microcosm#1387: the line-32 leaves the self-employment gate reads. + "partnership_income", + "s_corp_income", + "passive_partnership_s_corp_income", *US_ORG_OCCUPATION_AND_WORK_EXPERIENCE_OUTPUT_COLUMNS, } ), @@ -1273,7 +1277,9 @@ def table(self, entity: str) -> pd.DataFrame: return self._person -def _self_employment_person(sstb_on_acs: float) -> pd.DataFrame: +def _self_employment_person( + sstb_on_acs: float, partnership_on_acs_semp: float = 0.0 +) -> pd.DataFrame: return pd.DataFrame( { "person_spine": ["acs_2024_1yr", "acs_2024_1yr", "asec_puf"], @@ -1283,6 +1289,13 @@ def _self_employment_person(sstb_on_acs: float) -> pd.DataFrame: "sstb_self_employment_income_before_lsr": [sstb_on_acs, 0.0, 9_000.0], "farm_operations_income": [0.0, 0.0, 700.0], "partnership_self_employment_net_earnings": [0.0, 0.0, 300.0], + # microcosm#1387: the ASEC row's partnership income is outside + # the ACS selection, so it never affects the verdict. + "partnership_income": [2_000.0, partnership_on_acs_semp, 4_000.0], + "s_corp_income": [0.0, 3_000.0, 0.0], + "passive_partnership_s_corp_income": [0.0, 0.0, 0.0], + "person_tax_unit_id": [1, 2, 3], + "tax_unit_role_input": ["HEAD", "HEAD", "HEAD"], } ) @@ -1305,6 +1318,23 @@ def test_release_refuses_staging_that_stacks_self_employment_on_semp() -> None: ) +def test_release_refuses_partnership_income_that_semp_already_holds() -> None: + """An ACS row's SEMP includes its partnership income (microcosm#1387). + + A partnership draw on the ACS row that reports SEMP is refused; the same + amount on the ASEC row, and S-corp income on the ACS row, pass. + """ + + module = _load_tool_module() + + with pytest.raises(SystemExit, match="ACS SEMP already includes"): + module._require_acs_self_employment_identity( + _SelfEmploymentFrame( + _self_employment_person(0.0, partnership_on_acs_semp=2_500.0) + ) + ) + + def test_release_checks_self_employment_wherever_it_loads_staging() -> None: module = _load_tool_module() @@ -4016,6 +4046,11 @@ def _plausible_hours_frame(): sstb_self_employment_income_before_lsr=0.0, farm_operations_income=0.0, partnership_self_employment_net_earnings=0.0, + # microcosm#1387: the line-32 leaves the gate also grades. + partnership_income=0.0, + s_corp_income=0.0, + passive_partnership_s_corp_income=0.0, + tax_unit_role_input="HEAD", ) return Frame( { @@ -5543,8 +5578,10 @@ def test_package_records_the_stored_input_gate_bound_to_the_packaged_bytes( "failures": [], "engine": "policyengine-us 2.2.1", "register_sha256": stored_inputs.register_sha256(), - # The ACS rows' base-spine tag, a reviewed register entry. - "registered_non_variables": ["person_spine"], + # The ACS rows' base-spine tag and the tax-unit role the + # self-employment gate reads (microcosm#1387), both reviewed + # register entries. + "registered_non_variables": ["person_spine", "tax_unit_role_input"], "artifact_sha256": result["root_artifact"]["sha256"], "checked_at_stage": "package", } diff --git a/packages/microcosm-build/tests/engine_free/us/test_us_acs_multispine.py b/packages/microcosm-build/tests/engine_free/us/test_us_acs_multispine.py index c80318d9af..caeb1c53d6 100644 --- a/packages/microcosm-build/tests/engine_free/us/test_us_acs_multispine.py +++ b/packages/microcosm-build/tests/engine_free/us/test_us_acs_multispine.py @@ -88,9 +88,13 @@ def test_json_ready_omits_empty_opt_in_transfer_pattern_regimes() -> None: assert selected["target_regimes"] == [["fixture_target", "positive_only"]] +# microcosm#1387: the local lane's SEMP-covered partnership rule reaches the +# shared transfer only when asked for; off, the call is exactly as before. +@pytest.mark.parametrize("semp_covers", [False, True]) def test__given_source__then_stages_run_in_order_and_provenance_is_json_ready( monkeypatch, tmp_path, + semp_covers, ) -> None: events: list[tuple[Any, ...]] = [] # A base with no SPM independence role: the ACS spine derives none. @@ -175,6 +179,7 @@ def fake_pool(actual_base, actual_acs, *, acs_share): donor_channel="puf_support", seed=19, n_estimators=37, + semp_covers_partnership_income=semp_covers, ) assert events == [ @@ -191,6 +196,7 @@ def fake_pool(actual_base, actual_acs, *, acs_share): "seed": 19, "n_estimators": 37, "max_targets_per_fit": 8, + **({"semp_covers_partnership_income": True} if semp_covers else {}), }, ), ("pool", base, transferred_acs, 0.4), diff --git a/packages/microcosm-build/tests/engine_free/us/test_us_acs_multispine_base_builder.py b/packages/microcosm-build/tests/engine_free/us/test_us_acs_multispine_base_builder.py index 4c928b2186..d78d9b680a 100644 --- a/packages/microcosm-build/tests/engine_free/us/test_us_acs_multispine_base_builder.py +++ b/packages/microcosm-build/tests/engine_free/us/test_us_acs_multispine_base_builder.py @@ -309,6 +309,12 @@ def test_staging_refuses_self_employment_stacked_on_semp() -> None: "sstb_self_employment_income_before_lsr": [0.0, 1_000.0], "farm_operations_income": [0.0, 0.0], "partnership_self_employment_net_earnings": [0.0, 0.0], + # microcosm#1387: line 32 and the tax-unit columns the gate grades. + "partnership_income": [0.0, 6_000.0], + "s_corp_income": [900.0, 0.0], + "passive_partnership_s_corp_income": [0.0, 0.0], + "person_tax_unit_id": [1, 2], + "tax_unit_role_input": ["HEAD", "HEAD"], } ) @@ -316,6 +322,11 @@ def test_staging_refuses_self_employment_stacked_on_semp() -> None: assert gate.passed assert gate.details["acs_person_rows"] == 1 + stacked = person.copy() + stacked.loc[0, "partnership_income"] = 700.0 + with pytest.raises(SystemExit, match="ACS SEMP already includes"): + legacy._require_acs_self_employment_identity(_SelfEmploymentFrame(stacked)) + person.loc[0, "farm_operations_income"] = -1_200.0 with pytest.raises(SystemExit, match="counts that income twice"): legacy._require_acs_self_employment_identity(_SelfEmploymentFrame(person)) diff --git a/packages/microcosm-build/tests/engine_free/us/test_us_acs_multispine_legacy_builder.py b/packages/microcosm-build/tests/engine_free/us/test_us_acs_multispine_legacy_builder.py index 2c8713782e..2cab37a3ca 100644 --- a/packages/microcosm-build/tests/engine_free/us/test_us_acs_multispine_legacy_builder.py +++ b/packages/microcosm-build/tests/engine_free/us/test_us_acs_multispine_legacy_builder.py @@ -218,6 +218,13 @@ def test_main_wires_verified_sources_transfer_audit_export_and_summary( combined.table("person")["sstb_self_employment_income_before_lsr"] = [0.0, 2_042.0] combined.table("person")["farm_operations_income"] = [0.0, 0.0] combined.table("person")["partnership_self_employment_net_earnings"] = [0.0, 0.0] + # microcosm#1387: the ACS row reports SEMP, so its partnership income is + # zero; its S-corp income and the ASEC row's partnership income stand. + combined.table("person")["partnership_income"] = [3_000.0, 0.0] + combined.table("person")["s_corp_income"] = [0.0, 1_500.0] + combined.table("person")["passive_partnership_s_corp_income"] = [0.0, 0.0] + combined.table("person")["person_tax_unit_id"] = [1, 2] + combined.table("person")["tax_unit_role_input"] = ["HEAD", "HEAD"] # What the ACS local immigration stage returns (microcosm#1020): the # null audit, hours gate and export must all see this frame, not the # unlabelled pool. @@ -601,6 +608,7 @@ def staging_hours_gate(frame, *, source_null_audit): "work_disability_inputs": True, "income_transfer": True, "native_receipt_anchors": True, + "semp_covers_partnership_income": True, "donor_channel": builder.ACS_DONOR_CHANNEL_AUTO, "seed": 11, "n_estimators": 32, @@ -696,6 +704,10 @@ def staging_hours_gate(frame, *, source_null_audit): assert self_employment["details"]["mismatched_rows"] == 0 assert self_employment["details"]["non_acs_component_rows"] == 0 assert self_employment["details"]["base_and_sstb_rows"] == 0 + assert self_employment["details"]["partnership_on_semp_rows"] == 0 + assert self_employment["details"]["partnership_on_spouse_rows"] == 0 + assert self_employment["details"]["partnership_on_blank_semp_rows"] == 0 + assert self_employment["details"]["passive_without_line_32_rows"] == 0 assert "pending_engine_input_nulls" not in summary assert summary["staging_export_peak_estimate_bytes"] == 123_456 assert summary["geography_ladder"] == { diff --git a/packages/microcosm-build/tests/engine_free/us/test_us_acs_self_employment_identity.py b/packages/microcosm-build/tests/engine_free/us/test_us_acs_self_employment_identity.py index f4dc7156c0..c022459646 100644 --- a/packages/microcosm-build/tests/engine_free/us/test_us_acs_self_employment_identity.py +++ b/packages/microcosm-build/tests/engine_free/us/test_us_acs_self_employment_identity.py @@ -57,6 +57,27 @@ _NON_ACS = ("farm_operations_income", "partnership_self_employment_net_earnings") _LEAVES = (_TOTAL, *ACS_SELF_EMPLOYMENT_COMPONENT_INPUTS) _TOLERANCE = ACS_SELF_EMPLOYMENT_IDENTITY_TOLERANCE +#: microcosm#1387: the line-32 and tax-unit columns the gate also reads. +_LINE_32_COLUMNS = ( + "partnership_income", + "s_corp_income", + "passive_partnership_s_corp_income", + "person_tax_unit_id", + "tax_unit_role_input", +) + + +def _line_32_defaults(rows: int) -> dict[str, object]: + """No line-32 income, each person a tax-unit head of their own unit.""" + + return { + "partnership_income": np.zeros(rows), + "s_corp_income": np.zeros(rows), + "passive_partnership_s_corp_income": np.zeros(rows), + "person_tax_unit_id": np.arange(1, rows + 1), + "tax_unit_role_input": ["HEAD"] * rows, + } + _amounts = st.one_of( st.just(0.0), @@ -142,6 +163,7 @@ def _person(**columns) -> pd.DataFrame: defaults = { "ADJINC": [1_000_000.0] * rows, **{column: [0.0] * rows for column in _LEAVES}, + **_line_32_defaults(rows), } return pd.DataFrame({**defaults, **columns}) @@ -263,7 +285,7 @@ def test_gate_refuses_a_gap_that_overflows() -> None: assert gate.details["mismatched_rows"] == 1 -@pytest.mark.parametrize("column", ("SEMP", "ADJINC", *_LEAVES)) +@pytest.mark.parametrize("column", ("SEMP", "ADJINC", *_LEAVES, *_LINE_32_COLUMNS)) def test_gate_fails_closed_on_a_missing_column(column: str) -> None: person = _person(SEMP=[100.0], self_employment_income_before_lsr=[100.0]) @@ -337,6 +359,7 @@ def _split_rows(draw): _TOTAL: np.where(on_sstb, 0.0, total), _SSTB: np.where(on_sstb, total, 0.0), **{column: np.zeros(rows) for column in _NON_ACS}, + **_line_32_defaults(rows), } ) return person @@ -478,6 +501,9 @@ def _transfer_case(): "SEMP": semp, "ADJINC": adjinc, _TOTAL: semp * adjinc / 1_000_000, + # microcosm#1387: measured line 32 (none), so the transfer draws + # no partnership_income here and the gate's line-32 clauses hold. + **_line_32_defaults(4), } ) recipient = Frame( diff --git a/packages/microcosm-build/tests/engine_free/us/test_us_acs_semp_partnership.py b/packages/microcosm-build/tests/engine_free/us/test_us_acs_semp_partnership.py new file mode 100644 index 0000000000..f4e41b8958 --- /dev/null +++ b/packages/microcosm-build/tests/engine_free/us/test_us_acs_semp_partnership.py @@ -0,0 +1,938 @@ +"""Property and example tests for the SEMP-covered partnership rule (#1387). + +ACS SEMP includes own-partnership income and excludes incorporated-business +profit. On the ACS local lane, a donor ``partnership_income`` draw that SEMP +already accounts for is kept at zero; ``s_corp_income`` is never touched. + +Invariants of :func:`keep_semp_covered_partnership_income`, for every person +table and imputation mask, checked against an oracle written here: + +* **Exact cells.** A ``partnership_income`` cell becomes 0.0 exactly when the + transfer filled it, did not draw the row's self-employment total, and the + row reports a finite nonzero SEMP, is a HEAD or SPOUSE of a tax unit whose + HEAD or SPOUSE reports one, or has blank SEMP. +* **Nothing else moves.** Every other cell and column, ``s_corp_income`` + included, keeps its value. +* **Idempotent** and **sign-symmetric**: negating SEMP changes nothing but + the positive and negative receipt counts. +* **Receipt.** The counts equal the cells and nonzero draws in each set, and + the dollar sums equal the discarded draws' positive and negative parts. +* **Roles.** A role outside HEAD/SPOUSE/DEPENDENT (after decoding bytes and + folding case), or a missing role on a row with a tax unit, is refused. + +Invariants of the extended :func:`acs_self_employment_identity_gate`: + +* Its line-32 counts equal the oracle's, and it passes only when they are 0. +* Unselected rows never change the verdict, even in a shared tax unit and + whether they come before or after the selected rows (the pooled staging + frame puts ACS rows after the base's). + +The composition tests run the real transfer: the lane's output passes the +gate, the same transfer off the lane fails it on exactly the covered rows, +the two differ only in ``partnership_income`` and the passive subset and +fit the same models with the same seeds, and a step moved after the passive +reconciliation fails the gate's passive clause. +""" + +from __future__ import annotations + +import dataclasses +import inspect +import itertools + +import numpy as np +import pandas as pd +import pytest +from hypothesis import given, settings +from hypothesis import strategies as st + +import microcosm.build.us_runtime.acs_multispine as acs_multispine_module +import microcosm.build.us_runtime.acs_transfer as acs_transfer_module +from microcosm.build.serialization_dtypes import CANONICAL_STRING_DTYPE +from microcosm.build.us_runtime.acs_inputs import acs_self_employment_identity_gate +from microcosm.build.us_runtime.acs_transfer import ( + ACS_SELF_EMPLOYMENT_COMPONENT_INPUTS, + ACS_SEMP_COVERED_LINE_32_INPUTS, + acs_transfer_execution_contract_identity, + declared_acs_transfer_target_families, + keep_semp_covered_partnership_income, + semp_covered_partnership_cells, +) +from microcosm.frame import EntitySchema, Frame, WeightKind, Weights + +_P = "partnership_income" +_S = "s_corp_income" +_PASSIVE = "passive_partnership_s_corp_income" +_TOTAL = "self_employment_income_before_lsr" +_UNIT = "person_tax_unit_id" +_ROLE = "tax_unit_role_input" +_SETS = ("own_semp", "tax_unit", "blank_semp") + + +def _decode(value: object) -> str: + text = value.decode() if isinstance(value, (bytes, np.bytes_)) else str(value) + return text.upper() + + +def _oracle_sets(person: pd.DataFrame) -> dict[str, np.ndarray]: + """The three covered row sets, row by row, without the module's code.""" + + semp = pd.to_numeric(person["SEMP"], errors="coerce").to_numpy(dtype=float) + roles = [_decode(value) for value in person[_ROLE]] + units = person[_UNIT].tolist() + head_or_spouse = np.asarray([role in ("HEAD", "SPOUSE") for role in roles]) + own = np.isfinite(semp) & (semp != 0.0) + blank = np.isnan(semp) + reporting_units = { + unit + for unit, reports, member in zip(units, own, head_or_spouse, strict=True) + if reports and member and not pd.isna(unit) + } + in_reporting_unit = np.asarray( + [not pd.isna(unit) and unit in reporting_units for unit in units] + ) + return { + "own_semp": own, + "tax_unit": head_or_spouse & in_reporting_unit & ~own & ~blank, + "blank_semp": blank, + } + + +_semp = st.one_of( + st.just(np.nan), + st.just(0.0), + st.integers(min_value=-30_000, max_value=-1).map(float), + st.integers(min_value=1, max_value=200_000).map(float), +) +_amount = st.one_of( + st.just(0.0), + st.floats(min_value=-1e6, max_value=1e7, allow_nan=False, width=64), +) +_role = st.sampled_from( + ["HEAD", "SPOUSE", "DEPENDENT", b"HEAD", b"SPOUSE", "spouse", b"dependent"] +) +# Mostly small ids so rows share tax units; NaN is a row without one. +_unit = st.one_of(st.integers(min_value=1, max_value=4).map(float), st.just(np.nan)) +# Whole dollars, so a tax unit's line-32 sum is exact in any order and the +# oracle's zero test agrees with the gate's. Zeros, a cancelling pair and NaN +# are drawn often, so the passive clause (person and tax-unit line 32) and the +# NaN-as-zero reading are reached. +_dollars = st.one_of( + st.just(0.0), + st.just(np.nan), + st.sampled_from([-900.0, 900.0]), + st.integers(min_value=-1_000_000, max_value=10_000_000).map(float), +) + + +@st.composite +def _drawn_tables(draw): + rows = draw(st.integers(min_value=1, max_value=10)) + person = pd.DataFrame( + { + "SEMP": draw(st.lists(_semp, min_size=rows, max_size=rows)), + _UNIT: draw(st.lists(_unit, min_size=rows, max_size=rows)), + _ROLE: draw(st.lists(_role, min_size=rows, max_size=rows)), + _P: draw(st.lists(_amount, min_size=rows, max_size=rows)), + _S: draw(st.lists(_amount, min_size=rows, max_size=rows)), + "other": draw(st.lists(_amount, min_size=rows, max_size=rows)), + } + ) + # A recipient's index need not start at zero or run in order; the masks + # are positional either way. + start = draw(st.integers(min_value=0, max_value=50)) + index = np.arange(start, start + rows) + person.index = index[::-1] if draw(st.booleans()) else index + masks: dict[tuple[str, str], np.ndarray] = { + ("person", _P): np.asarray( + draw(st.lists(st.booleans(), min_size=rows, max_size=rows)), dtype=bool + ), + } + if draw(st.booleans()): + masks[("person", _TOTAL)] = np.asarray( + draw(st.lists(st.booleans(), min_size=rows, max_size=rows)), dtype=bool + ) + return person, masks + + +@given(_drawn_tables()) +@settings(max_examples=400, deadline=None) +def test_the_step_zeroes_exactly_the_covered_drawn_cells(case) -> None: + before, masks = case + after = before.copy(deep=True) + counts = keep_semp_covered_partnership_income(after, imputed_masks=masks) + + rows = len(before) + drawn = masks[("person", _P)] + if not drawn.any(): + assert counts is None + pd.testing.assert_frame_equal(after, before) + return + total_drawn = masks.get(("person", _TOTAL), np.zeros(rows, dtype=bool)) + sets = _oracle_sets(before) + mutable = drawn & ~total_drawn + covered = mutable & (sets["own_semp"] | sets["tax_unit"] | sets["blank_semp"]) + + assert (after.loc[covered, _P] == 0.0).all() + pd.testing.assert_series_equal(after.loc[~covered, _P], before.loc[~covered, _P]) + pd.testing.assert_frame_equal(after.drop(columns=[_P]), before.drop(columns=[_P])) + + nonzero = before[_P].to_numpy() != 0.0 + assert counts is not None + assert counts["cells_kept_at_zero"] == int(covered.sum()) + assert counts["nonzero_draws_discarded"] == int((covered & nonzero).sum()) + for name in _SETS: + cleared = mutable & sets[name] + assert counts[f"{name}_cells"] == int(cleared.sum()) + assert counts[f"{name}_nonzero_draws_discarded"] == int( + (cleared & nonzero).sum() + ) + semp = before["SEMP"].to_numpy(dtype=float) + own = mutable & sets["own_semp"] + assert counts["own_semp_positive_cells"] == int((own & (semp > 0.0)).sum()) + assert counts["own_semp_negative_cells"] == int((own & (semp < 0.0)).sum()) + amounts = before[_P].tolist() + for prefix, rows_in in [("", covered)] + [ + (f"{name}_", mutable & sets[name]) for name in _SETS + ]: + kept = [value for value, row in zip(amounts, rows_in, strict=True) if row] + assert ( + abs( + counts[f"{prefix}discarded_positive_dollars"] + - sum(value for value in kept if value > 0) + ) + <= 1 + ) + assert ( + abs( + counts[f"{prefix}discarded_negative_dollars"] + - sum(value for value in kept if value < 0) + ) + <= 1 + ) + assert not any("weighted" in key for key in counts) + + again = after.copy(deep=True) + keep_semp_covered_partnership_income(again, imputed_masks=masks) + pd.testing.assert_frame_equal(again, after) + + +@given(_drawn_tables()) +@settings(max_examples=200, deadline=None) +def test_the_step_is_symmetric_in_the_sign_of_semp(case) -> None: + before, masks = case + flipped = before.copy(deep=True) + flipped["SEMP"] = -flipped["SEMP"] + kept = before.copy(deep=True) + + counts = keep_semp_covered_partnership_income(kept, imputed_masks=masks) + flipped_counts = keep_semp_covered_partnership_income(flipped, imputed_masks=masks) + + pd.testing.assert_series_equal(flipped[_P], kept[_P]) + if counts is None: + assert flipped_counts is None + return + assert flipped_counts is not None + swap = { + "own_semp_positive_cells": "own_semp_negative_cells", + "own_semp_negative_cells": "own_semp_positive_cells", + } + assert {swap.get(key, key): value for key, value in counts.items()} == ( + flipped_counts + ) + + +@given(_drawn_tables()) +@settings(max_examples=200, deadline=None) +def test_the_covered_sets_are_disjoint_and_match_the_oracle(case) -> None: + person, _masks = case + + sets = semp_covered_partnership_cells(person) + expected = _oracle_sets(person) + + for name in _SETS: + np.testing.assert_array_equal(sets[name], expected[name]) + for left, right in itertools.combinations(_SETS, 2): + assert not (sets[left] & sets[right]).any() + + +def test_a_dependent_reporter_extends_to_no_one_and_a_unitless_row_to_no_one() -> None: + # Rows 2 and 3 have no tax unit; row 2 reports SEMP, so grouping unitless + # rows together would wrongly extend it to row 3. + person = pd.DataFrame( + { + "SEMP": [0.0, 3_000.0, 3_000.0, 0.0], + _UNIT: [40.0, 40.0, np.nan, np.nan], + _ROLE: ["HEAD", "DEPENDENT", "HEAD", "SPOUSE"], + } + ) + + sets = semp_covered_partnership_cells(person) + + assert sets["own_semp"].tolist() == [False, True, True, False] + assert sets["tax_unit"].tolist() == [False, False, False, False] + + +def test_case_and_bytes_fold_but_an_unknown_role_is_refused() -> None: + person = pd.DataFrame( + {"SEMP": [5_000.0, 0.0], _UNIT: [1, 1], _ROLE: [b"head", "Spouse"]} + ) + assert semp_covered_partnership_cells(person)["tax_unit"].tolist() == [ + False, + True, + ] + + for bad in ("SPOUSE ", "OTHER", 1, None): + malformed = person.astype({_ROLE: object}) + malformed.loc[1, _ROLE] = bad + with pytest.raises(ValueError, match="neither head nor spouse"): + semp_covered_partnership_cells(malformed) + + +def test_a_missing_role_is_allowed_only_without_a_tax_unit() -> None: + person = pd.DataFrame( + {"SEMP": [5_000.0, 0.0], _UNIT: [1.0, np.nan], _ROLE: ["HEAD", None]} + ) + + assert semp_covered_partnership_cells(person)["tax_unit"].tolist() == [ + False, + False, + ] + + +def test_the_step_does_nothing_when_no_partnership_income_was_drawn() -> None: + person = pd.DataFrame( + {"SEMP": [500.0], _UNIT: [1], _ROLE: ["HEAD"], _P: [700.0], _S: [9.0]} + ) + + assert keep_semp_covered_partnership_income(person, imputed_masks={}) is None + # The state the transfer makes: a mask for the planned target, all False. + # Nothing was drawn, so even a recipient without SEMP is not refused. + nothing = {("person", _P): np.asarray([False])} + assert keep_semp_covered_partnership_income(person, imputed_masks=nothing) is None + assert ( + keep_semp_covered_partnership_income( + person.drop(columns=["SEMP"]), imputed_masks=nothing + ) + is None + ) + assert person[_P].tolist() == [700.0] + + +@pytest.mark.parametrize( + "masks", + ( + {("person", _P): np.asarray([True, False])}, + {("person", _P): np.asarray([True]), ("person", _TOTAL): np.ones(2, bool)}, + ), +) +def test_the_step_refuses_masks_not_aligned_to_person(masks) -> None: + person = pd.DataFrame({"SEMP": [500.0], _UNIT: [1], _ROLE: ["HEAD"], _P: [7.0]}) + + with pytest.raises(ValueError, match="aligned to person"): + keep_semp_covered_partnership_income(person, imputed_masks=masks) + + +def test_the_receipt_weights_the_discarded_draws() -> None: + person = pd.DataFrame( + { + "SEMP": [500.0, 0.0, np.nan], + _UNIT: [1, 1, 2], + _ROLE: ["HEAD", "SPOUSE", "HEAD"], + _P: [700.0, -300.0, 50.0], + } + ) + + counts = keep_semp_covered_partnership_income( + person, + imputed_masks={("person", _P): np.ones(3, dtype=bool)}, + person_weights=np.asarray([2.0, 2.0, 10.0]), + ) + + assert counts is not None + assert counts["own_semp_discarded_positive_dollars"] == 700 + assert counts["tax_unit_discarded_negative_dollars"] == -300 + assert counts["blank_semp_discarded_positive_dollars"] == 50 + assert counts["discarded_positive_dollars"] == 750 + assert counts["discarded_negative_dollars"] == -300 + assert counts["household_weighted_discarded_positive_dollars"] == 1_900 + assert counts["household_weighted_discarded_negative_dollars"] == -600 + assert counts["tax_unit_household_weighted_discarded_negative_dollars"] == -600 + + +@pytest.mark.parametrize("column", ("SEMP", _UNIT, _ROLE)) +def test_the_step_refuses_a_recipient_missing_a_column_it_reads(column: str) -> None: + person = pd.DataFrame( + {"SEMP": [500.0], _UNIT: [1], _ROLE: ["HEAD"], _P: [700.0]} + ).drop(columns=[column]) + + with pytest.raises(ValueError, match="refusing to treat them as zero"): + keep_semp_covered_partnership_income( + person, imputed_masks={("person", _P): np.asarray([True])} + ) + + +# --- the gate --------------------------------------------------------------- + + +@st.composite +def _gate_tables(draw): + rows = draw(st.integers(min_value=1, max_value=10)) + semp = np.asarray(draw(st.lists(_semp, min_size=rows, max_size=rows))) + adjinc = np.full(rows, 1_000_000.0) + person = pd.DataFrame( + { + "SEMP": semp, + "ADJINC": adjinc, + _TOTAL: np.where(np.isnan(semp), np.nan, semp), + **{ + column: np.zeros(rows) + for column in ACS_SELF_EMPLOYMENT_COMPONENT_INPUTS + }, + _UNIT: draw(st.lists(_unit, min_size=rows, max_size=rows)), + _ROLE: draw(st.lists(_role, min_size=rows, max_size=rows)), + _P: draw(st.lists(_dollars, min_size=rows, max_size=rows)), + _S: draw(st.lists(_dollars, min_size=rows, max_size=rows)), + _PASSIVE: draw(st.lists(_dollars, min_size=rows, max_size=rows)), + } + ) + start = draw(st.integers(min_value=0, max_value=50)) + index = np.arange(start, start + rows) + person.index = index[::-1] if draw(st.booleans()) else index + return person + + +def _oracle_gate_counts(person: pd.DataFrame) -> dict[str, int]: + sets = _oracle_sets(person) + partnership = person[_P].to_numpy(dtype=float) + not_zero = ~(np.isfinite(partnership) & (partnership == 0.0)) + line_32 = (person[_P].fillna(0.0) + person[_S].fillna(0.0)).to_numpy() + units = person[_UNIT].tolist() + unit_line_32 = { + unit: sum( + value for other, value in zip(units, line_32, strict=True) if other == unit + ) + for unit in units + if not pd.isna(unit) + } + passive = person[_PASSIVE].fillna(0.0).to_numpy() + no_line_32 = np.asarray( + [ + own == 0.0 or (not pd.isna(unit) and unit_line_32[unit] == 0.0) + for own, unit in zip(line_32, units, strict=True) + ] + ) + return { + "partnership_on_semp_rows": int((sets["own_semp"] & not_zero).sum()), + "partnership_on_spouse_rows": int((sets["tax_unit"] & not_zero).sum()), + "partnership_on_blank_semp_rows": int((sets["blank_semp"] & not_zero).sum()), + "passive_without_line_32_rows": int((no_line_32 & (passive != 0.0)).sum()), + } + + +@given(_gate_tables()) +@settings(max_examples=400, deadline=None) +def test_the_gate_counts_exactly_the_line_32_violations(person) -> None: + gate = acs_self_employment_identity_gate( + person, rows=np.ones(len(person), dtype=bool) + ) + expected = _oracle_gate_counts(person) + + for key, value in expected.items(): + assert gate.details[key] == value, key + assert gate.passed is (sum(expected.values()) == 0) + + +@given(_gate_tables(), _gate_tables(), st.booleans()) +@settings(max_examples=300, deadline=None) +def test_unselected_rows_never_change_the_gate( + selected, ignored, ignored_first +) -> None: + alone = acs_self_employment_identity_gate( + selected, rows=np.ones(len(selected), dtype=bool) + ) + # The ignored rows share tax-unit ids with the selected ones. The pooled + # staging frame puts the base rows first, so the selected ACS rows then + # carry an index that does not start at zero. + blocks = [ignored, selected] if ignored_first else [selected, ignored] + combined = pd.concat(blocks, ignore_index=True) + flags = [np.zeros(len(ignored), bool), np.ones(len(selected), bool)] + rows = np.concatenate(flags if ignored_first else flags[::-1]) + + together = acs_self_employment_identity_gate(combined, rows=rows) + + assert together.passed is alone.passed + assert together.failures == alone.failures + assert together.details == alone.details + + +def _gate_row(**values) -> pd.DataFrame: + rows = len(next(iter(values.values()))) + base = { + "SEMP": [0.0] * rows, + "ADJINC": [1_000_000.0] * rows, + _TOTAL: [0.0] * rows, + **{column: [0.0] * rows for column in ACS_SELF_EMPLOYMENT_COMPONENT_INPUTS}, + _UNIT: list(range(1, rows + 1)), + _ROLE: ["HEAD"] * rows, + _P: [0.0] * rows, + _S: [0.0] * rows, + _PASSIVE: [0.0] * rows, + } + base.update(values) + if "SEMP" in values: + base[_TOTAL] = [np.nan if pd.isna(value) else value for value in values["SEMP"]] + return pd.DataFrame(base) + + +@pytest.mark.parametrize("index", (None, [10, 11], [11, 10])) +def test_the_gate_extends_a_reporting_head_to_the_spouse_at_any_index(index) -> None: + person = _gate_row( + **{ + "SEMP": [5_000.0, 0.0], + _UNIT: [3, 3], + _ROLE: ["HEAD", "SPOUSE"], + _P: [0.0, 7_000.0], + } + ) + if index is not None: + person.index = index + + gate = acs_self_employment_identity_gate(person, rows=np.ones(2, dtype=bool)) + + assert not gate.passed + assert gate.details["partnership_on_spouse_rows"] == 1 + + +@pytest.mark.parametrize("index", (None, [10, 11], [11, 10])) +def test_the_gate_reads_a_tax_unit_whose_line_32_cancels_as_zero(index) -> None: + # Each person has line 32, but the unit's total is zero (refuter A7). The + # pooled staging frame's ACS rows carry an index that does not start at 0. + person = _gate_row(**{_UNIT: [7, 7], _P: [900.0, -900.0], _PASSIVE: [300.0, 0.0]}) + if index is not None: + person.index = index + + gate = acs_self_employment_identity_gate(person, rows=np.ones(2, dtype=bool)) + + assert not gate.passed + assert gate.details["passive_without_line_32_rows"] == 1 + + +@pytest.mark.parametrize( + ("values", "violations"), + ( + # NaN partnership income on a SEMP row is not a finite zero. + ({"SEMP": [5_000.0], _P: [np.nan]}, {"partnership_on_semp_rows": 1}), + # NaN line-32 leaves read as zero under a passive draw. + ({_P: [np.nan], _PASSIVE: [300.0]}, {"passive_without_line_32_rows": 1}), + # A NaN passive draw is not a passive amount. + ({_PASSIVE: [np.nan]}, {}), + ), +) +def test_the_gate_reads_nan_line_32_leaves(values, violations) -> None: + gate = acs_self_employment_identity_gate( + _gate_row(**values), rows=np.ones(1, dtype=bool) + ) + + for key in ("partnership_on_semp_rows", "passive_without_line_32_rows"): + assert gate.details[key] == violations.get(key, 0), key + assert gate.passed is (not violations) + + +@pytest.mark.parametrize("bad", ("SPOUSE ", "OTHER", 2, None)) +def test_the_gate_fails_a_malformed_role_instead_of_exempting_its_unit(bad) -> None: + person = _gate_row( + **{"SEMP": [5_000.0, 0.0], _UNIT: [1, 1], _ROLE: ["HEAD", bad], _P: [0.0, 9.0]} + ) + + gate = acs_self_employment_identity_gate(person, rows=np.ones(2, dtype=bool)) + + assert not gate.passed + assert gate.details["malformed_tax_unit_role_rows"] == 1 + + +def test_the_gate_leaves_s_corp_income_and_partnership_on_unreported_rows_alone() -> ( + None +): + person = pd.DataFrame( + { + "SEMP": [0.0, 5_000.0, 0.0], + "ADJINC": [1_000_000.0] * 3, + _TOTAL: [0.0, 5_000.0, 0.0], + **{column: [0.0] * 3 for column in ACS_SELF_EMPLOYMENT_COMPONENT_INPUTS}, + _UNIT: [1, 2, 3], + _ROLE: ["HEAD", "HEAD", "HEAD"], + _P: [8_000.0, 0.0, -2_000.0], + _S: [0.0, 40_000.0, 0.0], + _PASSIVE: [500.0, 300.0, 0.0], + } + ) + + gate = acs_self_employment_identity_gate(person, rows=np.ones(3, dtype=bool)) + + assert gate.passed, gate.failures + + +@pytest.mark.parametrize("column", (_P, _S, _PASSIVE)) +def test_the_gate_refuses_an_infinite_line_32_value(column: str) -> None: + person = _gate_row(**{_S: [10.0], column: [np.inf]}) + + gate = acs_self_employment_identity_gate(person, rows=np.ones(1, dtype=bool)) + + assert not gate.passed + assert gate.details["infinite_line_32_rows"] == 1 + + +# --- the real transfer ------------------------------------------------------- + +_SCHEMA = EntitySchema(group_entities=("household", "tax_unit")) +_PASS_THROUGH = (_P, _S, _PASSIVE) + + +def _frame(person: pd.DataFrame, weights: np.ndarray, kind: WeightKind) -> Frame: + households = np.unique(person["person_household_id"]) + units = np.unique(person[_UNIT]) + return Frame( + { + "person": person, + "household": pd.DataFrame( + {"household_id": households, "state_fips": [6] * len(households)} + ), + "tax_unit": pd.DataFrame({"tax_unit_id": units}), + }, + _SCHEMA, + {"household": Weights(weights, kind)}, + ) + + +def _donor(s_corp: float) -> Frame: + person = pd.DataFrame( + { + "person_id": np.arange(1, 5, dtype=np.int64), + "person_household_id": np.asarray([10, 10, 20, 20], dtype=np.int64), + _UNIT: np.asarray([1, 1, 2, 2], dtype=np.int64), + "age": [45.0, 43.0, 30.0, 52.0], + "is_female": [False, True, True, False], + _TOTAL: [0.0, 20_000.0, 0.0, 5_000.0], + _P: [5_000.0, 0.0, 3_000.0, 0.0], + _S: [s_corp, 0.0, 0.0, 0.0], + _PASSIVE: [400.0, 0.0, 0.0, 0.0], + } + ) + return _frame(person, np.asarray([1.0, 2.0]), WeightKind.CALIBRATED) + + +# Seven ACS persons, one per covered case: +# 0 single head, SEMP 0 -> keeps its draw +# 1 head, SEMP 12,000 -> own SEMP (positive) +# 2 spouse of 1, SEMP 0 -> tax-unit extension +# 3 head, SEMP -800 -> own SEMP (negative) +# 4 dependent of 3, blank SEMP -> blank SEMP +# 5 head, SEMP 0 -> keeps: only a dependent reports +# 6 dependent of 5, SEMP 3,000 -> own SEMP (positive) +_SEMP = np.asarray([0.0, 12_000.0, 0.0, -800.0, np.nan, 0.0, 3_000.0]) +_COVERED = np.asarray([False, True, True, True, True, False, True]) + + +def _recipient() -> Frame: + rows = len(_SEMP) + person = pd.DataFrame( + { + "person_id": np.arange(101, 101 + rows, dtype=np.int64), + "person_household_id": np.asarray( + [110, 120, 120, 130, 130, 140, 140], dtype=np.int64 + ), + _UNIT: np.asarray([11, 12, 12, 13, 13, 14, 14], dtype=np.int64), + _ROLE: pd.array( + ["HEAD", "HEAD", "SPOUSE", "HEAD", "DEPENDENT", "HEAD", "DEPENDENT"], + dtype=CANONICAL_STRING_DTYPE, + ), + "age": [50.0, 44.0, 42.0, 61.0, 9.0, 47.0, 17.0], + "is_female": [True, False, True, False, True, False, True], + "SEMP": _SEMP, + "ADJINC": np.where(np.isnan(_SEMP), np.nan, 1_000_000.0), + _TOTAL: _SEMP, + **{ + column: np.zeros(rows) + for column in ACS_SELF_EMPLOYMENT_COMPONENT_INPUTS + }, + _P: np.full(rows, np.nan), + _S: np.full(rows, np.nan), + _PASSIVE: np.full(rows, np.nan), + } + ) + return _frame(person, np.asarray([5.0, 7.0, 3.0, 4.0]), WeightKind.DESIGN) + + +class _DonorMeanQRF: + def __init__(self, *, n_estimators: int, seed: int) -> None: + del n_estimators, seed + + def fit(self, frame, predictors, targets, *, weights): + del predictors + table = frame.table(frame.column_entity(targets[0])) + assert weights == frame.resolve_weights("person").kind.value + return _DonorMeanFitted( + {target: float(table[target].mean()) for target in targets}, weights + ) + + +class _DonorMeanFitted: + def __init__(self, means: dict[str, float], weight_kind: str) -> None: + self.means = means + self.weight_kind = weight_kind + + def predict(self, frame: pd.DataFrame) -> pd.DataFrame: + return pd.DataFrame( + {target: np.full(len(frame), mean) for target, mean in self.means.items()}, + index=frame.index, + ) + + +def _transfer(monkeypatch, *, lane: bool, s_corp: float = 0.0, targets=_PASS_THROUGH): + monkeypatch.setattr(acs_transfer_module, "QRF", _DonorMeanQRF) + return acs_transfer_module.transfer_acs_inputs( + _recipient(), + _donor(s_corp), + target_families={"person": {"pass_through": targets}}, + donor_channel=None, + n_estimators=1, + semp_covers_partnership_income=lane, + ) + + +def _gate(person: pd.DataFrame): + return acs_self_employment_identity_gate( + person, rows=np.ones(len(person), dtype=bool) + ) + + +def test_the_lane_keeps_semp_covered_draws_at_zero_and_passes_the_gate( + monkeypatch, +) -> None: + result = _transfer(monkeypatch, lane=True) + person = result.frame.table("person") + + assert (person.loc[_COVERED, _P] == 0.0).all() + assert np.allclose(person.loc[~_COVERED, _P], 2_000.0) + assert (person[_S] == 0.0).all() + # The passive reconciliation ran after the step: with no S-corp income, + # line 32 is zero exactly where the step cleared the partnership draw. + assert (person.loc[_COVERED, _PASSIVE] == 0.0).all() + assert np.allclose(person.loc[~_COVERED, _PASSIVE], 100.0) + gate = _gate(person) + assert gate.passed, gate.failures + + # Each covered cell held the donor mean, 2,000. Household design weights: + # 7 (rows 1-2), 3 (rows 3-4), 4 (rows 5-6). + record = next(item for item in result.imputed_inputs if item.column == _P) + assert record.reconciliation == { + "own_semp_cells": 3, + "own_semp_nonzero_draws_discarded": 3, + "own_semp_discarded_positive_dollars": 6_000, + "own_semp_discarded_negative_dollars": 0, + "own_semp_household_weighted_discarded_positive_dollars": 28_000, + "own_semp_household_weighted_discarded_negative_dollars": 0, + "tax_unit_cells": 1, + "tax_unit_nonzero_draws_discarded": 1, + "tax_unit_discarded_positive_dollars": 2_000, + "tax_unit_discarded_negative_dollars": 0, + "tax_unit_household_weighted_discarded_positive_dollars": 14_000, + "tax_unit_household_weighted_discarded_negative_dollars": 0, + "blank_semp_cells": 1, + "blank_semp_nonzero_draws_discarded": 1, + "blank_semp_discarded_positive_dollars": 2_000, + "blank_semp_discarded_negative_dollars": 0, + "blank_semp_household_weighted_discarded_positive_dollars": 6_000, + "blank_semp_household_weighted_discarded_negative_dollars": 0, + "own_semp_positive_cells": 2, + "own_semp_negative_cells": 1, + "cells_kept_at_zero": 5, + "nonzero_draws_discarded": 5, + "discarded_positive_dollars": 10_000, + "discarded_negative_dollars": 0, + "household_weighted_discarded_positive_dollars": 48_000, + "household_weighted_discarded_negative_dollars": 0, + } + + +def test_the_lane_keeps_s_corp_income_on_every_row(monkeypatch) -> None: + person = _transfer(monkeypatch, lane=True, s_corp=1_000.0).frame.table("person") + + assert np.allclose(person[_S], 250.0) + assert (person.loc[_COVERED, _P] == 0.0).all() + # Line 32 stays nonzero on every row, so every passive draw stands. + assert np.allclose(person[_PASSIVE], 100.0) + assert _gate(person).passed + + +def test_off_the_lane_the_gate_fails_on_exactly_the_covered_rows(monkeypatch) -> None: + person = _transfer(monkeypatch, lane=False).frame.table("person") + + gate = _gate(person) + + assert not gate.passed + assert gate.details["partnership_on_semp_rows"] == 3 + assert gate.details["partnership_on_positive_semp_rows"] == 2 + assert gate.details["partnership_on_negative_semp_rows"] == 1 + assert gate.details["partnership_on_spouse_rows"] == 1 + assert gate.details["partnership_on_blank_semp_rows"] == 1 + assert gate.details["passive_without_line_32_rows"] == 0 + + +class _RecordingQRF(_DonorMeanQRF): + calls: list[tuple[int, tuple[str, ...], tuple[str, ...]]] = [] + + def __init__(self, *, n_estimators: int, seed: int) -> None: + super().__init__(n_estimators=n_estimators, seed=seed) + self.seed = seed + + def fit(self, frame, predictors, targets, *, weights): + type(self).calls.append((self.seed, tuple(predictors), tuple(targets))) + return super().fit(frame, predictors, targets, weights=weights) + + +def test_the_lane_changes_only_partnership_income_and_the_passive_subset( + monkeypatch, +) -> None: + runs = {} + for lane in (True, False): + _RecordingQRF.calls = [] + monkeypatch.setattr(acs_transfer_module, "QRF", _RecordingQRF) + result = acs_transfer_module.transfer_acs_inputs( + _recipient(), + _donor(0.0), + target_families={"person": {"pass_through": _PASS_THROUGH}}, + donor_channel=None, + n_estimators=1, + semp_covers_partnership_income=lane, + ) + runs[lane] = (result, list(_RecordingQRF.calls)) + (on, on_calls), (off, off_calls) = runs[True], runs[False] + on_person, off_person = on.frame.table("person"), off.frame.table("person") + + pd.testing.assert_frame_equal( + on_person.drop(columns=[_P, _PASSIVE]), off_person.drop(columns=[_P, _PASSIVE]) + ) + assert (on_person[_P] != off_person[_P]).to_numpy().tolist() == _COVERED.tolist() + # Same models, seeds, predictors and target order; only the partnership + # record's receipt and the passive record's counts differ. + assert on_calls == off_calls and on_calls + assert on.fit_records == off.fit_records + assert [ + dataclasses.replace(item, reconciliation=None) for item in on.imputed_inputs + ] == [dataclasses.replace(item, reconciliation=None) for item in off.imputed_inputs] + + +def test_a_step_run_after_the_passive_reconciliation_fails_the_gate( + monkeypatch, +) -> None: + """The order matters: zeroing after the passive block strands passive.""" + + monkeypatch.setattr( + acs_transfer_module, + "keep_semp_covered_partnership_income", + lambda person, **_masks_and_weights: None, + ) + person = _transfer(monkeypatch, lane=True).frame.table("person") + person.loc[_COVERED, _P] = 0.0 + + gate = _gate(person) + + assert not gate.passed + assert gate.details["partnership_on_semp_rows"] == 0 + assert gate.details["passive_without_line_32_rows"] == int(_COVERED.sum()) + + +def test_the_lane_refuses_a_plan_without_s_corp_income(monkeypatch) -> None: + with pytest.raises(ValueError, match="without s_corp_income"): + _transfer(monkeypatch, lane=True, targets=(_P, _PASSIVE)) + + +class _NoFitQRF(_DonorMeanQRF): + def fit(self, frame, predictors, targets, *, weights): + raise AssertionError("the refusal must come before any fit") + + +@pytest.mark.parametrize("column", ("SEMP", _ROLE)) +def test_the_lane_refuses_a_recipient_without_a_column_the_rule_reads( + monkeypatch, column: str +) -> None: + recipient = _recipient() + tables = {name: recipient.table(name) for name in recipient.entities} + tables["person"] = tables["person"].drop(columns=[column]) + monkeypatch.setattr(acs_transfer_module, "QRF", _NoFitQRF) + + with pytest.raises(ValueError, match="refusing to treat them as zero"): + acs_transfer_module.transfer_acs_inputs( + Frame( + tables, + recipient.schema, + {"household": recipient.weights_for("household")}, + ), + _donor(0.0), + target_families={"person": {"pass_through": _PASS_THROUGH}}, + donor_channel=None, + n_estimators=1, + semp_covers_partnership_income=True, + ) + + +# --- the contract stays opt-in ----------------------------------------------- + +_DECLARED_TARGETS = tuple( + sorted( + { + target + for families in declared_acs_transfer_target_families().values() + for targets in families.values() + for target in targets + } + ) +) + + +@given(st.sets(st.sampled_from(_DECLARED_TARGETS))) +@settings(max_examples=150, deadline=None) +def test_the_contract_is_unchanged_off_the_lane(targets) -> None: + assert acs_transfer_execution_contract_identity( + targets=sorted(targets), semp_covers_partnership_income=False + ) == acs_transfer_execution_contract_identity(targets=sorted(targets)) + + +def test_the_lane_binds_its_rule_into_the_contract() -> None: + off = acs_transfer_execution_contract_identity(targets=_PASS_THROUGH) + on = acs_transfer_execution_contract_identity( + targets=_PASS_THROUGH, semp_covers_partnership_income=True + ) + without_partnership = acs_transfer_execution_contract_identity( + targets=(_S,), semp_covers_partnership_income=True + ) + + assert "semp_covered_partnership_income" not in off["post_transfer_structure"] + rule = on["post_transfer_structure"]["semp_covered_partnership_income"] + assert rule["enabled"] is True + assert rule["covered"] == list(ACS_SEMP_COVERED_LINE_32_INPUTS) == [_P] + assert rule["order"] == "before_passive_partnership_s_corp" + assert on["sha256"] != off["sha256"] + assert ( + without_partnership["post_transfer_structure"][ + "semp_covered_partnership_income" + ]["enabled"] + is False + ) + + +@pytest.mark.parametrize( + "function", + ( + acs_transfer_module.transfer_acs_inputs, + acs_transfer_execution_contract_identity, + acs_multispine_module.build_optional_acs_multispine, + ), +) +def test_every_entry_point_defaults_the_lane_off(function) -> None: + parameter = inspect.signature(function).parameters["semp_covers_partnership_income"] + + assert parameter.default is False + assert parameter.kind is inspect.Parameter.KEYWORD_ONLY diff --git a/packages/microcosm-build/tests/engine_workflow/us/test_us_multispine_pool_tool.py b/packages/microcosm-build/tests/engine_workflow/us/test_us_multispine_pool_tool.py index 7a68a3f439..c5e6cd3071 100644 --- a/packages/microcosm-build/tests/engine_workflow/us/test_us_multispine_pool_tool.py +++ b/packages/microcosm-build/tests/engine_workflow/us/test_us_multispine_pool_tool.py @@ -355,7 +355,9 @@ def capture_equality(expected: object, actual: object) -> None: # through the bundle's source stages. # The hierarchy value ranks move it through medicaid_take_up's # attested bytes. - "spec_sha256": "bd526d8cf819e9f97fa46c5fe279c7b9ef4458b3e2d3498f823602f45e6a7575", + # microcosm#1387's SEMP-covered partnership step moves it through + # acs_transfer's attested bytes. + "spec_sha256": "3c21db4468d0c92f91cc03a21c8afa7dedf21863fa0cef0429238ee63d7d4896", }, } diff --git a/tools/_legacy/build_us_acs_multispine_base.py b/tools/_legacy/build_us_acs_multispine_base.py index 47e1fb0c98..fd5e394855 100644 --- a/tools/_legacy/build_us_acs_multispine_base.py +++ b/tools/_legacy/build_us_acs_multispine_base.py @@ -581,6 +581,8 @@ def _build(args: argparse.Namespace, telemetry: LocalTelemetryEmitter) -> int: work_disability_inputs=True, income_transfer=True, native_receipt_anchors=True, + # microcosm#1387: ACS SEMP already includes own-partnership income. + semp_covers_partnership_income=True, donor_channel=args.donor_channel, seed=args.seed, n_estimators=args.n_estimators, @@ -1239,7 +1241,7 @@ def _require_benefit_participation_transfer(result: AcsMultispineResult) -> None def _require_acs_self_employment_identity(frame: Frame) -> GateResult: - """Refuse staging whose ACS self-employment leaves add to SEMP (#1380).""" + """Refuse staging whose ACS self-employment double-counts SEMP (#1380, #1387).""" person = frame.table("person") tag = spine_column("person") diff --git a/tools/build_us_acs_local_release.py b/tools/build_us_acs_local_release.py index f819b2c7b2..b64aad5d02 100644 --- a/tools/build_us_acs_local_release.py +++ b/tools/build_us_acs_local_release.py @@ -5381,14 +5381,15 @@ def _require_ssi_take_up_handling( def _require_acs_self_employment_identity(frame): - """Refuse a frame whose ACS self-employment leaves add to SEMP (#1380). + """Refuse a frame whose ACS self-employment double-counts SEMP. Staging built before the ACS transfer zeroed donor self-employment - components carries them on top of SEMP, and so does any checkpoint - calibrated from it. Materialize and calibrate check the staging frame; - package checks the calibrated H5 it ships, so a historical checkpoint - cannot reach a release through qa and finalize alone. Returns the - passing gate. + components (#1380) carries them on top of SEMP, and staging built before + it kept partnership_income at zero where SEMP already holds it (#1387) + carries that on top too; so does any checkpoint calibrated from either. + Materialize and calibrate check the staging frame; package checks the + calibrated H5 it ships, so a historical checkpoint cannot reach a + release through qa and finalize alone. Returns the passing gate. """ person = frame.table("person") @@ -5410,7 +5411,11 @@ def _require_acs_self_employment_identity(frame): ) if not gate.passed: raise SystemExit( - "ACS self-employment identity failed: " + "; ".join(gate.failures) + "ACS self-employment identity failed: " + + "; ".join(gate.failures) + + ". Staging, or a checkpoint calibrated from staging, built before " + "microcosm#1380 or #1387 must be rebuilt with the current ACS base " + "builder." ) return gate @@ -6296,8 +6301,9 @@ def do_package(args) -> dict: # release records as built-with. spm_measurement_gate = _require_spm_measurement(artifact_frame) package_hours_gate = _local_hours_gate(artifact_frame, staging_summary) - # microcosm#1380: a checkpoint calibrated from pre-fix staging stacks - # donor self-employment on SEMP; grade the bytes being packaged. + # microcosm#1380, #1387: a checkpoint calibrated from pre-fix staging + # stacks donor self-employment or partnership income on SEMP; grade the + # bytes being packaged. self_employment_gate = _require_acs_self_employment_identity(artifact_frame) del artifact_frame gc.collect() From d61f0ccfab7065c48f54dc6f61af523ee4c89e69 Mon Sep 17 00:00:00 2001 From: Max Ghenis Date: Sun, 15 Nov 2026 10:38:57 -0500 Subject: [PATCH 2/3] Fix the SEMP-covered partnership rule's round-1 review findings (#1387) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A blank or non-numeric SEMP was read as outside the ACS income universe, so an extract that lost SEMP would zero every partnership draw and pass the gate. The rule and the transfer preflight now refuse a SEMP value that does not parse as a number, and a recipient whose persons aged 15 or over all have blank SEMP; the gate fails both. Partial disagreement between blank SEMP and age is counted in the receipt and in the gate's semp_age details, not refused, until R1 shows what real PUMS holds. Roles: malformed roles are refused before any fit; bytes decode as UTF-8 with replacement, and a role must be ASCII before case folding, so a lookalike such as "ſpouſe" is not read as SPOUSE. Masks passed to the step must be boolean arrays of the person length or Series on the person index. The gate's partnership clauses count only finite nonzero values; a blank partnership_income on a covered row fails on its own clause as an unmodeled cell. The release tool names a rebuild only when a failure is a double count. The receipt marks its weighted sums (household_design_weights_applied, ACS design weights before pooling) and measures passive draws left on discarded rows whose S-corp income is nonzero, which no gate clause can see. The flag-on contract block binds the roles, role decoding, refusals and receipt. New tests pin the off-flag contract digests to main's values and the flag-on declared-plan digest; each new behavior has a test that fails on the previous head. acs_transfer.py is attested, so the US spec-engine pins are repinned. Co-Authored-By: Claude Opus 5.5 --- ...acs-semp-partnership-double-count.fixed.md | 2 +- docs/evidence/spec-engine/us-f0-coverage.json | 16 +- .../build/spec_engine/inventory_coverage.py | 4 +- .../microcosm/build/us_runtime/acs_inputs.py | 73 ++++- .../build/us_runtime/acs_transfer.py | 279 ++++++++++++++--- .../shared/test_spec_engine_loader.py | 2 +- .../us/test_us_acs_local_release_tool.py | 21 ++ .../us/test_us_acs_semp_partnership.py | 294 +++++++++++++++++- .../us/test_us_multispine_pool_tool.py | 2 +- tools/build_us_acs_local_release.py | 28 +- 10 files changed, 635 insertions(+), 86 deletions(-) diff --git a/changelog.d/1387-acs-semp-partnership-double-count.fixed.md b/changelog.d/1387-acs-semp-partnership-double-count.fixed.md index c79ac24ccd..70e2a8f479 100644 --- a/changelog.d/1387-acs-semp-partnership-double-count.fixed.md +++ b/changelog.d/1387-acs-semp-partnership-double-count.fixed.md @@ -1 +1 @@ -The ACS local lane no longer counts a respondent's partnership income twice (microcosm#1387). ACS SEMP already includes income from one's own partnership, and the 2024 ACS form tells respondents to report jointly received income wholly under one person, yet the transfer drew the PUF donor's nonpassive `partnership_income` onto those rows. A new keyword-only `semp_covers_partnership_income` on `transfer_acs_inputs`, `acs_transfer_execution_contract_identity` and `build_optional_acs_multispine` (off by default; only the legacy ACS base builder turns it on) keeps a newly drawn `partnership_income` at zero on rows with a finite nonzero SEMP, on tax-unit heads and spouses whose head or spouse reports one, and on rows with blank SEMP, before the passive partnership/S-corp subset is reconciled to line 32. `s_corp_income` is kept: ACS counts incorporated owners as wage workers. The rule refuses a plan that transfers `partnership_income` without `s_corp_income`, a recipient without `SEMP`, `person_tax_unit_id` or `tax_unit_role_input` (before any fit), and a tax-unit role outside HEAD/SPOUSE/DEPENDENT. The partnership provenance record carries a receipt: per row set, the cells kept at zero, the nonzero draws discarded, and the discarded draws in whole dollars, unweighted and household-weighted. Off the flag every contract payload and draw is unchanged; the US spec-engine attestation pins move because `acs_transfer.py` is an attested kernel module. The `acs_self_employment_identity` gate now also requires `partnership_income` to be zero on those three row sets, the passive subset to be zero wherever the person's or tax unit's line 32 is zero, finite line-32 values and well-formed tax-unit roles, and it needs the line-32, tax-unit and role columns. The gate is not behind the flag, so ACS local staging and calibrated checkpoints built before this fix fail materialize, consumer export and package and must be rebuilt. +The ACS local lane no longer counts a respondent's partnership income twice (microcosm#1387). ACS SEMP already includes income from one's own partnership, and the 2024 ACS form tells respondents to report jointly received income wholly under one person, yet the transfer drew the PUF donor's nonpassive `partnership_income` onto those rows. A new keyword-only `semp_covers_partnership_income` on `transfer_acs_inputs`, `acs_transfer_execution_contract_identity` and `build_optional_acs_multispine` (off by default; only the legacy ACS base builder turns it on) keeps a newly drawn `partnership_income` at zero on rows with a finite nonzero SEMP, on tax-unit heads and spouses whose head or spouse reports one, and on rows with blank SEMP, before the passive partnership/S-corp subset is reconciled to line 32. `s_corp_income` is kept: ACS counts incorporated owners as wage workers. The rule refuses, before any fit, a plan that transfers `partnership_income` without `s_corp_income`, a recipient without `SEMP`, `person_tax_unit_id` or `tax_unit_role_input`, a `SEMP` value that is not a number, a recipient whose persons aged 15 or over all have blank `SEMP` (an extract that lost it), and a tax-unit role outside HEAD/SPOUSE/DEPENDENT, including non-ASCII lookalikes and undecodable bytes. An imputation mask that is not a boolean array on the person rows is refused. The partnership provenance record carries a receipt: per row set, the cells kept at zero, the nonzero draws discarded, and the discarded draws in whole dollars, unweighted and weighted by ACS household design weights; the count of persons aged 15 or over with blank `SEMP` and under 15 with a finite one; and the passive draws left on discarded rows whose S-corp income is nonzero, which the gate cannot see. Off the flag every contract payload and draw is unchanged; the US spec-engine attestation pins move because `acs_transfer.py` is an attested kernel module. The `acs_self_employment_identity` gate now also requires `partnership_income` to be zero on those three row sets, the passive subset to be zero wherever the person's or tax unit's line 32 is zero, finite line-32 values, numeric `SEMP` and well-formed tax-unit roles, and it needs the line-32, tax-unit and role columns. A blank `partnership_income` on those rows fails as an unmodeled cell, apart from the double-count clauses, and the gate records `SEMP` against the income universe's age. The release tool names a rebuild only when a failure is a double count. The gate is not behind the flag, so ACS local staging and calibrated checkpoints built before this fix fail materialize, consumer export and package and must be rebuilt. diff --git a/docs/evidence/spec-engine/us-f0-coverage.json b/docs/evidence/spec-engine/us-f0-coverage.json index 019061e72a..877aff5fa8 100644 --- a/docs/evidence/spec-engine/us-f0-coverage.json +++ b/docs/evidence/spec-engine/us-f0-coverage.json @@ -1642,13 +1642,13 @@ "compiler_ir.node_slices" ], "expected": { - "map_sha256": "dc4e5675d73adb4ac385a86e9f8bd4dafbd6cf3f7adffaf570fd27932bd5361b", - "protocol_sha256": "deaa56165bd46eb61b814abed73e9033d761db20a2aa4ea01337c43a5c76be69" + "map_sha256": "20304ea60c343b1d91a472a252f54c5a8aea64323b003f89391c11431eeaee87", + "protocol_sha256": "eb35a3afd7df7121fa858866180d2ec3b4334e5552f0a9c8ea62fd53e611305c" }, "failures": [], "observed": { - "map_sha256": "dc4e5675d73adb4ac385a86e9f8bd4dafbd6cf3f7adffaf570fd27932bd5361b", - "protocol_sha256": "deaa56165bd46eb61b814abed73e9033d761db20a2aa4ea01337c43a5c76be69" + "map_sha256": "20304ea60c343b1d91a472a252f54c5a8aea64323b003f89391c11431eeaee87", + "protocol_sha256": "eb35a3afd7df7121fa858866180d2ec3b4334e5552f0a9c8ea62fd53e611305c" }, "status": "covered" }, @@ -1663,7 +1663,7 @@ "compiler_ir.seed_stream_map" ], "expected": { - "implementation_sha256": "deaa56165bd46eb61b814abed73e9033d761db20a2aa4ea01337c43a5c76be69", + "implementation_sha256": "eb35a3afd7df7121fa858866180d2ec3b4334e5552f0a9c8ea62fd53e611305c", "protocol": "legacy-v1", "streams": [ "build_model", @@ -1684,7 +1684,7 @@ }, "failures": [], "observed": { - "implementation_sha256": "deaa56165bd46eb61b814abed73e9033d761db20a2aa4ea01337c43a5c76be69", + "implementation_sha256": "eb35a3afd7df7121fa858866180d2ec3b4334e5552f0a9c8ea62fd53e611305c", "protocol": "legacy-v1", "streams": [ "build_model", @@ -2585,7 +2585,7 @@ "country": "us", "schema_id": "country_spec", "schema_version": 1, - "spec_sha256": "3c21db4468d0c92f91cc03a21c8afa7dedf21863fa0cef0429238ee63d7d4896" + "spec_sha256": "34cee3b7498a41d0e1b3eb08c65bf84a312cf37942af8aa50ea0cc7a901cb06c" } }, "report_schema_version": 3, @@ -2595,7 +2595,7 @@ "country": "us", "schema_id": "country_spec", "schema_version": 1, - "spec_sha256": "3c21db4468d0c92f91cc03a21c8afa7dedf21863fa0cef0429238ee63d7d4896" + "spec_sha256": "34cee3b7498a41d0e1b3eb08c65bf84a312cf37942af8aa50ea0cc7a901cb06c" }, "status": "pass" } diff --git a/packages/microcosm-build/src/microcosm/build/spec_engine/inventory_coverage.py b/packages/microcosm-build/src/microcosm/build/spec_engine/inventory_coverage.py index ceab6cbfd2..b4dea66eb3 100644 --- a/packages/microcosm-build/src/microcosm/build/spec_engine/inventory_coverage.py +++ b/packages/microcosm-build/src/microcosm/build/spec_engine/inventory_coverage.py @@ -392,8 +392,8 @@ # microcosm#1387 moves both again: the ACS transfer's opt-in SEMP-covered # partnership step changes acs_transfer's attested bytes. Off its flag no # draw, RNG rule or QRF target changes. - "seed_map": "dc4e5675d73adb4ac385a86e9f8bd4dafbd6cf3f7adffaf570fd27932bd5361b", - "seed_protocol": "deaa56165bd46eb61b814abed73e9033d761db20a2aa4ea01337c43a5c76be69", + "seed_map": "20304ea60c343b1d91a472a252f54c5a8aea64323b003f89391c11431eeaee87", + "seed_protocol": "eb35a3afd7df7121fa858866180d2ec3b4334e5552f0a9c8ea62fd53e611305c", "source_manifest": "dc3879886d2a69f20fb982a675d7fb322c0e4017afef6471be54b0ee3cbd2af6", "take_up": "9522ce40f7dea569312dd7a7beb474e5a5afadd2f1e10cb5876534c3ef623d35", "tail": "565f0ceeadab69d3e96a886a00dd0305f7425fa3acde24d12ba48db2b37d5fc0", diff --git a/packages/microcosm-build/src/microcosm/build/us_runtime/acs_inputs.py b/packages/microcosm-build/src/microcosm/build/us_runtime/acs_inputs.py index 59a7cb6824..29f828555a 100644 --- a/packages/microcosm-build/src/microcosm/build/us_runtime/acs_inputs.py +++ b/packages/microcosm-build/src/microcosm/build/us_runtime/acs_inputs.py @@ -25,6 +25,8 @@ from microcosm.build.us_runtime.acs_transfer import ( ACS_SELF_EMPLOYMENT_COMPONENT_INPUTS, ACS_TAX_UNIT_ROLES, + acs_semp_age_counts, + acs_semp_values, acs_tax_unit_head_or_spouse, ) from microcosm.build.us_runtime.spm_role_source import ( @@ -718,8 +720,21 @@ def acs_self_employment_identity_gate( wherever the person's or the tax unit's line 32 (partnership plus S-corp income) is zero, and an infinite line-32 or passive value fails. A tax-unit role outside HEAD/SPOUSE/DEPENDENT, or a missing role on a row - with a tax unit, fails rather than exempting its unit. Every column the - gate reads must be present; none is read as zero. + with a tax unit, fails rather than exempting its unit. A blank + ``partnership_income`` on one of those rows fails on its own, as an + unmodeled cell rather than a double count. Every column the gate reads + must be present; none is read as zero. + + ``SEMP`` must be a number or blank: a value that does not parse fails + rather than being read as blank. With an ``age`` column, the gate + records how many persons aged 15 or over have blank SEMP and how many + under 15 have a finite one (real PUMS has neither: SEMP is asked from + age 15), and fails when every person aged 15 or over has blank SEMP, + which means the extract lost it. Tax units are grouped within the + selected rows, so select whole tax units. The gate cannot see passive + income left on a row whose partnership draw the transfer discarded while + its S-corp income is nonzero; the transfer's receipt measures that + (``passive_kept_on_discarded_rows``). """ name = "acs_self_employment_identity" @@ -754,7 +769,8 @@ def numeric(column: str) -> np.ndarray: dtype=np.float64, na_value=np.nan ) - semp = numeric("SEMP") + semp, non_numeric_semp = acs_semp_values(subset["SEMP"]) + semp_age = acs_semp_age_counts(subset, semp) adjinc = numeric("ADJINC") leaves = np.column_stack([numeric(column) for column in _SELF_EMPLOYMENT_LEAVES]) reported = np.isfinite(semp) @@ -784,6 +800,9 @@ def numeric(column: str) -> np.ndarray: s_corp = numeric(_S_CORP) passive = numeric(_PASSIVE) partnership_zero = np.isfinite(partnership) & (partnership == 0.0) + # A blank cell is unmodeled, not a double count: it fails on its own below. + partnership_blank = np.isnan(partnership) + partnership_nonzero = ~partnership_zero & ~partnership_blank own_semp = np.isfinite(semp) & (semp != 0.0) units = subset[_TAX_UNIT] head_or_spouse, malformed_role = acs_tax_unit_head_or_spouse( @@ -797,11 +816,13 @@ def numeric(column: str) -> np.ndarray: .fillna(False) .to_numpy(dtype=bool) ) - partnership_on_semp = own_semp & ~partnership_zero - partnership_on_spouse = ( - head_or_spouse & unit_reports & ~own_semp & ~blank_semp & ~partnership_zero + covered_spouse = head_or_spouse & unit_reports & ~own_semp & ~blank_semp + partnership_on_semp = own_semp & partnership_nonzero + partnership_on_spouse = covered_spouse & partnership_nonzero + partnership_on_blank = blank_semp & partnership_nonzero + partnership_blank_on_covered = partnership_blank & ( + own_semp | covered_spouse | blank_semp ) - partnership_on_blank = blank_semp & ~partnership_zero line_32_values = np.column_stack([partnership, s_corp, passive]) infinite_line_32 = np.isinf(line_32_values).any(axis=1) person_line_32 = pd.Series( @@ -848,20 +869,41 @@ def numeric(column: str) -> np.ndarray: if partnership_on_semp.any(): failures.append( f"{int(partnership_on_semp.sum())} ACS person row(s) reporting a " - "nonzero SEMP carry partnership_income that is not exactly zero; " - "ACS SEMP already includes own-partnership income." + "nonzero SEMP carry nonzero partnership_income; ACS SEMP already " + "includes own-partnership income." ) if partnership_on_spouse.any(): failures.append( f"{int(partnership_on_spouse.sum())} ACS tax-unit head or spouse " - "row(s) carry partnership_income that is not exactly zero while " - "their tax unit's head or spouse reports a nonzero SEMP, which " - "may hold the couple's jointly received partnership income." + "row(s) carry nonzero partnership_income while their tax unit's " + "head or spouse reports a nonzero SEMP, which may hold the couple's " + "jointly received partnership income." ) if partnership_on_blank.any(): failures.append( f"{int(partnership_on_blank.sum())} ACS person row(s) with blank " - "SEMP carry partnership_income that is not exactly zero." + "SEMP carry nonzero partnership_income." + ) + if partnership_blank_on_covered.any(): + failures.append( + f"{int(partnership_blank_on_covered.sum())} ACS person row(s) where " + "SEMP covers partnership income have a blank partnership_income; " + "the cell was never modeled." + ) + if non_numeric_semp.any(): + failures.append( + f"{int(non_numeric_semp.sum())} ACS person row(s) have a SEMP that " + "is not a number." + ) + if ( + semp_age is not None + and semp_age["persons_aged_15_plus"] > 0 + and semp_age["blank_semp_age_15_plus_rows"] == semp_age["persons_aged_15_plus"] + ): + failures.append( + "SEMP is blank on every one of the " + f"{semp_age['persons_aged_15_plus']} ACS person row(s) aged 15 or " + "over; the extract has lost SEMP." ) if passive_without_line_32.any(): failures.append( @@ -922,6 +964,11 @@ def numeric(column: str) -> np.ndarray: ), "partnership_on_spouse_rows": int(partnership_on_spouse.sum()), "partnership_on_blank_semp_rows": int(partnership_on_blank.sum()), + "partnership_blank_on_covered_rows": int( + partnership_blank_on_covered.sum() + ), + "non_numeric_semp_rows": int(non_numeric_semp.sum()), + "semp_age": semp_age, "passive_without_line_32_rows": int(passive_without_line_32.sum()), "infinite_line_32_rows": int(infinite_line_32.sum()), "malformed_tax_unit_role_rows": int(malformed_role.sum()), diff --git a/packages/microcosm-build/src/microcosm/build/us_runtime/acs_transfer.py b/packages/microcosm-build/src/microcosm/build/us_runtime/acs_transfer.py index 4a464141a4..8363e318f6 100644 --- a/packages/microcosm-build/src/microcosm/build/us_runtime/acs_transfer.py +++ b/packages/microcosm-build/src/microcosm/build/us_runtime/acs_transfer.py @@ -72,6 +72,9 @@ "acs_transfer_donor_requirements", "acs_transfer_execution_contract_identity", "acs_adult_care_qualifying_rows", + "ACS_INCOME_UNIVERSE_MIN_AGE", + "acs_semp_age_counts", + "acs_semp_values", "acs_tax_unit_head_or_spouse", "assert_acs_transfer_targets_are_input_leaves", "declared_acs_transfer_target_families", @@ -535,6 +538,15 @@ def acs_transfer_execution_contract_identity( "operation": "set_to_zero", "order": "before_passive_partnership_s_corp", "mutable_rows": ("newly_imputed_cells_where_recipient_total_not_imputed"), + "tax_unit_roles": list(ACS_TAX_UNIT_ROLES), + "role_decoding": "utf8_replace_then_ascii_upper", + "refuse": [ + "missing_column", + "malformed_tax_unit_role", + "non_numeric_semp", + "semp_blank_on_every_person_aged_15_plus", + ], + "receipt": "discarded_draws_unweighted_and_household_weighted", } payload["sha256"] = hashlib.sha256( json.dumps( @@ -890,23 +902,38 @@ def acs_tax_unit_head_or_spouse( ) -> tuple[np.ndarray, np.ndarray]: """Return ``(head_or_spouse, malformed)`` masks for tax-unit roles. - Bytes decode and case folds to upper, as the PUF tax-unit demographics - read roles. ``malformed`` marks a role outside HEAD/SPOUSE/DEPENDENT and a + Bytes decode as UTF-8 (an undecodable byte becomes U+FFFD) and ASCII + roles fold to upper case, as the PUF tax-unit demographics read roles. + ``malformed`` marks a role outside HEAD/SPOUSE/DEPENDENT, a non-ASCII + role (so a lookalike such as ``"ſpouſe"`` is not read as SPOUSE) and a missing role on a row that has a tax unit. The SEMP-covered partnership rule and its gate refuse those rows rather than read them as neither head nor spouse, which would skip their tax unit silently (microcosm#1387). """ decoded = ( - roles.map(lambda value: value.decode() if isinstance(value, bytes) else value) + roles.map( + lambda value: ( + value.decode("utf-8", errors="replace") + if isinstance(value, bytes) + else value + ) + ) .astype("object") .astype("string") - .str.upper() ) + ascii_only = ( + decoded.map(lambda value: value.isascii(), na_action="ignore") + .astype("boolean") + .to_numpy(dtype=bool, na_value=False) + ) + decoded = decoded.str.upper() present = decoded.notna().to_numpy(dtype=bool) - known = decoded.isin(ACS_TAX_UNIT_ROLES).to_numpy(dtype=bool, na_value=False) + known = ascii_only & decoded.isin(ACS_TAX_UNIT_ROLES).to_numpy( + dtype=bool, na_value=False + ) has_unit = units.notna().to_numpy(dtype=bool) - head_or_spouse = decoded.isin(("HEAD", "SPOUSE")).to_numpy( + head_or_spouse = known & decoded.isin(("HEAD", "SPOUSE")).to_numpy( dtype=bool, na_value=False ) malformed = (present & ~known) | (~present & has_unit) @@ -922,6 +949,105 @@ def _require_semp_covered_columns(columns: Sequence[str]) -> None: ) +#: ACS asks the income questions of people aged 15 and over; SEMP is blank +#: below that age (2024 ACS PUMS data dictionary). +ACS_INCOME_UNIVERSE_MIN_AGE = 15 + + +def acs_semp_values(semp: pd.Series) -> tuple[np.ndarray, np.ndarray]: + """Return ``(values, non_numeric)`` for an ACS ``SEMP`` column. + + ``values`` is float64 with blank cells as NaN. ``non_numeric`` marks a + cell that holds something (text, a blank string) that does not parse as + a number; reading it as blank would put the row outside the income + universe and zero its partnership draw silently (microcosm#1387). + """ + + values = pd.to_numeric(semp, errors="coerce").to_numpy( + dtype=np.float64, na_value=np.nan + ) + non_numeric = semp.notna().to_numpy(dtype=bool) & np.isnan(values) + return values, non_numeric + + +def acs_semp_age_counts( + person: pd.DataFrame, semp: np.ndarray +) -> dict[str, int] | None: + """Count SEMP cells that disagree with the ACS income universe's age. + + Returns ``None`` without an ``age`` column. ``blank_semp_age_15_plus_rows`` + counts blank SEMP at age 15 or over and ``finite_semp_under_15_rows`` + finite SEMP below it; real PUMS has neither, and + ``persons_aged_15_plus`` is the denominator. + """ + + if "age" not in person.columns: + return None + age = pd.to_numeric(person["age"], errors="coerce").to_numpy( + dtype=np.float64, na_value=np.nan + ) + adult = age >= ACS_INCOME_UNIVERSE_MIN_AGE + child = age < ACS_INCOME_UNIVERSE_MIN_AGE + return { + "persons_aged_15_plus": int(adult.sum()), + "blank_semp_age_15_plus_rows": int((adult & np.isnan(semp)).sum()), + "finite_semp_under_15_rows": int((child & np.isfinite(semp)).sum()), + } + + +def _check_semp_covered_inputs( + person: pd.DataFrame, +) -> tuple[np.ndarray, np.ndarray, dict[str, int] | None]: + """Refuse inputs the SEMP-covered partnership rule cannot read honestly. + + Returns ``(semp, head_or_spouse, age_counts)``. Refuses a missing column, + a malformed tax-unit role, a ``SEMP`` cell that is not a number, and a + frame with an ``age`` column in which every person aged 15 or over has + blank ``SEMP`` (an extract that lost SEMP would otherwise zero every + partnership draw as outside the income universe). Partial disagreement + with the income universe's age is counted, not refused. + """ + + _require_semp_covered_columns(person.columns) + semp, non_numeric = acs_semp_values(person[_ACS_SEMP]) + if non_numeric.any(): + examples = sorted( + {repr(value) for value in person[_ACS_SEMP].to_numpy()[non_numeric]} + )[:5] + raise ValueError( + f"The SEMP-covered partnership rule found {int(non_numeric.sum())} " + f"SEMP value(s) that are not numbers (examples {examples}); " + "refusing to read them as blank." + ) + head_or_spouse, malformed = acs_tax_unit_head_or_spouse( + person[_ADULT_CARE_ROLE], person[_ADULT_CARE_UNIT] + ) + if malformed.any(): + examples = sorted( + {str(value) for value in person[_ADULT_CARE_ROLE].to_numpy()[malformed]} + )[:5] + raise ValueError( + "The SEMP-covered partnership rule found " + f"{int(malformed.sum())} person row(s) whose tax_unit_role_input is " + f"not one of {list(ACS_TAX_UNIT_ROLES)} (examples {examples}); " + "refusing to read them as neither head nor spouse." + ) + age_counts = acs_semp_age_counts(person, semp) + if ( + age_counts is not None + and age_counts["persons_aged_15_plus"] > 0 + and age_counts["blank_semp_age_15_plus_rows"] + == age_counts["persons_aged_15_plus"] + ): + raise ValueError( + "SEMP is blank on every one of the " + f"{age_counts['persons_aged_15_plus']} person row(s) aged 15 or " + "over; the ACS extract has lost SEMP, and the SEMP-covered " + "partnership rule would zero every partnership draw." + ) + return semp, head_or_spouse, age_counts + + def _acs_person_design_weights(recipient: Frame) -> np.ndarray | None: """Return each person's household design weight, or None without one. @@ -1779,10 +1905,8 @@ def transfer_acs_inputs( for entity, _family, targets in active ): # Before any fit: partnership_income has cells to draw, so the rule - # will need these columns. - _require_semp_covered_columns( - recipient.table(recipient.schema.person_entity).columns - ) + # will need these columns, numeric SEMP and well-formed roles. + _check_semp_covered_inputs(recipient.table(recipient.schema.person_entity)) if selected_regime_evidence: requested_families = { (entity, family): targets for entity, family, targets in requested @@ -2220,17 +2344,14 @@ def _apply_post_transfer_structure( # microcosm#1387: before the passive block, so a partnership draw this # step zeroes also clears the passive subset that rested on it. semp_contract = post_transfer_contract.get("semp_covered_partnership_income") + semp_counts: dict[str, int] | None = None + semp_discarded = np.zeros(len(person), dtype=bool) if isinstance(semp_contract, Mapping) and semp_contract["enabled"] is True: - semp_counts = keep_semp_covered_partnership_income( + semp_counts, semp_discarded = _keep_semp_covered_partnership_income( person, imputed_masks=imputed_masks, person_weights=person_weights, ) - if semp_counts is not None: - for index, item in enumerate(provenance): - if item.column == _SEMP_COVERED_PARTNERSHIP and item.entity == "person": - provenance[index] = replace(item, reconciliation=semp_counts) - break passive_contract = post_transfer_contract.get("passive_partnership_s_corp") passive_mask = imputed_masks.get(("person", _PASSIVE_PARTNERSHIP_S_CORP)) @@ -2250,6 +2371,20 @@ def _apply_post_transfer_structure( provenance[index] = replace(item, reconciliation=counts) break + if semp_counts is not None: + # The passive step clears passive only where line 32 is zero. A row + # whose partnership draw the SEMP rule discarded but whose S-corp + # income is nonzero keeps a passive draw that was made jointly with + # the discarded partnership value; the identity gate cannot see it, + # so the receipt measures it (microcosm#1387). + semp_counts.update( + _passive_kept_on_discarded_rows(person, semp_discarded, person_weights) + ) + for index, item in enumerate(provenance): + if item.column == _SEMP_COVERED_PARTNERSHIP and item.entity == "person": + provenance[index] = replace(item, reconciliation=semp_counts) + break + component_contract = post_transfer_contract["self_employment_components"] assert isinstance(component_contract, Mapping) if component_contract["enabled"] is True: @@ -2263,6 +2398,30 @@ def _apply_post_transfer_structure( provenance[index] = replace(item, reconciliation=counts) +def _passive_kept_on_discarded_rows( + person: pd.DataFrame, + discarded: np.ndarray, + person_weights: np.ndarray | None, +) -> dict[str, int]: + """Measure passive income left on rows whose partnership draw was discarded.""" + + if _PASSIVE_PARTNERSHIP_S_CORP not in person.columns: + return {} + passive = pd.to_numeric( + person[_PASSIVE_PARTNERSHIP_S_CORP], errors="coerce" + ).to_numpy(dtype=np.float64, na_value=np.nan) + kept = discarded & np.isfinite(passive) & (passive != 0.0) + counts = { + "passive_kept_on_discarded_rows": int(kept.sum()), + "passive_kept_on_discarded_rows_dollars": int(np.round(passive[kept].sum())), + } + if person_weights is not None: + counts["passive_kept_on_discarded_rows_household_weighted_dollars"] = int( + np.round((passive[kept] * person_weights[kept]).sum()) + ) + return counts + + def keep_measured_self_employment_totals( person: pd.DataFrame, *, @@ -2329,28 +2488,16 @@ def semp_covered_partnership_cells(person: pd.DataFrame) -> dict[str, np.ndarray The masks are disjoint. A missing ``SEMP``, ``person_tax_unit_id`` or ``tax_unit_role_input`` column raises ``ValueError``: none is read as zero. So does a role outside HEAD/SPOUSE/DEPENDENT, or a missing role on a row - with a tax unit (:func:`acs_tax_unit_head_or_spouse`). + with a tax unit (:func:`acs_tax_unit_head_or_spouse`), a ``SEMP`` value + that is not a number, and blank ``SEMP`` on every person aged 15 or over + (:func:`_check_semp_covered_inputs`). An infinite ``SEMP`` is in none of + the sets; the identity gate refuses it. Tax-unit rows are grouped over + the whole frame, so pass whole tax units. """ - _require_semp_covered_columns(person.columns) - semp = pd.to_numeric(person[_ACS_SEMP], errors="coerce").to_numpy( - dtype=np.float64, na_value=np.nan - ) + semp, head_or_spouse, _age_counts = _check_semp_covered_inputs(person) own = np.isfinite(semp) & (semp != 0.0) blank = np.isnan(semp) - head_or_spouse, malformed = acs_tax_unit_head_or_spouse( - person[_ADULT_CARE_ROLE], person[_ADULT_CARE_UNIT] - ) - if malformed.any(): - examples = sorted( - {str(value) for value in person[_ADULT_CARE_ROLE].to_numpy()[malformed]} - )[:5] - raise ValueError( - "The SEMP-covered partnership rule found " - f"{int(malformed.sum())} person row(s) whose tax_unit_role_input is " - f"not one of {list(ACS_TAX_UNIT_ROLES)} (examples {examples}); " - "refusing to read them as neither head nor spouse." - ) reporter = pd.Series(own & head_or_spouse, index=person.index) # A row without a tax unit has no spouse to extend from. unit_reports = ( @@ -2367,6 +2514,17 @@ def semp_covered_partnership_cells(person: pd.DataFrame) -> dict[str, np.ndarray } +def _aligned_bool_mask(mask: object, person: pd.DataFrame, name: str) -> np.ndarray: + if isinstance(mask, pd.Series | pd.Index) and not ( + isinstance(mask, pd.Series) and mask.index.equals(person.index) + ): + raise ValueError(f"{name} must be a boolean array aligned to person.") + values = np.asarray(mask) + if values.dtype != np.bool_ or values.shape != (len(person),): + raise ValueError(f"{name} must be a boolean array aligned to person.") + return values + + def keep_semp_covered_partnership_income( person: pd.DataFrame, *, @@ -2389,32 +2547,51 @@ def keep_semp_covered_partnership_income( and negative parts in whole dollars, unweighted and, when ``person_weights`` is given, weighted by them. The discarded draws never reach the output, so these sums are the only measure of what the rule - removed. + removed. Each sum is rounded on its own, so the per-set sums can differ + from the total by up to a dollar per set. + ``household_design_weights_applied`` is 1 when the weighted sums are + present: they use the ACS household design + weights before pooling, not the staging or calibrated weights. With an + ``age`` column the receipt also counts SEMP cells that disagree with the + income universe's age (:func:`acs_semp_age_counts`). """ + counts, _discarded = _keep_semp_covered_partnership_income( + person, imputed_masks=imputed_masks, person_weights=person_weights + ) + return counts + + +def _keep_semp_covered_partnership_income( + person: pd.DataFrame, + *, + imputed_masks: Mapping[tuple[str, str], np.ndarray], + person_weights: np.ndarray | None = None, +) -> tuple[dict[str, int] | None, np.ndarray]: + """:func:`keep_semp_covered_partnership_income`, plus the discarded rows. + + The second value marks the rows whose nonzero draw the rule discarded. + """ + + nothing = np.zeros(len(person), dtype=bool) drawn = imputed_masks.get(("person", _SEMP_COVERED_PARTNERSHIP)) if drawn is None or _SEMP_COVERED_PARTNERSHIP not in person.columns: - return None - drawn = np.asarray(drawn, dtype=bool) - total_drawn = np.asarray( - imputed_masks.get( - ("person", _SELF_EMPLOYMENT_TOTAL), np.zeros(len(person), bool) - ), - dtype=bool, + return None, nothing + drawn = _aligned_bool_mask(drawn, person, "imputed masks") + total_drawn = _aligned_bool_mask( + imputed_masks.get(("person", _SELF_EMPLOYMENT_TOTAL), nothing), + person, + "imputed masks", ) - if drawn.shape != (len(person),) or total_drawn.shape != (len(person),): - raise ValueError("imputed masks must be aligned to person.") if person_weights is not None: person_weights = np.asarray(person_weights, dtype=np.float64) if person_weights.shape != (len(person),): raise ValueError("person_weights must be aligned to person.") if not drawn.any(): - return None + return None, nothing mutable = drawn & ~total_drawn cells = semp_covered_partnership_cells(person) - semp = pd.to_numeric(person[_ACS_SEMP], errors="coerce").to_numpy( - dtype=np.float64, na_value=np.nan - ) + semp, _non_numeric = acs_semp_values(person[_ACS_SEMP]) values = pd.to_numeric(person[_SEMP_COVERED_PARTNERSHIP], errors="coerce").to_numpy( dtype=np.float64, na_value=np.nan ) @@ -2451,8 +2628,12 @@ def dollars(prefix: str, rows: np.ndarray, into: dict[str, int]) -> None: counts["cells_kept_at_zero"] = int(covered.sum()) counts["nonzero_draws_discarded"] = int((covered & nonzero).sum()) dollars("", covered, counts) + counts["household_design_weights_applied"] = int(person_weights is not None) + age_counts = acs_semp_age_counts(person, semp) + if age_counts is not None: + counts.update(age_counts) person.loc[covered, _SEMP_COVERED_PARTNERSHIP] = 0.0 - return counts + return counts, covered & nonzero def _model_target_names(targets: Sequence[str]) -> tuple[str, ...]: diff --git a/packages/microcosm-build/tests/engine_free/shared/test_spec_engine_loader.py b/packages/microcosm-build/tests/engine_free/shared/test_spec_engine_loader.py index 538981c4c3..652a5d33fa 100644 --- a/packages/microcosm-build/tests/engine_free/shared/test_spec_engine_loader.py +++ b/packages/microcosm-build/tests/engine_free/shared/test_spec_engine_loader.py @@ -28,7 +28,7 @@ def test_semantic_hash_has_golden_vector_and_surface_separation(tmp_path) -> Non # microcosm#1387's SEMP-covered partnership step moves acs_transfer's # attested bytes. assert first.spec_sha256 == ( - "bf67d5d913958b6b7c7ba81ca6c59fd208ea09f8f9ac9209f2b65218eb4cf09a" + "a68579ad0903aeddb6b628f7cd67bb1345d94fcf31c495270c1e0b2f8154bd5c" ) second_root = _rich_minimal(tmp_path / "xy", note="second", store="local:b") diff --git a/packages/microcosm-build/tests/engine_free/us/test_us_acs_local_release_tool.py b/packages/microcosm-build/tests/engine_free/us/test_us_acs_local_release_tool.py index b50a4293b1..47223d6ed1 100644 --- a/packages/microcosm-build/tests/engine_free/us/test_us_acs_local_release_tool.py +++ b/packages/microcosm-build/tests/engine_free/us/test_us_acs_local_release_tool.py @@ -1335,6 +1335,27 @@ def test_release_refuses_partnership_income_that_semp_already_holds() -> None: ) +def test_release_names_a_rebuild_only_for_income_counted_twice() -> None: + """A rebuild cures a double count, not an unmodeled cell (microcosm#1387).""" + + module = _load_tool_module() + unmodeled = _self_employment_person(0.0) + # The ACS row that reports SEMP, with its partnership cell left blank. + unmodeled.loc[1, "partnership_income"] = np.nan + + with pytest.raises(SystemExit) as refused: + module._require_acs_self_employment_identity(_SelfEmploymentFrame(unmodeled)) + + assert "never modeled" in str(refused.value) + assert "must be rebuilt" not in str(refused.value) + with pytest.raises(SystemExit, match="must be rebuilt"): + module._require_acs_self_employment_identity( + _SelfEmploymentFrame( + _self_employment_person(0.0, partnership_on_acs_semp=2_500.0) + ) + ) + + def test_release_checks_self_employment_wherever_it_loads_staging() -> None: module = _load_tool_module() diff --git a/packages/microcosm-build/tests/engine_free/us/test_us_acs_semp_partnership.py b/packages/microcosm-build/tests/engine_free/us/test_us_acs_semp_partnership.py index f4e41b8958..bf9736b15b 100644 --- a/packages/microcosm-build/tests/engine_free/us/test_us_acs_semp_partnership.py +++ b/packages/microcosm-build/tests/engine_free/us/test_us_acs_semp_partnership.py @@ -53,6 +53,8 @@ from microcosm.build.us_runtime.acs_transfer import ( ACS_SELF_EMPLOYMENT_COMPONENT_INPUTS, ACS_SEMP_COVERED_LINE_32_INPUTS, + ACS_TAX_UNIT_ROLES, + acs_tax_unit_head_or_spouse, acs_transfer_execution_contract_identity, declared_acs_transfer_target_families, keep_semp_covered_partnership_income, @@ -289,6 +291,27 @@ def test_case_and_bytes_fold_but_an_unknown_role_is_refused() -> None: semp_covered_partnership_cells(malformed) +@pytest.mark.parametrize( + "bad", + ( + "\u017fpou\u017fe", # long s: upper-cases to "SPOUSE" + "\uff28\uff25\uff21\uff24", # full-width HEAD + "HEAD\u200b", # zero-width space + b"SP\xffOUSE", # not UTF-8 + ), +) +def test_a_lookalike_or_undecodable_role_is_refused(bad) -> None: + roles = pd.Series(["HEAD", bad], dtype=object) + + head_or_spouse, malformed = acs_tax_unit_head_or_spouse(roles, pd.Series([1, 1])) + + assert head_or_spouse.tolist() == [True, False] + assert malformed.tolist() == [False, True] + person = pd.DataFrame({"SEMP": [5_000.0, 0.0], _UNIT: [1, 1], _ROLE: roles}) + with pytest.raises(ValueError, match="neither head nor spouse"): + semp_covered_partnership_cells(person) + + def test_a_missing_role_is_allowed_only_without_a_tax_unit() -> None: person = pd.DataFrame( {"SEMP": [5_000.0, 0.0], _UNIT: [1.0, np.nan], _ROLE: ["HEAD", None]} @@ -324,6 +347,12 @@ def test_the_step_does_nothing_when_no_partnership_income_was_drawn() -> None: ( {("person", _P): np.asarray([True, False])}, {("person", _P): np.asarray([True]), ("person", _TOTAL): np.ones(2, bool)}, + # An integer mask would select by label, not by row. + {("person", _P): np.asarray([1])}, + {("person", _P): np.asarray([1.0])}, + # A Series on another index would line up by label, not by row. + {("person", _P): pd.Series([True], index=[5])}, + {("person", _P): pd.Index([True])}, ), ) def test_the_step_refuses_masks_not_aligned_to_person(masks) -> None: @@ -360,6 +389,83 @@ def test_the_receipt_weights_the_discarded_draws() -> None: assert counts["tax_unit_household_weighted_discarded_negative_dollars"] == -600 +def test_the_step_accepts_a_series_mask_on_the_person_index() -> None: + person = pd.DataFrame( + {"SEMP": [500.0, 0.0], _UNIT: [1, 2], _ROLE: ["HEAD", "HEAD"], _P: [7.0, 9.0]}, + index=[40, 41], + ) + + keep_semp_covered_partnership_income( + person, imputed_masks={("person", _P): pd.Series([True, True], index=[40, 41])} + ) + + assert person[_P].tolist() == [0.0, 9.0] + + +@pytest.mark.parametrize("bad", ("5000x", "", " ", "NA ")) +def test_the_step_refuses_a_semp_that_is_not_a_number(bad: str) -> None: + person = pd.DataFrame( + { + "SEMP": pd.Series([500.0, bad], dtype=object), + _UNIT: [1, 2], + _ROLE: ["HEAD", "HEAD"], + _P: [7.0, 9.0], + } + ) + + with pytest.raises(ValueError, match="not numbers"): + keep_semp_covered_partnership_income( + person, imputed_masks={("person", _P): np.ones(2, dtype=bool)} + ) + assert person[_P].tolist() == [7.0, 9.0] + + +def test_the_step_refuses_an_extract_that_lost_semp() -> None: + person = pd.DataFrame( + { + "SEMP": [np.nan, np.nan, np.nan], + "age": [40.0, 38.0, 9.0], + _UNIT: [1, 1, 1], + _ROLE: ["HEAD", "SPOUSE", "DEPENDENT"], + _P: [7.0, 9.0, 0.0], + } + ) + + with pytest.raises(ValueError, match="lost SEMP"): + keep_semp_covered_partnership_income( + person, imputed_masks={("person", _P): np.ones(3, dtype=bool)} + ) + assert person[_P].tolist() == [7.0, 9.0, 0.0] + + +def test_the_receipt_counts_semp_that_disagrees_with_the_income_universe_age() -> None: + person = pd.DataFrame( + { + "SEMP": [500.0, np.nan, 0.0, 200.0, np.nan], + "age": [40.0, 30.0, 70.0, 12.0, 3.0], + _UNIT: [1, 2, 3, 4, 5], + _ROLE: ["HEAD"] * 5, + _P: [7.0, 9.0, 3.0, 4.0, 0.0], + } + ) + masks = {("person", _P): np.ones(5, dtype=bool)} + + counts = keep_semp_covered_partnership_income(person.copy(), imputed_masks=masks) + without_age = keep_semp_covered_partnership_income( + person.drop(columns=["age"]), imputed_masks=masks + ) + + assert counts is not None and without_age is not None + assert counts["persons_aged_15_plus"] == 3 + assert counts["blank_semp_age_15_plus_rows"] == 1 + assert counts["finite_semp_under_15_rows"] == 1 + assert counts["household_design_weights_applied"] == 0 + assert not any( + key.startswith(("persons_aged", "blank_semp_age", "finite_semp")) + for key in without_age + ) + + @pytest.mark.parametrize("column", ("SEMP", _UNIT, _ROLE)) def test_the_step_refuses_a_recipient_missing_a_column_it_reads(column: str) -> None: person = pd.DataFrame( @@ -405,7 +511,10 @@ def _gate_tables(draw): def _oracle_gate_counts(person: pd.DataFrame) -> dict[str, int]: sets = _oracle_sets(person) partnership = person[_P].to_numpy(dtype=float) - not_zero = ~(np.isfinite(partnership) & (partnership == 0.0)) + # A blank cell is unmodeled, counted on its own, not as a double count. + not_zero = np.isfinite(partnership) & (partnership != 0.0) + blank = np.isnan(partnership) + covered = sets["own_semp"] | sets["tax_unit"] | sets["blank_semp"] line_32 = (person[_P].fillna(0.0) + person[_S].fillna(0.0)).to_numpy() units = person[_UNIT].tolist() unit_line_32 = { @@ -427,6 +536,7 @@ def _oracle_gate_counts(person: pd.DataFrame) -> dict[str, int]: "partnership_on_spouse_rows": int((sets["tax_unit"] & not_zero).sum()), "partnership_on_blank_semp_rows": int((sets["blank_semp"] & not_zero).sum()), "passive_without_line_32_rows": int((no_line_32 & (passive != 0.0)).sum()), + "partnership_blank_on_covered_rows": int((covered & blank).sum()), } @@ -521,8 +631,9 @@ def test_the_gate_reads_a_tax_unit_whose_line_32_cancels_as_zero(index) -> None: @pytest.mark.parametrize( ("values", "violations"), ( - # NaN partnership income on a SEMP row is not a finite zero. - ({"SEMP": [5_000.0], _P: [np.nan]}, {"partnership_on_semp_rows": 1}), + # NaN partnership income on a SEMP row is not a finite zero: an + # unmodeled cell, reported apart from a double count. + ({"SEMP": [5_000.0], _P: [np.nan]}, {"partnership_blank_on_covered_rows": 1}), # NaN line-32 leaves read as zero under a passive draw. ({_P: [np.nan], _PASSIVE: [300.0]}, {"passive_without_line_32_rows": 1}), # A NaN passive draw is not a passive amount. @@ -534,12 +645,18 @@ def test_the_gate_reads_nan_line_32_leaves(values, violations) -> None: _gate_row(**values), rows=np.ones(1, dtype=bool) ) - for key in ("partnership_on_semp_rows", "passive_without_line_32_rows"): + for key in ( + "partnership_on_semp_rows", + "partnership_blank_on_covered_rows", + "passive_without_line_32_rows", + ): assert gate.details[key] == violations.get(key, 0), key assert gate.passed is (not violations) -@pytest.mark.parametrize("bad", ("SPOUSE ", "OTHER", 2, None)) +@pytest.mark.parametrize( + "bad", ("SPOUSE ", "OTHER", 2, None, "\u017fpou\u017fe", b"SP\xffOUSE") +) def test_the_gate_fails_a_malformed_role_instead_of_exempting_its_unit(bad) -> None: person = _gate_row( **{"SEMP": [5_000.0, 0.0], _UNIT: [1, 1], _ROLE: ["HEAD", bad], _P: [0.0, 9.0]} @@ -573,6 +690,46 @@ def test_the_gate_leaves_s_corp_income_and_partnership_on_unreported_rows_alone( assert gate.passed, gate.failures +def test_the_gate_fails_a_semp_that_is_not_a_number() -> None: + person = _gate_row(SEMP=[5_000.0, 0.0]) + person["SEMP"] = pd.Series([5_000.0, "5000x"], dtype=object) + + gate = acs_self_employment_identity_gate(person, rows=np.ones(2, dtype=bool)) + + assert not gate.passed + assert gate.details["non_numeric_semp_rows"] == 1 + assert any("not a number" in failure for failure in gate.failures) + + +def test_the_gate_records_semp_against_the_income_universe_age() -> None: + person = _gate_row(SEMP=[5_000.0, np.nan, 0.0, np.nan], age=[40.0, 30.0, 12.0, 6.0]) + + gate = acs_self_employment_identity_gate(person, rows=np.ones(4, dtype=bool)) + + # Partial disagreement is recorded, not failed. + assert gate.passed, gate.failures + assert gate.details["semp_age"] == { + "persons_aged_15_plus": 2, + "blank_semp_age_15_plus_rows": 1, + "finite_semp_under_15_rows": 1, + } + assert ( + acs_self_employment_identity_gate( + person.drop(columns=["age"]), rows=np.ones(4, dtype=bool) + ).details["semp_age"] + is None + ) + + +def test_the_gate_fails_an_extract_that_lost_semp() -> None: + person = _gate_row(SEMP=[np.nan, np.nan], age=[40.0, 9.0]) + + gate = acs_self_employment_identity_gate(person, rows=np.ones(2, dtype=bool)) + + assert not gate.passed + assert any("lost SEMP" in failure for failure in gate.failures) + + @pytest.mark.parametrize("column", (_P, _S, _PASSIVE)) def test_the_gate_refuses_an_infinite_line_32_value(column: str) -> None: person = _gate_row(**{_S: [10.0], column: [np.inf]}) @@ -753,17 +910,39 @@ def test_the_lane_keeps_semp_covered_draws_at_zero_and_passes_the_gate( "discarded_negative_dollars": 0, "household_weighted_discarded_positive_dollars": 48_000, "household_weighted_discarded_negative_dollars": 0, + "household_design_weights_applied": 1, + # The blank-SEMP row is the nine-year-old: inside the ACS universe. + "persons_aged_15_plus": 6, + "blank_semp_age_15_plus_rows": 0, + "finite_semp_under_15_rows": 0, + # No S-corp income, so the passive step cleared every discarded row. + "passive_kept_on_discarded_rows": 0, + "passive_kept_on_discarded_rows_dollars": 0, + "passive_kept_on_discarded_rows_household_weighted_dollars": 0, } def test_the_lane_keeps_s_corp_income_on_every_row(monkeypatch) -> None: - person = _transfer(monkeypatch, lane=True, s_corp=1_000.0).frame.table("person") + result = _transfer(monkeypatch, lane=True, s_corp=1_000.0) + person = result.frame.table("person") assert np.allclose(person[_S], 250.0) assert (person.loc[_COVERED, _P] == 0.0).all() # Line 32 stays nonzero on every row, so every passive draw stands. assert np.allclose(person[_PASSIVE], 100.0) assert _gate(person).passed + # The gate cannot see the passive draws left on the five discarded rows; + # the receipt measures them. Household weights of those rows sum to 24. + receipt = next(item for item in result.imputed_inputs if item.column == _P) + assert receipt.reconciliation is not None + assert receipt.reconciliation["passive_kept_on_discarded_rows"] == 5 + assert receipt.reconciliation["passive_kept_on_discarded_rows_dollars"] == 500 + assert ( + receipt.reconciliation[ + "passive_kept_on_discarded_rows_household_weighted_dollars" + ] + == 2_400 + ) def test_off_the_lane_the_gate_fails_on_exactly_the_covered_rows(monkeypatch) -> None: @@ -831,8 +1010,8 @@ def test_a_step_run_after_the_passive_reconciliation_fails_the_gate( monkeypatch.setattr( acs_transfer_module, - "keep_semp_covered_partnership_income", - lambda person, **_masks_and_weights: None, + "_keep_semp_covered_partnership_income", + lambda person, **_masks_and_weights: (None, np.zeros(len(person), bool)), ) person = _transfer(monkeypatch, lane=True).frame.table("person") person.loc[_COVERED, _P] = 0.0 @@ -854,6 +1033,61 @@ def fit(self, frame, predictors, targets, *, weights): raise AssertionError("the refusal must come before any fit") +@pytest.mark.parametrize( + ("column", "value", "message"), + ( + ("SEMP", "5000x", "not numbers"), + (_ROLE, "\u017fpou\u017fe", "neither head nor spouse"), + ), +) +def test_the_lane_refuses_a_recipient_it_cannot_read_before_any_fit( + monkeypatch, column: str, value: str, message: str +) -> None: + recipient = _recipient() + tables = {name: recipient.table(name) for name in recipient.entities} + person = tables["person"].astype({column: object}) + person.loc[2, column] = value + tables["person"] = person + monkeypatch.setattr(acs_transfer_module, "QRF", _NoFitQRF) + + with pytest.raises(ValueError, match=message): + acs_transfer_module.transfer_acs_inputs( + Frame( + tables, + recipient.schema, + {"household": recipient.weights_for("household")}, + ), + _donor(0.0), + target_families={"person": {"pass_through": _PASS_THROUGH}}, + donor_channel=None, + n_estimators=1, + semp_covers_partnership_income=True, + ) + + +def test_the_lane_refuses_an_extract_that_lost_semp_before_any_fit( + monkeypatch, +) -> None: + recipient = _recipient() + tables = {name: recipient.table(name) for name in recipient.entities} + tables["person"] = tables["person"].assign(SEMP=np.nan) + monkeypatch.setattr(acs_transfer_module, "QRF", _NoFitQRF) + + with pytest.raises(ValueError, match="lost SEMP"): + acs_transfer_module.transfer_acs_inputs( + Frame( + tables, + recipient.schema, + {"household": recipient.weights_for("household")}, + ), + _donor(0.0), + target_families={"person": {"pass_through": _PASS_THROUGH}}, + donor_channel=None, + n_estimators=1, + semp_covers_partnership_income=True, + ) + + @pytest.mark.parametrize("column", ("SEMP", _ROLE)) def test_the_lane_refuses_a_recipient_without_a_column_the_rule_reads( monkeypatch, column: str @@ -900,6 +1134,39 @@ def test_the_contract_is_unchanged_off_the_lane(targets) -> None: ) == acs_transfer_execution_contract_identity(targets=sorted(targets)) +#: Off the lane, anchored to main before microcosm#1387: the declared plan +#: (also pinned in test_us_acs_transfer.py) and the pass-through targets. +_DECLARED_PLAN_CONTRACT_SHA256 = ( + "e90a808a1218681a7084d16807f926d5522717556f2b97708e416082a876e0ca" +) +_PASS_THROUGH_CONTRACT_SHA256 = ( + "5d9c94b6441a510093335ee66ea6006c3105d1c25bde7a55aaf0713852094ecd" +) +#: On the lane, the declared plan. Moving this is a contract change. +_DECLARED_PLAN_LANE_CONTRACT_SHA256 = ( + "77efd0fc5931ab0cdea12bc99c3d4c8627655304ead2fd3f435cbc990039e668" +) + + +def test_the_off_lane_contract_matches_main_and_the_lane_contract_is_pinned() -> None: + identity = acs_transfer_execution_contract_identity + for off in ({}, {"semp_covers_partnership_income": False}): + assert ( + identity(targets=_DECLARED_TARGETS, **off)["sha256"] + == _DECLARED_PLAN_CONTRACT_SHA256 + ) + assert ( + identity(targets=_PASS_THROUGH, **off)["sha256"] + == _PASS_THROUGH_CONTRACT_SHA256 + ) + assert ( + identity(targets=_DECLARED_TARGETS, semp_covers_partnership_income=True)[ + "sha256" + ] + == _DECLARED_PLAN_LANE_CONTRACT_SHA256 + ) + + def test_the_lane_binds_its_rule_into_the_contract() -> None: off = acs_transfer_execution_contract_identity(targets=_PASS_THROUGH) on = acs_transfer_execution_contract_identity( @@ -914,6 +1181,17 @@ def test_the_lane_binds_its_rule_into_the_contract() -> None: assert rule["enabled"] is True assert rule["covered"] == list(ACS_SEMP_COVERED_LINE_32_INPUTS) == [_P] assert rule["order"] == "before_passive_partnership_s_corp" + # The rule's values, not only its labels: the roles it reads, how it + # decodes them, what it refuses and what its receipt holds. + assert rule["tax_unit_roles"] == list(ACS_TAX_UNIT_ROLES) + assert rule["role_decoding"] == "utf8_replace_then_ascii_upper" + assert rule["refuse"] == [ + "missing_column", + "malformed_tax_unit_role", + "non_numeric_semp", + "semp_blank_on_every_person_aged_15_plus", + ] + assert rule["receipt"] == "discarded_draws_unweighted_and_household_weighted" assert on["sha256"] != off["sha256"] assert ( without_partnership["post_transfer_structure"][ diff --git a/packages/microcosm-build/tests/engine_workflow/us/test_us_multispine_pool_tool.py b/packages/microcosm-build/tests/engine_workflow/us/test_us_multispine_pool_tool.py index c5e6cd3071..f96fdbe4f0 100644 --- a/packages/microcosm-build/tests/engine_workflow/us/test_us_multispine_pool_tool.py +++ b/packages/microcosm-build/tests/engine_workflow/us/test_us_multispine_pool_tool.py @@ -357,7 +357,7 @@ def capture_equality(expected: object, actual: object) -> None: # attested bytes. # microcosm#1387's SEMP-covered partnership step moves it through # acs_transfer's attested bytes. - "spec_sha256": "3c21db4468d0c92f91cc03a21c8afa7dedf21863fa0cef0429238ee63d7d4896", + "spec_sha256": "34cee3b7498a41d0e1b3eb08c65bf84a312cf37942af8aa50ea0cc7a901cb06c", }, } diff --git a/tools/build_us_acs_local_release.py b/tools/build_us_acs_local_release.py index b64aad5d02..936118fed7 100644 --- a/tools/build_us_acs_local_release.py +++ b/tools/build_us_acs_local_release.py @@ -5410,16 +5410,38 @@ def _require_acs_self_employment_identity(frame): ), ) if not gate.passed: + double_counted = any( + gate.details.get(key, 0) for key in _SELF_EMPLOYMENT_DOUBLE_COUNT_DETAILS + ) raise SystemExit( "ACS self-employment identity failed: " + "; ".join(gate.failures) - + ". Staging, or a checkpoint calibrated from staging, built before " - "microcosm#1380 or #1387 must be rebuilt with the current ACS base " - "builder." + + ( + ". Staging, or a checkpoint calibrated from staging, built before " + "microcosm#1380 or #1387 must be rebuilt with the current ACS base " + "builder." + if double_counted + else "." + ) ) return gate +#: Gate detail counts that mean income counted twice, which staging built +#: before microcosm#1380 or #1387 carries; other failures (a malformed role, +#: a blank or non-numeric value) need their input fixed, not a rebuild. +_SELF_EMPLOYMENT_DOUBLE_COUNT_DETAILS = ( + "mismatched_rows", + "blank_semp_nonzero_rows", + "non_acs_component_rows", + "base_and_sstb_rows", + "partnership_on_semp_rows", + "partnership_on_spouse_rows", + "partnership_on_blank_semp_rows", + "passive_without_line_32_rows", +) + + def do_finalize(args) -> None: from microcosm.build.us_runtime.hours_worked import ( US_HOURS_WORKED_POOL_OUTPUT_COLUMNS, From 6d18316276ceb58b11ac0350351b70fe9cdb6d23 Mon Sep 17 00:00:00 2001 From: Max Ghenis Date: Sun, 15 Nov 2026 16:09:43 -0500 Subject: [PATCH 3/3] Count only finite line-32 values as double counts; test the edges (#1387) Round-2 review findings on the SEMP-covered partnership rule: - The identity gate counted an infinite partnership_income on a covered row as a double count, and an infinite passive amount on a row with no line 32 likewise, so either named a rebuild. Both clauses now count finite nonzero values only, as the docstring and PR already state; an infinity still fails on its own clause. inf minus inf no longer warns. - New tests: infinities on own-SEMP, spouse, blank-SEMP and no-line-32 rows (gate and release rebuild hint); the age-15 boundary and a children-only frame (step and gate); a zero partnership draw on covered rows beside S-corp and passive income, which is not counted as discarded. The gate's property test now draws infinities. - Each of the six weaknesses (infinite partnership, infinite passive, age > 15, either positive-adult guard removed, covered instead of covered & nonzero) was reapplied by hand and fails a new test. Co-Authored-By: Claude Opus 5.5 --- .../microcosm/build/us_runtime/acs_inputs.py | 24 +-- .../us/test_us_acs_local_release_tool.py | 25 ++- .../us/test_us_acs_semp_partnership.py | 193 ++++++++++++++++-- 3 files changed, 207 insertions(+), 35 deletions(-) diff --git a/packages/microcosm-build/src/microcosm/build/us_runtime/acs_inputs.py b/packages/microcosm-build/src/microcosm/build/us_runtime/acs_inputs.py index 29f828555a..c7feece9df 100644 --- a/packages/microcosm-build/src/microcosm/build/us_runtime/acs_inputs.py +++ b/packages/microcosm-build/src/microcosm/build/us_runtime/acs_inputs.py @@ -799,10 +799,10 @@ def numeric(column: str) -> np.ndarray: partnership = numeric(_PARTNERSHIP) s_corp = numeric(_S_CORP) passive = numeric(_PASSIVE) - partnership_zero = np.isfinite(partnership) & (partnership == 0.0) - # A blank cell is unmodeled, not a double count: it fails on its own below. + # A blank cell is unmodeled and an infinite one is not a dollar amount; + # each fails on its own below, not as a double count. partnership_blank = np.isnan(partnership) - partnership_nonzero = ~partnership_zero & ~partnership_blank + partnership_nonzero = np.isfinite(partnership) & (partnership != 0.0) own_semp = np.isfinite(semp) & (semp != 0.0) units = subset[_TAX_UNIT] head_or_spouse, malformed_role = acs_tax_unit_head_or_spouse( @@ -825,18 +825,18 @@ def numeric(column: str) -> np.ndarray: ) line_32_values = np.column_stack([partnership, s_corp, passive]) infinite_line_32 = np.isinf(line_32_values).any(axis=1) - person_line_32 = pd.Series( - np.where(np.isnan(partnership), 0.0, partnership) - + np.where(np.isnan(s_corp), 0.0, s_corp), - index=subset.index, - ) - unit_line_32 = person_line_32.groupby(units, sort=False).transform("sum") + # Infinite inputs fail on their own clause; inf minus inf is NaN here. + with np.errstate(invalid="ignore"): + person_line_32 = pd.Series( + np.where(np.isnan(partnership), 0.0, partnership) + + np.where(np.isnan(s_corp), 0.0, s_corp), + index=subset.index, + ) + unit_line_32 = person_line_32.groupby(units, sort=False).transform("sum") no_line_32 = (person_line_32 == 0.0).to_numpy() | (unit_line_32 == 0.0).to_numpy( dtype=bool, na_value=False ) - passive_without_line_32 = no_line_32 & ( - np.where(np.isnan(passive), 0.0, passive) != 0.0 - ) + passive_without_line_32 = no_line_32 & np.isfinite(passive) & (passive != 0.0) failures: list[str] = [] if not selected.any(): diff --git a/packages/microcosm-build/tests/engine_free/us/test_us_acs_local_release_tool.py b/packages/microcosm-build/tests/engine_free/us/test_us_acs_local_release_tool.py index 47223d6ed1..e822c0a408 100644 --- a/packages/microcosm-build/tests/engine_free/us/test_us_acs_local_release_tool.py +++ b/packages/microcosm-build/tests/engine_free/us/test_us_acs_local_release_tool.py @@ -1335,18 +1335,29 @@ def test_release_refuses_partnership_income_that_semp_already_holds() -> None: ) -def test_release_names_a_rebuild_only_for_income_counted_twice() -> None: - """A rebuild cures a double count, not an unmodeled cell (microcosm#1387).""" +@pytest.mark.parametrize( + ("partnership", "failure"), + ( + (np.nan, "never modeled"), + (np.inf, "an infinite partnership"), + (-np.inf, "an infinite partnership"), + ), +) +def test_release_names_a_rebuild_only_for_income_counted_twice( + partnership: float, failure: str +) -> None: + """A rebuild cures a double count, not a blank or infinite cell (#1387).""" module = _load_tool_module() - unmodeled = _self_employment_person(0.0) - # The ACS row that reports SEMP, with its partnership cell left blank. - unmodeled.loc[1, "partnership_income"] = np.nan + person = _self_employment_person(0.0) + # The ACS row that reports SEMP: a blank partnership cell is unmodeled and + # an infinite one is not a dollar amount, so neither is counted twice. + person.loc[1, "partnership_income"] = partnership with pytest.raises(SystemExit) as refused: - module._require_acs_self_employment_identity(_SelfEmploymentFrame(unmodeled)) + module._require_acs_self_employment_identity(_SelfEmploymentFrame(person)) - assert "never modeled" in str(refused.value) + assert failure in str(refused.value) assert "must be rebuilt" not in str(refused.value) with pytest.raises(SystemExit, match="must be rebuilt"): module._require_acs_self_employment_identity( diff --git a/packages/microcosm-build/tests/engine_free/us/test_us_acs_semp_partnership.py b/packages/microcosm-build/tests/engine_free/us/test_us_acs_semp_partnership.py index bf9736b15b..c5f0fd197f 100644 --- a/packages/microcosm-build/tests/engine_free/us/test_us_acs_semp_partnership.py +++ b/packages/microcosm-build/tests/engine_free/us/test_us_acs_semp_partnership.py @@ -118,11 +118,13 @@ def _oracle_sets(person: pd.DataFrame) -> dict[str, np.ndarray]: # Whole dollars, so a tax unit's line-32 sum is exact in any order and the # oracle's zero test agrees with the gate's. Zeros, a cancelling pair and NaN # are drawn often, so the passive clause (person and tax-unit line 32) and the -# NaN-as-zero reading are reached. +# NaN-as-zero reading are reached. An infinity fails on its own clause and +# never as a double count. _dollars = st.one_of( st.just(0.0), st.just(np.nan), st.sampled_from([-900.0, 900.0]), + st.sampled_from([-np.inf, np.inf]), st.integers(min_value=-1_000_000, max_value=10_000_000).map(float), ) @@ -466,6 +468,57 @@ def test_the_receipt_counts_semp_that_disagrees_with_the_income_universe_age() - ) +def test_the_income_universe_starts_at_age_15() -> None: + """SEMP is asked from age 15, so a 15-year-old is inside the universe.""" + + masks = {("person", _P): np.ones(2, dtype=bool)} + reporting = pd.DataFrame( + { + "SEMP": [500.0, np.nan], + "age": [15.0, 14.0], + _UNIT: [1, 2], + _ROLE: ["HEAD", "HEAD"], + _P: [7.0, 9.0], + } + ) + + counts = keep_semp_covered_partnership_income(reporting, imputed_masks=masks) + + assert counts is not None + assert counts["persons_aged_15_plus"] == 1 + assert counts["blank_semp_age_15_plus_rows"] == 0 + assert counts["finite_semp_under_15_rows"] == 0 + # The only person aged 15 or over is exactly 15 and has blank SEMP. + lost = reporting.assign(SEMP=[np.nan, np.nan], **{_P: [7.0, 9.0]}) + with pytest.raises(ValueError, match="lost SEMP"): + keep_semp_covered_partnership_income(lost, imputed_masks=masks) + assert lost[_P].tolist() == [7.0, 9.0] + + +def test_the_step_does_not_refuse_a_frame_of_children_only() -> None: + """No one is asked SEMP below 15, so blank SEMP everywhere is expected.""" + + person = pd.DataFrame( + { + "SEMP": [np.nan, np.nan], + "age": [9.0, 3.0], + _UNIT: [1, 1], + _ROLE: ["DEPENDENT", "DEPENDENT"], + _P: [7.0, 0.0], + } + ) + + counts = keep_semp_covered_partnership_income( + person, imputed_masks={("person", _P): np.ones(2, dtype=bool)} + ) + + assert counts is not None + assert counts["persons_aged_15_plus"] == 0 + assert counts["blank_semp_age_15_plus_rows"] == 0 + assert counts["blank_semp_cells"] == 2 + assert person[_P].tolist() == [0.0, 0.0] + + @pytest.mark.parametrize("column", ("SEMP", _UNIT, _ROLE)) def test_the_step_refuses_a_recipient_missing_a_column_it_reads(column: str) -> None: person = pd.DataFrame( @@ -511,20 +564,27 @@ def _gate_tables(draw): def _oracle_gate_counts(person: pd.DataFrame) -> dict[str, int]: sets = _oracle_sets(person) partnership = person[_P].to_numpy(dtype=float) - # A blank cell is unmodeled, counted on its own, not as a double count. + # A blank cell is unmodeled and an infinite one is not a dollar amount; + # each is counted on its own, not as a double count. not_zero = np.isfinite(partnership) & (partnership != 0.0) blank = np.isnan(partnership) covered = sets["own_semp"] | sets["tax_unit"] | sets["blank_semp"] - line_32 = (person[_P].fillna(0.0) + person[_S].fillna(0.0)).to_numpy() units = person[_UNIT].tolist() - unit_line_32 = { - unit: sum( - value for other, value in zip(units, line_32, strict=True) if other == unit - ) - for unit in units - if not pd.isna(unit) - } - passive = person[_PASSIVE].fillna(0.0).to_numpy() + # A person whose line 32 is inf minus inf (NaN) drops out of the tax-unit + # sum, as in a pandas groupby sum; that row fails as infinite regardless. + with np.errstate(invalid="ignore"): + line_32 = (person[_P].fillna(0.0) + person[_S].fillna(0.0)).to_numpy() + unit_line_32 = { + unit: sum( + value + for other, value in zip(units, line_32, strict=True) + if other == unit and not np.isnan(value) + ) + for unit in units + if not pd.isna(unit) + } + passive = person[_PASSIVE].to_numpy(dtype=float) + infinite = np.isinf(person[[_P, _S, _PASSIVE]].to_numpy(dtype=float)).any(axis=1) no_line_32 = np.asarray( [ own == 0.0 or (not pd.isna(unit) and unit_line_32[unit] == 0.0) @@ -535,8 +595,11 @@ def _oracle_gate_counts(person: pd.DataFrame) -> dict[str, int]: "partnership_on_semp_rows": int((sets["own_semp"] & not_zero).sum()), "partnership_on_spouse_rows": int((sets["tax_unit"] & not_zero).sum()), "partnership_on_blank_semp_rows": int((sets["blank_semp"] & not_zero).sum()), - "passive_without_line_32_rows": int((no_line_32 & (passive != 0.0)).sum()), + "passive_without_line_32_rows": int( + (no_line_32 & np.isfinite(passive) & (passive != 0.0)).sum() + ), "partnership_blank_on_covered_rows": int((covered & blank).sum()), + "infinite_line_32_rows": int(infinite.sum()), } @@ -730,6 +793,72 @@ def test_the_gate_fails_an_extract_that_lost_semp() -> None: assert any("lost SEMP" in failure for failure in gate.failures) +def test_the_gate_puts_a_15_year_old_inside_the_income_universe() -> None: + reporting = _gate_row(SEMP=[500.0, np.nan], age=[15.0, 14.0]) + lost = _gate_row(SEMP=[np.nan, np.nan], age=[15.0, 14.0]) + + gate = acs_self_employment_identity_gate(reporting, rows=np.ones(2, dtype=bool)) + refused = acs_self_employment_identity_gate(lost, rows=np.ones(2, dtype=bool)) + + assert gate.passed, gate.failures + assert gate.details["semp_age"] == { + "persons_aged_15_plus": 1, + "blank_semp_age_15_plus_rows": 0, + "finite_semp_under_15_rows": 0, + } + assert not refused.passed + assert any("lost SEMP" in failure for failure in refused.failures) + + +def test_the_gate_passes_a_frame_of_children_only() -> None: + person = _gate_row( + SEMP=[np.nan, np.nan], + age=[9.0, 3.0], + **{_UNIT: [1, 1], _ROLE: ["DEPENDENT", "DEPENDENT"]}, + ) + + gate = acs_self_employment_identity_gate(person, rows=np.ones(2, dtype=bool)) + + assert gate.passed, gate.failures + assert gate.details["semp_age"] == { + "persons_aged_15_plus": 0, + "blank_semp_age_15_plus_rows": 0, + "finite_semp_under_15_rows": 0, + } + + +@pytest.mark.parametrize("infinity", (np.inf, -np.inf)) +def test_an_infinite_line_32_value_is_never_a_double_count(infinity: float) -> None: + """An infinity fails on its own clause, so it names no rebuild.""" + + # Own SEMP, the spouse it covers and blank SEMP, each with an infinite + # partnership draw beside S-corp income; then passive income on a row + # whose line 32 is zero. + person = _gate_row( + SEMP=[1_000.0, 0.0, np.nan, 0.0], + **{ + _UNIT: [1, 1, 2, 3], + _ROLE: ["HEAD", "SPOUSE", "HEAD", "HEAD"], + _P: [infinity, infinity, infinity, 0.0], + _S: [10.0, 10.0, 10.0, 0.0], + _PASSIVE: [0.0, 0.0, 0.0, infinity], + }, + ) + + gate = acs_self_employment_identity_gate(person, rows=np.ones(4, dtype=bool)) + + assert not gate.passed + assert gate.details["infinite_line_32_rows"] == 4 + for key in ( + "partnership_on_semp_rows", + "partnership_on_spouse_rows", + "partnership_on_blank_semp_rows", + "partnership_blank_on_covered_rows", + "passive_without_line_32_rows", + ): + assert gate.details[key] == 0, key + + @pytest.mark.parametrize("column", (_P, _S, _PASSIVE)) def test_the_gate_refuses_an_infinite_line_32_value(column: str) -> None: person = _gate_row(**{_S: [10.0], column: [np.inf]}) @@ -762,7 +891,10 @@ def _frame(person: pd.DataFrame, weights: np.ndarray, kind: WeightKind) -> Frame ) -def _donor(s_corp: float) -> Frame: +_DONOR_PARTNERSHIP = (5_000.0, 0.0, 3_000.0, 0.0) + + +def _donor(s_corp: float, partnership=_DONOR_PARTNERSHIP) -> Frame: person = pd.DataFrame( { "person_id": np.arange(1, 5, dtype=np.int64), @@ -771,7 +903,7 @@ def _donor(s_corp: float) -> Frame: "age": [45.0, 43.0, 30.0, 52.0], "is_female": [False, True, True, False], _TOTAL: [0.0, 20_000.0, 0.0, 5_000.0], - _P: [5_000.0, 0.0, 3_000.0, 0.0], + _P: list(partnership), _S: [s_corp, 0.0, 0.0, 0.0], _PASSIVE: [400.0, 0.0, 0.0, 0.0], } @@ -846,11 +978,18 @@ def predict(self, frame: pd.DataFrame) -> pd.DataFrame: ) -def _transfer(monkeypatch, *, lane: bool, s_corp: float = 0.0, targets=_PASS_THROUGH): +def _transfer( + monkeypatch, + *, + lane: bool, + s_corp: float = 0.0, + targets=_PASS_THROUGH, + partnership=_DONOR_PARTNERSHIP, +): monkeypatch.setattr(acs_transfer_module, "QRF", _DonorMeanQRF) return acs_transfer_module.transfer_acs_inputs( _recipient(), - _donor(s_corp), + _donor(s_corp, partnership), target_families={"person": {"pass_through": targets}}, donor_channel=None, n_estimators=1, @@ -945,6 +1084,28 @@ def test_the_lane_keeps_s_corp_income_on_every_row(monkeypatch) -> None: ) +def test_a_zero_partnership_draw_is_kept_at_zero_but_not_discarded( + monkeypatch, +) -> None: + """Passive income beside a zero draw is not counted as left on a discard.""" + + result = _transfer( + monkeypatch, lane=True, s_corp=1_000.0, partnership=(0.0, 0.0, 0.0, 0.0) + ) + person = result.frame.table("person") + + assert (person[_P] == 0.0).all() + assert np.allclose(person[_S], 250.0) + assert np.allclose(person[_PASSIVE], 100.0) + assert _gate(person).passed + receipt = next(item for item in result.imputed_inputs if item.column == _P) + assert receipt.reconciliation is not None + assert receipt.reconciliation["cells_kept_at_zero"] == int(_COVERED.sum()) + assert receipt.reconciliation["nonzero_draws_discarded"] == 0 + assert receipt.reconciliation["passive_kept_on_discarded_rows"] == 0 + assert receipt.reconciliation["passive_kept_on_discarded_rows_dollars"] == 0 + + def test_off_the_lane_the_gate_fails_on_exactly_the_covered_rows(monkeypatch) -> None: person = _transfer(monkeypatch, lane=False).frame.table("person")