From 44a11af9d63e0289cfd96bcda780b3fd8f563055 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mar=C3=ADa=20Juaristi?= <127882282+juaristi22@users.noreply.github.com> Date: Tue, 17 Nov 2026 10:34:50 +0000 Subject: [PATCH 01/31] Add a donor-patch tool for the County Files PoC ACS staging The County Files proof of concept (#922, plan #1647) stages its ACS rows from 766b7c7's national donor, which R1 refuses at three donor gates. tools/patch_us_acs_donor_columns.py writes a patched copy of that donor for the proof of concept only: - It adds reviewed all-zero columns on the entity the US engine gives them, after checking that the engine default is 0: strike_benefits (no donor or ASEC pppub23-26 row has OI_OFF == 12) and passive_partnership_s_corp_income (the donor holds partnership and S-corp income as one combined partnership_income). - It refuses a column that is already present with any other value. - It starts from a byte copy of the input and rewrites only the changed entity tables, through the shared frame-table codec, in their stored format (fixed, or table with the same data columns). Every other table, column, dtype and root attribute is kept and verified. - It writes a receipt: both SHA-256 digests, row counts per entity, each added column with its entity and reason, and the tool's commit. asec_work_column_step is reserved for the next commit on this tool, which restores the three ASEC work columns from the pinned ASEC person files. The tool's writer joins the frame-serializer registry with a round-trip adapter. Co-Authored-By: Claude Opus 5.5 --- .../us-acs-poc-donor-patch-922.added.md | 1 + .../build/frame_serializer_registry.py | 14 + .../shared/test_frame_serializer_registry.py | 8 +- .../us/test_us_acs_donor_column_patch.py | 443 ++++++++++++ .../frame_serializer_registry.py | 22 + tools/patch_us_acs_donor_columns.py | 672 ++++++++++++++++++ 6 files changed, 1156 insertions(+), 4 deletions(-) create mode 100644 changelog.d/us-acs-poc-donor-patch-922.added.md create mode 100644 packages/microcosm-build/tests/engine_free/us/test_us_acs_donor_column_patch.py create mode 100644 tools/patch_us_acs_donor_columns.py diff --git a/changelog.d/us-acs-poc-donor-patch-922.added.md b/changelog.d/us-acs-poc-donor-patch-922.added.md new file mode 100644 index 0000000000..0dacf50517 --- /dev/null +++ b/changelog.d/us-acs-poc-donor-patch-922.added.md @@ -0,0 +1 @@ +`tools/patch_us_acs_donor_columns.py` writes a patched copy of a published US national donor H5 for the County Files proof of concept's ACS staging (microcosm#922, plan microcosm#1647). It adds reviewed all-zero columns on the entity the US engine gives them (`strike_benefits`: no donor or ASEC pppub23–26 row has `OI_OFF` 12; `passive_partnership_s_corp_income`: the donor holds partnership and S-corp income as one combined `partnership_income`), refuses a column that is already present with any other value, keeps every other table, column, dtype and root attribute, and writes a receipt with both SHA-256 digests, the row counts, each added column with its reason, and the tool's commit. A restore step for the three ASEC work columns is reserved for a later commit. The published donor is read only, and no default changes. diff --git a/packages/microcosm-build/src/microcosm/build/frame_serializer_registry.py b/packages/microcosm-build/src/microcosm/build/frame_serializer_registry.py index 515e547465..aea8297509 100644 --- a/packages/microcosm-build/src/microcosm/build/frame_serializer_registry.py +++ b/packages/microcosm-build/src/microcosm/build/frame_serializer_registry.py @@ -170,6 +170,20 @@ class HdfWriteExclusion: version_owner="derive_spm_role_source parent person/spm_unit contract", nullable_boolean_storage="numpy_bool_or_object_pd_na_v1", ), + FrameSerializerSpec( + serializer_id="us_acs_donor_column_patch", + writer=HdfWriteSite( + "tools/patch_us_acs_donor_columns.py", + "_rewrite_entity_tables", + ), + backend="pandas.HDFStore in the input table's own format", + routes=( + "County Files proof-of-concept donor copy for the ACS staging " + "(microcosm#922): entity tables that gain reviewed columns", + ), + version_owner="RECEIPT_VERSION in tools/patch_us_acs_donor_columns.py", + nullable_boolean_storage="numpy_bool_or_object_pd_na_v1", + ), ) diff --git a/packages/microcosm-build/tests/engine_free/shared/test_frame_serializer_registry.py b/packages/microcosm-build/tests/engine_free/shared/test_frame_serializer_registry.py index 18b7e56567..04b835696b 100644 --- a/packages/microcosm-build/tests/engine_free/shared/test_frame_serializer_registry.py +++ b/packages/microcosm-build/tests/engine_free/shared/test_frame_serializer_registry.py @@ -12,10 +12,10 @@ def test_registry_classifies_every_writable_production_hdf_site() -> None: assert _discover_writable_hdf_sites() == classified -def test_registry_has_exactly_ten_unique_frame_table_serializers() -> None: - assert len(FRAME_TABLE_SERIALIZERS) == 10 - assert len({spec.serializer_id for spec in FRAME_TABLE_SERIALIZERS}) == 10 - assert len({spec.writer.key for spec in FRAME_TABLE_SERIALIZERS}) == 10 +def test_registry_has_exactly_eleven_unique_frame_table_serializers() -> None: + assert len(FRAME_TABLE_SERIALIZERS) == 11 + assert len({spec.serializer_id for spec in FRAME_TABLE_SERIALIZERS}) == 11 + assert len({spec.writer.key for spec in FRAME_TABLE_SERIALIZERS}) == 11 def test_round_trip_adapter_registry_exactly_matches_serializer_registry() -> None: diff --git a/packages/microcosm-build/tests/engine_free/us/test_us_acs_donor_column_patch.py b/packages/microcosm-build/tests/engine_free/us/test_us_acs_donor_column_patch.py new file mode 100644 index 0000000000..36b50cfc74 --- /dev/null +++ b/packages/microcosm-build/tests/engine_free/us/test_us_acs_donor_column_patch.py @@ -0,0 +1,443 @@ +"""The proof-of-concept donor patch for the ACS staging (microcosm#922). + +``tools/patch_us_acs_donor_columns.py`` writes a patched copy of a US +national donor H5 with reviewed all-zero columns added. These tests use a +small fixture H5 in the nullable layout R1's ``_load_base_frame`` reads and a +stand-in engine, so no country engine is imported. +""" + +from __future__ import annotations + +import hashlib +import importlib.util +import json +import sys +from pathlib import Path + +import numpy as np +import pandas as pd +import pytest + +from microcosm.build.us_runtime.acs_local_income import ( + ACS_LOCAL_ALIGNED_RETIREMENT_DONOR_COMPONENTS, + ACS_LOCAL_INCOME_TRANSFER_COLUMNS, + ACS_LOCAL_OTHER_INCOME_DONOR_COMPONENTS, +) +from microcosm.build.us_runtime.h5_io import ( + read_nullable_us_h5_metadata, + write_nullable_us_h5, +) +from microcosm.build.us_runtime.support_provenance import ( + support_channel_column, + support_clone_index_column, + support_source_id_column, +) +from microcosm.frame import ( + US_SCHEMA, + Frame, + VariableMetadata, + WeightKind, + Weights, + read_frame_table, +) +from test_support.paths import paths_for + +_TEST_PATHS = paths_for("microcosm-build") +_ROOT_ATTRIBUTES = { + "populace_release_id": "fixture-release", + "populace_location_rule": "legacy", +} +_ZERO_COLUMNS = ("strike_benefits", "passive_partnership_s_corp_income") + + +def _load_tool(relative: str, name: str): + path = _TEST_PATHS.repository / relative + spec = importlib.util.spec_from_file_location(name, path) + module = importlib.util.module_from_spec(spec) + assert spec.loader is not None + # Dataclasses resolve their annotations through sys.modules. + sys.modules[name] = module + spec.loader.exec_module(module) + return module + + +@pytest.fixture(scope="module") +def tool(): + return _load_tool("tools/patch_us_acs_donor_columns.py", "patch_us_acs_donor") + + +@pytest.fixture(scope="module") +def builder(): + return _load_tool( + "tools/_legacy/build_us_acs_multispine_base.py", + "legacy_build_us_acs_multispine_base_for_patch", + ) + + +class _Engine: + """Stand-in for the US engine's variable metadata and defaults.""" + + def __init__( + self, + *, + entities: dict[str, str] | None = None, + defaults: dict[str, object] | None = None, + dtype: str = "float", + ) -> None: + self.entities = entities or {} + self.defaults = {name: 0.0 for name in _ZERO_COLUMNS} | (defaults or {}) + self.dtype = dtype + + def variable_metadata(self, name: str) -> VariableMetadata: + return VariableMetadata( + name=name, + entity=self.entities.get(name, "person"), + dtype=self.dtype, + period="year", + ) + + def default_values(self, names): + return {name: self.defaults[name] for name in names if name in self.defaults} + + +class _NoDefaults(_Engine): + def default_values(self, names): + return {} + + +def _donor_frame(person_extra: dict[str, object] | None = None) -> Frame: + """Two ASEC persons and their two PUF clones, one household each. + + The person table carries every column R1's income-donor gate reads, + except ``strike_benefits``, plus a nullable boolean with a null and a + text column, so the tests see dtypes kept through the copy. + """ + + n = 4 + ids = np.arange(1, n + 1) + person = pd.DataFrame( + { + "person_id": ids, + **{f"person_{entity}_id": ids for entity in US_SCHEMA.group_entities}, + "age": [34.0, 70.0, 34.0, 70.0], + "is_female": [False, True, False, True], + } + ) + amounts = ( + *ACS_LOCAL_INCOME_TRANSFER_COLUMNS, + *ACS_LOCAL_OTHER_INCOME_DONOR_COMPONENTS, + *ACS_LOCAL_ALIGNED_RETIREMENT_DONOR_COMPONENTS, + ) + for offset, column in enumerate(dict.fromkeys(amounts)): + if column != "strike_benefits": + person[column] = [0.0, 100.0 + offset, 0.0, 200.0 + offset] + person["partnership_income"] = [0.0, 5_000.0, 0.0, 7_000.0] + person["s_corp_income"] = np.zeros(n) + person["has_marketplace_health_coverage_at_interview"] = pd.array( + [True, None, False, True], dtype="boolean" + ) + person["fixture_label"] = pd.Series(["a", "b", "c", "d"], dtype=object) + for column, values in (person_extra or {}).items(): + person[column] = values + tables = {"person": person} + for entity in US_SCHEMA.group_entities: + tables[entity] = pd.DataFrame({f"{entity}_id": ids}) + tables["household"]["state_fips"] = [6, 36, 6, 36] + roles = ["asec", "asec", "puf_tax_detail", "puf_tax_detail"] + for entity, table in tables.items(): + table[support_channel_column(entity)] = pd.Series(roles, dtype=object) + table[support_source_id_column(entity)] = [1, 2, 1, 2] + table[support_clone_index_column(entity)] = [0, 0, 1, 1] + return Frame( + tables, + US_SCHEMA, + { + "household": Weights( + np.asarray([40.0, 60.0, 50.0, 30.0]), WeightKind.CALIBRATED + ) + }, + ) + + +def _write_donor(path: Path, person_extra: dict[str, object] | None = None) -> Path: + write_nullable_us_h5( + _donor_frame(person_extra), + path, + period=2024, + artifact_kind="fixture_national_release_h5", + root_attributes=_ROOT_ATTRIBUTES, + ) + return path + + +def _sha256(path: Path) -> str: + return hashlib.sha256(path.read_bytes()).hexdigest() + + +def _patch(tool, tmp_path: Path, donor: Path, *, engine: _Engine | None = None): + output = tmp_path / "out" / "donor_patched.h5" + receipt_path = tmp_path / "out" / "donor_patched.receipt.json" + receipt = tool.patch_donor_h5( + donor, + output, + steps=tool.build_patch_steps( + zero_columns=list(_ZERO_COLUMNS), engine=engine or _Engine() + ), + receipt_path=receipt_path, + tool_identity={"commit": "f" * 40, "tool_dirty": False}, + engine_identity={"package": "policyengine-us", "version": "fixture"}, + ) + return output, receipt_path, receipt + + +def _tables(path: Path) -> tuple[list[str], dict[str, pd.DataFrame], dict, dict]: + with pd.HDFStore(path, mode="r") as store: + keys = sorted(store.keys()) + tables = {key: read_frame_table(store, key) for key in US_SCHEMA.entities} + others = { + key: store[key] for key in keys if key.lstrip("/") not in US_SCHEMA.entities + } + attributes = store.get_node("/")._v_attrs + root = {name: attributes[name] for name in attributes._v_attrnames} + return keys, tables, others, root + + +def test_added_columns_are_present_and_zero_on_their_engine_entity( + tool, tmp_path: Path +) -> None: + donor = _write_donor(tmp_path / "donor.h5") + output, _receipt_path, receipt = _patch(tool, tmp_path, donor) + + _keys, before, _others, _root = _tables(donor) + _keys, after, _others, _root = _tables(output) + person = after["person"] + assert list(person.columns) == [*before["person"].columns, *_ZERO_COLUMNS] + for column in _ZERO_COLUMNS: + assert person[column].dtype == np.float64 + assert person[column].tolist() == [0.0] * len(person) + assert [(r["entity"], r["column"]) for r in receipt["added_columns"]] == [ + ("person", column) for column in _ZERO_COLUMNS + ] + for record in receipt["added_columns"]: + assert record["reason"] == tool.REVIEWED_ZERO_COLUMNS[record["column"]] + assert record["step"] == tool.ZERO_STEP + assert record["action"] == "added" + assert record["engine_default"] == 0.0 + assert record["value"] == 0 + assert record["dtype"] == "float64" + assert receipt["kept_columns"] == [] + assert receipt["rewritten_tables"] == ["person"] + + +def test_every_other_table_column_dtype_and_root_attribute_is_unchanged( + tool, tmp_path: Path +) -> None: + donor = _write_donor(tmp_path / "donor.h5") + donor_sha256 = _sha256(donor) + output, _receipt_path, receipt = _patch(tool, tmp_path, donor) + + keys_before, before, others_before, root_before = _tables(donor) + keys_after, after, others_after, root_after = _tables(output) + assert keys_after == keys_before + assert set(root_after) == set(root_before) + for name, value in root_before.items(): + assert root_after[name] == value + for name, value in _ROOT_ATTRIBUTES.items(): + assert root_after[name] == value + assert others_after.keys() == others_before.keys() + for key, value in others_before.items(): + assert others_after[key].equals(value) + assert read_nullable_us_h5_metadata(output) == read_nullable_us_h5_metadata(donor) + for entity in US_SCHEMA.entities: + original = before[entity] + pd.testing.assert_frame_equal( + after[entity][list(original.columns)], original, check_exact=True + ) + if entity != "person": + pd.testing.assert_frame_equal(after[entity], original, check_exact=True) + person = after["person"] + nullable = person["has_marketplace_health_coverage_at_interview"] + assert nullable.isna().tolist() == [False, True, False, False] + assert person["fixture_label"].tolist() == ["a", "b", "c", "d"] + assert receipt["preserved"]["tables"] == keys_before + assert set(receipt["preserved"]["root_attributes"]) == set(root_before) + # The input is read only. + assert _sha256(donor) == donor_sha256 + + +def test_receipt_records_correct_hashes_rows_and_commit(tool, tmp_path: Path) -> None: + donor = _write_donor(tmp_path / "donor.h5") + output, receipt_path, receipt = _patch(tool, tmp_path, donor) + + assert json.loads(receipt_path.read_text()) == receipt + assert receipt["input"]["sha256"] == _sha256(donor) + assert receipt["output"]["sha256"] == _sha256(output) + assert receipt["input"]["sha256"] != receipt["output"]["sha256"] + assert receipt["input"]["path"] == str(donor.resolve()) + assert receipt["output"]["path"] == str(output.resolve()) + expected_rows = {entity: 4 for entity in US_SCHEMA.entities} + assert receipt["input"]["rows"] == expected_rows + assert receipt["output"]["rows"] == expected_rows + assert receipt["tool"] == "tools/patch_us_acs_donor_columns.py" + assert receipt["tool_commit"] == {"commit": "f" * 40, "tool_dirty": False} + assert receipt["engine"] == {"package": "policyengine-us", "version": "fixture"} + assert receipt["steps"] == [ + { + "name": tool.ZERO_STEP, + "columns": [f"person.{column}" for column in _ZERO_COLUMNS], + } + ] + # No temporary file is left beside the copy. + assert sorted(path.name for path in output.parent.iterdir()) == [ + "donor_patched.h5", + "donor_patched.receipt.json", + ] + + +@pytest.mark.parametrize( + ("values", "match"), + [ + ([0.0, 0.0, 25.0, 0.0], "refusing to overwrite"), + ([0.0, np.nan, 0.0, 0.0], "refusing to overwrite"), + ], +) +def test_existing_column_with_a_nonzero_or_null_value_is_refused( + tool, tmp_path: Path, values: list[float], match: str +) -> None: + donor = _write_donor(tmp_path / "donor.h5", {"strike_benefits": values}) + donor_sha256 = _sha256(donor) + + with pytest.raises(ValueError, match=match): + _patch(tool, tmp_path, donor) + + assert not (tmp_path / "out").exists() or not any((tmp_path / "out").iterdir()) + assert _sha256(donor) == donor_sha256 + + +def test_existing_all_zero_column_is_kept_not_duplicated(tool, tmp_path: Path) -> None: + donor = _write_donor(tmp_path / "donor.h5", {"strike_benefits": np.zeros(4)}) + output, _receipt_path, receipt = _patch(tool, tmp_path, donor) + + _keys, after, _others, _root = _tables(output) + assert list(after["person"].columns).count("strike_benefits") == 1 + assert [r["column"] for r in receipt["kept_columns"]] == ["strike_benefits"] + assert [r["column"] for r in receipt["added_columns"]] == [ + "passive_partnership_s_corp_income" + ] + + +def test_zero_columns_follow_the_engine_entity_and_default( + tool, tmp_path: Path +) -> None: + donor = _write_donor(tmp_path / "donor.h5") + engine = _Engine(entities={"passive_partnership_s_corp_income": "tax_unit"}) + output, _receipt_path, receipt = _patch(tool, tmp_path, donor, engine=engine) + + _keys, after, _others, _root = _tables(output) + assert after["tax_unit"]["passive_partnership_s_corp_income"].tolist() == [0.0] * 4 + assert "passive_partnership_s_corp_income" not in after["person"] + assert receipt["rewritten_tables"] == ["person", "tax_unit"] + + # A NumPy scalar default is read as its Python value. + step = tool.reviewed_zero_column_step( + ["strike_benefits"], engine=_Engine(defaults={"strike_benefits": np.int64(0)}) + ) + assert step.name == tool.ZERO_STEP + with pytest.raises(ValueError, match="not 0"): + tool.reviewed_zero_column_step( + ["strike_benefits"], engine=_Engine(defaults={"strike_benefits": 1.0}) + ) + with pytest.raises(ValueError, match="no default"): + tool.reviewed_zero_column_step(["strike_benefits"], engine=_NoDefaults()) + with pytest.raises(ValueError, match="numeric input"): + tool.reviewed_zero_column_step( + ["strike_benefits"], engine=_Engine(dtype="bool") + ) + with pytest.raises(ValueError, match="No reviewed reason"): + tool.reviewed_zero_column_step(["s_corp_income"], engine=_Engine()) + with pytest.raises(SystemExit): + tool._parse_args( + ["--input-h5", "a.h5", "--output-h5", "b.h5", "--zero-column", "x"] + ) + + +def test_r1_income_donor_gate_passes_on_the_patched_fixture( + tool, builder, tmp_path: Path +) -> None: + donor = _write_donor(tmp_path / "donor.h5") + with pytest.raises(SystemExit, match="strike_benefits"): + builder._require_income_donor(builder._load_base_frame(donor)) + + output, _receipt_path, _receipt = _patch(tool, tmp_path, donor) + + builder._require_income_donor(builder._load_base_frame(output)) + + +def test_command_writes_the_default_receipt_beside_the_copy( + tool, tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + import microcosm.frame.adapters.policyengine_us as adapter + + donor = _write_donor(tmp_path / "donor.h5") + monkeypatch.setattr(adapter, "PolicyEngineUSEngine", _Engine) + monkeypatch.setattr( + tool, "current_tool_identity", lambda: {"commit": "c" * 40, "tool_dirty": False} + ) + output = tmp_path / "patched.h5" + + assert tool.main(["--input-h5", str(donor), "--output-h5", str(output)]) == 0 + + receipt = json.loads((tmp_path / "patched.receipt.json").read_text()) + assert receipt["output"]["sha256"] == _sha256(output) + assert receipt["tool_commit"]["commit"] == "c" * 40 + assert [r["column"] for r in receipt["added_columns"]] == list( + tool.REVIEWED_ZERO_COLUMNS + ) + + with pytest.raises(SystemExit, match="Donor patch refused"): + tool.main(["--input-h5", str(donor), "--output-h5", str(donor)]) + + +def test_table_format_donor_keeps_its_layout(tool, builder, tmp_path: Path) -> None: + """A donor stored like BuildP: compound tables, every column a data column.""" + + frame = _donor_frame() + donor = tmp_path / "donor-table.h5" + with pd.HDFStore(donor, mode="w") as store: + for entity in US_SCHEMA.entities: + table = frame.table(entity).copy() + if entity == "household": + table["household_weight"] = frame.weights_for("household").values + # Table format stores no null Boolean; the published donor has none. + table = table.drop( + columns=["has_marketplace_health_coverage_at_interview"], + errors="ignore", + ) + store.put(entity, table, format="table", data_columns=True) + store.get_node("/")._v_attrs["populace_release_id"] = "fixture-release" + + output, _receipt_path, receipt = _patch(tool, tmp_path, donor) + + keys_before, before, _others, root_before = _tables(donor) + keys_after, after, _others, root_after = _tables(output) + assert keys_after == keys_before + assert set(root_after) == set(root_before) + assert root_after["populace_release_id"] == "fixture-release" + with pd.HDFStore(donor, mode="r") as old, pd.HDFStore(output, mode="r") as new: + for entity in US_SCHEMA.entities: + assert new.get_storer(entity).is_table + assert set(new.get_storer(entity).data_columns) == set( + after[entity].columns + ) + assert set(old.get_storer(entity).data_columns) == set( + before[entity].columns + ) + for entity in US_SCHEMA.entities: + pd.testing.assert_frame_equal( + after[entity][list(before[entity].columns)], + before[entity], + check_exact=True, + ) + assert after["person"]["strike_benefits"].tolist() == [0.0] * 4 + assert receipt["rewritten_tables"] == ["person"] + builder._require_income_donor(builder._load_base_frame(output)) diff --git a/test_support/microcosm_build/frame_serializer_registry.py b/test_support/microcosm_build/frame_serializer_registry.py index 5beee24bae..688b2a8955 100644 --- a/test_support/microcosm_build/frame_serializer_registry.py +++ b/test_support/microcosm_build/frame_serializer_registry.py @@ -399,6 +399,27 @@ def _round_trip_spm_role_projection( return _semantic_observation(source, before, loaded) +def _round_trip_us_acs_donor_column_patch( + tmp_path: Path, nullable_case: str +) -> BooleanRoundTrip: + pytest.importorskip("tables") + tool = _load_tool( + "tools/patch_us_acs_donor_columns.py", + "registry_us_acs_donor_column_patch", + ) + source = _dtype_family_table(nullable_case) + before = source.copy(deep=True) + path = tmp_path / "donor-column-patch.h5" + tool._rewrite_entity_tables( + path, + {"person": source}, + {"person": tool._StoredLayout("fixed", None, ())}, + ) + with pd.HDFStore(path, mode="r") as store: + loaded = read_frame_table(store, "person") + return _semantic_observation(source, before, loaded) + + ROUND_TRIP_ADAPTERS: dict[str, RoundTripAdapter] = { "frame_checkpoint": _round_trip_frame_checkpoint, "nullable_us_h5": _round_trip_nullable_us_h5, @@ -410,6 +431,7 @@ def _round_trip_spm_role_projection( "acs_local_lean_checkpoint": _round_trip_acs_lean, "fiscal_target_frame_checkpoint": _round_trip_fiscal_checkpoint, "spm_role_derivation_projection": _round_trip_spm_role_projection, + "us_acs_donor_column_patch": _round_trip_us_acs_donor_column_patch, } ENGINE_REQUIRED_SERIALIZER_IDS = frozenset( diff --git a/tools/patch_us_acs_donor_columns.py b/tools/patch_us_acs_donor_columns.py new file mode 100644 index 0000000000..6050db874b --- /dev/null +++ b/tools/patch_us_acs_donor_columns.py @@ -0,0 +1,672 @@ +"""Write a patched copy of a US national donor H5 for the ACS staging (R1). + +The County Files proof of concept (microcosm#922, plan microcosm#1647) stages +its ACS rows from the national donor of build 766b7c7 +(``populace-us-2024-spm-receipts-20260923``). The ACS staging tool +(``tools/_legacy/build_us_acs_multispine_base.py``, R1) refuses that donor: +it predates three later donor contracts. This tool writes a patched copy of +the donor for the proof of concept only. It reads the published file and +never changes it. The real County Files donor will be a new national build +from ``main``. + +The copy keeps every table, column, dtype and HDF5 root attribute of the +input. Each patch step only adds named columns to the entity tables: + +- ``reviewed_zero_columns`` adds reviewed all-zero columns. It looks up each + column's entity, dtype and default in the US engine and refuses a column + whose engine default is not 0. ``REVIEWED_ZERO_COLUMNS`` holds the reason + for each column. +- The ASEC work-column restore step (:func:`asec_work_column_step`) is + reserved for a later commit. It restores ``detailed_industry_recode``, + ``major_industry_recode`` and ``worked_last_year`` from the pinned ASEC + person files. + +A step never overwrites data: when a column is already present, the step +must give exactly the stored values, or the tool refuses the input. The tool +writes the copy atomically, verifies it against the input, and writes a JSON +receipt with both SHA-256 digests, the row counts per entity, each added +column with its entity and reason, and the tool's commit. + +Usage:: + + python tools/patch_us_acs_donor_columns.py \\ + --input-h5 populace_us_2024_receipt_qualified.h5 \\ + --output-h5 donor_patched_for_poc.h5 + +R1 then reads the copy with ``--base-h5 donor_patched_for_poc.h5`` and no +``--donor-release-manifest`` (the copy's digest is not the published one). +""" + +# No ``from __future__ import annotations``: test loaders run this file +# without registering it in ``sys.modules``, where string annotations break +# the dataclasses below. +import argparse +import hashlib +import json +import numbers +import os +import shutil +import subprocess +import uuid +from collections.abc import Callable, Mapping, Sequence +from dataclasses import dataclass, field +from pathlib import Path +from types import MappingProxyType +from typing import Any + +import numpy as np +import pandas as pd + +from microcosm.build.us_runtime.h5_io import ( + assert_h5_unchanged, + refuse_denied_pool_h5, +) +from microcosm.frame import put_frame_table, read_frame_table +from microcosm.frame.materialize import _PYTABLES_FRAME_TABLE_CODEC_ATTR +from microcosm.frame.units import US_SCHEMA + +TOOL = "tools/patch_us_acs_donor_columns.py" +RECEIPT_VERSION = 1 +ISSUE = "microcosm#922" +PLAN = "microcosm#1647" +PURPOSE = ( + "County Files proof of concept only: a patched copy of the published " + "national donor that the ACS staging (R1) accepts. The real County Files " + "donor is a new national build from main." +) +_CONSUMER = f"US ACS donor column patch ({TOOL})" +_REPOSITORY_ROOT = Path(__file__).resolve().parents[1] + +#: Each reviewed all-zero column and the reason its true values are unknown +#: or zero on the donor. The fill must equal the engine default (0). +REVIEWED_ZERO_COLUMNS: Mapping[str, str] = MappingProxyType( + { + "strike_benefits": "no donor or ASEC pppub23–26 row has OI_OFF == 12", + "passive_partnership_s_corp_income": ( + "the donor holds partnership and S-corp income as one combined " + "amount in `partnership_income`; the split is unknown" + ), + } +) +ZERO_STEP = "reviewed_zero_columns" + +#: The ASEC work columns that R1's ``_require_donor_work_experience`` needs +#: and that the reserved restore step adds (see :func:`asec_work_column_step`). +ASEC_WORK_COLUMNS: tuple[str, ...] = ( + "detailed_industry_recode", + "major_industry_recode", + "worked_last_year", +) +ASEC_WORK_STEP = "asec_work_columns" + +_NUMERIC_DTYPES: Mapping[str, type[np.generic]] = MappingProxyType( + {"float": np.float64, "int": np.int64} +) + + +@dataclass(frozen=True) +class ColumnPatch: + """One column that a step adds to one entity table. + + ``values`` must have the entity table's index. ``record`` goes into the + receipt with the column, entity, dtype, step and action. + """ + + entity: str + column: str + values: pd.Series + record: Mapping[str, object] = field(default_factory=dict) + + +@dataclass(frozen=True) +class PatchStepResult: + """A step's column patches and its step-level receipt (sources, counts).""" + + patches: tuple[ColumnPatch, ...] + receipt: Mapping[str, object] = field(default_factory=dict) + + +@dataclass(frozen=True) +class PatchStep: + """A named step. ``run`` gets the entity tables after earlier steps. + + ``run`` must not change the tables it gets; it returns column patches. + """ + + name: str + run: Callable[[Mapping[str, pd.DataFrame]], PatchStepResult] + + +def reviewed_zero_column_step(columns: Sequence[str], *, engine: Any) -> PatchStep: + """Add the named reviewed columns as zeros on their engine entity. + + ``engine`` is the US engine adapter (or a stand-in with the same + ``variable_metadata`` and ``default_values``). Each column must be in + ``REVIEWED_ZERO_COLUMNS``, be a numeric engine input with a default, and + have the engine default 0, so the fill is the value the engine would use. + """ + + unknown = sorted(set(columns) - set(REVIEWED_ZERO_COLUMNS)) + if unknown: + raise ValueError( + f"No reviewed reason for zero column(s) {unknown}; reviewed columns " + f"are {sorted(REVIEWED_ZERO_COLUMNS)}." + ) + if len(set(columns)) != len(columns) or not columns: + raise ValueError( + f"Zero columns must be distinct and non-empty; got {list(columns)}." + ) + specs: list[tuple[str, str, str, object]] = [] + for column in columns: + metadata = engine.variable_metadata(column) + if metadata.dtype not in _NUMERIC_DTYPES: + raise ValueError( + f"{column}: the engine dtype is {metadata.dtype!r}; a zero fill " + "needs a numeric input." + ) + defaults = engine.default_values([column]) + if column not in defaults: + raise ValueError( + f"{column}: the engine reports no default for it (an unknown, " + "formula-owned or declared source input); a zero fill must " + "equal the engine default." + ) + default = defaults[column] + if isinstance(default, np.generic): + default = default.item() + if isinstance(default, bool) or not isinstance(default, numbers.Real): + raise ValueError(f"{column}: engine default {default!r} is not numeric.") + if default != 0: + raise ValueError( + f"{column}: the engine default is {default!r}, not 0; a zero " + "fill would differ from the engine default." + ) + specs.append((column, metadata.entity, metadata.dtype, default)) + + def run(tables: Mapping[str, pd.DataFrame]) -> PatchStepResult: + patches = [] + for column, entity, dtype, default in specs: + if entity not in tables: + raise ValueError( + f"{column}: the engine entity {entity!r} has no table in " + "the donor H5." + ) + index = tables[entity].index + patches.append( + ColumnPatch( + entity=entity, + column=column, + values=pd.Series( + np.zeros(len(index), dtype=_NUMERIC_DTYPES[dtype]), + index=index, + name=column, + ), + record={ + "engine_dtype": dtype, + "engine_default": default, + "value": 0, + "reason": REVIEWED_ZERO_COLUMNS[column], + }, + ) + ) + return PatchStepResult(patches=tuple(patches)) + + return PatchStep(name=ZERO_STEP, run=run) + + +def asec_work_column_step(*args: object, **kwargs: object) -> PatchStep: + """Restore ``ASEC_WORK_COLUMNS`` from the pinned ASEC person files. + + Reserved for the next commit on this tool, which Max's agents add from + their verified local step. Its contract: + + - Read the pinned ASEC person files (``pppub23``-``pppub26``) and refuse a + file whose SHA-256 is not the pinned one. + - Match each donor person on its source year and ``PERIDNUM``. Refuse a + donor person with no match or with more than one match. + - Return a :class:`PatchStep` named ``ASEC_WORK_STEP``. Its ``run`` + returns a :class:`PatchStepResult` with one :class:`ColumnPatch` per + column on ``person`` (the source item in each ``record``), and the + files, their digests and the match counts in the step ``receipt``. + - Register it in :func:`build_patch_steps` before the zero step, with its + command-line options in :func:`_parse_args`. + + R1's ``_require_donor_work_experience`` must then pass on the copy. + """ + + raise NotImplementedError( + "The ASEC work-column restore step is not in this commit; the next " + "commit on this tool adds it (microcosm#1647)." + ) + + +def build_patch_steps( + *, + zero_columns: Sequence[str], + engine: Any, +) -> list[PatchStep]: + """The steps the command runs, in order. + + The ASEC work-column restore step (:func:`asec_work_column_step`) goes + first when it lands, then the reviewed zero columns. + """ + + return [reviewed_zero_column_step(zero_columns, engine=engine)] + + +def patch_donor_h5( + input_h5: Path, + output_h5: Path, + *, + steps: Sequence[PatchStep], + receipt_path: Path, + tool_identity: Mapping[str, object] | None = None, + engine_identity: Mapping[str, object] | None = None, +) -> dict[str, object]: + """Write the patched copy and its receipt; return the receipt. + + The input must have every US entity table that R1's ``_load_base_frame`` + reads. The copy starts as a byte copy of the input; only the entity + tables a step changes are rewritten, through the shared frame-table + codec, in their stored HDF format. The copy is verified before it + replaces ``output_h5``. + """ + + input_h5, output_h5 = Path(input_h5), Path(output_h5) + receipt_path = Path(receipt_path) + _validate_paths(input_h5, output_h5, receipt_path) + input_sha256 = refuse_denied_pool_h5(input_h5, consumer=_CONSUMER) + with pd.HDFStore(input_h5, mode="r") as store: + keys = sorted(store.keys()) + absent = [entity for entity in US_SCHEMA.entities if f"/{entity}" not in keys] + if absent: + raise ValueError( + f"{input_h5} lacks entity table(s) {absent}; R1 reads every " + f"US entity table ({list(US_SCHEMA.entities)})." + ) + tables = { + entity: read_frame_table(store, entity) for entity in US_SCHEMA.entities + } + layouts = { + entity: _stored_layout(store, entity, tables[entity]) + for entity in US_SCHEMA.entities + } + other_keys = [key for key in keys if key.lstrip("/") not in tables] + others = {key: store[key] for key in other_keys} + root_attributes = _root_attributes(store) + assert_h5_unchanged(input_h5, input_sha256, consumer=_CONSUMER) + + patched, columns, step_receipts = _apply_steps(tables, steps) + changed = sorted( + entity for entity in patched if patched[entity] is not tables[entity] + ) + + output_h5.parent.mkdir(parents=True, exist_ok=True) + temporary = output_h5.with_name(f".{output_h5.name}.{uuid.uuid4().hex}.tmp") + try: + shutil.copyfile(input_h5, temporary) + _rewrite_entity_tables( + temporary, {entity: patched[entity] for entity in changed}, layouts + ) + _verify_copy( + temporary, + original=tables, + patched=patched, + formats={entity: layout.format for entity, layout in layouts.items()}, + keys=keys, + others=others, + root_attributes=root_attributes, + ) + os.replace(temporary, output_h5) + except BaseException: + temporary.unlink(missing_ok=True) + raise + assert_h5_unchanged(input_h5, input_sha256, consumer=_CONSUMER) + + receipt: dict[str, object] = { + "version": RECEIPT_VERSION, + "tool": TOOL, + "tool_commit": dict(tool_identity) if tool_identity is not None else None, + "issue": ISSUE, + "plan": PLAN, + "purpose": PURPOSE, + "engine": dict(engine_identity) if engine_identity is not None else None, + "input": { + "path": str(input_h5.resolve()), + "sha256": input_sha256, + "rows": {entity: len(tables[entity]) for entity in US_SCHEMA.entities}, + }, + "output": { + "path": str(output_h5.resolve()), + "sha256": _sha256(output_h5), + "rows": {entity: len(patched[entity]) for entity in US_SCHEMA.entities}, + }, + "rewritten_tables": changed, + "preserved": { + "tables": keys, + "root_attributes": sorted(root_attributes), + }, + "added_columns": [r for r in columns if r["action"] == "added"], + "kept_columns": [r for r in columns if r["action"] == "kept_existing"], + "steps": step_receipts, + } + receipt_path.parent.mkdir(parents=True, exist_ok=True) + receipt_path.write_text( + json.dumps(receipt, indent=2, sort_keys=True, allow_nan=False) + "\n", + encoding="utf-8", + ) + return receipt + + +@dataclass(frozen=True) +class _StoredLayout: + """How the input stored one entity table, so the rewrite can keep it.""" + + format: str + data_columns: bool | tuple[str, ...] | None + nullable_boolean_columns: tuple[str, ...] + + +def _stored_layout( + store: pd.HDFStore, entity: str, table: pd.DataFrame +) -> _StoredLayout: + storer = store.get_storer(entity) + raw_codec = getattr(storer.attrs, _PYTABLES_FRAME_TABLE_CODEC_ATTR, None) + nullable = ( + tuple(json.loads(raw_codec)["nullable_boolean_columns"]) + if raw_codec is not None + else () + ) + if not storer.is_table: + return _StoredLayout("fixed", None, nullable) + data_columns = tuple(getattr(storer, "data_columns", None) or ()) + if data_columns and set(data_columns) == set(table.columns): + return _StoredLayout("table", True, nullable) + return _StoredLayout("table", data_columns or None, nullable) + + +def _rewrite_entity_tables( + path: Path, + tables: Mapping[str, pd.DataFrame], + layouts: Mapping[str, _StoredLayout], +) -> None: + """Replace the changed entity tables in the copy, in their stored layout. + + Columns the input's frame-table codec declared nullable Boolean go back + to ``boolean`` dtype first, so the shared codec writes them, and its + table attribute, as the input had them. + """ + + with pd.HDFStore(path, mode="a") as store: + for entity, table in tables.items(): + layout = layouts[entity] + if layout.nullable_boolean_columns: + table = table.copy(deep=False) + for column in layout.nullable_boolean_columns: + table[column] = table[column].astype("boolean") + put_frame_table( + store, + entity, + table, + preferred_format=layout.format, + data_columns=( + list(layout.data_columns) + if isinstance(layout.data_columns, tuple) + else layout.data_columns + ), + ) + + +def _apply_steps( + tables: Mapping[str, pd.DataFrame], + steps: Sequence[PatchStep], +) -> tuple[dict[str, pd.DataFrame], list[dict[str, object]], list[dict[str, object]]]: + patched = dict(tables) + added: list[dict[str, object]] = [] + step_receipts: list[dict[str, object]] = [] + seen: set[tuple[str, str]] = set() + names = [step.name for step in steps] + if len(set(names)) != len(names): + raise ValueError(f"Patch step names must be distinct; got {names}.") + for step in steps: + result = step.run(MappingProxyType(dict(patched))) + records = [] + for patch in result.patches: + key = (patch.entity, patch.column) + if key in seen: + raise ValueError( + f"{patch.entity}.{patch.column}: two patches name the column." + ) + seen.add(key) + if patch.entity not in patched: + raise ValueError( + f"{step.name}: no {patch.entity!r} table for {patch.column}." + ) + table = patched[patch.entity] + values = patch.values + if not isinstance(values, pd.Series) or not values.index.equals( + table.index + ): + raise ValueError( + f"{step.name}: {patch.entity}.{patch.column} values must be " + "a Series on the table's index." + ) + action = "added" + if patch.column in table.columns: + stored = table[patch.column] + if not _same_values(stored, values): + raise ValueError( + f"{step.name}: {patch.entity}.{patch.column} is already " + "in the donor with other values (a nonzero, null or " + "different value); refusing to overwrite it." + ) + action = "kept_existing" + else: + table = table.copy(deep=False) + table[patch.column] = values.rename(patch.column) + patched[patch.entity] = table + record = { + **dict(patch.record), + "column": patch.column, + "entity": patch.entity, + "dtype": str(patched[patch.entity][patch.column].dtype), + "step": step.name, + "action": action, + } + records.append(record) + added.append(record) + step_receipts.append( + { + **dict(result.receipt), + "name": step.name, + "columns": [f"{r['entity']}.{r['column']}" for r in records], + } + ) + return patched, added, step_receipts + + +def _same_values(stored: pd.Series, values: pd.Series) -> bool: + """Whether a stored column already holds exactly the patch values.""" + + if stored.isna().any() or values.isna().any(): + return False + try: + left = pd.to_numeric(stored, errors="raise").to_numpy(dtype=np.float64) + right = pd.to_numeric(values, errors="raise").to_numpy(dtype=np.float64) + except (TypeError, ValueError): + return bool(stored.astype(object).equals(values.astype(object))) + return bool(np.array_equal(left, right)) + + +def _verify_copy( + path: Path, + *, + original: Mapping[str, pd.DataFrame], + patched: Mapping[str, pd.DataFrame], + formats: Mapping[str, str], + keys: Sequence[str], + others: Mapping[str, Any], + root_attributes: Mapping[str, object], +) -> None: + """Refuse a copy that lost or changed anything but the added columns.""" + + with pd.HDFStore(path, mode="r") as store: + if sorted(store.keys()) != list(keys): + raise RuntimeError( + f"Patched copy changed the table list: {sorted(store.keys())} " + f"against {list(keys)}." + ) + if _root_attributes(store) != dict(root_attributes): + raise RuntimeError("Patched copy changed the HDF5 root attributes.") + for key, expected in others.items(): + stored = store[key] + if type(stored) is not type(expected) or not stored.equals(expected): + raise RuntimeError(f"Patched copy changed {key!r}.") + for entity, before in original.items(): + stored = read_frame_table(store, entity) + after = patched[entity] + if list(stored.columns) != list(after.columns): + raise RuntimeError( + f"Patched copy has {entity!r} columns {list(stored.columns)}; " + f"expected {list(after.columns)}." + ) + try: + pd.testing.assert_frame_equal( + stored[list(before.columns)], before, check_exact=True + ) + pd.testing.assert_frame_equal(stored, after, check_exact=True) + except AssertionError as error: + raise RuntimeError( + f"Patched copy changed {entity!r}: {error}" + ) from error + stored_format = "table" if store.get_storer(entity).is_table else "fixed" + if stored_format != formats[entity]: + raise RuntimeError( + f"Patched copy stored {entity!r} in {stored_format} format; " + f"the input used {formats[entity]}." + ) + + +def _root_attributes(store: pd.HDFStore) -> dict[str, object]: + attributes = store.get_node("/")._v_attrs + return { + name: _attribute_value(attributes[name]) + for name in sorted(attributes._v_attrnames) + } + + +def _attribute_value(value: object) -> object: + if isinstance(value, bytes): + return value.decode("utf-8") + if isinstance(value, np.ndarray): + return value.tolist() + if isinstance(value, np.generic): + return value.item() + return value + + +def _validate_paths(input_h5: Path, output_h5: Path, receipt_path: Path) -> None: + if not input_h5.is_file(): + raise ValueError(f"--input-h5 is not a file: {input_h5}.") + if output_h5.suffix != ".h5": + raise ValueError(f"--output-h5 must end with .h5, got {output_h5.name!r}.") + resolved = {input_h5.resolve(), output_h5.resolve()} + if len(resolved) != 2: + raise ValueError("--output-h5 must differ from --input-h5.") + if receipt_path.resolve() in resolved: + raise ValueError("--receipt must differ from --input-h5 and --output-h5.") + + +def _sha256(path: Path) -> str: + digest = hashlib.sha256() + with path.open("rb") as file: + while chunk := file.read(1024 * 1024): + digest.update(chunk) + return digest.hexdigest() + + +def current_tool_identity(repository: Path = _REPOSITORY_ROOT) -> dict[str, object]: + """The commit this tool runs from, and whether its file is edited.""" + + def git(*arguments: str) -> str | None: + try: + completed = subprocess.run( + ["git", "-C", str(repository), *arguments], + check=True, + capture_output=True, + text=True, + ) + except (OSError, subprocess.CalledProcessError): + return None + return completed.stdout.strip() + + commit = git("rev-parse", "HEAD") + status = git("status", "--porcelain", "--", TOOL) + return { + "commit": commit, + "tool_dirty": None if status is None else bool(status), + } + + +def _engine_identity() -> dict[str, object]: + from importlib.metadata import PackageNotFoundError, version + + try: + installed = version("policyengine-us") + except PackageNotFoundError: + installed = None + return {"package": "policyengine-us", "version": installed} + + +def _parse_args(argv: Sequence[str] | None = None) -> argparse.Namespace: + parser = argparse.ArgumentParser( + description=( + "Write a patched copy of a US national donor H5 for the ACS " + "staging, for the County Files proof of concept only." + ) + ) + parser.add_argument("--input-h5", required=True, type=Path) + parser.add_argument("--output-h5", required=True, type=Path) + parser.add_argument( + "--receipt", + type=Path, + help="JSON receipt path (default: OUTPUT-H5 with a .receipt.json suffix).", + ) + parser.add_argument( + "--zero-column", + action="append", + choices=sorted(REVIEWED_ZERO_COLUMNS), + help=( + "Reviewed column to add as zeros on its engine entity; repeat for " + "more than one (default: every reviewed column)." + ), + ) + return parser.parse_args(argv) + + +def main(argv: Sequence[str] | None = None) -> int: + args = _parse_args(argv) + receipt_path = args.receipt or args.output_h5.with_suffix(".receipt.json") + from microcosm.frame.adapters.policyengine_us import PolicyEngineUSEngine + + try: + steps = build_patch_steps( + zero_columns=args.zero_column or list(REVIEWED_ZERO_COLUMNS), + engine=PolicyEngineUSEngine(), + ) + receipt = patch_donor_h5( + args.input_h5, + args.output_h5, + steps=steps, + receipt_path=receipt_path, + tool_identity=current_tool_identity(), + engine_identity=_engine_identity(), + ) + except ValueError as error: + raise SystemExit(f"Donor patch refused: {error}") from error + print(json.dumps(receipt, indent=2, sort_keys=True)) + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) From 601cf86cc4f00bbbd5f23b301e32ffcff06a7182 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mar=C3=ADa=20Juaristi?= <127882282+juaristi22@users.noreply.github.com> Date: Tue, 17 Nov 2026 10:44:52 +0000 Subject: [PATCH 02/31] Let R1 accept named all-default donor columns by explicit allowance R1's dense-donor coverage gate refuses a transfer-consumed donor column whose every value equals the engine default, with no exception path. The County Files proof of concept's patched donor (#922) holds s_corp_income at 0 and gets passive_partnership_s_corp_income as 0, because it stores partnership and S-corp income combined in partnership_income. --allow-default-donor-column COLUMN=REASON (repeatable) names a column the gate may accept although every donor value equals the engine default. The gate skips only that failure for listed columns. It still refuses an absent column or one with no observed value, a name that is not transfer-consumed, a name the engine has no default for, and a stale allowance for a column with donor signal. The staging summary records each allowance and its reason (allowed_default_donor_columns, orchestration.allow_default_donor_columns) and a reviewed limitation, allowed_default_valued_donor_columns, which R2's finalize carries into the release. The Modal stage plan owns the flag and never passes it, as for the location flags (#1047). Without the flag the gate call, the outputs and the summary are unchanged. Co-Authored-By: Claude Opus 5.5 --- ...ng-allow-default-donor-column-922.added.md | 1 + docs/agent-guide.md | 6 + docs/us-modal-stage-runbook.md | 8 +- .../test_us_acs_multispine_legacy_builder.py | 229 +++++++++++++++++- ...t_us_modal_stage_acs_multispine_staging.py | 1 + tools/_legacy/build_us_acs_multispine_base.py | 156 +++++++++++- tools/modal_us_stage_plan.py | 4 + 7 files changed, 390 insertions(+), 15 deletions(-) create mode 100644 changelog.d/us-acs-staging-allow-default-donor-column-922.added.md diff --git a/changelog.d/us-acs-staging-allow-default-donor-column-922.added.md b/changelog.d/us-acs-staging-allow-default-donor-column-922.added.md new file mode 100644 index 0000000000..3da47c7eb3 --- /dev/null +++ b/changelog.d/us-acs-staging-allow-default-donor-column-922.added.md @@ -0,0 +1 @@ +The legacy ACS staging builder (`tools/_legacy/build_us_acs_multispine_base.py`) takes `--allow-default-donor-column COLUMN=REASON` (repeatable) for the County Files proof of concept's patched donor (microcosm#922). The dense-donor coverage gate then accepts that transfer-consumed column although every donor value equals the engine default; it still refuses an absent, unknown or not transfer-consumed column, and an allowance for a column with donor signal. The staging summary records each allowance and its reason (`allowed_default_donor_columns`, `orchestration.allow_default_donor_columns`) and adds the reviewed limitation `allowed_default_valued_donor_columns`, which the release carries forward. Modal staging plans never pass the flag. Without the flag, the gate, the outputs and the summary are unchanged. diff --git a/docs/agent-guide.md b/docs/agent-guide.md index e3793d8c5b..f9279e6b21 100644 --- a/docs/agent-guide.md +++ b/docs/agent-guide.md @@ -541,6 +541,12 @@ worked-last-year inputs on every final person row and binds that verdict to the H5 hash. ACS staging checks its preserved ASEC donor before acquisition; historical donors and staging files missing these inputs must be rebuilt through the exact ASEC restoration/fiscal carry and native ACS mapping. +The one reviewed exception is the County Files proof of concept +(microcosm#922): `tools/patch_us_acs_donor_columns.py` writes a patched copy of +766b7c7's donor with a receipt, and the staging builder's +`--allow-default-donor-column COLUMN=REASON` accepts named all-default donor +columns and records each one in the staging summary. Neither changes a +default. US household ladders carry both `county_fips` (2020 counties for the locked policyengine-us rules) and `county_fips_2023` (3,144 county-equivalents for calibration, including Connecticut's nine planning regions). The latter is diff --git a/docs/us-modal-stage-runbook.md b/docs/us-modal-stage-runbook.md index bb70b79e8a..fa306fff22 100644 --- a/docs/us-modal-stage-runbook.md +++ b/docs/us-modal-stage-runbook.md @@ -1457,10 +1457,12 @@ existing network use; the tool runs with `HF_HUB_OFFLINE=1`, without credential-name environment values, and consumes the staged files. The runner owns `--base-h5`, `--donor-release-manifest`, `--source-manifest`, -`--inputs-dir`, `--puma-ladder`, `--out-h5`, `--summary`, `--sipp-donor` and +`--inputs-dir`, `--puma-ladder`, `--out-h5`, `--summary`, `--sipp-donor`, the household-location flags (`--location-rule`, `--location-seed`, -`--location-clones`, `--block-ladder`). It never passes the last five, so a -staging run keeps the `legacy` location rule. Plans may set +`--location-clones`, `--block-ladder`) and `--allow-default-donor-column`. +It never passes the last six, so a staging run keeps the `legacy` location +rule and the whole dense-donor coverage gate (an allowance is a reviewed local +decision for one patched donor, microcosm#922). Plans may set only the builder's tuning flags: `--acs-share`, `--n-estimators`, `--max-targets-per-fit`, `--seed`, `--geography-seed`, `--chunksize`, `--donor-channel`, `--hours-under15-policy`, `--max-households` and diff --git a/packages/microcosm-build/tests/engine_free/us/test_us_acs_multispine_legacy_builder.py b/packages/microcosm-build/tests/engine_free/us/test_us_acs_multispine_legacy_builder.py index 2cab37a3ca..ba05c59a11 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 @@ -195,11 +195,13 @@ def test_parser_exposes_production_defaults_and_transfer_controls() -> None: assert local.sipp_donor == Path("pu2023.csv") +@pytest.mark.parametrize("allow_default", [False, True]) @pytest.mark.parametrize("staging_hours_pass", [True, False]) def test_main_wires_verified_sources_transfer_audit_export_and_summary( monkeypatch: pytest.MonkeyPatch, tmp_path: Path, staging_hours_pass: bool, + allow_default: bool, ) -> None: builder = _load_builder_module() manifest = _manifest() @@ -475,11 +477,15 @@ def staging_hours_gate(frame, *, source_null_audit): "prepare_acs_local_hours_donor", lambda frame, **kwargs: (frame, frame, {"source_agreement": True}), ) - monkeypatch.setattr( - builder, - "_require_dense_donor_coverage", - lambda frame, **kwargs: None, - ) + + def fake_dense_coverage(frame, **kwargs): + captured["dense_coverage"] = kwargs + return { + column: {"entity": "person", "engine_default": 0, "reason": reason} + for column, reason in kwargs.get("allowed_default_columns", {}).items() + } + + monkeypatch.setattr(builder, "_require_dense_donor_coverage", fake_dense_coverage) monkeypatch.setattr( builder, "acs_local_transfer_target_families", @@ -578,6 +584,13 @@ def staging_hours_gate(frame, *, source_null_audit): "--geography-seed", "19", ] + allowances = { + "s_corp_income": "the donor holds S-corp income in partnership_income", + "passive_partnership_s_corp_income": "the split is unknown", + } + if allow_default: + for column, reason in allowances.items(): + arguments += ["--allow-default-donor-column", f"{column}={reason}"] if not staging_hours_pass: with pytest.raises( SystemExit, match="Local staging hours gate failed.*asec_puf" @@ -649,7 +662,24 @@ def staging_hours_gate(frame, *, source_null_audit): "sub_puma_geographic_precision", "acs_spm_independence_role_household_partition", "acs_group_quarters_children_outside_spm_universe", - ] + ] + (["allowed_default_valued_donor_columns"] if allow_default else []) + if allow_default: + recorded = { + column: {"entity": "person", "engine_default": 0, "reason": reason} + for column, reason in allowances.items() + } + assert captured["dense_coverage"]["allowed_default_columns"] == allowances + assert summary["orchestration"]["allow_default_donor_columns"] == allowances + assert summary["allowed_default_donor_columns"] == recorded + limitation = summary["reviewed_limitations"][-1] + assert limitation["columns"] == recorded + assert limitation["issue"] == "microcosm#922" + assert limitation["calibration_blocker"] is False + else: + # Without the flag the gate call and the summary are unchanged. + assert "allowed_default_columns" not in captured["dense_coverage"] + assert "allow_default_donor_columns" not in summary["orchestration"] + assert "allowed_default_donor_columns" not in summary assert summary["reviewed_limitations"][2]["unavailable_exact_geography"] == [ "block_geoid", "tract_geoid", @@ -1175,6 +1205,193 @@ def test_dense_donor_default_consumed_optional_feature_fails_hard() -> None: assert "every observed donor value equals the engine default" in message +class _LineThirtyTwoEngine(_DefaultsEngine): + _defaults = { + **_DefaultsEngine._defaults, + "s_corp_income": 0.0, + "passive_partnership_s_corp_income": 0.0, + } + + +_LINE_32_PLAN = { + "person": { + "puf_tax_itemization": ("s_corp_income", "passive_partnership_s_corp_income") + } +} +_LINE_32_ALLOWANCES = { + "s_corp_income": "the donor holds S-corp income in partnership_income", + "passive_partnership_s_corp_income": "the split is unknown", +} + + +def _line_32_frame(**columns: list[float]) -> Frame: + base = _frame() + base.person["s_corp_income"] = [0.0, 0.0] + base.person["passive_partnership_s_corp_income"] = [0.0, 0.0] + for column, values in columns.items(): + base.person[column] = values + return base + + +def test_dense_donor_default_columns_still_fail_without_an_allowance() -> None: + builder = _load_builder_module() + + with pytest.raises(SystemExit) as exc: + builder._require_dense_donor_coverage( + _line_32_frame(), + engine=_LineThirtyTwoEngine(), + donor_channel=None, + target_families=_LINE_32_PLAN, + ) + + message = str(exc.value) + for column in _LINE_32_ALLOWANCES: + assert ( + f"person.{column}: every observed donor value equals the engine " + "default (0.0)" + ) in message + assert "--allow-default-donor-column" not in message + + +def test_allowed_default_donor_columns_pass_and_are_returned() -> None: + builder = _load_builder_module() + + allowed = builder._require_dense_donor_coverage( + _line_32_frame(), + engine=_LineThirtyTwoEngine(), + donor_channel=None, + target_families=_LINE_32_PLAN, + allowed_default_columns=_LINE_32_ALLOWANCES, + ) + + assert allowed == { + column: {"entity": "person", "engine_default": 0.0, "reason": reason} + for column, reason in _LINE_32_ALLOWANCES.items() + } + # Without allowances a passing gate returns nothing to record. + assert ( + builder._require_dense_donor_coverage( + _line_32_frame( + s_corp_income=[0.0, 10.0], passive_partnership_s_corp_income=[0.0, 5.0] + ), + engine=_LineThirtyTwoEngine(), + donor_channel=None, + target_families=_LINE_32_PLAN, + ) + == {} + ) + + +def test_an_allowance_skips_only_its_own_default_failure() -> None: + builder = _load_builder_module() + base = _line_32_frame(employment_income_before_lsr=[0.0, 0.0]) + + with pytest.raises(SystemExit) as exc: + builder._require_dense_donor_coverage( + base, + engine=_LineThirtyTwoEngine(), + donor_channel=None, + target_families=_LINE_32_PLAN, + allowed_default_columns=_LINE_32_ALLOWANCES, + ) + + message = str(exc.value) + assert "person.employment_income_before_lsr: every observed donor value" in message + assert "person.s_corp_income" not in message + + +@pytest.mark.parametrize( + ("base_columns", "plan", "allowances", "expected"), + [ + pytest.param( + {}, + {"person": {"health": ("has_esi",)}}, + {"has_esi": "reason"}, + "person.has_esi: transfer-consumed column is absent", + id="absent", + ), + pytest.param( + {"has_esi": [np.nan, np.nan]}, + {"person": {"health": ("has_esi",)}}, + {"has_esi": "reason"}, + "person.has_esi: transfer-consumed column has no observed donor values", + id="no-observed-values", + ), + pytest.param( + {"mystery_input": [0.0, 0.0]}, + {"person": {"health": ("mystery_input",)}}, + {"mystery_input": "reason"}, + "--allow-default-donor-column mystery_input: the engine reports no default", + id="unknown", + ), + pytest.param( + {"alimony_income": [0.0, 0.0]}, + _LINE_32_PLAN, + {**_LINE_32_ALLOWANCES, "alimony_income": "reason"}, + "--allow-default-donor-column alimony_income: not a transfer-consumed", + id="not-transfer-consumed", + ), + pytest.param( + {"s_corp_income": [0.0, 25.0]}, + _LINE_32_PLAN, + _LINE_32_ALLOWANCES, + "--allow-default-donor-column s_corp_income: the donor has values " + "other than the engine default", + id="stale", + ), + ], +) +def test_an_allowance_still_refuses_absent_unknown_and_unconsumed_columns( + base_columns, plan, allowances, expected +) -> None: + builder = _load_builder_module() + base = _line_32_frame(**base_columns) + + with pytest.raises(SystemExit) as exc: + builder._require_dense_donor_coverage( + base, + engine=_LineThirtyTwoEngine(), + donor_channel=None, + target_families=plan, + allowed_default_columns=allowances, + ) + + assert expected in str(exc.value) + + +def test_allow_default_donor_column_arguments_parse_or_refuse() -> None: + builder = _load_builder_module() + args = builder._parse_args( + [ + "--base-h5", + "d.h5", + "--out-h5", + "c.h5", + "--allow-default-donor-column", + "s_corp_income=held in partnership_income", + "--allow-default-donor-column", + " passive_partnership_s_corp_income = split = unknown ", + ] + ) + assert builder._default_donor_column_allowances( + args.allow_default_donor_column + ) == { + "s_corp_income": "held in partnership_income", + "passive_partnership_s_corp_income": "split = unknown", + } + default = builder._parse_args(["--base-h5", "d.h5", "--out-h5", "c.h5"]) + assert default.allow_default_donor_column is None + assert builder._default_donor_column_allowances(None) == {} + for values, match in ( + (["s_corp_income"], "must be COLUMN=REASON"), + (["=reason"], "must be COLUMN=REASON"), + (["s_corp_income= "], "must be COLUMN=REASON"), + (["a=x", "a=y"], "more than once"), + ): + with pytest.raises(SystemExit, match=match): + builder._default_donor_column_allowances(values) + + def test_signal_bearing_release_exclusion_is_irrelevant_to_donor_gate( capsys: pytest.CaptureFixture[str], ) -> None: diff --git a/packages/microcosm-build/tests/engine_free/us/test_us_modal_stage_acs_multispine_staging.py b/packages/microcosm-build/tests/engine_free/us/test_us_modal_stage_acs_multispine_staging.py index 03477b59dc..faf7974adf 100644 --- a/packages/microcosm-build/tests/engine_free/us/test_us_modal_stage_acs_multispine_staging.py +++ b/packages/microcosm-build/tests/engine_free/us/test_us_modal_stage_acs_multispine_staging.py @@ -61,6 +61,7 @@ "--location-seed", "--location-clones", "--block-ladder", + "--allow-default-donor-column", } diff --git a/tools/_legacy/build_us_acs_multispine_base.py b/tools/_legacy/build_us_acs_multispine_base.py index fd5e394855..5609e48c4e 100644 --- a/tools/_legacy/build_us_acs_multispine_base.py +++ b/tools/_legacy/build_us_acs_multispine_base.py @@ -17,6 +17,16 @@ summary (``household_location``, ``orchestration``, ``geography_ladder``) and the staging H5's root attributes. The legacy default is unchanged. +``--allow-default-donor-column COLUMN=REASON`` (repeatable; default none) lets +the dense-donor coverage gate accept a transfer-consumed donor column although +every donor value equals the engine default. It skips that one failure only: +an absent, unknown or not transfer-consumed column is still refused, and so is +an allowance for a column with donor signal. The summary records each +allowance and its reason (``allowed_default_donor_columns``, +``orchestration.allow_default_donor_columns``) and a reviewed limitation. It +exists for the County Files proof of concept's patched donor (microcosm#922); +without it the gate, the outputs and the summary are unchanged. + Telemetry: after parsing its arguments the builder starts the emitter (``microcosm.build.program_telemetry``, pipeline ``us_acs_multispine_staging``), records a stage change at each main phase (``load_donor``, @@ -97,6 +107,7 @@ ) from microcosm.build.us_runtime.acs_transfer import ( ACS_DONOR_CHANNEL_AUTO, + ASEC_PUF_DONOR_SPINE, DEFAULT_ACS_TRANSFER_MAX_TARGETS_PER_FIT, TargetFamilies, acs_derived_transfer_expectations, @@ -327,9 +338,50 @@ def _parse_args(argv: list[str] | None = None) -> argparse.Namespace: "identity is pinned into the staging summary." ), ) + parser.add_argument( + "--allow-default-donor-column", + action="append", + metavar="COLUMN=REASON", + help=( + "Let the dense-donor coverage gate accept the transfer-consumed " + "donor column COLUMN although every donor value equals the engine " + "default, for the stated REASON; repeat for more columns (default: " + "none). Only that failure is skipped: an absent, unknown or not " + "transfer-consumed column is still refused, and so is an allowance " + "for a column with donor signal. Each allowance and its reason is " + "recorded in the summary (microcosm#922)." + ), + ) return parser.parse_args(argv) +#: The reviewed limitation an allowance adds to the staging summary. +DEFAULT_DONOR_COLUMN_LIMITATION = "allowed_default_valued_donor_columns" +DEFAULT_DONOR_COLUMN_ISSUE = "microcosm#922" + + +def _default_donor_column_allowances( + values: list[str] | None, +) -> dict[str, str]: + """``--allow-default-donor-column`` values as ``{column: reason}``.""" + + allowances: dict[str, str] = {} + for value in values or (): + column, separator, reason = value.partition("=") + column, reason = column.strip(), reason.strip() + if not separator or not column or not reason: + raise SystemExit( + f"--allow-default-donor-column {value!r} must be COLUMN=REASON " + "with a column name and a non-empty reason." + ) + if column in allowances: + raise SystemExit( + f"--allow-default-donor-column names {column!r} more than once." + ) + allowances[column] = reason + return allowances + + def _donor_release_identity( manifest_path: Path | None, base_sha256: str, @@ -496,6 +548,9 @@ def _build(args: argparse.Namespace, telemetry: LocalTelemetryEmitter) -> int: summary_path = args.summary or args.out_h5.with_suffix(".summary.json") _validate_artifact_paths(args, summary_path=summary_path) _validate_location_arguments(args) + default_donor_allowances = _default_donor_column_allowances( + args.allow_default_donor_column + ) block_location = args.location_rule != US_LOCATION_RULE_LEGACY block_ladder: UsLocationLadder | None = None base_location: dict[str, object] | None = None @@ -527,10 +582,18 @@ def _build(args: argparse.Namespace, telemetry: LocalTelemetryEmitter) -> int: _require_ssi_disability_donor(base) _require_donor_work_experience(base) transfer_plan = declared_acs_transfer_target_families() - _require_dense_donor_coverage( - base, - donor_channel=args.donor_channel, - target_families=transfer_plan, + # Without an allowance the gate is called exactly as before. + allowance_options: dict[str, object] = {} + if default_donor_allowances: + allowance_options["allowed_default_columns"] = default_donor_allowances + allowed_default_columns = ( + _require_dense_donor_coverage( + base, + donor_channel=args.donor_channel, + target_families=transfer_plan, + **allowance_options, + ) + or {} ) # microcosm#1022: resolve and verify the pinned SIPP donor before the ACS # fetch and transfer, so an unavailable donor fails in minutes, not hours. @@ -706,6 +769,14 @@ def _build(args: argparse.Namespace, telemetry: LocalTelemetryEmitter) -> int: ladder_agreement=ladder_agreement, gate=location_gate, ) + if default_donor_allowances: + summary["orchestration"]["allow_default_donor_columns"] = dict( + default_donor_allowances + ) + summary["allowed_default_donor_columns"] = allowed_default_columns + summary["reviewed_limitations"].append( + _default_donor_column_limitation(allowed_default_columns) + ) summary["local_hours_source"] = result.provenance.get("local_hours_source") summary["acs_self_employment_identity_gate"] = { "name": self_employment_gate.name, @@ -1138,8 +1209,19 @@ def _require_dense_donor_coverage( *, donor_channel: str | None = ACS_DONOR_CHANNEL_AUTO, target_families: TargetFamilies | None = None, -) -> None: - """Fail unless every column consumed by the QRF plan has donor signal.""" + allowed_default_columns: Mapping[str, str] | None = None, +) -> dict[str, dict[str, object]]: + """Fail unless every column consumed by the QRF plan has donor signal. + + ``allowed_default_columns`` (``--allow-default-donor-column``) maps a + column to the reason it may carry only the engine default. For those + columns the gate skips only the "every observed donor value equals the + engine default" failure. It still refuses a listed column that is absent + or has no observed value, one that is not transfer-consumed, one the + engine has no default for, and one with donor signal (a stale + allowance). Returns the applied allowances: column -> entity, engine + default and reason; empty without allowances. + """ if engine is None: from microcosm.frame.adapters.policyengine_us import PolicyEngineUSEngine @@ -1156,8 +1238,23 @@ def _require_dense_donor_coverage( ) from exc failures: list[str] = [] + allowances = dict(allowed_default_columns or {}) present_values: dict[str, Any] = {} owners: dict[str, str] = {} + consumed = {column for columns in requirements.values() for column in columns} + allowance_defaults = engine.default_values(sorted(allowances)) if allowances else {} + for column in allowances: + if column not in consumed: + failures.append( + f"--allow-default-donor-column {column}: not a transfer-consumed " + "donor column of this plan, so there is nothing to allow." + ) + elif column not in allowance_defaults: + failures.append( + f"--allow-default-donor-column {column}: the engine reports no " + "default for it (unknown, formula-owned or a declared source " + "input)." + ) for entity, columns in requirements.items(): if entity not in selected.entities: failures.extend( @@ -1192,18 +1289,65 @@ def _require_dense_donor_coverage( defaults = engine.default_values(sorted(present_values)) default_gate = default_valued_columns_gate(present_values, defaults) default_valued = default_gate.details["default_valued_columns"] + allowed: dict[str, dict[str, object]] = {} for column, default in sorted(default_valued.items()): + if column in allowances: + allowed[column] = { + "entity": owners[column], + "engine_default": _json_scalar(default), + "reason": allowances[column], + } + continue failures.append( f"{owners[column]}.{column}: every observed donor value equals " f"the engine default ({default!r}); QRF transfer requires usable " "target/predictor signal." ) + for column in sorted(set(allowances) & set(present_values) - set(default_valued)): + if column in allowance_defaults: + failures.append( + f"--allow-default-donor-column {column}: the donor has values " + "other than the engine default, so the allowance is stale." + ) if failures: raise SystemExit( "Dense ASEC-by-PUF donor failed the hard ACS transfer-consumption " f"gate; selected channel={resolved_channel!r}:\n " + "\n ".join(failures) ) + return allowed + + +def _json_scalar(value: object) -> object: + """A NumPy scalar as its Python value, for the JSON summary.""" + + return value.item() if isinstance(value, np.generic) else value + + +def _default_donor_column_limitation( + allowed: Mapping[str, Mapping[str, object]], +) -> dict[str, object]: + """The reviewed limitation for ``--allow-default-donor-column`` columns.""" + + return { + "id": DEFAULT_DONOR_COLUMN_LIMITATION, + "status": "reviewed_default_valued_donor_columns", + "issue": DEFAULT_DONOR_COLUMN_ISSUE, + "affected_spines": [ASEC_PUF_DONOR_SPINE, ACS_2024_1YR_SPINE], + "columns": {column: dict(record) for column, record in allowed.items()}, + "reason": ( + "The dense-donor coverage gate accepted these transfer-consumed " + "donor columns although every donor value equals the engine " + "default (--allow-default-donor-column, with the reason recorded " + "for each column)." + ), + "treatment": ( + "Donor rows keep the engine default in these columns. The QRF " + "transfer has no donor signal for them, so the ACS rows' values " + "carry no information from the donor either." + ), + "calibration_blocker": False, + } def _column_owner(frame: Frame, column: str) -> str | None: diff --git a/tools/modal_us_stage_plan.py b/tools/modal_us_stage_plan.py index adbbdcbcb8..782279121a 100644 --- a/tools/modal_us_stage_plan.py +++ b/tools/modal_us_stage_plan.py @@ -1192,6 +1192,10 @@ def _acs_multispine_staging_argv( "--location-seed", "--location-clones", "--block-ladder", + # The dense-donor coverage allowance (microcosm#922). The runner + # never passes it, so a Modal staging plan keeps the whole gate: + # an allowance is a reviewed local decision for one patched donor. + "--allow-default-donor-column", } ), argv_builder=_acs_multispine_staging_argv, From 77f5fa163877bb75a3d0e227b9651e1c7dda4a48 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mar=C3=ADa=20Juaristi?= <127882282+juaristi22@users.noreply.github.com> Date: Tue, 17 Nov 2026 11:04:57 +0000 Subject: [PATCH 03/31] Register the strike_benefits reviewed fill on ACS rows Since d5aa4e25c the local income pass's OIP predictor uses strike_benefits as a component, so R1 requires every donor to carry it. Neither the shared plan nor the local income pass transfers it, so every ACS person reaches R2 with a null strike_benefits, R2 fills the engine default 0, and finalize's reviewed-fill consumer gate refuses the fill as unregistered (package refuses it too). This blocks the County Files proof of concept's R2 (#922) and any staging built from a current national donor. The register entry names the 13 means-tested consumers that the engine-tier test recomputes from policyengine-us 2.2.1, with the verdict harmless: no pinned ASEC respondent reports other-income code 12, so every donor value is 0, and a transfer would draw 0 too. The engine-free test that pins the register's column set now lists fills added since release 767312d60. Co-Authored-By: Claude Opus 5.5 --- ...strike-benefits-reviewed-fill-922.fixed.md | 1 + .../acs_local_reviewed_fill_consumers.yaml | 28 +++++++++++++++++++ .../us/test_us_acs_local_release_tool.py | 13 +++++++-- 3 files changed, 40 insertions(+), 2 deletions(-) create mode 100644 changelog.d/us-acs-strike-benefits-reviewed-fill-922.fixed.md diff --git a/changelog.d/us-acs-strike-benefits-reviewed-fill-922.fixed.md b/changelog.d/us-acs-strike-benefits-reviewed-fill-922.fixed.md new file mode 100644 index 0000000000..db5a10ca08 --- /dev/null +++ b/changelog.d/us-acs-strike-benefits-reviewed-fill-922.fixed.md @@ -0,0 +1 @@ +The ACS local lane's reviewed-fill register (`acs_local_reviewed_fill_consumers.yaml`) lists `person.strike_benefits` (microcosm#922). Since the local income pass's OIP predictor took strike benefits as a component, every ACS staging donor carries the column, but nothing transfers it, so the release fills 0 on every ACS person, and finalize's reviewed-fill gate refused that fill as unregistered. The entry names its 13 means-tested consumers with the verdict harmless: no pinned ASEC respondent reports strike benefits, so every donor value is 0 as well. diff --git a/packages/microcosm-build/src/microcosm/build/us_runtime/acs_local_reviewed_fill_consumers.yaml b/packages/microcosm-build/src/microcosm/build/us_runtime/acs_local_reviewed_fill_consumers.yaml index 678ee0c408..06213ba69d 100644 --- a/packages/microcosm-build/src/microcosm/build/us_runtime/acs_local_reviewed_fill_consumers.yaml +++ b/packages/microcosm-build/src/microcosm/build/us_runtime/acs_local_reviewed_fill_consumers.yaml @@ -920,6 +920,34 @@ entries: no program reads it, and programs count ssi directly (policyengine-us#9111). consumers: [] notes: [] + - entity: person + column: strike_benefits + fill_value: "0" + spines: [acs_2024_1yr] + rows: "every ACS person" + summary: >- + Strike benefits (ASEC other-income code 12). The ACS asks no separate item: OIP is + one combined amount. Neither the shared plan nor the local income pass transfers + the column; the donor carries it only as a component of the OIP predictor analog + (ACS_LOCAL_OTHER_INCOME_DONOR_COMPONENTS). No respondent in the pinned public ASEC + person files reports code 12, so every donor-spine value is 0 too + (microcosm#922). + consumers: [aca_ptc, chip, ctc, general_assistance, head_start, housing_assistance, + lifeline, medicaid, school_meals, snap, state_benefits, tanf, wic] + notes: + - programs: [aca_ptc, chip, ctc, general_assistance, head_start, + housing_assistance, lifeline, medicaid, school_meals, snap, state_benefits, + tanf, wic] + verdict: harmless + note: >- + 0 is the value the donor gives every person: no pinned ASEC respondent reports + strike benefits, so a QRF transfer from the donor would also draw 0 on these + rows. HUD unearned income, school-meal and WIC income, Missouri and Texas TANF + unearned income, Marin and San Bernardino general relief and several state + child-care and assistance programs count it directly; the other consumers read + it only through those programs' results. The fill differs from the true value + only for ACS respondents whose OIP includes strike pay, which no pinned ASEC + year observes. - entity: person column: tip_income fill_value: "0" diff --git a/packages/microcosm-build/tests/engine_free/us/test_us_acs_local_release_tool.py b/packages/microcosm-build/tests/engine_free/us/test_us_acs_local_release_tool.py index 58428953c0..e3715cb40b 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 @@ -6449,9 +6449,17 @@ def _reviewed_fill(entity, column, fill_value="0", spine="acs_2024_1yr") -> dict } +#: Reviewed fills added since release 767312d60, each with its register entry. +#: strike_benefits: the OIP predictor extension (d5aa4e25c) makes every donor +#: carry it, and nothing transfers it, so every ACS person is filled +#: (microcosm#922). +_REVIEWED_FILLS_ADDED_SINCE_767312D60 = {("person", "strike_benefits")} + + def test_the_register_covers_every_remaining_reviewed_fill() -> None: """Release 767312d60 default-filled 79 columns; the stack now fills 20 of - them (NEVER_DEFAULT_FILLED), and every other one has a register entry.""" + them (NEVER_DEFAULT_FILLED), and every other one has a register entry, as + does each reviewed fill added since.""" module = _load_tool_module() document = load_reviewed_fill_consumer_register() @@ -6473,7 +6481,8 @@ def test_the_register_covers_every_remaining_reviewed_fill() -> None: # returned to a reviewed fill after the microcosm#1064 review (VEH counts # vehicles available, not owned): it left NEVER_DEFAULT_FILLED and gained # an entry together, so this still holds. - assert registered == released - now_filled + assert registered == (released - now_filled) | _REVIEWED_FILLS_ADDED_SINCE_767312D60 + assert not released & _REVIEWED_FILLS_ADDED_SINCE_767312D60 def test_do_finalize_hard_fails_on_an_unregistered_reviewed_fill( From b9e7f40103570041dc3f2753e0e005b484ff85aa Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mar=C3=ADa=20Juaristi?= <127882282+juaristi22@users.noreply.github.com> Date: Tue, 17 Nov 2026 11:20:19 +0000 Subject: [PATCH 04/31] Let the donor-patch tool write a release manifest for the copy Without --donor-release-manifest, R1 records donor_release as null, R2 copies the null into us_source_coverage.json, and the local-area release contract refuses the release at publication. The amended ruling (#1647) allows a manifest for the copy instead. - --release-manifest PATH with --manifest-release and --manifest-build (and --manifest-repo-id, default policyengine/populace-us-staging) writes a build-folder release manifest whose one microdata artifact is the copy, plus the receipt as a second artifact. R1's --donor-release-manifest then verifies the copy's SHA-256 against it and records the copy's build, which referenced_build and the release contract accept. Its dataset_role is proof_of_concept_donor_copy, not a release role, so the copy's folder cannot pass as a release. - --input-release-manifest checks the input against the published donor's release manifest and records that build in the receipt and in the copy's manifest (derived_from). - The uploaded manifest names files, not local paths. Both options are opt-in; the copy and the receipt are unchanged without them. Co-Authored-By: Claude Opus 5.5 --- .../us-acs-poc-donor-patch-922.added.md | 2 +- docs/agent-guide.md | 3 +- .../us/test_us_acs_donor_column_patch.py | 167 +++++++++- tools/patch_us_acs_donor_columns.py | 307 +++++++++++++++++- 4 files changed, 463 insertions(+), 16 deletions(-) diff --git a/changelog.d/us-acs-poc-donor-patch-922.added.md b/changelog.d/us-acs-poc-donor-patch-922.added.md index 0dacf50517..7f7b314761 100644 --- a/changelog.d/us-acs-poc-donor-patch-922.added.md +++ b/changelog.d/us-acs-poc-donor-patch-922.added.md @@ -1 +1 @@ -`tools/patch_us_acs_donor_columns.py` writes a patched copy of a published US national donor H5 for the County Files proof of concept's ACS staging (microcosm#922, plan microcosm#1647). It adds reviewed all-zero columns on the entity the US engine gives them (`strike_benefits`: no donor or ASEC pppub23–26 row has `OI_OFF` 12; `passive_partnership_s_corp_income`: the donor holds partnership and S-corp income as one combined `partnership_income`), refuses a column that is already present with any other value, keeps every other table, column, dtype and root attribute, and writes a receipt with both SHA-256 digests, the row counts, each added column with its reason, and the tool's commit. A restore step for the three ASEC work columns is reserved for a later commit. The published donor is read only, and no default changes. +`tools/patch_us_acs_donor_columns.py` writes a patched copy of a published US national donor H5 for the County Files proof of concept's ACS staging (microcosm#922, plan microcosm#1647). It adds reviewed all-zero columns on the entity the US engine gives them (`strike_benefits`: no donor or ASEC pppub23–26 row has `OI_OFF` 12; `passive_partnership_s_corp_income`: the donor holds partnership and S-corp income as one combined `partnership_income`), refuses a column that is already present with any other value, keeps every other table, column, dtype and root attribute, and writes a receipt with both SHA-256 digests, the row counts, each added column with its reason, and the tool's commit. A restore step for the three ASEC work columns is reserved for a later commit. The published donor is read only, and no default changes. With `--input-release-manifest` it checks the input against the published donor's release manifest and records that build in the receipt. With `--release-manifest`, `--manifest-release` and `--manifest-build` it also writes a build-folder release manifest for the copy (in `policyengine/populace-us-staging` by default), so the ACS staging can take it as `--donor-release-manifest` and record the copy's build as `donor_release`, which the local-area release contract requires before publication. diff --git a/docs/agent-guide.md b/docs/agent-guide.md index f9279e6b21..e2b596c57f 100644 --- a/docs/agent-guide.md +++ b/docs/agent-guide.md @@ -543,7 +543,8 @@ historical donors and staging files missing these inputs must be rebuilt through the exact ASEC restoration/fiscal carry and native ACS mapping. The one reviewed exception is the County Files proof of concept (microcosm#922): `tools/patch_us_acs_donor_columns.py` writes a patched copy of -766b7c7's donor with a receipt, and the staging builder's +766b7c7's donor with a receipt (and, when asked, a build-folder release manifest +for the copy, for `--donor-release-manifest`), and the staging builder's `--allow-default-donor-column COLUMN=REASON` accepts named all-default donor columns and records each one in the staging summary. Neither changes a default. diff --git a/packages/microcosm-build/tests/engine_free/us/test_us_acs_donor_column_patch.py b/packages/microcosm-build/tests/engine_free/us/test_us_acs_donor_column_patch.py index 36b50cfc74..d4ef4d9dc8 100644 --- a/packages/microcosm-build/tests/engine_free/us/test_us_acs_donor_column_patch.py +++ b/packages/microcosm-build/tests/engine_free/us/test_us_acs_donor_column_patch.py @@ -32,6 +32,8 @@ support_clone_index_column, support_source_id_column, ) +from microcosm.data import contract +from microcosm.data.build_folder_manifests import referenced_build from microcosm.frame import ( US_SCHEMA, Frame, @@ -174,7 +176,9 @@ def _sha256(path: Path) -> str: return hashlib.sha256(path.read_bytes()).hexdigest() -def _patch(tool, tmp_path: Path, donor: Path, *, engine: _Engine | None = None): +def _patch( + tool, tmp_path: Path, donor: Path, *, engine: _Engine | None = None, **options +): output = tmp_path / "out" / "donor_patched.h5" receipt_path = tmp_path / "out" / "donor_patched.receipt.json" receipt = tool.patch_donor_h5( @@ -186,6 +190,7 @@ def _patch(tool, tmp_path: Path, donor: Path, *, engine: _Engine | None = None): receipt_path=receipt_path, tool_identity={"commit": "f" * 40, "tool_dirty": False}, engine_identity={"package": "policyengine-us", "version": "fixture"}, + **options, ) return output, receipt_path, receipt @@ -441,3 +446,163 @@ def test_table_format_donor_keeps_its_layout(tool, builder, tmp_path: Path) -> N assert after["person"]["strike_benefits"].tolist() == [0.0] * 4 assert receipt["rewritten_tables"] == ["person"] builder._require_income_donor(builder._load_base_frame(output)) + + +_PUBLISHED_RELEASE = "microcosm-us-2024-receipt-donor" +_PUBLISHED_BUILD = "populace-us-2024-spm-receipts-20260923" +_COPY_RELEASE = "county-files-poc-donor" +_COPY_BUILD = "spm-receipts-20260923-patched-20261117" + + +def _published_manifest(sha256: str) -> dict: + """The published donor's release manifest, in the build-folder layout.""" + + return { + "schema_version": 1, + "release": _PUBLISHED_RELEASE, + "build": _PUBLISHED_BUILD, + "dataset_role": "national_default", + "is_default": False, + "artifacts": { + "donor": { + "kind": "microdata", + "path": "donor.h5", + "repo_id": "policyengine/populace-us", + "sha256": sha256, + "role": "dataset", + } + }, + } + + +def test_release_manifest_names_the_copy_for_r1_and_the_publisher( + tool, builder, tmp_path: Path +) -> None: + donor = _write_donor(tmp_path / "donor.h5") + published = tmp_path / "published_release_manifest.json" + published.write_text(json.dumps(_published_manifest(_sha256(donor)))) + manifest_path = tmp_path / "out" / "release_manifest.json" + target = tool.CopyReleaseManifest( + path=manifest_path, release=_COPY_RELEASE, build=_COPY_BUILD + ) + + output, receipt_path, receipt = _patch( + tool, + tmp_path, + donor, + input_release_manifest=published, + release_manifest=target, + ) + + # R1 verifies the copy against the manifest and names the copy's build. + identity = builder._donor_release_identity(manifest_path, _sha256(output)) + assert {key: identity[key] for key in ("repo_id", "release", "build")} == { + "repo_id": "policyengine/populace-us-staging", + "release": _COPY_RELEASE, + "build": _COPY_BUILD, + } + assert identity["sha256"] == _sha256(output) + assert identity["dataset_role"] == tool.COPY_DATASET_ROLE + assert identity["is_default"] is False + copy_folder = f"releases/{_COPY_RELEASE}/{_COPY_BUILD}" + assert referenced_build(identity).folder == copy_folder + # The local-area release contract accepts it as the donor reference. + failures: list[str] = [] + contract._check_local_area_donor_reference(identity, failures) + assert failures == [] + # The published manifest still names the input, never the copy. + with pytest.raises(SystemExit, match="does not match its release manifest"): + builder._donor_release_identity(published, _sha256(output)) + + manifest = json.loads(manifest_path.read_text()) + published_folder = f"releases/{_PUBLISHED_RELEASE}/{_PUBLISHED_BUILD}" + assert manifest["derived_from"]["sha256"] == _sha256(donor) + assert manifest["derived_from"]["release"]["folder"] == published_folder + assert manifest["artifacts"]["patch_receipt"] == { + "kind": "receipt", + "path": "donor_patched.receipt.json", + "repo_id": "policyengine/populace-us-staging", + "sha256": _sha256(receipt_path), + "role": "patch_receipt", + } + assert manifest["patch"]["added_columns"] == [ + f"person.{column}" for column in _ZERO_COLUMNS + ] + assert receipt["input"]["release"]["folder"] == published_folder + assert receipt["input"]["release"]["manifest"] == published.name + assert receipt["release_manifest"]["folder"] == copy_folder + # The uploaded manifest names files, not this machine's paths. + assert str(tmp_path) not in manifest_path.read_text() + + +def test_input_release_manifest_must_pin_the_input(tool, tmp_path: Path) -> None: + donor = _write_donor(tmp_path / "donor.h5") + published = tmp_path / "published_release_manifest.json" + published.write_text(json.dumps(_published_manifest("0" * 64))) + + with pytest.raises(ValueError, match="pins '0000"): + _patch(tool, tmp_path, donor, input_release_manifest=published) + + assert not (tmp_path / "out").exists() + unreadable = _published_manifest(_sha256(donor)) + del unreadable["artifacts"]["donor"]["repo_id"] + published.write_text(json.dumps(unreadable)) + with pytest.raises(ValueError, match="names no readable build"): + _patch(tool, tmp_path, donor, input_release_manifest=published) + + +@pytest.mark.parametrize( + ("options", "match"), + [ + ({"release": "a/b"}, "one folder name"), + ({"build": ""}, "one folder name"), + ({"repo_id": "populace-us-staging"}, "OWNER/NAME"), + ], +) +def test_copy_release_manifest_refuses_a_bad_build_name( + tool, tmp_path: Path, options: dict, match: str +) -> None: + fields = {"release": _COPY_RELEASE, "build": _COPY_BUILD} | options + with pytest.raises(ValueError, match=match): + tool.CopyReleaseManifest(path=tmp_path / "release_manifest.json", **fields) + + +def test_command_writes_the_copy_release_manifest_only_when_asked( + tool, tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + import microcosm.frame.adapters.policyengine_us as adapter + + donor = _write_donor(tmp_path / "donor.h5") + monkeypatch.setattr(adapter, "PolicyEngineUSEngine", _Engine) + monkeypatch.setattr( + tool, "current_tool_identity", lambda: {"commit": "c" * 40, "tool_dirty": False} + ) + base = ["--input-h5", str(donor), "--output-h5", str(tmp_path / "patched.h5")] + manifest_path = tmp_path / "release_manifest.json" + + assert ( + tool.main( + [ + *base, + "--release-manifest", + str(manifest_path), + "--manifest-release", + _COPY_RELEASE, + "--manifest-build", + _COPY_BUILD, + ] + ) + == 0 + ) + manifest = json.loads(manifest_path.read_text()) + assert manifest["artifacts"]["patched"]["sha256"] == _sha256( + tmp_path / "patched.h5" + ) + assert manifest["release"] == _COPY_RELEASE + for partial in ( + ["--release-manifest", str(manifest_path)], + ["--release-manifest", str(manifest_path), "--manifest-build", _COPY_BUILD], + ["--manifest-release", _COPY_RELEASE, "--manifest-build", _COPY_BUILD], + ): + with pytest.raises(SystemExit): + tool._parse_args([*base, *partial]) diff --git a/tools/patch_us_acs_donor_columns.py b/tools/patch_us_acs_donor_columns.py index 6050db874b..83737d16b9 100644 --- a/tools/patch_us_acs_donor_columns.py +++ b/tools/patch_us_acs_donor_columns.py @@ -27,14 +27,32 @@ receipt with both SHA-256 digests, the row counts per entity, each added column with its entity and reason, and the tool's commit. +Two options record lineage (both optional): + +- ``--input-release-manifest`` is the published donor's + ``release_manifest.json``. The input's SHA-256 must match its one microdata + artifact, and the receipt records the donor build it names. +- ``--release-manifest`` with ``--manifest-release`` and ``--manifest-build`` + writes a release manifest in the build-folder layout that names the copy + and its receipt. Upload the copy, the receipt and this file (as + ``release_manifest.json``) to ``releases///`` in + ``--manifest-repo-id``, where ``referenced_build`` reads a build. R1's + ``--donor-release-manifest`` then verifies the copy against it and records + the copy's build as ``donor_release``, which the local-area release + contract requires before publication. + Usage:: python tools/patch_us_acs_donor_columns.py \\ --input-h5 populace_us_2024_receipt_qualified.h5 \\ - --output-h5 donor_patched_for_poc.h5 - -R1 then reads the copy with ``--base-h5 donor_patched_for_poc.h5`` and no -``--donor-release-manifest`` (the copy's digest is not the published one). + --input-release-manifest published_release_manifest.json \\ + --output-h5 run/donor_patched_poc.h5 \\ + --release-manifest run/release_manifest.json \\ + --manifest-release RELEASE --manifest-build BUILD + +R1 then reads the copy with ``--base-h5 run/donor_patched_poc.h5`` and +``--donor-release-manifest run/release_manifest.json``, or without a manifest +(``donor_release`` is then null, and the publisher refuses the release). """ # No ``from __future__ import annotations``: test loaders run this file @@ -45,11 +63,13 @@ import json import numbers import os +import re import shutil import subprocess import uuid from collections.abc import Callable, Mapping, Sequence from dataclasses import dataclass, field +from datetime import UTC, datetime from pathlib import Path from types import MappingProxyType from typing import Any @@ -61,6 +81,7 @@ assert_h5_unchanged, refuse_denied_pool_h5, ) +from microcosm.data.build_folder_manifests import referenced_build from microcosm.frame import put_frame_table, read_frame_table from microcosm.frame.materialize import _PYTABLES_FRAME_TABLE_CODEC_ATTR from microcosm.frame.units import US_SCHEMA @@ -77,6 +98,15 @@ _CONSUMER = f"US ACS donor column patch ({TOOL})" _REPOSITORY_ROOT = Path(__file__).resolve().parents[1] +#: The repository the amended ruling names for the copy (microcosm#1647). +DEFAULT_MANIFEST_REPO_ID = "policyengine/populace-us-staging" +#: The copy's dataset role: not a release role, so the release contract +#: refuses the copy's folder as a release of its own. +COPY_DATASET_ROLE = "proof_of_concept_donor_copy" +#: A release or build name is one folder name (``releases//``). +_FOLDER_NAME = re.compile(r"[A-Za-z0-9][A-Za-z0-9._-]*") +_REPO_ID = re.compile(r"[A-Za-z0-9][A-Za-z0-9._-]*/[A-Za-z0-9][A-Za-z0-9._-]*") + #: Each reviewed all-zero column and the reason its true values are unknown #: or zero on the donor. The fill must equal the engine default (0). REVIEWED_ZERO_COLUMNS: Mapping[str, str] = MappingProxyType( @@ -240,6 +270,166 @@ def asec_work_column_step(*args: object, **kwargs: object) -> PatchStep: ) +@dataclass(frozen=True) +class CopyReleaseManifest: + """Where to write the copy's release manifest, and the build it names.""" + + path: Path + release: str + build: str + repo_id: str = DEFAULT_MANIFEST_REPO_ID + + def __post_init__(self) -> None: + for name in ("release", "build"): + value = getattr(self, name) + if not isinstance(value, str) or not _FOLDER_NAME.fullmatch(value): + raise ValueError( + f"The copy's manifest {name} must be one folder name " + f"(letters, digits, '.', '_', '-'); got {value!r}." + ) + if not isinstance(self.repo_id, str) or not _REPO_ID.fullmatch(self.repo_id): + raise ValueError( + f"The copy's manifest repo_id must be OWNER/NAME; got {self.repo_id!r}." + ) + + def identity(self) -> dict[str, str]: + return { + "path": str(Path(self.path).resolve()), + "repo_id": self.repo_id, + "release": self.release, + "build": self.build, + "folder": referenced_build( + {"repo_id": self.repo_id, "release": self.release, "build": self.build} + ).folder, + } + + +def input_release_identity(manifest_path: Path, input_sha256: str) -> dict[str, object]: + """Verify the input against its published release manifest; name its build. + + The manifest must carry exactly one microdata artifact, whose SHA-256 is + the input's, and name a build that ``referenced_build`` accepts: a build + folder (``release`` and ``build``) or a tag (``build.build_id`` and the + artifact's ``revision``). + """ + + manifest_path = Path(manifest_path) + try: + raw = manifest_path.read_bytes() + manifest = json.loads(raw) + except (OSError, ValueError) as error: + raise ValueError( + f"Cannot read --input-release-manifest {manifest_path}: {error}." + ) from error + artifacts = manifest.get("artifacts") if isinstance(manifest, dict) else None + if not isinstance(artifacts, dict): + raise ValueError(f"{manifest_path} carries no artifacts map.") + microdata = [ + (name, entry) + for name, entry in artifacts.items() + if isinstance(entry, dict) and entry.get("kind") == "microdata" + ] + if len(microdata) != 1: + raise ValueError( + f"{manifest_path} must carry exactly one microdata artifact; found " + f"{sorted(name for name, _ in microdata)}." + ) + name, entry = microdata[0] + if entry.get("sha256") != input_sha256: + raise ValueError( + f"--input-h5 has SHA-256 {input_sha256}, but {manifest_path} pins " + f"{entry.get('sha256')!r} for {name!r}." + ) + build = manifest.get("build") + if isinstance(build, dict): + reference = { + "repo_id": entry.get("repo_id"), + "release_id": build.get("build_id"), + "revision": entry.get("revision"), + } + else: + reference = { + "repo_id": entry.get("repo_id"), + "release": manifest.get("release"), + "build": build, + } + try: + location = referenced_build(reference) + except ValueError as error: + raise ValueError(f"{manifest_path} names no readable build: {error}") from error + return { + "manifest": manifest_path.name, + "manifest_sha256": hashlib.sha256(raw).hexdigest(), + "artifact": name, + **{key: value for key, value in reference.items() if value is not None}, + "folder": location.folder, + "sha256": input_sha256, + } + + +def copy_release_manifest( + receipt: Mapping[str, Any], + *, + receipt_path: Path, + receipt_sha256: str, + target: CopyReleaseManifest, + built_at: str, +) -> dict[str, object]: + """The copy's release manifest in the build-folder layout. + + Its one microdata artifact is the copy, so R1's + ``--donor-release-manifest`` check (the base H5's SHA-256 against it) + passes on the copy only. ``derived_from`` names the input; ``patch`` + names the tool, its commit, the receipt and the added columns. + """ + + output, source = receipt["output"], receipt["input"] + assert isinstance(output, Mapping) and isinstance(source, Mapping) + output_path = Path(str(output["path"])) + added = receipt["added_columns"] + assert isinstance(added, list) + return { + "schema_version": 1, + "release": target.release, + "build": target.build, + "built_at": built_at, + "dataset_role": COPY_DATASET_ROLE, + "is_default": False, + "issue": ISSUE, + "plan": PLAN, + "purpose": PURPOSE, + "derived_from": { + "file": Path(str(source["path"])).name, + "sha256": source["sha256"], + "rows": source["rows"], + "release": source.get("release"), + }, + "patch": { + "tool": TOOL, + "tool_commit": receipt.get("tool_commit"), + "engine": receipt.get("engine"), + "receipt": Path(receipt_path).name, + "added_columns": [f"{r['entity']}.{r['column']}" for r in added], + }, + "artifacts": { + output_path.stem: { + "kind": "microdata", + "path": output_path.name, + "repo_id": target.repo_id, + "sha256": output["sha256"], + "role": "dataset", + }, + "patch_receipt": { + "kind": "receipt", + "path": Path(receipt_path).name, + "repo_id": target.repo_id, + "sha256": receipt_sha256, + "role": "patch_receipt", + }, + }, + } + + def build_patch_steps( *, zero_columns: Sequence[str], @@ -262,6 +452,8 @@ def patch_donor_h5( receipt_path: Path, tool_identity: Mapping[str, object] | None = None, engine_identity: Mapping[str, object] | None = None, + input_release_manifest: Path | None = None, + release_manifest: CopyReleaseManifest | None = None, ) -> dict[str, object]: """Write the patched copy and its receipt; return the receipt. @@ -269,13 +461,25 @@ def patch_donor_h5( reads. The copy starts as a byte copy of the input; only the entity tables a step changes are rewritten, through the shared frame-table codec, in their stored HDF format. The copy is verified before it - replaces ``output_h5``. + replaces ``output_h5``. ``input_release_manifest`` is checked before any + work; ``release_manifest`` is written last, after the receipt. """ input_h5, output_h5 = Path(input_h5), Path(output_h5) receipt_path = Path(receipt_path) - _validate_paths(input_h5, output_h5, receipt_path) + _validate_paths( + input_h5, + output_h5, + receipt_path, + *(() if input_release_manifest is None else (Path(input_release_manifest),)), + *(() if release_manifest is None else (Path(release_manifest.path),)), + ) input_sha256 = refuse_denied_pool_h5(input_h5, consumer=_CONSUMER) + input_release = ( + None + if input_release_manifest is None + else input_release_identity(Path(input_release_manifest), input_sha256) + ) with pd.HDFStore(input_h5, mode="r") as store: keys = sorted(store.keys()) absent = [entity for entity in US_SCHEMA.entities if f"/{entity}" not in keys] @@ -335,6 +539,7 @@ def patch_donor_h5( "path": str(input_h5.resolve()), "sha256": input_sha256, "rows": {entity: len(tables[entity]) for entity in US_SCHEMA.entities}, + "release": input_release, }, "output": { "path": str(output_h5.resolve()), @@ -349,15 +554,36 @@ def patch_donor_h5( "added_columns": [r for r in columns if r["action"] == "added"], "kept_columns": [r for r in columns if r["action"] == "kept_existing"], "steps": step_receipts, + "release_manifest": ( + None if release_manifest is None else release_manifest.identity() + ), } - receipt_path.parent.mkdir(parents=True, exist_ok=True) - receipt_path.write_text( - json.dumps(receipt, indent=2, sort_keys=True, allow_nan=False) + "\n", - encoding="utf-8", - ) + receipt_sha256 = _write_json(receipt_path, receipt) + if release_manifest is not None: + _write_json( + Path(release_manifest.path), + copy_release_manifest( + receipt, + receipt_path=receipt_path, + receipt_sha256=receipt_sha256, + target=release_manifest, + built_at=datetime.now(UTC).isoformat(timespec="seconds"), + ), + ) return receipt +def _write_json(path: Path, document: Mapping[str, object]) -> str: + """Write ``document`` as sorted, indented JSON; return the bytes' SHA-256.""" + + data = ( + json.dumps(document, indent=2, sort_keys=True, allow_nan=False) + "\n" + ).encode("utf-8") + path.parent.mkdir(parents=True, exist_ok=True) + path.write_bytes(data) + return hashlib.sha256(data).hexdigest() + + @dataclass(frozen=True) class _StoredLayout: """How the input stored one entity table, so the rewrite can keep it.""" @@ -565,7 +791,9 @@ def _attribute_value(value: object) -> object: return value -def _validate_paths(input_h5: Path, output_h5: Path, receipt_path: Path) -> None: +def _validate_paths( + input_h5: Path, output_h5: Path, receipt_path: Path, *manifests: Path +) -> None: if not input_h5.is_file(): raise ValueError(f"--input-h5 is not a file: {input_h5}.") if output_h5.suffix != ".h5": @@ -575,6 +803,12 @@ def _validate_paths(input_h5: Path, output_h5: Path, receipt_path: Path) -> None raise ValueError("--output-h5 must differ from --input-h5.") if receipt_path.resolve() in resolved: raise ValueError("--receipt must differ from --input-h5 and --output-h5.") + paths = [*resolved, receipt_path.resolve(), *(path.resolve() for path in manifests)] + if len(set(paths)) != len(paths): + raise ValueError( + "--input-h5, --output-h5, --receipt, --input-release-manifest and " + "--release-manifest must be different files." + ) def _sha256(path: Path) -> str: @@ -641,7 +875,42 @@ def _parse_args(argv: Sequence[str] | None = None) -> argparse.Namespace: "more than one (default: every reviewed column)." ), ) - return parser.parse_args(argv) + parser.add_argument( + "--input-release-manifest", + type=Path, + help=( + "The published donor's release_manifest.json. The input's SHA-256 " + "must match its one microdata artifact; the receipt records the " + "donor build it names." + ), + ) + parser.add_argument( + "--release-manifest", + type=Path, + help=( + "Write a build-folder release manifest for the copy here, for R1's " + "--donor-release-manifest. Needs --manifest-release and " + "--manifest-build. Upload the copy, the receipt and this file (as " + "release_manifest.json) to releases/// in " + "--manifest-repo-id." + ), + ) + parser.add_argument( + "--manifest-repo-id", + default=DEFAULT_MANIFEST_REPO_ID, + help=f"Repository the copy is uploaded to (default: {DEFAULT_MANIFEST_REPO_ID}).", + ) + parser.add_argument("--manifest-release", help="Release folder name of the copy.") + parser.add_argument("--manifest-build", help="Build folder name of the copy.") + args = parser.parse_args(argv) + names = (args.manifest_release, args.manifest_build) + if args.release_manifest is None and any(name is not None for name in names): + parser.error("--manifest-release and --manifest-build need --release-manifest.") + if args.release_manifest is not None and any(name is None for name in names): + parser.error( + "--release-manifest needs --manifest-release and --manifest-build." + ) + return args def main(argv: Sequence[str] | None = None) -> int: @@ -654,6 +923,16 @@ def main(argv: Sequence[str] | None = None) -> int: zero_columns=args.zero_column or list(REVIEWED_ZERO_COLUMNS), engine=PolicyEngineUSEngine(), ) + release_manifest = ( + None + if args.release_manifest is None + else CopyReleaseManifest( + path=args.release_manifest, + release=args.manifest_release, + build=args.manifest_build, + repo_id=args.manifest_repo_id, + ) + ) receipt = patch_donor_h5( args.input_h5, args.output_h5, @@ -661,6 +940,8 @@ def main(argv: Sequence[str] | None = None) -> int: receipt_path=receipt_path, tool_identity=current_tool_identity(), engine_identity=_engine_identity(), + input_release_manifest=args.input_release_manifest, + release_manifest=release_manifest, ) except ValueError as error: raise SystemExit(f"Donor patch refused: {error}") from error From 06b53f6255c105eb89df8ff67b6f57237b5b18c2 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mar=C3=ADa=20Juaristi?= <127882282+juaristi22@users.noreply.github.com> Date: Tue, 17 Nov 2026 11:42:33 +0000 Subject: [PATCH 05/31] Add a pre-R2 check for counties with an empty SOI AGI row R2's attach_surface builds each county's IRS SOI rows from the state rows' stored entries, and the state AGI row stores no zero. A county whose households all have AGI of exactly 0 therefore gets an empty AGI row, and attach_surface refuses the run after the materialize engine pass (#1630 review, finding 1). Minimum support fills only counties with no household. tools/check_us_acs_county_agi_support.py runs on the staging H5 before R2, in minutes and with no engine pass: - It reads the household table and only the AGI income columns of the person and tax-unit tables (fixed-format blocks are streamed in row chunks). - The AGI income columns are the money inputs of policyengine-us's irs_gross_income closure, read from the installed engine's source without importing it, less Social Security (taxable share only) and deductions, expenses and contributions. A null cell counts as 0, the default R2 fills. The check errs towards listing a county. - With --puma-ladder it takes the county list from the ladder and applies R2's own minimum-support moves first. - It writes a JSON report and exits 2 when a county is at risk. Co-Authored-By: Claude Opus 5.5 --- ...-acs-county-agi-support-check-922.added.md | 1 + .../us/test_us_acs_county_agi_support.py | 238 +++++++++ tools/check_us_acs_county_agi_support.py | 471 ++++++++++++++++++ 3 files changed, 710 insertions(+) create mode 100644 changelog.d/us-acs-county-agi-support-check-922.added.md create mode 100644 packages/microcosm-build/tests/engine_free/us/test_us_acs_county_agi_support.py create mode 100644 tools/check_us_acs_county_agi_support.py diff --git a/changelog.d/us-acs-county-agi-support-check-922.added.md b/changelog.d/us-acs-county-agi-support-check-922.added.md new file mode 100644 index 0000000000..aa8837ad26 --- /dev/null +++ b/changelog.d/us-acs-county-agi-support-check-922.added.md @@ -0,0 +1 @@ +`tools/check_us_acs_county_agi_support.py` lists, before the ACS local release (R2) runs, the counties whose county IRS SOI AGI row R2 would build empty: counties with households but none that can carry a nonzero AGI (microcosm#922; microcosm#1630 review, finding 1). The state AGI row stores no zero, so such a county makes `attach_surface` refuse the run after the materialize engine pass. The check reads the staging H5's household table and only the AGI income columns, which it takes from policyengine-us's `irs_gross_income` inputs without importing the engine (Social Security and deductions are left out, so it errs towards listing a county). With `--puma-ladder` it applies R2's own minimum-support moves first. It exits 2 when a county is at risk. diff --git a/packages/microcosm-build/tests/engine_free/us/test_us_acs_county_agi_support.py b/packages/microcosm-build/tests/engine_free/us/test_us_acs_county_agi_support.py new file mode 100644 index 0000000000..dd02ef50cb --- /dev/null +++ b/packages/microcosm-build/tests/engine_free/us/test_us_acs_county_agi_support.py @@ -0,0 +1,238 @@ +"""The pre-R2 check for counties whose SOI AGI row would be empty (microcosm#922). + +``tools/check_us_acs_county_agi_support.py`` lists counties that have +households but none that can carry a nonzero AGI: R2's ``attach_surface`` +refuses such a county after the engine pass. These tests use small fixture +H5 files and a stand-in engine index, so no country engine is imported. +""" + +from __future__ import annotations + +import importlib.util +import json +import sys +from dataclasses import dataclass +from pathlib import Path + +import numpy as np +import pandas as pd +import pytest + +from microcosm.build.us_runtime.h5_io import write_nullable_us_h5 +from microcosm.frame import US_SCHEMA, Frame, VariableMetadata, WeightKind, Weights +from test_support.paths import paths_for + +_TEST_PATHS = paths_for("microcosm-build") + + +@pytest.fixture(scope="module") +def check(): + path = _TEST_PATHS.repository / "tools" / "check_us_acs_county_agi_support.py" + spec = importlib.util.spec_from_file_location("check_us_county_agi", path) + module = importlib.util.module_from_spec(spec) + assert spec.loader is not None + sys.modules[spec.name] = module + spec.loader.exec_module(module) + return module + + +@dataclass(frozen=True) +class _Closure: + input_leaves: tuple[str, ...] + engine_version: str = "fixture" + sha256: str = "c" * 64 + + +class _Index: + """Stand-in for PolicyEngineUSVariableMetadataIndex.""" + + leaves = { + "employment_income_before_lsr": ("person", "float", "currency-USD"), + "taxable_interest_income": ("person", "float", "currency-USD"), + "social_security_retirement": ("person", "float", "currency-USD"), + "student_loan_interest": ("person", "float", "currency-USD"), + "other_net_gain": ("tax_unit", "float", "currency-USD"), + "age": ("person", "float", None), + "is_blind": ("person", "bool", None), + } + + def variable_dependency_closure(self, name): + assert name == "irs_gross_income" + return _Closure(tuple(sorted(self.leaves))) + + def variable_metadata(self, name): + entity, dtype, _unit = self.leaves[name] + return VariableMetadata(name=name, entity=entity, dtype=dtype, period="year") + + def variable_unit(self, name): + return self.leaves[name][2] + + +def _frame(person_income: dict[str, list[float]], unit_income=None) -> Frame: + """Six households in three counties of state 01, one person each. + + 01001: two households with income. 01003: two households, the first with + Social Security only, the second with a null wage. 01005: two ACS + households, one a group-quarters record. + """ + + n = 6 + ids = np.arange(1, n + 1) + person = pd.DataFrame( + { + "person_id": ids, + **{f"person_{entity}_id": ids for entity in US_SCHEMA.group_entities}, + "age": np.full(n, 40.0), + } + ) + for column, values in person_income.items(): + person[column] = values + tables = {"person": person} + for entity in US_SCHEMA.group_entities: + tables[entity] = pd.DataFrame({f"{entity}_id": ids}) + household = tables["household"] + household["state_fips"] = np.full(n, 1) + household["county_fips"] = [1001, 1001, 1003, 1003, 1005, 1005] + household["county_fips_2023"] = household["county_fips"] + household["household_spine"] = pd.Series( + ["asec_puf"] * 4 + ["acs_2024_1yr"] * 2, dtype=object + ) + household["TYPEHUGQ"] = [np.nan] * 4 + [1.0, 3.0] + for column, values in (unit_income or {}).items(): + tables["tax_unit"][column] = values + return Frame( + tables, + US_SCHEMA, + {"household": Weights(np.ones(n), WeightKind.CALIBRATED)}, + ) + + +_INCOME = { + "employment_income_before_lsr": [100.0, 0.0, 0.0, np.nan, 0.0, 0.0], + "taxable_interest_income": [0.0, 5.0, 0.0, 0.0, 0.0, 0.0], + "social_security_retirement": [0.0, 0.0, 900.0, 0.0, 0.0, 0.0], + "student_loan_interest": [0.0, 0.0, 0.0, 0.0, 300.0, 0.0], +} + + +def test_agi_income_columns_drop_social_security_and_deductions(check) -> None: + sources = check.agi_income_columns(_Index()) + + assert sources["person"] == [ + "employment_income_before_lsr", + "taxable_interest_income", + ] + assert sources["tax_unit"] == ["other_net_gain"] + assert sources["excluded"] == { + "social_security_retirement": "social_security_taxable_share_only", + "student_loan_interest": "deduction_expense_or_contribution", + } + assert sources["engine_version"] == "fixture" + + +def test_households_without_agi_income_are_found(check) -> None: + frame = _frame(_INCOME) + + flags = check.household_income_flags( + frame.table("household"), + frame.table("person"), + frame.table("tax_unit"), + person_columns=["employment_income_before_lsr", "taxable_interest_income"], + ) + + # Social Security only, a null wage, a deduction only: no AGI income. + assert flags.tolist() == [True, True, False, False, False, False] + + +def test_tax_unit_income_reaches_its_household(check) -> None: + frame = _frame(_INCOME, unit_income={"other_net_gain": [0, 0, 0, 0, 0, 7.0]}) + + flags = check.household_income_flags( + frame.table("household"), + frame.table("person"), + frame.table("tax_unit"), + person_columns=["employment_income_before_lsr"], + tax_unit_columns=["other_net_gain"], + ) + + assert flags.tolist() == [True, False, False, False, False, True] + + +def test_report_lists_counties_with_households_but_no_agi_income(check) -> None: + frame = _frame(_INCOME) + households = frame.table("household") + income = np.asarray([True, True, False, False, False, True]) + + report = check.county_agi_report( + households, + income, + county_column="county_fips_2023", + county_populations={1001: 10.0, 1003: 5.0, 1005: 5.0, 1007: 3.0}, + ) + + assert report["at_risk"] == ["01003"] + assert report["at_risk_detail"]["01003"] == { + "households": 2, + "supporting_households": 2, + "households_with_agi_income": 0, + } + # 1007 has ladder population but no household: minimum support's case. + assert report["no_household"] == ["01007"] + # A group-quarters record counts for AGI but not for support. + assert report["by_county"]["01005"]["supporting_households"] == 1 + assert report["fewer_than_min_support_with_agi_income"] == ["01001", "01005"] + assert report["counties_outside_ladder"] == [] + + +@pytest.mark.parametrize("layout", ["fixed", "table"]) +def test_read_columns_reads_only_the_named_columns( + check, tmp_path: Path, layout: str +) -> None: + frame = _frame(_INCOME) + path = tmp_path / f"{layout}.h5" + if layout == "fixed": + write_nullable_us_h5(frame, path, period=2024, artifact_kind="fixture") + else: + with pd.HDFStore(path, mode="w") as store: + store.put("person", frame.table("person"), format="table") + + read = check.read_columns( + path, + "person", + ["person_household_id", "taxable_interest_income", "not_a_column"], + ) + + assert list(read.columns) == ["person_household_id", "taxable_interest_income"] + np.testing.assert_array_equal( + read["taxable_interest_income"].to_numpy(), _INCOME["taxable_interest_income"] + ) + np.testing.assert_array_equal( + read["person_household_id"].to_numpy(), np.arange(1, 7) + ) + + +def test_command_exits_2_and_reports_an_at_risk_county( + check, tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + import microcosm.frame.adapters.policyengine_us as adapter + + monkeypatch.setattr(adapter, "PolicyEngineUSVariableMetadataIndex", _Index) + staging = tmp_path / "staging.h5" + write_nullable_us_h5(_frame(_INCOME), staging, period=2024, artifact_kind="fixture") + out = tmp_path / "report.json" + + status = check.main(["--h5", str(staging), "--out", str(out)]) + + report = json.loads(out.read_text()) + assert status == check.EXIT_AT_RISK + assert report["at_risk"] == ["01003", "01005"] + assert report["agi_income_columns"]["person_present"] == [ + "employment_income_before_lsr", + "taxable_interest_income", + ] + assert report["agi_income_columns"]["tax_unit_present"] == [] + assert report["minimum_support"] is None + + healthy = dict(_INCOME, taxable_interest_income=[0.0, 5.0, 1.0, 0.0, 2.0, 0.0]) + write_nullable_us_h5(_frame(healthy), staging, period=2024, artifact_kind="fixture") + assert check.main(["--h5", str(staging), "--county-column", "county_fips"]) == 0 diff --git a/tools/check_us_acs_county_agi_support.py b/tools/check_us_acs_county_agi_support.py new file mode 100644 index 0000000000..138bf672f0 --- /dev/null +++ b/tools/check_us_acs_county_agi_support.py @@ -0,0 +1,471 @@ +"""List counties whose county SOI AGI row R2 would build empty (pre-check). + +The ACS local release (R2, ``tools/build_us_acs_local_release.py``) builds a +county's IRS SOI rows in ``attach_surface`` from the stored entries of the +state SOI rows for the county's households (``split_state_rows``). The state +AGI row stores no zero, so when every household of a county has an AGI of +exactly 0 the county's AGI row is empty. ``attach_surface`` then refuses the +run, after the materialize stage's engine pass (microcosm#1630 review, +finding 1). Minimum county support fills only counties with no household, so +it does not help here. + +This check runs on the staging H5 (R1's output) before R2, with no engine +pass and in minutes: + +- It reads the household table, and only the AGI income columns of the + person and tax-unit tables. +- The AGI income columns are the money inputs behind policyengine-us's + ``irs_gross_income`` (its gross income sources), read from the installed + engine's source without importing it, less the leaves that cannot make + gross income nonzero on their own: Social Security (only its taxable share + counts, which is 0 without other income) and deductions, expenses and + contributions (``NOT_INCOME_LEAVES``). +- A household can carry a nonzero AGI when any of its persons or tax units + has a nonzero, non-null value in one of those columns. R2 fills a null + income cell with the engine default, 0. +- With ``--puma-ladder`` it applies R2's own minimum-support moves + (``plan_minimum_support`` with ``--county-min-support``, default R2's 3) + and takes the county list from the ladder, as R2 does. +- A county is **at risk** when it has households but none can carry a + nonzero AGI. The check is conservative: a household whose only income is + Social Security counts as zero, so a listed county may still pass. + Return-count rows count every tax unit, so they are never empty. + +Exit status 0: no county at risk. Exit status 2: at least one county at +risk; the JSON report (``--out``) lists them. Each needs a ruling before R2 +(drop the county's AGI row with a receipt, or give it a declared SOI cell). + +Usage:: + + python tools/check_us_acs_county_agi_support.py \\ + --h5 /acs_multispine_staging.h5 \\ + --county-column county_fips_2023 \\ + --puma-ladder build/us/us_puma_ladder_2020.npz \\ + --out /county_agi_support.json +""" + +# No ``from __future__ import annotations``: test loaders run this file +# without registering it in ``sys.modules``. +import argparse +import json +import sys +import time +from collections import defaultdict +from collections.abc import Mapping, Sequence +from pathlib import Path +from typing import Any + +import h5py +import numpy as np +import pandas as pd + +_TOOLS = Path(__file__).resolve().parent +if str(_TOOLS) not in sys.path: + sys.path.insert(0, str(_TOOLS)) + +import us_acs_local_county_surface as county_surface # noqa: E402 + +from microcosm.frame import read_frame_table # noqa: E402 + +TOOL = "tools/check_us_acs_county_agi_support.py" +ISSUE = "microcosm#922" +#: The engine variable whose input leaves are the AGI income columns. +GROSS_INCOME_ROOT = "irs_gross_income" +#: Social Security enters gross income only through its taxable share, which +#: is 0 for a household without enough other income. +SOCIAL_SECURITY_LEAVES = frozenset( + { + "social_security_dependents", + "social_security_disability", + "social_security_retirement", + "social_security_survivors", + } +) +#: Money leaves of the ``irs_gross_income`` closure that are deductions, +#: expenses, contributions or tax-exempt amounts: none makes gross income +#: nonzero on its own. +NOT_INCOME_LEAVES = frozenset( + { + "alimony_expense", + "domestic_production_ald", + "early_withdrawal_penalty", + "educator_expense", + "health_insurance_premiums", + "health_savings_account_ald", + "health_savings_account_payroll_contributions", + "pre_tax_health_insurance_premiums", + "qualified_adoption_assistance_expense", + "qualified_tuition_expenses", + "roth_401k_contributions_desired", + "roth_403b_contributions_desired", + "roth_ira_contributions_desired", + "self_employed_pension_contributions_desired", + "student_loan_interest", + "tax_exempt_interest_income", + "traditional_401k_contributions_desired", + "traditional_403b_contributions_desired", + "traditional_ira_contributions_desired", + "us_bonds_for_higher_ed", + } +) +EXIT_AT_RISK = 2 +_ROW_CHUNK = 250_000 + + +def agi_income_columns(index: Any) -> dict[str, Any]: + """The AGI income columns by entity, from the engine's static index. + + ``index`` is a ``PolicyEngineUSVariableMetadataIndex`` (or a stand-in + with ``variable_dependency_closure``, ``variable_metadata`` and + ``variable_unit``). Returns the person and tax-unit columns, the leaves + left out and why, and the closure's engine version and digest. + """ + + closure = index.variable_dependency_closure(GROSS_INCOME_ROOT) + columns: dict[str, list[str]] = defaultdict(list) + excluded: dict[str, str] = {} + for leaf in closure.input_leaves: + metadata = index.variable_metadata(leaf) + if metadata.dtype != "float" or index.variable_unit(leaf) != "currency-USD": + continue + if leaf in SOCIAL_SECURITY_LEAVES: + excluded[leaf] = "social_security_taxable_share_only" + elif leaf in NOT_INCOME_LEAVES: + excluded[leaf] = "deduction_expense_or_contribution" + else: + columns[metadata.entity].append(leaf) + unexpected = sorted(set(columns) - {"person", "tax_unit"}) + if unexpected: + raise ValueError( + f"{GROSS_INCOME_ROOT} money leaves on entities {unexpected}; the " + "check reads person and tax-unit columns only." + ) + return { + "root": GROSS_INCOME_ROOT, + "engine_version": closure.engine_version, + "closure_sha256": closure.sha256, + "person": sorted(columns.get("person", [])), + "tax_unit": sorted(columns.get("tax_unit", [])), + "excluded": dict(sorted(excluded.items())), + } + + +def read_columns(path: Path, key: str, columns: Sequence[str]) -> pd.DataFrame: + """Read only ``columns`` (those present) of one pandas H5 table. + + A table-format table is read with ``select``. A fixed-format table's + numeric blocks are streamed in row chunks, so memory holds only the + requested columns; a requested column in an object block is read through + the shared frame-table reader instead. + """ + + with pd.HDFStore(path, mode="r") as store: + if store.get_storer(key).is_table: + names = set(store.select(key, start=0, stop=0).columns) + present = list(dict.fromkeys(c for c in columns if c in names)) + return store.select(key, columns=present) + wanted = list(dict.fromkeys(columns)) + result: dict[str, np.ndarray] = {} + slow: list[str] = [] + with h5py.File(path, "r") as handle: + group = handle[key] + names = [_text(name) for name in group["axis0"][:]] + rows = int(group["axis1"].shape[0]) + for block in range(int(group.attrs["nblocks"])): + items = [_text(name) for name in group[f"block{block}_items"][:]] + values = group[f"block{block}_values"] + hits = [ + (position, item) + for position, item in enumerate(items) + if item in wanted + ] + if not hits: + continue + if values.dtype == object or values.ndim != 2: + slow.extend(item for _position, item in hits) + continue + parts: dict[str, list[np.ndarray]] = {item: [] for _p, item in hits} + for start in range(0, rows, _ROW_CHUNK): + chunk = values[start : start + _ROW_CHUNK] + for position, item in hits: + parts[item].append(np.asarray(chunk[:, position])) + for item, chunks in parts.items(): + result[item] = np.concatenate(chunks) if chunks else np.empty(0) + del names + if slow: + with pd.HDFStore(path, mode="r") as store: + table = read_frame_table(store, key) + for column in slow: + result[column] = table[column].to_numpy() + del table + return pd.DataFrame({c: result[c] for c in wanted if c in result}) + + +def _text(value: object) -> str: + return value.decode("utf-8") if isinstance(value, bytes) else str(value) + + +def household_income_flags( + households: pd.DataFrame, + person: pd.DataFrame, + tax_unit: pd.DataFrame | None, + *, + person_columns: Sequence[str], + tax_unit_columns: Sequence[str] = (), +) -> np.ndarray: + """Per household (in ``households`` order): can it carry a nonzero AGI? + + True when any of its persons, or any tax unit one of its persons belongs + to, has a nonzero, non-null value in an AGI income column. A null cell + counts as 0, the engine default R2 fills. + """ + + household_ids = households["household_id"].to_numpy() + position = pd.Index(household_ids) + if not position.is_unique: + raise ValueError("Household ids must be unique.") + person_household = person["person_household_id"].to_numpy() + person_rows = position.get_indexer(person_household) + if (person_rows < 0).any(): + raise ValueError("Persons name households the household table lacks.") + person_income = np.zeros(len(person), dtype=bool) + for column in person_columns: + if column in person.columns: + values = pd.to_numeric(person[column], errors="coerce").to_numpy(float) + person_income |= np.nan_to_num(values, nan=0.0) != 0.0 + flags = np.zeros(len(households), dtype=bool) + np.logical_or.at(flags, person_rows, person_income) + present = [ + column + for column in tax_unit_columns + if tax_unit is not None and column in tax_unit.columns + ] + if present: + unit_income = np.zeros(len(tax_unit), dtype=bool) + for column in present: + values = pd.to_numeric(tax_unit[column], errors="coerce").to_numpy(float) + unit_income |= np.nan_to_num(values, nan=0.0) != 0.0 + units = pd.Index(tax_unit["tax_unit_id"].to_numpy()) + person_units = units.get_indexer(person["person_tax_unit_id"].to_numpy()) + if (person_units < 0).any(): + raise ValueError("Persons name tax units the tax-unit table lacks.") + np.logical_or.at(flags, person_rows, unit_income[person_units]) + return flags + + +def county_agi_report( + households: pd.DataFrame, + income: np.ndarray, + *, + county_column: str, + county_populations: Mapping[int, float] | None = None, +) -> dict[str, Any]: + """Per-county household counts and the counties at risk. + + ``county_populations`` (the ladder's, as R2 uses) sets the county list; + without it the list is the counties the households name. + """ + + codes = county_surface.county_codes(households, county_column=county_column) + support = county_surface.support_universe(households) + totals, supporting, with_income = (defaultdict(int) for _ in range(3)) + for code, supports, earns in zip( + codes.tolist(), support.tolist(), income.tolist(), strict=True + ): + totals[code] += 1 + supporting[code] += int(supports) + with_income[code] += int(earns) + if county_populations is None: + counties = sorted(totals) + else: + counties = sorted( + int(code) for code, value in county_populations.items() if float(value) > 0 + ) + at_risk, no_household, thin = [], [], [] + rows = {} + for code in counties: + record = { + "households": totals.get(code, 0), + "supporting_households": supporting.get(code, 0), + "households_with_agi_income": with_income.get(code, 0), + } + rows[f"{code:05d}"] = record + if record["households"] == 0: + no_household.append(f"{code:05d}") + elif record["households_with_agi_income"] == 0: + at_risk.append(f"{code:05d}") + elif ( + record["households_with_agi_income"] + < county_surface.DEFAULT_COUNTY_MIN_SUPPORT + ): + thin.append(f"{code:05d}") + outside = ( + sorted(set(totals) - set(counties)) if county_populations is not None else [] + ) + return { + "county_column": county_column, + "counties": len(counties), + "households": int(len(households)), + "households_with_agi_income": int(income.sum()), + "at_risk": at_risk, + "at_risk_detail": {code: rows[code] for code in at_risk}, + "no_household": no_household, + "fewer_than_min_support_with_agi_income": thin, + "counties_outside_ladder": [f"{code:05d}" for code in outside], + "by_county": rows, + } + + +def _parse_args(argv: Sequence[str] | None = None) -> argparse.Namespace: + parser = argparse.ArgumentParser( + description=( + "List counties whose county SOI AGI row R2 would build empty: " + "counties with households but none that can carry a nonzero AGI." + ) + ) + parser.add_argument( + "--h5", required=True, type=Path, help="Staging H5 (R1 output)." + ) + parser.add_argument( + "--county-column", + default=county_surface.COUNTY_COLUMN_2023, + choices=county_surface.COUNTY_FIPS_COLUMNS, + help="R2's --county-column (default county_fips_2023).", + ) + parser.add_argument( + "--puma-ladder", + type=Path, + help=( + "R2's PUMA ladder. With it, the check takes the county list from " + "the ladder and applies R2's minimum-support moves first." + ), + ) + parser.add_argument( + "--county-min-support", + type=int, + default=county_surface.DEFAULT_COUNTY_MIN_SUPPORT, + help=( + "R2's --county-min-support (default " + f"{county_surface.DEFAULT_COUNTY_MIN_SUPPORT}); used only with --puma-ladder." + ), + ) + parser.add_argument("--out", type=Path, help="JSON report path.") + return parser.parse_args(argv) + + +def main(argv: Sequence[str] | None = None) -> int: + args = _parse_args(argv) + started = time.time() + from microcosm.frame.adapters.policyengine_us import ( + PolicyEngineUSVariableMetadataIndex, + ) + + sources = agi_income_columns(PolicyEngineUSVariableMetadataIndex()) + with pd.HDFStore(args.h5, mode="r") as store: + households = read_frame_table(store, "household") + person = read_columns( + args.h5, + "person", + ["person_household_id", "person_tax_unit_id", *sources["person"]], + ) + tax_unit = ( + read_columns(args.h5, "tax_unit", ["tax_unit_id", *sources["tax_unit"]]) + if sources["tax_unit"] + else None + ) + present_person = [ + column for column in sources["person"] if column in person.columns + ] + present_unit = [ + column + for column in sources["tax_unit"] + if tax_unit is not None and column in tax_unit.columns + ] + income = household_income_flags( + households, + person, + tax_unit, + person_columns=present_person, + tax_unit_columns=present_unit, + ) + populations = None + support = None + if args.puma_ladder is not None: + from microcosm.build.us_runtime.puma_ladder import load_us_puma_ladder + + ladder = load_us_puma_ladder(args.puma_ladder) + populations = county_surface.with_county_populations( + ladder, {}, {"county": True}, county_column=args.county_column + )["county"] + needed = county_surface.unsupported_counties( + households, populations, county_column=args.county_column + ) + if args.county_min_support > 0 and needed: + overlaps = county_surface.county_puma_overlaps( + args.puma_ladder, args.county_column + ) + moves, support = county_surface.plan_minimum_support( + households, + populations, + overlaps, + county_column=args.county_column, + per_county=args.county_min_support, + ) + households = county_surface.apply_support_moves( + households, + moves, + county_column=args.county_column, + columns=support["rewritten_columns"], + ) + report = county_agi_report( + households, + income, + county_column=args.county_column, + county_populations=populations, + ) + report.update( + { + "tool": TOOL, + "issue": ISSUE, + "h5": str(args.h5), + "agi_income_columns": { + **sources, + "person_present": present_person, + "tax_unit_present": present_unit, + }, + "minimum_support": ( + None + if support is None + else { + "households_per_county": args.county_min_support, + "moves": len(support.get("moves", [])), + "moves_sha256": support.get("moves_sha256"), + "moved_counties": support.get("moved_counties", []), + } + ), + "seconds": round(time.time() - started, 1), + } + ) + rendered = json.dumps(report, indent=2, sort_keys=True) + "\n" + if args.out is not None: + args.out.parent.mkdir(parents=True, exist_ok=True) + args.out.write_text(rendered, encoding="utf-8") + summary = { + key: report[key] + for key in ( + "county_column", + "counties", + "households", + "at_risk", + "at_risk_detail", + "no_household", + "fewer_than_min_support_with_agi_income", + "seconds", + ) + } + print(json.dumps(summary, indent=2, sort_keys=True)) + return EXIT_AT_RISK if report["at_risk"] else 0 + + +if __name__ == "__main__": + raise SystemExit(main()) From 78acba5f5aef305941b8e2494944cd0f99e3676d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mar=C3=ADa=20Juaristi?= <127882282+juaristi22@users.noreply.github.com> Date: Tue, 17 Nov 2026 11:42:33 +0000 Subject: [PATCH 06/31] Let R2 drop an empty county SOI row with a receipt, by explicit flag A county whose households all have a zero measure (AGI exactly 0) gets an empty county SOI row, and attach_surface refuses the run after the engine pass. The #1630 review leaves the remedy to a ruling: drop the row with a receipt, or give the county a declared SOI cell. The declared-cell path (DECLARED_SOI_COMBINED_CELLS) covers only a county absent from the SOI facts, so it cannot take a county that is present. --county-drop-empty-soi-rows (off by default) drops such a row instead of refusing: only an SOI row whose county cell has households. A county without households, and an empty ACS households row, are refused as before. county_surface.json records each dropped row (target, county cell, concept, target value, households) under zero_measure_soi_rows_dropped; the run identity records the flag and county_targets_dropped, the reliability report lists the dropped rows, and the refresh recipe repeats the flag. Without the flag nothing changes, the identity bytes included. Co-Authored-By: Claude Opus 5.5 --- ...cs-county-drop-empty-soi-rows-922.added.md | 1 + .../us/test_us_acs_local_county_surface.py | 90 ++++++++++++++++++- tools/us_acs_local_county_surface.py | 83 ++++++++++++++--- 3 files changed, 162 insertions(+), 12 deletions(-) create mode 100644 changelog.d/us-acs-county-drop-empty-soi-rows-922.added.md diff --git a/changelog.d/us-acs-county-drop-empty-soi-rows-922.added.md b/changelog.d/us-acs-county-drop-empty-soi-rows-922.added.md new file mode 100644 index 0000000000..9420d127ce --- /dev/null +++ b/changelog.d/us-acs-county-drop-empty-soi-rows-922.added.md @@ -0,0 +1 @@ +The ACS local release takes `--county-drop-empty-soi-rows` (microcosm#922). With it, a county IRS SOI row that is empty although the county has households (every household's measure, for example AGI, is 0, and the state row stores no zero) is dropped with a receipt in `county_surface.json` (`zero_measure_soi_rows_dropped`), the run identity and the reliability report, instead of refusing the run after the engine pass. A county without households is refused as before. The flag is off by default, and passing it is a reviewed decision; the refresh recipe repeats it. diff --git a/packages/microcosm-build/tests/engine_free/us/test_us_acs_local_county_surface.py b/packages/microcosm-build/tests/engine_free/us/test_us_acs_local_county_surface.py index f1d6f553ad..946a8a280d 100644 --- a/packages/microcosm-build/tests/engine_free/us/test_us_acs_local_county_surface.py +++ b/packages/microcosm-build/tests/engine_free/us/test_us_acs_local_county_surface.py @@ -814,13 +814,16 @@ def _materialize_county_fixture( households=None, county_column="planning_region", overlaps=None, + state_matrix=None, + extra_args=(), ): """Materialize a state_county fixture, with a fake engine. By default three households and no county support move. ``households`` replaces the household table (one person each, design weight 10), and ``overlaps`` stands in for the ladder's county-PUMA overlaps that minimum - support reads. + support reads. ``state_matrix`` replaces the two state parents' rows + (return count, AGI); ``extra_args`` are added to the materialize argv. """ from microcosm.build import ledger_artifact from microcosm.build.us_runtime import county_facts as county_facts_module @@ -921,6 +924,7 @@ def _materialize_county_fixture( "0.01", "--county-holdout-fraction", "0.5", + *extra_args, ] ) parents = [_state_spec(), _state_spec("adjusted_gross_income", 1000.0)] @@ -979,7 +983,12 @@ def _materialize_county_fixture( materialized = SimpleNamespace( compiled_specs=parents, matrix=sparse.csr_array( - np.asarray([[1] * len(ids), [10] * len(ids)], np.float32) + np.asarray( + state_matrix + if state_matrix is not None + else [[1] * len(ids), [10] * len(ids)], + np.float32, + ) ), chunk_stats=[], carrier_check={}, @@ -1760,3 +1769,80 @@ def test_projected_county_rows_give_the_same_soi_surface_as_full_rows( assert [(s.name, s.value, s.metadata) for s in projected.specs] == [ (s.name, s.value, s.metadata) for s in full.specs ] + + +def test_a_county_whose_households_all_have_zero_agi_refuses_or_drops_its_row( + monkeypatch, tmp_path +) -> None: + """microcosm#922: 01003's only household has AGI 0, so its AGI row is empty. + + The state row stores no zero, so the county has a household but no entry. + By default attach_surface refuses the run; with + --county-drop-empty-soi-rows it drops that row with a receipt. + """ + zero_agi = [[1, 1, 1], [10, 0, 10]] + for name in ("default", "drop"): + (tmp_path / name).mkdir() + with pytest.raises(SystemExit, match="no supporting household"): + _materialize_county_fixture( + monkeypatch, tmp_path / "default", state_matrix=zero_agi + ) + surface = json.loads( + (tmp_path / "default" / "checkpoint" / "county_surface.json").read_text() + ) + assert "zero_measure_soi_rows_dropped" not in surface + (agi_row,) = surface["unsupported_targets"] + assert agi_row.startswith("county_01003__") + + run = _materialize_county_fixture( + monkeypatch, + tmp_path / "drop", + state_matrix=zero_agi, + extra_args=("--county-drop-empty-soi-rows",), + ) + checkpoint = run.args.checkpoint_dir + surface = json.loads((checkpoint / "county_surface.json").read_text()) + (dropped,) = surface["zero_measure_soi_rows_dropped"] + assert dropped["target"] == agi_row + assert dropped["county_fips"] == "01003" + assert dropped["cell_members"] == ["01003"] + assert dropped["concept"] == "adjusted_gross_income" + assert dropped["households"] == 1 + identity = json.loads((checkpoint / "run_identity.json").read_text()) + assert identity["county_targets_dropped"] == [agi_row] + assert identity["county_drop_empty_soi_rows"] is True + assert run.county.refresh_recipe("release", identity).endswith( + " --county-drop-empty-soi-rows" + ) + _loaded, _design, registry, _records, matrix = run.module.load_checkpoint_surface( + checkpoint, identity + ) + # The default fixture's 12 rows less the dropped AGI row. + assert matrix.shape == (11, 3) + assert agi_row not in {spec.name for spec in registry} + + +def test_dropping_empty_soi_rows_never_drops_a_county_without_households() -> None: + county = _county() + households = pd.DataFrame( + {"household_id": [1, 2], "state_fips": [1, 1], "county_fips": [1001, 1001]} + ) + specs = [ + SimpleNamespace( + name=f"county_{code}__agi", + value=5.0, + metadata={ + "county_fips": code, + "source_measure_id": "adjusted_gross_income", + "state_county_parent_target_name": "agi", + }, + ) + for code in ("01001", "01003") + ] + + rows = county.zero_measure_soi_rows( + specs, households, ["county_01001__agi", "county_01003__agi"] + ) + + assert [row["county_fips"] for row in rows] == ["01001"] + assert rows[0]["households"] == 2 diff --git a/tools/us_acs_local_county_surface.py b/tools/us_acs_local_county_surface.py index 35d128d1e9..d230aa70f5 100644 --- a/tools/us_acs_local_county_surface.py +++ b/tools/us_acs_local_county_surface.py @@ -2367,6 +2367,45 @@ def apply_recorded_support(frame, identity, checkpoint_dir): return with_household_table(frame, households) +def zero_measure_soi_rows(specs, households, empty, *, county_column=COUNTY_COLUMN): + """The empty county SOI rows whose county cell has households. + + The state SOI rows store no zero, so a county whose households all have a + zero measure (every household's AGI exactly 0, say) gets an empty row + although it has households. Each record names the row, its county cell, + concept and target, and the cell's household count. + """ + codes = county_codes(households, county_column=county_column) + counts = defaultdict(int) + for code in codes.tolist(): + counts[int(code)] += 1 + empty = set(empty) + rows = [] + for spec in specs: + if spec.name not in empty: + continue + members = cell_members(spec.metadata) + in_cell = sum(counts.get(member, 0) for member in members) + if in_cell == 0: + continue + rows.append( + { + "target": spec.name, + "county_fips": str(spec.metadata["county_fips"]), + "cell_members": [f"{member:05d}" for member in members], + "concept": spec.metadata.get("source_measure_id"), + "parent": spec.metadata.get("state_county_parent_target_name"), + "target_value": float(spec.value), + "households": int(in_cell), + "reason": ( + "every household in the county cell has a zero measure, " + "and the state row stores no zero" + ), + } + ) + return rows + + def require_support(dropped, *, capped_smoke=False): if dropped and not capped_smoke: raise SystemExit( @@ -2403,6 +2442,19 @@ def add_arguments(parser): "Every move is recorded in county_support.json." ), ) + parser.add_argument( + "--county-drop-empty-soi-rows", + action="store_true", + help=( + "Drop, with a receipt in county_surface.json and the run identity, " + "a county IRS SOI row that is empty although the county has " + "households: every household's measure is 0 (for example AGI), " + "and the state row stores no zero. Without the flag such a row " + "refuses the run after the engine pass. A county with no household " + "is refused either way. Off by default; passing it is a reviewed " + "decision (microcosm#922)." + ), + ) def _validate_county_facts(args, parser, geographies): @@ -2700,18 +2752,24 @@ def attach_surface(surface, materialized, frame, populations, args): for index, spec in enumerate(specs) if spec.value != 0 and rows.indptr[index] == rows.indptr[index + 1] ] - (args.checkpoint_dir / SURFACE_FILENAME).write_text( - json.dumps( - { - **county.receipt, - "acs_households": acs.receipt, - "unsupported_targets": empty, - }, - indent=2, + receipt = { + **county.receipt, + "acs_households": acs.receipt, + "unsupported_targets": empty, + } + refused = empty + if getattr(args, "county_drop_empty_soi_rows", False): + # Only SOI rows of counties that have households; an ACS households + # row or a county without households is still refused. + dropped = zero_measure_soi_rows( + county.specs, households, empty, county_column=column ) - ) + receipt["zero_measure_soi_rows_dropped"] = dropped + names = {row["target"] for row in dropped} + refused = [name for name in empty if name not in names] + (args.checkpoint_dir / SURFACE_FILENAME).write_text(json.dumps(receipt, indent=2)) require_support( - empty, + refused, capped_smoke=bool(args.allow_partial_geography and args.sample_fraction < 1), ) county_specs = [*county.specs, *acs.specs] @@ -2769,6 +2827,9 @@ def run_metadata(args, county_holdout): "county_holdout": county_holdout, "county_targets_dropped": getattr(args, "county_targets_dropped", []), } + # Recorded only when set, so every other run identity keeps its bytes. + if getattr(args, "county_drop_empty_soi_rows", False): + metadata["county_drop_empty_soi_rows"] = True # Only a run that read county facts (or ran the county support step) # records them, so a no-county run identity keeps its pre-county bytes. for key, attribute in ( @@ -3027,6 +3088,8 @@ def refresh_recipe(command, materialize_rss): # or the run predates it), so its replay must turn the step off too. support = materialize_rss.get("county_support") or {} command += f" --county-min-support {int(support.get('households_per_county', 0))}" + if materialize_rss.get("county_drop_empty_soi_rows"): + command += " --county-drop-empty-soi-rows" return command From 46674e01f18a91d9e36b1466e60f86dbc60ab037 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mar=C3=ADa=20Juaristi?= <127882282+juaristi22@users.noreply.github.com> Date: Tue, 17 Nov 2026 12:05:33 +0000 Subject: [PATCH 07/31] Add a post-staging check of R2's reviewed-fill rules R2's finalize stage grades every reviewed default fill against acs_local_reviewed_fill_consumers.yaml and refuses an unregistered fill, a different fill value or spine, or another policyengine-us. That refusal comes after materialize and calibrate, hours into the run. tools/check_us_acs_local_reviewed_fills.py runs in seconds after R1: - it reads the staging summary's reviewed_engine_input_nulls (names and counts by spine); - it refuses what materialize refuses: a NEVER_DEFAULT_FILLED null off the ACS spine, and a null ESI employer premium; - it builds the fill records R2 writes, with the fill values R2's _resolve_engine_default gives, and runs R2's own finalize gate on them. A null that an R2 stage fills first counts as a fill, so it errs towards a refusal. It exits 2 when R2 would refuse. Co-Authored-By: Claude Opus 5.5 --- ...s-acs-reviewed-fills-precheck-922.added.md | 1 + .../test_us_acs_local_reviewed_fills_check.py | 160 ++++++++++++ tools/check_us_acs_local_reviewed_fills.py | 238 ++++++++++++++++++ 3 files changed, 399 insertions(+) create mode 100644 changelog.d/us-acs-reviewed-fills-precheck-922.added.md create mode 100644 packages/microcosm-build/tests/engine_free/us/test_us_acs_local_reviewed_fills_check.py create mode 100644 tools/check_us_acs_local_reviewed_fills.py diff --git a/changelog.d/us-acs-reviewed-fills-precheck-922.added.md b/changelog.d/us-acs-reviewed-fills-precheck-922.added.md new file mode 100644 index 0000000000..c81e708a75 --- /dev/null +++ b/changelog.d/us-acs-reviewed-fills-precheck-922.added.md @@ -0,0 +1 @@ +`tools/check_us_acs_local_reviewed_fills.py` grades a staging summary's reviewed engine-input nulls against the ACS local release's fill rules in seconds, before the release runs (microcosm#922). It refuses what materialize would refuse (a null in a never-default-filled column off the ACS spine, a null ESI premium), builds the fill records the release would write with the engine defaults the release resolves, and runs the release's own finalize gate (`acs_local_reviewed_fill_consumer_gate`) on them, which otherwise refuses an unregistered fill hours into the run. It exits 2 when the release would refuse. diff --git a/packages/microcosm-build/tests/engine_free/us/test_us_acs_local_reviewed_fills_check.py b/packages/microcosm-build/tests/engine_free/us/test_us_acs_local_reviewed_fills_check.py new file mode 100644 index 0000000000..e0f8df3b3f --- /dev/null +++ b/packages/microcosm-build/tests/engine_free/us/test_us_acs_local_reviewed_fills_check.py @@ -0,0 +1,160 @@ +"""The post-staging pre-check of R2's reviewed-fill rules (microcosm#922). + +``tools/check_us_acs_local_reviewed_fills.py`` grades a staging summary's +reviewed nulls with R2's own fill constants and finalize gate. These tests +use synthetic summaries and a stand-in engine, so no country engine is +imported. +""" + +from __future__ import annotations + +import importlib.util +import json +import sys +from pathlib import Path +from types import SimpleNamespace + +import pytest + +from microcosm.build.us_runtime.esi_premiums import US_ESI_EMPLOYER_PREMIUM_COLUMN +from test_support.paths import paths_for + +_TEST_PATHS = paths_for("microcosm-build") +_ACS = "acs_2024_1yr" + + +@pytest.fixture(scope="module") +def check(): + path = _TEST_PATHS.repository / "tools" / "check_us_acs_local_reviewed_fills.py" + spec = importlib.util.spec_from_file_location("check_us_acs_fills", path) + module = importlib.util.module_from_spec(spec) + assert spec.loader is not None + sys.modules[spec.name] = module + spec.loader.exec_module(module) + return module + + +@pytest.fixture(scope="module") +def release(check): + return check._release_tool() + + +def _null(column, spines, *, entity="person"): + return { + "entity": entity, + "column": column, + "dtype": "float", + "missing_rows": sum(spines.values()), + "rows": 100, + "missing_rows_by_spine": spines, + } + + +def _resolve(column): + return 0, "int" + + +def test_staged_nulls_split_as_r2_fill_step_treats_them(check, release) -> None: + never_entity, never_column = sorted(release.NEVER_DEFAULT_FILLED)[0] + nulls = [ + _null("strike_benefits", {_ACS: 7}), + _null(never_column, {_ACS: 3}, entity=never_entity), + _null(never_column, {"asec_puf": 2}, entity=never_entity), + _null(US_ESI_EMPLOYER_PREMIUM_COLUMN, {_ACS: 4}), + ] + + split = check.expected_fills( + nulls, + never_default_filled=release.NEVER_DEFAULT_FILLED, + resolve_default=_resolve, + ) + + assert [fill["column"] for fill in split["fills"]] == ["strike_benefits"] + assert split["fills"][0]["fill_value"] == "0" + assert split["fills"][0]["missing_rows_by_spine"] == {_ACS: 7} + assert [item["missing_rows_by_spine"] for item in split["natively_filled"]] == [ + {_ACS: 3} + ] + assert [item["missing_rows_by_spine"] for item in split["denied"]] == [ + {"asec_puf": 2} + ] + assert [item["column"] for item in split["esi"]] == [ + f"person.{US_ESI_EMPLOYER_PREMIUM_COLUMN}" + ] + + +@pytest.mark.parametrize( + ("nulls", "version", "passed", "message"), + [ + ([_null("strike_benefits", {_ACS: 7})], "2.2.1", True, None), + ( + [_null("not_a_registered_input", {_ACS: 7})], + "2.2.1", + False, + "person.not_a_registered_input", + ), + ( + [_null("strike_benefits", {_ACS: 7, "asec_puf": 1})], + "2.2.1", + False, + "person.strike_benefits", + ), + ([_null("strike_benefits", {_ACS: 7})], "2.3.0", False, "2.3.0"), + ], +) +def test_r2_gate_grades_the_expected_fills( + check, release, nulls, version, passed, message +) -> None: + split = check.expected_fills( + nulls, + never_default_filled=release.NEVER_DEFAULT_FILLED, + resolve_default=_resolve, + ) + + report = check.grade( + split, + manifest_names=release.REVIEWED_FILL_MANIFESTS, + never_default_filled=release.NEVER_DEFAULT_FILLED, + installed_engine_version=version, + ) + + assert report["passed"] is passed + if message is not None: + assert any(message in refusal for refusal in report["refusals"]) + + +def test_command_exits_2_on_an_unregistered_fill( + check, tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + variables = { + "strike_benefits": SimpleNamespace(default_value=0), + "not_a_registered_input": SimpleNamespace(default_value=0.0), + } + monkeypatch.setattr( + check, "_tax_benefit_system", lambda: SimpleNamespace(variables=variables) + ) + monkeypatch.setattr(check, "_engine_version", lambda _release: "2.2.1") + summary = tmp_path / "staging.summary.json" + out = tmp_path / "report.json" + summary.write_text( + json.dumps( + {"reviewed_engine_input_nulls": [_null("strike_benefits", {_ACS: 7})]} + ) + ) + + assert check.main(["--staging-summary", str(summary), "--out", str(out)]) == 0 + assert json.loads(out.read_text())["expected_fills"] == 1 + + summary.write_text( + json.dumps( + { + "reviewed_engine_input_nulls": [ + _null("strike_benefits", {_ACS: 7}), + _null("not_a_registered_input", {_ACS: 2}), + ] + } + ) + ) + assert check.main(["--staging-summary", str(summary), "--out", str(out)]) == 2 + refusals = json.loads(out.read_text())["refusals"] + assert any("not_a_registered_input" in refusal for refusal in refusals) diff --git a/tools/check_us_acs_local_reviewed_fills.py b/tools/check_us_acs_local_reviewed_fills.py new file mode 100644 index 0000000000..6e74108935 --- /dev/null +++ b/tools/check_us_acs_local_reviewed_fills.py @@ -0,0 +1,238 @@ +"""Grade a staging run's nulls against R2's reviewed-fill rules (pre-check). + +The ACS local release (R2, ``tools/build_us_acs_local_release.py``) fills +each reviewed engine-input null of the staging H5 with the policyengine-us +default (``fill_reviewed_nulls``). Its materialize stage refuses a null in a +``NEVER_DEFAULT_FILLED`` column and a null ESI employer premium. Its finalize +stage, hours later, grades every applied fill against +``acs_local_reviewed_fill_consumers.yaml`` with +``acs_local_reviewed_fill_consumer_gate``: it refuses a fill without a +register entry, a fill value or spines that differ from the entry, and a +policyengine-us other than the register's ``reviewed_against``. + +This check runs in seconds after the staging (R1), before R2: + +- It reads the staging summary's ``reviewed_engine_input_nulls`` (column + names and null counts by spine; no row values). +- A null in a ``NEVER_DEFAULT_FILLED`` column on any spine but the ACS one + is refused, as materialize refuses it; R2's own stages fill the ACS cells. +- A null in an ESI premium output is refused, as materialize refuses it. +- Every other null becomes the fill record R2 writes, with the fill value R2 + resolves from the installed engine, and R2's own gate grades the records. + A null that one of R2's stages fills before the fill step counts as a fill + here, so the check errs towards a refusal. + +Exit status 0: R2's fill rules pass. Exit status 2: R2 would refuse; the +JSON report (``--out``) says why. Add the missing register entries (each a +reviewed ruling) and commit them before R2's calibrate stage. + +Usage:: + + python tools/check_us_acs_local_reviewed_fills.py \\ + --staging-summary /acs_multispine_staging.summary.json \\ + --out /reviewed_fills_precheck.json +""" + +# No ``from __future__ import annotations``: test loaders run this file +# without registering it in ``sys.modules``. +import argparse +import importlib.util +import json +import sys +from collections.abc import Callable, Collection, Mapping, Sequence +from pathlib import Path +from typing import Any + +from microcosm.build.us_runtime.acs_local_reviewed_fill_consumers import ( + acs_local_reviewed_fill_consumer_gate, + load_reviewed_fill_consumer_register, +) +from microcosm.build.us_runtime.esi_premiums import US_ESI_PREMIUMS_OUTPUT_COLUMNS + +TOOL = "tools/check_us_acs_local_reviewed_fills.py" +ISSUE = "microcosm#922" +ACS_SPINE = "acs_2024_1yr" +EXIT_REFUSED = 2 +_RELEASE_TOOL = Path(__file__).resolve().parent / "build_us_acs_local_release.py" + + +def _release_tool(): + """R2's module, for its own fill constants and default resolver.""" + + tools = str(_RELEASE_TOOL.parent) + if tools not in sys.path: + sys.path.insert(0, tools) + spec = importlib.util.spec_from_file_location( + "build_us_acs_local_release_for_fill_check", _RELEASE_TOOL + ) + module = importlib.util.module_from_spec(spec) + assert spec.loader is not None + sys.modules[spec.name] = module + spec.loader.exec_module(module) + return module + + +def expected_fills( + nulls: Sequence[Mapping[str, Any]], + *, + never_default_filled: Collection[tuple[str, str]], + resolve_default: Callable[[str], tuple[object, str]], +) -> dict[str, list]: + """Split the staged nulls as R2's fill step treats them. + + Returns ``fills`` (the records R2 writes, in its manifest's shape), + ``denied`` (never-default nulls off the ACS spine), ``esi`` (null ESI + premium outputs) and ``natively_filled`` (never-default nulls on the ACS + spine only, which R2's stages fill). + """ + + never = set(never_default_filled) + result: dict[str, list] = { + "fills": [], + "denied": [], + "esi": [], + "natively_filled": [], + } + for item in nulls: + entity, column = str(item["entity"]), str(item["column"]) + by_spine = { + str(spine): int(rows) + for spine, rows in dict(item.get("missing_rows_by_spine") or {}).items() + if int(rows) + } + name = f"{entity}.{column}" + if entity == "person" and column in US_ESI_PREMIUMS_OUTPUT_COLUMNS: + result["esi"].append({"column": name, "missing_rows_by_spine": by_spine}) + continue + if (entity, column) in never: + off_acs = { + spine: rows for spine, rows in by_spine.items() if spine != ACS_SPINE + } + target = "denied" if off_acs or not by_spine else "natively_filled" + result[target].append({"column": name, "missing_rows_by_spine": by_spine}) + continue + fill_value, kind = resolve_default(column) + missing = int(item["missing_rows"]) + result["fills"].append( + { + "entity": entity, + "column": column, + "filled_rows": missing, + "rows": int(item.get("rows", missing)), + "fill_value": repr(fill_value), + "fill_kind": kind, + "register_missing_rows": missing, + "missing_rows_by_spine": by_spine, + } + ) + return result + + +def grade( + split: Mapping[str, list], + *, + manifest_names: Sequence[str], + never_default_filled: Collection[tuple[str, str]], + installed_engine_version: str, + document: object | None = None, +) -> dict[str, Any]: + """Run R2's finalize gate on the expected fills; add materialize's refusals.""" + + manifest = {"fills": list(split["fills"]), "unregistered_violations": []} + gate = acs_local_reviewed_fill_consumer_gate( + {name: manifest for name in manifest_names}, + document=document + if document is not None + else load_reviewed_fill_consumer_register(), + never_default_filled=never_default_filled, + installed_engine_version=installed_engine_version, + ) + refusals = [ + *( + f"{item['column']}: null on {sorted(item['missing_rows_by_spine'])}, " + "a column R2 never default-fills (materialize refuses it)" + for item in split["denied"] + ), + *( + f"{item['column']}: null ESI employer premium (materialize refuses it)" + for item in split["esi"] + ), + *(f"finalize gate: {failure}" for failure in gate.failures), + ] + return { + "passed": not refusals, + "refusals": refusals, + "expected_fills": len(split["fills"]), + "natively_filled": split["natively_filled"], + "gate": { + "name": gate.name, + "passed": gate.passed, + "failures": list(gate.failures), + }, + } + + +def _parse_args(argv: Sequence[str] | None = None) -> argparse.Namespace: + parser = argparse.ArgumentParser( + description=( + "Grade a staging summary's reviewed nulls against R2's fill " + "rules and its finalize reviewed-fill gate, before R2 runs." + ) + ) + parser.add_argument("--staging-summary", required=True, type=Path) + parser.add_argument("--out", type=Path, help="JSON report path.") + return parser.parse_args(argv) + + +def _tax_benefit_system(): + from policyengine_us import CountryTaxBenefitSystem + + return CountryTaxBenefitSystem() + + +def _engine_version(release) -> str: + return release._installed_engine_version() + + +def main(argv: Sequence[str] | None = None) -> int: + args = _parse_args(argv) + summary = json.loads(args.staging_summary.read_text()) + nulls = summary.get("reviewed_engine_input_nulls") + if not isinstance(nulls, list): + raise SystemExit( + f"{args.staging_summary} carries no reviewed_engine_input_nulls list." + ) + release = _release_tool() + system = _tax_benefit_system() + split = expected_fills( + nulls, + never_default_filled=release.NEVER_DEFAULT_FILLED, + resolve_default=lambda column: release._resolve_engine_default(system, column), + ) + report = { + "tool": TOOL, + "issue": ISSUE, + "staging_summary": str(args.staging_summary), + "staged_null_columns": len(nulls), + **grade( + split, + manifest_names=release.REVIEWED_FILL_MANIFESTS, + never_default_filled=release.NEVER_DEFAULT_FILLED, + installed_engine_version=_engine_version(release), + ), + } + rendered = json.dumps(report, indent=2, sort_keys=True) + "\n" + if args.out is not None: + args.out.parent.mkdir(parents=True, exist_ok=True) + args.out.write_text(rendered, encoding="utf-8") + print( + json.dumps( + {key: report[key] for key in ("passed", "refusals", "expected_fills")}, + indent=2, + ) + ) + return 0 if report["passed"] else EXIT_REFUSED + + +if __name__ == "__main__": + raise SystemExit(main()) From 3bffc4aed6da20251f62fe7fdfb34c6537c24708 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mar=C3=ADa=20Juaristi?= <127882282+juaristi22@users.noreply.github.com> Date: Tue, 17 Nov 2026 13:43:41 +0000 Subject: [PATCH 08/31] Give the ACS staging telemetry test the new flag's parser default The telemetry test builds the staging builder's arguments by hand, so it had no value for --allow-default-donor-column and the builder stopped on an AttributeError before its first stage. Add the parser's default (None: no default-valued donor column is allowed), as the test already does for the household-location defaults. Part of #922. Co-Authored-By: Claude Opus 5.5 --- .../engine_free/us/test_us_modal_build_programs_telemetry.py | 2 ++ 1 file changed, 2 insertions(+) diff --git a/packages/microcosm-build/tests/engine_free/us/test_us_modal_build_programs_telemetry.py b/packages/microcosm-build/tests/engine_free/us/test_us_modal_build_programs_telemetry.py index 471028e8cb..0fb949c88a 100644 --- a/packages/microcosm-build/tests/engine_free/us/test_us_modal_build_programs_telemetry.py +++ b/packages/microcosm-build/tests/engine_free/us/test_us_modal_build_programs_telemetry.py @@ -477,6 +477,8 @@ def test_the_acs_staging_builder_records_its_phases_up_to_a_failure( location_seed=0, location_clones=1, block_ladder=None, + # The parser's default: no default-valued donor column is allowed (#922). + allow_default_donor_column=None, ) base = SimpleNamespace(weights_for=lambda unit: SimpleNamespace(total=1.0)) monkeypatch.setattr(module, "_parse_args", lambda argv: args) From 36bd0dafa3450bd220e4af087800745b3548998e Mon Sep 17 00:00:00 2001 From: Max Ghenis Date: Tue, 17 Nov 2026 08:44:25 -0500 Subject: [PATCH 09/31] Restore the ASEC work columns in the donor-patch tool (#1647) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit R1's _require_donor_work_experience refuses 766b7c7's donor: it predates the #719 work columns. asec_work_column_step now restores them on the patched copy, ported from the route 2 step reviewed on #1647, and runs before the zero step. - It reads each donor income year's pinned ASEC person member (survey year source_year + 1, via _resolve_pin) through the pinned reader, which refuses a file whose size or SHA-256 is not the pin's. Only the donor's income years are read. - WEIND and WEMIND join on (source_year, PERIDNUM as exact 22-digit text), many donor rows (an ASEC row and its PUF-support clones) to one member row. It refuses a donor person with no member row, a member that repeats a PERIDNUM (a person would match twice), and any row whose source_household_id (Census PH_SEQ), P_SEQ, A_LINENO, A_AGE, WKSWORK, POCCU2, PRDTRACE or PRDTHSP differs from the member's. - The restoration's domains and work-experience identities run on each member and on the joined rows. The columns are the output of org_wages.derive_us_org_occupation_inputs (int16, int16, bool), whose other outputs must equal the donor's own columns. - One ColumnPatch per column on person, with its source item (WEIND, WEMIND, WKSWORK > 0) in the record. The step receipt holds the files, their pinned digests, the match counts per income year, the clone counts, the carry checks and the nonzero shares beside the carry's gate bands. A work column on another entity is refused; one already on person must equal the restored values. - build_patch_steps takes asec_sources; the command always passes it, so the copy always carries the columns. --asec-source-cache (default ~/.cache/microcosm/cps/asec_education) and --asec-fetch (download a missing pinned archive, verified) are its options. Tests (engine-free, invented members with measured pins, no Census read or download): the year-scoped join with clones, dtypes and the receipt; R1's _require_donor_work_experience and _require_income_donor pass on the patched fixture; a table-format donor keeps its layout; exact-text keys; each refusal; the cache, archive and fetch paths; the command. Written by Claude Code, Max Ghenis's agent, at María's request on #1660. Co-Authored-By: Claude Opus 5.5 --- .../us-acs-poc-donor-patch-922.added.md | 2 +- docs/agent-guide.md | 6 +- docs/us-work-experience-columns.md | 14 + .../us/test_us_acs_donor_column_patch.py | 645 ++++++++++++++++- tools/patch_us_acs_donor_columns.py | 648 +++++++++++++++++- 5 files changed, 1269 insertions(+), 46 deletions(-) diff --git a/changelog.d/us-acs-poc-donor-patch-922.added.md b/changelog.d/us-acs-poc-donor-patch-922.added.md index 7f7b314761..ee20b274b4 100644 --- a/changelog.d/us-acs-poc-donor-patch-922.added.md +++ b/changelog.d/us-acs-poc-donor-patch-922.added.md @@ -1 +1 @@ -`tools/patch_us_acs_donor_columns.py` writes a patched copy of a published US national donor H5 for the County Files proof of concept's ACS staging (microcosm#922, plan microcosm#1647). It adds reviewed all-zero columns on the entity the US engine gives them (`strike_benefits`: no donor or ASEC pppub23–26 row has `OI_OFF` 12; `passive_partnership_s_corp_income`: the donor holds partnership and S-corp income as one combined `partnership_income`), refuses a column that is already present with any other value, keeps every other table, column, dtype and root attribute, and writes a receipt with both SHA-256 digests, the row counts, each added column with its reason, and the tool's commit. A restore step for the three ASEC work columns is reserved for a later commit. The published donor is read only, and no default changes. With `--input-release-manifest` it checks the input against the published donor's release manifest and records that build in the receipt. With `--release-manifest`, `--manifest-release` and `--manifest-build` it also writes a build-folder release manifest for the copy (in `policyengine/populace-us-staging` by default), so the ACS staging can take it as `--donor-release-manifest` and record the copy's build as `donor_release`, which the local-area release contract requires before publication. +`tools/patch_us_acs_donor_columns.py` writes a patched copy of a published US national donor H5 for the County Files proof of concept's ACS staging (microcosm#922, plan microcosm#1647). It adds reviewed all-zero columns on the entity the US engine gives them (`strike_benefits`: no donor or ASEC pppub23–26 row has `OI_OFF` 12; `passive_partnership_s_corp_income`: the donor holds partnership and S-corp income as one combined `partnership_income`), refuses a column that is already present with any other value, keeps every other table, column, dtype and root attribute, and writes a receipt with both SHA-256 digests, the row counts, each added column with its reason, and the tool's commit. It first restores the three ASEC work columns (`detailed_industry_recode`, `major_industry_recode`, `worked_last_year`) on `person`, valued as the #720 restoration and the `org_wages` carry value them: it reads each donor income year's pinned ASEC person member (refusing a file whose SHA-256 is not pinned), joins `WEIND` and `WEMIND` on source year and exact `PERIDNUM`, refuses a donor person with no member row or more than one, checks eight Census identity columns on every row, and records the files, their digests and the match counts in the receipt. It reads the members from `--asec-source-cache` (default `~/.cache/microcosm/cps/asec_education`) and downloads a missing pinned archive only with `--asec-fetch`. The published donor is read only, and no default changes. With `--input-release-manifest` it checks the input against the published donor's release manifest and records that build in the receipt. With `--release-manifest`, `--manifest-release` and `--manifest-build` it also writes a build-folder release manifest for the copy (in `policyengine/populace-us-staging` by default), so the ACS staging can take it as `--donor-release-manifest` and record the copy's build as `donor_release`, which the local-area release contract requires before publication. diff --git a/docs/agent-guide.md b/docs/agent-guide.md index e2b596c57f..97d8db0bdd 100644 --- a/docs/agent-guide.md +++ b/docs/agent-guide.md @@ -543,8 +543,10 @@ historical donors and staging files missing these inputs must be rebuilt through the exact ASEC restoration/fiscal carry and native ACS mapping. The one reviewed exception is the County Files proof of concept (microcosm#922): `tools/patch_us_acs_donor_columns.py` writes a patched copy of -766b7c7's donor with a receipt (and, when asked, a build-folder release manifest -for the copy, for `--donor-release-manifest`), and the staging builder's +766b7c7's donor, with the three work columns restored from the pinned ASEC +person files by source year and `PERIDNUM`, and a receipt (and, when asked, a +build-folder release manifest for the copy, for `--donor-release-manifest`), +and the staging builder's `--allow-default-donor-column COLUMN=REASON` accepts named all-default donor columns and records each one in the staging summary. Neither changes a default. diff --git a/docs/us-work-experience-columns.md b/docs/us-work-experience-columns.md index 9301f12391..2469e6f854 100644 --- a/docs/us-work-experience-columns.md +++ b/docs/us-work-experience-columns.md @@ -123,6 +123,20 @@ rows and binds the result to its hash, so an older green staging summary cannot bypass this requirement. The assembly-first nullable pool remains an intermediate input; its fiscal release applies that carry to every row. +The one reviewed exception is the County Files proof of concept (#922, +plan #1647). Its donor-patch tool, `tools/patch_us_acs_donor_columns.py`, +restores the three columns on a copy of 766b7c7's donor, valued as the +restoration and carry value them. Each donor person's `source_year` is its +ASEC income year, so its member is the survey-year `source_year + 1` file, +read through the pinned reader. `WEIND` and `WEMIND` join by exact +`(source_year, PERIDNUM)`, many donor rows (an ASEC row and its PUF-support +clones) to one member row. The tool refuses a donor person with no member row +or more than one, and any row whose `source_household_id` (the Census +`PH_SEQ`), `P_SEQ`, `A_LINENO`, `A_AGE`, `WKSWORK`, `POCCU2`, `PRDTRACE` or +`PRDTHSP` differs from the member's. The columns are the output of +`derive_us_org_occupation_inputs`, whose other outputs must equal the donor's +own. Raw `WEIND`/`WEMIND` are not written. + The 2026-10-23 branch refresh preserves main's current stage and graph structure, including its six ESI source fields alongside the industry restoration. Main's independent refusal of mixed ACS inputs with null ESI diff --git a/packages/microcosm-build/tests/engine_free/us/test_us_acs_donor_column_patch.py b/packages/microcosm-build/tests/engine_free/us/test_us_acs_donor_column_patch.py index d4ef4d9dc8..a216bd9c8b 100644 --- a/packages/microcosm-build/tests/engine_free/us/test_us_acs_donor_column_patch.py +++ b/packages/microcosm-build/tests/engine_free/us/test_us_acs_donor_column_patch.py @@ -1,9 +1,11 @@ """The proof-of-concept donor patch for the ACS staging (microcosm#922). ``tools/patch_us_acs_donor_columns.py`` writes a patched copy of a US -national donor H5 with reviewed all-zero columns added. These tests use a -small fixture H5 in the nullable layout R1's ``_load_base_frame`` reads and a -stand-in engine, so no country engine is imported. +national donor H5 with the ASEC work columns restored and reviewed all-zero +columns added. These tests use a small fixture H5 in the nullable layout R1's +``_load_base_frame`` reads, a stand-in engine and invented ASEC person +members whose pins are measured here, so no country engine is imported and +no Census file is read or downloaded. """ from __future__ import annotations @@ -11,8 +13,11 @@ import hashlib import importlib.util import json +import shutil import sys +import zipfile from pathlib import Path +from types import SimpleNamespace import numpy as np import pandas as pd @@ -23,10 +28,13 @@ ACS_LOCAL_INCOME_TRANSFER_COLUMNS, ACS_LOCAL_OTHER_INCOME_DONOR_COMPONENTS, ) +from microcosm.build.us_runtime.asec_census_person_columns import WEIND_TO_WEMIND from microcosm.build.us_runtime.h5_io import ( read_nullable_us_h5_metadata, write_nullable_us_h5, ) +from microcosm.build.us_runtime.org_wages import derive_us_org_occupation_inputs +from microcosm.build.us_runtime.spm_role_source import AsecSpmRoleSource from microcosm.build.us_runtime.support_provenance import ( support_channel_column, support_clone_index_column, @@ -177,7 +185,13 @@ def _sha256(path: Path) -> str: def _patch( - tool, tmp_path: Path, donor: Path, *, engine: _Engine | None = None, **options + tool, + tmp_path: Path, + donor: Path, + *, + engine: _Engine | None = None, + asec_sources=None, + **options, ): output = tmp_path / "out" / "donor_patched.h5" receipt_path = tmp_path / "out" / "donor_patched.receipt.json" @@ -185,7 +199,9 @@ def _patch( donor, output, steps=tool.build_patch_steps( - zero_columns=list(_ZERO_COLUMNS), engine=engine or _Engine() + zero_columns=list(_ZERO_COLUMNS), + engine=engine or _Engine(), + asec_sources=asec_sources, ), receipt_path=receipt_path, tool_identity={"commit": "f" * 40, "tool_dirty": False}, @@ -379,11 +395,11 @@ def test_r1_income_donor_gate_passes_on_the_patched_fixture( def test_command_writes_the_default_receipt_beside_the_copy( - tool, tmp_path: Path, monkeypatch: pytest.MonkeyPatch + tool, asec, tmp_path: Path, monkeypatch: pytest.MonkeyPatch ) -> None: import microcosm.frame.adapters.policyengine_us as adapter - donor = _write_donor(tmp_path / "donor.h5") + donor = _write_asec_donor(tmp_path / "donor.h5") monkeypatch.setattr(adapter, "PolicyEngineUSEngine", _Engine) monkeypatch.setattr( tool, "current_tool_identity", lambda: {"commit": "c" * 40, "tool_dirty": False} @@ -395,9 +411,10 @@ def test_command_writes_the_default_receipt_beside_the_copy( receipt = json.loads((tmp_path / "patched.receipt.json").read_text()) assert receipt["output"]["sha256"] == _sha256(output) assert receipt["tool_commit"]["commit"] == "c" * 40 - assert [r["column"] for r in receipt["added_columns"]] == list( - tool.REVIEWED_ZERO_COLUMNS - ) + assert [r["column"] for r in receipt["added_columns"]] == [ + *tool.ASEC_WORK_COLUMNS, + *tool.REVIEWED_ZERO_COLUMNS, + ] with pytest.raises(SystemExit, match="Donor patch refused"): tool.main(["--input-h5", str(donor), "--output-h5", str(donor)]) @@ -568,11 +585,11 @@ def test_copy_release_manifest_refuses_a_bad_build_name( def test_command_writes_the_copy_release_manifest_only_when_asked( - tool, tmp_path: Path, monkeypatch: pytest.MonkeyPatch + tool, asec, tmp_path: Path, monkeypatch: pytest.MonkeyPatch ) -> None: import microcosm.frame.adapters.policyengine_us as adapter - donor = _write_donor(tmp_path / "donor.h5") + donor = _write_asec_donor(tmp_path / "donor.h5") monkeypatch.setattr(adapter, "PolicyEngineUSEngine", _Engine) monkeypatch.setattr( tool, "current_tool_identity", lambda: {"commit": "c" * 40, "tool_dirty": False} @@ -606,3 +623,607 @@ def test_command_writes_the_copy_release_manifest_only_when_asked( ): with pytest.raises(SystemExit): tool._parse_args([*base, *partial]) + + +# -------------------------------------------------------------------------- +# The ASEC work-column restore step +# -------------------------------------------------------------------------- + +#: Invented ASEC person members by income year: key -> (PH_SEQ, P_SEQ, +#: A_LINENO, A_AGE, WKSWORK, POCCU2, PRDTRACE, PRDTHSP, WEIND). Key 1 is in +#: both years with different answers (CPS rotation), so a join that ignored +#: source_year would pair the wrong person. Keys 2 and 3 are member-only: the +#: donor is a subset of each member, as the real donor is. +_ASEC_MEMBERS = { + 2022: { + 1: (11, 1, 1, 34, 52, 8, 1, 0, 5), + 2: (12, 1, 1, 9, 0, 0, 1, 0, 0), + }, + 2023: { + 1: (21, 1, 1, 70, 0, 0, 2, 1, 23), + 3: (22, 1, 1, 30, 30, 52, 4, 0, 22), + }, +} +_ASEC_MEMBER_FIELDS = ( + "PH_SEQ", + "P_SEQ", + "A_LINENO", + "A_AGE", + "WKSWORK", + "POCCU2", + "PRDTRACE", + "PRDTHSP", + "WEIND", +) +#: The fixture donor's persons as (source_year, key): rows 2 and 3 are the +#: PUF-support clones of rows 0 and 1 (``_donor_frame``'s support ids). +_ASEC_DONOR_KEYS = ((2022, 1), (2023, 1), (2022, 1), (2023, 1)) +_EXPECTED_WORK = { + "detailed_industry_recode": [5, 23, 5, 23], + "major_industry_recode": [WEIND_TO_WEMIND[5], 15, WEIND_TO_WEMIND[5], 15], + "worked_last_year": [True, False, True, False], +} +_DONOR_IDENTITY = ( + "source_household_id", + "P_SEQ", + "A_LINENO", + "A_AGE", + "WKSWORK", + "POCCU2", + "PRDTRACE", + "PRDTHSP", +) + + +def _peridnum(key: int, *, wide: bool = False) -> str: + # Leading zeros: the join must compare exact text, never numbers. Wide keys + # share their first 15 digits, so they collide as float64. + return f"91{key:020d}" if wide else f"{key * 7:022d}" + + +def _asec_member_row(year: int, key: int) -> dict[str, int]: + values = dict(zip(_ASEC_MEMBER_FIELDS, _ASEC_MEMBERS[year][key], strict=True)) + values["WEMIND"] = WEIND_TO_WEMIND[values["WEIND"]] + return values + + +def _asec_person_columns( + *, wide_keys: bool = False, overrides: dict | None = None, drop: tuple = () +) -> dict[str, pd.Series]: + """The ASEC person columns a pre-restoration donor carries. + + The identity columns equal each row's member; the carry's other outputs + are the carry's own; the three work columns and raw WEIND/WEMIND are + absent, as on 766b7c7's donor. + """ + + members = [_asec_member_row(year, key) for year, key in _ASEC_DONOR_KEYS] + table = pd.DataFrame( + { + "PERIDNUM": [_peridnum(key, wide=wide_keys) for _, key in _ASEC_DONOR_KEYS], + "source_year": [year for year, _ in _ASEC_DONOR_KEYS], + "source_household_id": [row["PH_SEQ"] for row in members], + **{ + column: [row[column] for row in members] + for column in _DONOR_IDENTITY[1:] + }, + } + ) + carried = derive_us_org_occupation_inputs( + table.assign( + WEIND=[row["WEIND"] for row in members], + WEMIND=[row["WEMIND"] for row in members], + ) + ) + columns = {column: table[column] for column in table.columns} + for column in carried.columns: + if column not in _EXPECTED_WORK: + columns[column] = carried[column] + for column, values in (overrides or {}).items(): + columns[column] = pd.Series(values) + return {column: values for column, values in columns.items() if column not in drop} + + +def _write_asec_donor(path: Path, **options) -> Path: + return _write_donor(path, _asec_person_columns(**options)) + + +def _write_member( + path: Path, + year: int, + *, + drop_keys: tuple[int, ...] = (), + overrides: dict | None = None, + wide_keys: bool = False, + duplicate_keys: tuple[int, ...] = (), +) -> Path: + rows = [] + for key in _ASEC_MEMBERS[year]: + if key in drop_keys: + continue + row = { + "PERIDNUM": _peridnum(key, wide=wide_keys), + **_asec_member_row(year, key), + } + row.update((overrides or {}).get(key, {})) + row["A_FNLWGT"] = 1000.0 + key + rows.append(row) + if key in duplicate_keys: + rows.append(dict(row)) + path.parent.mkdir(parents=True, exist_ok=True) + pd.DataFrame(rows).to_csv(path, index=False, lineterminator="\n") + return path + + +def _measured_pin(path: Path, year: int) -> AsecSpmRoleSource: + return AsecSpmRoleSource( + income_year=year, + survey_year=year + 1, + csv_sha256=_sha256(path), + csv_size_bytes=path.stat().st_size, + persons=int(len(pd.read_csv(path))), + units=0, + official_archive_url=f"https://example.invalid/asecpub{str(year + 1)[2:]}csv.zip", + archive_sha256="0" * 64, + member=path.name, + ) + + +def _refuse_download(*args, **kwargs): + raise AssertionError("a test attempted an ASEC download") + + +@pytest.fixture +def asec(tool, tmp_path: Path, monkeypatch: pytest.MonkeyPatch): + """Invented members with measured pins, as the test's default ASEC cache. + + The command resolves its pins through ``_resolve_pin``; here that falls + back to the measured pins (the vintage check still runs). No test reads + the real cache or downloads. + """ + + def build(**member_options) -> SimpleNamespace: + cache = tmp_path / "asec-cache" + paths, pins = {}, {} + for year in _ASEC_MEMBERS: + options = { + name: value.get(year, ()) if name != "wide_keys" else value + for name, value in member_options.items() + } + if "overrides" in options and options["overrides"] == (): + options["overrides"] = None + path = _write_member( + cache / f"pppub{str(year + 1)[2:]}.csv", year, **options + ) + paths[year], pins[year] = path, _measured_pin(path, year) + resolve = tool._resolve_pin + monkeypatch.setattr( + tool, + "_resolve_pin", + lambda year, pin: resolve(year, pin if pin is not None else pins[year]), + ) + monkeypatch.setattr(tool, "DEFAULT_ASEC_SOURCE_CACHE", cache) + monkeypatch.setattr( + tool.education_assistance_source, + "fetch_asec_education_assistance_source", + _refuse_download, + ) + return SimpleNamespace( + cache=cache, + paths=paths, + pins=pins, + sources=tool.AsecPersonSources(paths=paths, pins=pins), + ) + + build() + return build + + +def test_work_columns_are_restored_by_the_year_scoped_key( + tool, asec, tmp_path: Path +) -> None: + fixture = asec() + donor = _write_asec_donor(tmp_path / "donor.h5") + + output, _receipt_path, receipt = _patch( + tool, tmp_path, donor, asec_sources=fixture.sources + ) + + _keys, before, _others, _root = _tables(donor) + _keys, after, _others, _root = _tables(output) + person = after["person"] + assert list(person.columns) == [ + *before["person"].columns, + *tool.ASEC_WORK_COLUMNS, + *_ZERO_COLUMNS, + ] + for column, dtype in tool.ASEC_WORK_DTYPES.items(): + assert person[column].dtype == np.dtype(dtype) + assert person[column].tolist() == _EXPECTED_WORK[column] + # Key 1 takes each year's own answer; each PUF clone its sibling's. + assert person["detailed_industry_recode"].tolist()[:2] == [5, 23] + for entity in US_SCHEMA.entities: + pd.testing.assert_frame_equal( + after[entity][list(before[entity].columns)], + before[entity], + check_exact=True, + ) + + work = [r for r in receipt["added_columns"] if r["step"] == tool.ASEC_WORK_STEP] + assert [(r["entity"], r["column"], r["dtype"]) for r in work] == [ + ("person", "detailed_industry_recode", "int16"), + ("person", "major_industry_recode", "int16"), + ("person", "worked_last_year", "bool"), + ] + assert [r["source_item"] for r in work] == ["WEIND", "WEMIND", "WKSWORK > 0"] + assert receipt["rewritten_tables"] == ["person"] + step = receipt["steps"][0] + assert step["name"] == tool.ASEC_WORK_STEP + assert step["columns"] == [f"person.{c}" for c in tool.ASEC_WORK_COLUMNS] + assert receipt["steps"][1]["name"] == tool.ZERO_STEP + for year in (2022, 2023): + record = step["files"][str(year)] + assert record["member_sha256"] == _sha256(fixture.paths[year]) + assert record["path"] == str(fixture.paths[year].resolve()) + assert record["form"] == "csv" + assert (record["income_year"], record["survey_year"]) == (year, year + 1) + assert record["persons"] == 2 + assert step["join"]["by_income_year"][str(year)] == { + "donor_rows": 2, + "donor_rows_matched_once": 2, + "distinct_keys_matched": 1, + "member_rows": 2, + "member_rows_not_in_donor": 1, + "identity_mismatches": 0, + } + assert step["join"]["donor_rows"] == 4 + assert step["join"]["unmatched_donor_rows"] == 0 + assert step["join"]["multiply_matched_donor_rows"] == 0 + assert step["clones"]["keys_with_two_rows"] == 2 + assert step["clones"]["repeated_key_channel_composition"] == { + "asec+puf_tax_detail": 2 + } + assert "cps_race" in step["carry"]["reemitted_columns_verified_equal"] + shares = step["work_experience"]["nonzero_shares"]["worked_last_year"] + # Persons 1 and 3 (weights 40 and 50 of 180) worked last year. + assert shares["weighted_nonzero_share"] == pytest.approx(90 / 180) + json.dumps(receipt, allow_nan=False) + + +def test_r1_work_experience_gate_passes_on_the_patched_fixture( + tool, builder, asec, tmp_path: Path +) -> None: + fixture = asec() + donor = _write_asec_donor(tmp_path / "donor.h5") + with pytest.raises(SystemExit, match="detailed_industry_recode"): + builder._require_donor_work_experience(builder._load_base_frame(donor)) + + output, _receipt_path, _receipt = _patch( + tool, tmp_path, donor, asec_sources=fixture.sources + ) + + frame = builder._load_base_frame(output) + builder._require_donor_work_experience(frame) + builder._require_income_donor(frame) + + +def test_table_format_donor_keeps_its_layout_with_the_work_columns( + tool, builder, asec, tmp_path: Path +) -> None: + """The published donor's layout: compound tables, every column indexed.""" + + fixture = asec() + frame = _donor_frame(_asec_person_columns()) + donor = tmp_path / "donor-table.h5" + with pd.HDFStore(donor, mode="w") as store: + for entity in US_SCHEMA.entities: + table = frame.table(entity).copy() + if entity == "household": + table["household_weight"] = frame.weights_for("household").values + table = table.drop( + columns=["has_marketplace_health_coverage_at_interview"], + errors="ignore", + ) + store.put(entity, table, format="table", data_columns=True) + + output, _receipt_path, receipt = _patch( + tool, tmp_path, donor, asec_sources=fixture.sources + ) + + _keys, after, _others, _root = _tables(output) + with pd.HDFStore(output, mode="r") as store: + storer = store.get_storer("person") + assert storer.is_table + assert set(tool.ASEC_WORK_COLUMNS) <= set(storer.data_columns) + for column, dtype in tool.ASEC_WORK_DTYPES.items(): + assert after["person"][column].dtype == np.dtype(dtype) + assert after["person"][column].tolist() == _EXPECTED_WORK[column] + assert receipt["rewritten_tables"] == ["person"] + builder._require_donor_work_experience(builder._load_base_frame(output)) + + +def test_join_compares_exact_text_keys(tool, asec, tmp_path: Path) -> None: + # Every key shares its first 15 digits, so a numeric join could not tell + # the people apart. + fixture = asec(wide_keys=True) + assert len({float(_peridnum(key, wide=True)) for key in (1, 2, 3)}) == 1 + donor = _write_asec_donor(tmp_path / "donor.h5", wide_keys=True) + + output, _receipt_path, _receipt = _patch( + tool, tmp_path, donor, asec_sources=fixture.sources + ) + + _keys, after, _others, _root = _tables(output) + for column, expected in _EXPECTED_WORK.items(): + assert after["person"][column].tolist() == expected + + +def _refused(tool, tmp_path: Path, donor: Path, sources, match: str) -> None: + donor_sha256 = _sha256(donor) + with pytest.raises(ValueError, match=match): + _patch(tool, tmp_path, donor, asec_sources=sources) + assert not (tmp_path / "out").exists() or not any((tmp_path / "out").iterdir()) + assert _sha256(donor) == donor_sha256 + + +def test_refuses_a_donor_person_without_a_member_row( + tool, asec, tmp_path: Path +) -> None: + fixture = asec(drop_keys={2023: (1,)}) + donor = _write_asec_donor(tmp_path / "donor.h5") + + _refused( + tool, + tmp_path, + donor, + fixture.sources, + "2 donor person rows of income year 2023 have no row", + ) + + +def test_refuses_a_member_that_would_match_a_person_twice( + tool, asec, tmp_path: Path +) -> None: + fixture = asec(duplicate_keys={2022: (1,)}) + donor = _write_asec_donor(tmp_path / "donor.h5") + + _refused(tool, tmp_path, donor, fixture.sources, "repeats PERIDNUM on 2 rows") + + +def test_refuses_a_file_whose_sha256_is_not_pinned(tool, asec, tmp_path: Path) -> None: + fixture = asec() + donor = _write_asec_donor(tmp_path / "donor.h5") + pins = dict(fixture.pins) + pins[2022] = AsecSpmRoleSource(**{**vars(pins[2022]), "csv_sha256": "0" * 64}) + + _refused( + tool, + tmp_path, + donor, + tool.AsecPersonSources(paths=fixture.paths, pins=pins), + "SHA-256 mismatch", + ) + # A file of another year is refused against its year's pin, by name. + _refused( + tool, + tmp_path, + donor, + tool.AsecPersonSources( + paths={2022: fixture.paths[2023], 2023: fixture.paths[2023]}, + pins=fixture.pins, + ), + r"pppub23\.csv \(read from pppub24\.csv\)", + ) + + +def test_refuses_a_pin_for_another_vintage(tool, asec, tmp_path: Path) -> None: + fixture = asec() + donor = _write_asec_donor(tmp_path / "donor.h5") + pins = {2022: fixture.pins[2023], 2023: fixture.pins[2023]} + + _refused( + tool, + tmp_path, + donor, + tool.AsecPersonSources(paths=fixture.paths, pins=pins), + "pin is for income year 2023", + ) + + +@pytest.mark.parametrize("column", _DONOR_IDENTITY) +def test_refuses_one_row_that_disagrees_on_any_identity_column( + tool, asec, tmp_path: Path, column: str +) -> None: + fixture = asec() + # Row 2 is the 2022 PUF clone; only the named column changes. + values = _asec_person_columns()[column].tolist() + values[2] += 1 + donor = _write_asec_donor(tmp_path / "donor.h5", overrides={column: values}) + + _refused( + tool, + tmp_path, + donor, + fixture.sources, + rf"Income year 2022 donor rows disagree .*\{{'{column}': 1\}}", + ) + + +def test_refuses_a_code_outside_the_reviewed_domain(tool, asec, tmp_path: Path) -> None: + fixture = asec(overrides={2023: {3: {"WEIND": 99}}}) + donor = _write_asec_donor(tmp_path / "donor.h5") + + _refused(tool, tmp_path, donor, fixture.sources, "outside its reviewed Census") + + +def test_refuses_a_donor_the_carry_did_not_build(tool, asec, tmp_path: Path) -> None: + fixture = asec() + cps_race = _asec_person_columns()["cps_race"].copy() + cps_race.iloc[1] = 7 + donor = _write_asec_donor(tmp_path / "donor.h5", overrides={"cps_race": cps_race}) + + _refused(tool, tmp_path, donor, fixture.sources, "Donor cps_race differs") + + +def test_refuses_a_donor_without_the_join_columns(tool, asec, tmp_path: Path) -> None: + fixture = asec() + donor = _write_asec_donor(tmp_path / "donor.h5", drop=("P_SEQ",)) + + _refused(tool, tmp_path, donor, fixture.sources, r"lacks \['P_SEQ'\]") + + +def test_existing_work_columns_are_kept_only_when_equal( + tool, asec, tmp_path: Path +) -> None: + fixture = asec() + same = pd.Series(_EXPECTED_WORK["worked_last_year"]) + donor = _write_asec_donor( + tmp_path / "donor.h5", overrides={"worked_last_year": same} + ) + + _output, _receipt_path, receipt = _patch( + tool, tmp_path, donor, asec_sources=fixture.sources + ) + + assert [r["column"] for r in receipt["kept_columns"]] == ["worked_last_year"] + + other = tmp_path / "other" + other.mkdir() + different = pd.Series([True, True, True, False]) + donor = _write_asec_donor( + other / "donor.h5", overrides={"worked_last_year": different} + ) + _refused(tool, other, donor, fixture.sources, "refusing to overwrite") + + # A work column on another entity is refused, not duplicated on person. + step = tool.asec_work_column_step(fixture.sources) + with pytest.raises(ValueError, match="on tax_unit; refusing to duplicate"): + step.run( + { + "person": pd.DataFrame(_asec_person_columns()), + "tax_unit": pd.DataFrame({"worked_last_year": [True]}), + } + ) + + +def test_reads_the_cache_as_member_csvs_or_official_archives( + tool, asec, tmp_path: Path +) -> None: + fixture = asec() + donor = _write_asec_donor(tmp_path / "donor.h5") + archives = tmp_path / "archives" + archives.mkdir() + pins = {} + for year, path in fixture.paths.items(): + pin = fixture.pins[year] + archive = archives / Path(pin.official_archive_url).name + with zipfile.ZipFile(archive, "w") as handle: + handle.write(path, arcname=pin.member) + pins[year] = AsecSpmRoleSource( + **{**vars(pin), "archive_sha256": _sha256(archive)} + ) + + _output, _receipt_path, receipt = _patch( + tool, + tmp_path, + donor, + asec_sources=tool.AsecPersonSources(cache=archives, pins=pins), + ) + + files = receipt["steps"][0]["files"] + assert [files[str(year)]["form"] for year in (2022, 2023)] == ["archive"] * 2 + assert files["2022"]["archive_sha256"] == pins[2022].archive_sha256 + assert files["2022"]["path"].endswith("asecpub23csv.zip") + + # The CSV form, from the default cache. + shutil.rmtree(tmp_path / "out") + _output, _receipt_path, receipt = _patch( + tool, tmp_path, donor, asec_sources=tool.AsecPersonSources(pins=fixture.pins) + ) + files = receipt["steps"][0]["files"] + assert files["2023"]["path"] == str((fixture.cache / "pppub24.csv").resolve()) + assert files["2023"]["form"] == "csv" + + +def test_refuses_absent_members_and_fetches_only_when_asked( + tool, asec, tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + fixture = asec() + donor = _write_asec_donor(tmp_path / "donor.h5") + cache = tmp_path / "partial-cache" + cache.mkdir() + shutil.copyfile(fixture.paths[2022], cache / "pppub23.csv") + + _refused( + tool, + tmp_path, + donor, + tool.AsecPersonSources(cache=cache, pins=fixture.pins), + r"income year\(s\) \['2023'\] are not in .*--asec-fetch", + ) + + calls = [] + + def download(income_year, cache_dir=None): + calls.append((income_year, Path(cache_dir))) + target = Path(cache_dir) / fixture.pins[income_year].member + shutil.copyfile(fixture.paths[income_year], target) + return target + + monkeypatch.setattr( + tool.education_assistance_source, + "fetch_asec_education_assistance_source", + download, + ) + _output, _receipt_path, receipt = _patch( + tool, + tmp_path, + donor, + asec_sources=tool.AsecPersonSources(cache=cache, fetch=True, pins=fixture.pins), + ) + assert calls == [(2023, cache)] + assert receipt["steps"][0]["files"]["2023"]["path"] == str( + (cache / "pppub24.csv").resolve() + ) + + +def test_command_restores_the_work_columns_and_passes_its_options( + tool, asec, tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + import microcosm.frame.adapters.policyengine_us as adapter + + fixture = asec() + donor = _write_asec_donor(tmp_path / "donor.h5") + monkeypatch.setattr(adapter, "PolicyEngineUSEngine", _Engine) + monkeypatch.setattr( + tool, "current_tool_identity", lambda: {"commit": "c" * 40, "tool_dirty": False} + ) + base = ["--input-h5", str(donor), "--output-h5", str(tmp_path / "patched.h5")] + + # Without the members, the command refuses rather than skip the step. + monkeypatch.setattr(tool, "DEFAULT_ASEC_SOURCE_CACHE", tmp_path / "absent") + with pytest.raises(SystemExit, match="Donor patch refused: The pinned ASEC"): + tool.main(base) + + assert tool.main([*base, "--asec-source-cache", str(fixture.cache)]) == 0 + receipt = json.loads((tmp_path / "patched.receipt.json").read_text()) + assert receipt["steps"][0]["name"] == tool.ASEC_WORK_STEP + assert receipt["steps"][0]["files"]["2022"]["path"] == str( + fixture.paths[2022].resolve() + ) + + seen = {} + + def capture(**kwargs): + seen.update(kwargs) + raise ValueError("captured") + + monkeypatch.setattr(tool, "build_patch_steps", capture) + with pytest.raises(SystemExit, match="captured"): + tool.main([*base, "--asec-source-cache", str(tmp_path / "c"), "--asec-fetch"]) + assert seen["asec_sources"] == tool.AsecPersonSources( + cache=tmp_path / "c", fetch=True + ) + with pytest.raises(SystemExit, match="captured"): + tool.main(base) + assert seen["asec_sources"] == tool.AsecPersonSources() diff --git a/tools/patch_us_acs_donor_columns.py b/tools/patch_us_acs_donor_columns.py index 83737d16b9..9f5cd43d8e 100644 --- a/tools/patch_us_acs_donor_columns.py +++ b/tools/patch_us_acs_donor_columns.py @@ -10,22 +10,30 @@ from ``main``. The copy keeps every table, column, dtype and HDF5 root attribute of the -input. Each patch step only adds named columns to the entity tables: - +input. Each patch step only adds named columns to the entity tables, in this +order: + +- ``asec_work_columns`` (:func:`asec_work_column_step`) restores + ``detailed_industry_recode``, ``major_industry_recode`` and + ``worked_last_year`` on ``person`` from the pinned ASEC person files + (``pppub23``-``pppub26``), matched on source year and ``PERIDNUM``, as the + #720 restoration and the fiscal ``org_wages`` carry value them (int16, + int16, bool). It refuses a file whose SHA-256 is not pinned and a donor + person with no match or more than one. The command looks the files up in + ``--asec-source-cache`` (default ``~/.cache/microcosm/cps/asec_education``) + and downloads a missing pinned archive only with ``--asec-fetch``. - ``reviewed_zero_columns`` adds reviewed all-zero columns. It looks up each column's entity, dtype and default in the US engine and refuses a column whose engine default is not 0. ``REVIEWED_ZERO_COLUMNS`` holds the reason for each column. -- The ASEC work-column restore step (:func:`asec_work_column_step`) is - reserved for a later commit. It restores ``detailed_industry_recode``, - ``major_industry_recode`` and ``worked_last_year`` from the pinned ASEC - person files. A step never overwrites data: when a column is already present, the step must give exactly the stored values, or the tool refuses the input. The tool writes the copy atomically, verifies it against the input, and writes a JSON receipt with both SHA-256 digests, the row counts per entity, each added -column with its entity and reason, and the tool's commit. +column with its entity and reason or source item, each step's own record +(for the work columns: the files read, their pinned SHA-256 digests and the +match counts), and the tool's commit. Two options record lineage (both optional): @@ -59,6 +67,7 @@ # without registering it in ``sys.modules``, where string annotations break # the dataclasses below. import argparse +import gc import hashlib import json import numbers @@ -73,14 +82,35 @@ from pathlib import Path from types import MappingProxyType from typing import Any +from urllib.parse import urlparse import numpy as np import pandas as pd +from microcosm.build.us_runtime import education_assistance_source, org_wages + +# The #720 restoration's pin resolver, domain specs and work-experience +# identities, and the pinned reader's exact-key parser, are reused rather than +# re-derived, so the work-column step checks what the restoration checks. +from microcosm.build.us_runtime.asec_census_person_columns import ( # noqa: PLC2701 + ASEC_CENSUS_PERSON_COLUMNS, + WORKER_INDUSTRY_CODES, + _check_work_experience_universe, + _resolve_pin, +) from microcosm.build.us_runtime.h5_io import ( assert_h5_unchanged, refuse_denied_pool_h5, ) +from microcosm.build.us_runtime.org_wages import ( + derive_us_org_occupation_inputs, + require_us_occupation_and_work_experience_inputs, +) +from microcosm.build.us_runtime.spm_role_source import ( # noqa: PLC2701 + AsecSpmRoleSource, + _exact_person_keys, + read_pinned_asec_person_columns, +) from microcosm.data.build_folder_manifests import referenced_build from microcosm.frame import put_frame_table, read_frame_table from microcosm.frame.materialize import _PYTABLES_FRAME_TABLE_CODEC_ATTR @@ -121,7 +151,7 @@ ZERO_STEP = "reviewed_zero_columns" #: The ASEC work columns that R1's ``_require_donor_work_experience`` needs -#: and that the reserved restore step adds (see :func:`asec_work_column_step`). +#: and that the restore step adds (see :func:`asec_work_column_step`). ASEC_WORK_COLUMNS: tuple[str, ...] = ( "detailed_industry_recode", "major_industry_recode", @@ -129,6 +159,64 @@ ) ASEC_WORK_STEP = "asec_work_columns" +#: Each work column's source item in the pinned ASEC person member and its +#: dtype: those of ``org_wages.derive_us_org_occupation_inputs`` (#719). +ASEC_WORK_SOURCE_ITEMS: Mapping[str, str] = MappingProxyType( + { + "detailed_industry_recode": "WEIND", + "major_industry_recode": "WEMIND", + "worked_last_year": "WKSWORK > 0", + } +) +ASEC_WORK_DTYPES: Mapping[str, str] = MappingProxyType( + { + "detailed_industry_recode": "int16", + "major_industry_recode": "int16", + "worked_last_year": "bool", + } +) +#: Where the pinned members are looked up by default (the cache of +#: ``education_assistance_source.fetch_asec_education_assistance_source``). +DEFAULT_ASEC_SOURCE_CACHE = Path.home() / ".cache/microcosm/cps/asec_education" + +#: Donor person column -> member column, compared on every joined row. The +#: donor's ``PH_SEQ`` is the pooled household id; the Census ``PH_SEQ`` +#: survives as ``source_household_id`` (``asec_pool._remap_source_year``). +ASEC_IDENTITY_COLUMNS: Mapping[str, str] = MappingProxyType( + { + "source_household_id": "PH_SEQ", + "P_SEQ": "P_SEQ", + "A_LINENO": "A_LINENO", + "A_AGE": "A_AGE", + "WKSWORK": "WKSWORK", + "POCCU2": "POCCU2", + "PRDTRACE": "PRDTRACE", + "PRDTHSP": "PRDTHSP", + } +) +#: Member columns read: the join key, the identity and the two restored codes. +_ASEC_MEMBER_COLUMNS: tuple[str, ...] = ( + "PERIDNUM", + *dict.fromkeys(ASEC_IDENTITY_COLUMNS.values()), + "WEIND", + "WEMIND", +) +#: The restoration's reviewed domains for the two restored codes. +_ASEC_RESTORED_DOMAINS: Mapping[str, Any] = MappingProxyType( + { + spec.name: spec.domain + for spec in ASEC_CENSUS_PERSON_COLUMNS + if spec.name in ("WEIND", "WEMIND") + } +) +_ASEC_REQUIRED_PERSON_COLUMNS: tuple[str, ...] = ( + "PERIDNUM", + "source_year", + *ASEC_IDENTITY_COLUMNS, + "detailed_occupation_recode", +) +_SUPPORT_CHANNEL_COLUMN = "person_support_channel" + _NUMERIC_DTYPES: Mapping[str, type[np.generic]] = MappingProxyType( {"float": np.float64, "int": np.int64} ) @@ -244,30 +332,504 @@ def run(tables: Mapping[str, pd.DataFrame]) -> PatchStepResult: return PatchStep(name=ZERO_STEP, run=run) -def asec_work_column_step(*args: object, **kwargs: object) -> PatchStep: - """Restore ``ASEC_WORK_COLUMNS`` from the pinned ASEC person files. +@dataclass(frozen=True) +class AsecPersonSources: + """Where :func:`asec_work_column_step` finds the pinned ASEC person files. + + ``paths`` names each income year's file (the official archive or its + person CSV). Otherwise each is looked up in ``cache`` (default + :data:`DEFAULT_ASEC_SOURCE_CACHE`) as the pinned member CSV, then as the + official archive, and downloaded through the pin-verifying + ``fetch_asec_education_assistance_source`` only with ``fetch``. ``pins`` + overrides ``spm_role_source.ASEC_SPM_ROLE_SOURCES`` per income year, for + synthetic tests; the restoration's resolver still refuses a pin whose + survey year is not the income year plus one. Every file is read through + ``read_pinned_asec_person_columns``, which refuses a size or SHA-256 that + is not the pin's. + """ + + cache: Path | None = None + paths: Mapping[int, Path] | None = None + fetch: bool = False + pins: Mapping[int, AsecSpmRoleSource] | None = None + + +def _asec_income_years(person: pd.DataFrame) -> tuple[np.ndarray, tuple[int, ...]]: + years = pd.to_numeric(person["source_year"], errors="coerce").to_numpy( + dtype=np.float64, na_value=np.nan + ) + if not np.isfinite(years).all() or not np.equal(years, np.floor(years)).all(): + raise ValueError("Donor person source_year must be finite integers.") + years = years.astype(np.int64) + return years, tuple(sorted({int(year) for year in years})) + + +def resolve_asec_person_files( + pins: Mapping[int, AsecSpmRoleSource], sources: AsecPersonSources +) -> dict[int, Path]: + """Locate each income year's pinned member; pins are checked when read.""" + + if sources.paths is not None: + missing = sorted( + str(year) + for year in pins + if year not in sources.paths or not Path(sources.paths[year]).is_file() + ) + if missing: + raise ValueError( + f"No ASEC person file for income year(s) {missing}; every " + "donor income year needs its pinned member." + ) + return {year: Path(sources.paths[year]) for year in pins} + cache = Path(sources.cache or DEFAULT_ASEC_SOURCE_CACHE).expanduser() + resolved: dict[int, Path] = {} + absent: list[str] = [] + for year, pin in pins.items(): + member = cache / pin.member + archive = cache / Path(urlparse(pin.official_archive_url).path).name + if member.is_file(): + resolved[year] = member + elif archive.is_file(): + resolved[year] = archive + elif sources.fetch: + resolved[year] = ( + education_assistance_source.fetch_asec_education_assistance_source( + year, cache_dir=cache + ) + ) + else: + absent.append(str(year)) + if absent: + raise ValueError( + f"The pinned ASEC person member(s) for income year(s) {absent} are " + f"not in {cache}; pass --asec-source-cache DIR, or --asec-fetch to " + "download the pinned archives." + ) + return resolved + + +def read_asec_work_member( + path: Path, pin: AsecSpmRoleSource +) -> tuple[pd.DataFrame, dict[str, object]]: + """Read and check one pinned member's join key, identity and codes.""" + + # The label names the file actually read beside the pin's member, so a + # wrong-year file is reported as itself. + label = ( + f"ASEC {pin.survey_year} Census person member {pin.member} " + f"(read from {Path(path).name})" + ) + source, form = read_pinned_asec_person_columns( + Path(path).expanduser(), pin, label, _ASEC_MEMBER_COLUMNS + ) + if len(source) != pin.persons: + raise ValueError( + f"{label} holds {len(source)} persons; the pin records {pin.persons}." + ) + for column in _ASEC_MEMBER_COLUMNS[1:]: + values = source[column] + if not pd.api.types.is_integer_dtype(values) or pd.api.types.is_bool_dtype( + values + ): + raise ValueError( + f"{label} column {column} parsed as {values.dtype}, not integer." + ) + for column, domain in _ASEC_RESTORED_DOMAINS.items(): + outside = int((~source[column].isin(domain)).sum()) + if outside: + raise ValueError( + f"{label} column {column} has {outside} values outside its " + f"reviewed Census codes {sorted(domain)}." + ) + source = source.copy() + source["PERIDNUM"] = _exact_person_keys(source["PERIDNUM"], label) + repeated = int(source["PERIDNUM"].duplicated(keep=False).sum()) + if repeated: + raise ValueError( + f"{label} repeats PERIDNUM on {repeated} rows, so a donor person " + "could match more than one member row." + ) + universe = _check_work_experience_universe(source, label) + return source.reset_index(drop=True), { + "path": str(Path(path).expanduser().resolve()), + "form": form, + "income_year": pin.income_year, + "survey_year": pin.survey_year, + "member": pin.member, + "member_sha256": pin.csv_sha256, + "member_size_bytes": pin.csv_size_bytes, + "archive_sha256": pin.archive_sha256 if form == "archive" else None, + "official_archive_url": pin.official_archive_url, + "persons": len(source), + "work_experience_universe": universe, + } + + +def _integer_values(values: pd.Series, label: str) -> np.ndarray: + numeric = pd.to_numeric(values, errors="coerce").to_numpy( + dtype=np.float64, na_value=np.nan + ) + invalid = ~np.isfinite(numeric) | (numeric != np.floor(numeric)) + if invalid.any(): + raise ValueError( + f"{label} has {int(invalid.sum())} missing or non-integer rows." + ) + return numeric.astype(np.int64) + + +def _member_positions(member_keys: pd.Series, keys: np.ndarray) -> np.ndarray: + """Each donor key's member row by exact text, or -1.""" + + return pd.Index(member_keys).get_indexer(keys) + + +def join_asec_work_codes( + person: pd.DataFrame, + years: np.ndarray, + keys: np.ndarray, + members: Mapping[int, pd.DataFrame], +) -> tuple[np.ndarray, np.ndarray, dict[str, dict[str, object]]]: + """``WEIND``/``WEMIND`` for every donor row, by exact (year, PERIDNUM). + + Many donor rows may join one member row (an ASEC row and its PUF-support + clones); every donor row must match exactly one member row, and agree + with it on every :data:`ASEC_IDENTITY_COLUMNS` pair. + """ + + rows = len(person) + weind = np.full(rows, -1, dtype=np.int64) + wemind = np.full(rows, -1, dtype=np.int64) + per_year: dict[str, dict[str, object]] = {} + for year in sorted(members): + mask = years == year + member = members[year] + if not member["PERIDNUM"].is_unique: + raise ValueError( + f"Income year {year} member repeats PERIDNUM; a donor person " + "could match more than one member row." + ) + positions = _member_positions(member["PERIDNUM"], keys[mask]) + missing = int((positions < 0).sum()) + if missing: + raise ValueError( + f"{missing} donor person rows of income year {year} have no row " + "in its pinned ASEC person member; every donor person must match." + ) + aligned = member.iloc[positions] + if not np.array_equal(aligned["PERIDNUM"].to_numpy(), keys[mask]): + raise ValueError( + f"Income year {year} member rows did not align by PERIDNUM." + ) + mismatches: dict[str, int] = {} + for donor_column, member_column in ASEC_IDENTITY_COLUMNS.items(): + donor_values = _integer_values( + person.loc[mask, donor_column], + f"Donor person {donor_column} (income year {year})", + ) + disagree = donor_values != aligned[member_column].to_numpy(dtype=np.int64) + if disagree.any(): + mismatches[donor_column] = int(disagree.sum()) + if mismatches: + raise ValueError( + f"Income year {year} donor rows disagree with their ASEC person " + f"member after the (source_year, PERIDNUM) join: {mismatches} rows " + "by column; the join would pair the wrong people." + ) + weind[mask] = aligned["WEIND"].to_numpy(dtype=np.int64) + wemind[mask] = aligned["WEMIND"].to_numpy(dtype=np.int64) + distinct = int(len(np.unique(positions))) + per_year[str(year)] = { + "donor_rows": int(mask.sum()), + "donor_rows_matched_once": int(mask.sum()), + "distinct_keys_matched": distinct, + "member_rows": int(len(member)), + "member_rows_not_in_donor": int(len(member) - distinct), + "identity_mismatches": 0, + } + if (weind < 0).any() or (wemind < 0).any(): + raise ValueError("A donor person row was left without a joined ASEC code.") + return weind, wemind, per_year + + +def asec_clone_summary( + person: pd.DataFrame, years: np.ndarray, keys: np.ndarray +) -> dict[str, object]: + """Counts of the donor rows that share a (source_year, PERIDNUM) key.""" + + channels = ( + person[_SUPPORT_CHANNEL_COLUMN].astype(str).to_numpy() + if _SUPPORT_CHANNEL_COLUMN in person + else np.full(len(person), "unlabelled", dtype=object) + ) + frame = pd.DataFrame({"year": years, "key": keys, "channel": channels}) + grouped = frame.groupby(["year", "key"], sort=False)["channel"] + sizes = grouped.size() + composition = grouped.agg(lambda values: "+".join(sorted(values))) + repeated = sizes.gt(1) + return { + "rows": int(len(frame)), + "distinct_keys": int(len(sizes)), + "keys_with_one_row": int(sizes.eq(1).sum()), + "keys_with_two_rows": int(sizes.eq(2).sum()), + "keys_with_more_rows": int(sizes.gt(2).sum()), + "repeated_key_channel_composition": { + str(label): int(count) + for label, count in composition[repeated] + .value_counts() + .sort_index() + .items() + }, + "rows_by_support_channel": { + str(label): int(count) + for label, count in frame["channel"].value_counts().sort_index().items() + }, + "handling": ( + "Every row sharing a key joins the same member row and must match " + "it on every identity column, so clones get identical codes." + ), + } + - Reserved for the next commit on this tool, which Max's agents add from - their verified local step. Its contract: - - - Read the pinned ASEC person files (``pppub23``-``pppub26``) and refuse a - file whose SHA-256 is not the pinned one. - - Match each donor person on its source year and ``PERIDNUM``. Refuse a - donor person with no match or with more than one match. - - Return a :class:`PatchStep` named ``ASEC_WORK_STEP``. Its ``run`` - returns a :class:`PatchStepResult` with one :class:`ColumnPatch` per - column on ``person`` (the source item in each ``record``), and the - files, their digests and the match counts in the step ``receipt``. - - Register it in :func:`build_patch_steps` before the zero step, with its - command-line options in :func:`_parse_args`. - - R1's ``_require_donor_work_experience`` must then pass on the copy. +def carry_asec_work_columns( + person: pd.DataFrame, weind: np.ndarray, wemind: np.ndarray +) -> tuple[dict[str, np.ndarray], dict[str, object]]: + """The three columns, from ``derive_us_org_occupation_inputs`` itself. + + The carry's other outputs must equal the donor's own columns (value and + dtype), so the donor is known to come from the same carry. """ - raise NotImplementedError( - "The ASEC work-column restore step is not in this commit; the next " - "commit on this tool adds it (microcosm#1647)." + restored = person[["PRDTRACE", "PRDTHSP", "POCCU2", "WKSWORK"]].copy() + restored["WEIND"] = weind + restored["WEMIND"] = wemind + universe = _check_work_experience_universe(restored, "Donor person rows") + carried = derive_us_org_occupation_inputs(restored) + derived: dict[str, np.ndarray] = {} + for column, dtype in ASEC_WORK_DTYPES.items(): + values = carried[column].to_numpy() + if values.dtype != np.dtype(dtype) or values.shape != (len(person),): + raise ValueError( + f"The carry did not emit {column} as a person-grain {dtype}." + ) + derived[column] = values + verified, absent = [], [] + for column in carried.columns: + if column in ASEC_WORK_DTYPES: + continue + if column not in person: + absent.append(column) + continue + if ( + not np.array_equal(person[column].to_numpy(), carried[column].to_numpy()) + or person[column].dtype != carried[column].dtype + ): + raise ValueError( + f"Donor {column} differs from the carry's value; the donor was " + "not built by the carry these columns come from." + ) + verified.append(column) + candidate = pd.DataFrame( + {"detailed_occupation_recode": person["detailed_occupation_recode"]}, + index=person.index, + ) + for column, values in derived.items(): + candidate[column] = values + require_us_occupation_and_work_experience_inputs( + candidate, label="Donor with restored work columns" ) + return derived, { + "function": ( + "microcosm.build.us_runtime.org_wages.derive_us_org_occupation_inputs" + ), + "inputs": ["PRDTRACE", "PRDTHSP", "POCCU2", "WKSWORK", "WEIND", "WEMIND"], + "donor_work_experience_universe": universe, + "reemitted_columns_verified_equal": verified, + "reemitted_columns_absent_from_donor": absent, + "require_us_occupation_and_work_experience_inputs": "passed", + } + + +def _person_weights(tables: Mapping[str, pd.DataFrame]) -> np.ndarray | None: + """``household_weight`` resolved to persons, or None without one.""" + + household, person = tables["household"], tables["person"] + if "household_weight" not in household or "person_household_id" not in person: + return None + weights = pd.Series( + household["household_weight"].to_numpy(dtype=np.float64), + index=household["household_id"].to_numpy(), + ) + resolved = person["person_household_id"].map(weights) + if resolved.isna().any(): + return None + return resolved.to_numpy(dtype=np.float64) + + +def asec_work_summary( + weights: np.ndarray | None, + years: np.ndarray, + derived: Mapping[str, np.ndarray], +) -> dict[str, object]: + """Nonzero shares beside the carry's gate bands, and code counts.""" + + bands = org_wages._SHARE_BANDS # noqa: SLF001 - the carry's measured bands + detailed = derived["detailed_industry_recode"].astype(np.int64) + major = derived["major_industry_recode"].astype(np.int64) + worked = derived["worked_last_year"].astype(bool) + worker = np.isin(detailed, WORKER_INDUSTRY_CODES) + shares: dict[str, object] = {} + for column, values in derived.items(): + nonzero = np.asarray(values).astype(np.int64) != 0 + low, high = bands[column] + entry: dict[str, object] = { + "unweighted_nonzero_share": float(nonzero.mean()) if nonzero.size else 0.0, + "gate_band": [low, high], + } + if weights is not None and float(weights.sum()): + weighted = float(weights[nonzero].sum() / weights.sum()) + entry["weighted_nonzero_share"] = weighted + entry["within_band"] = bool(low <= weighted <= high) + entry["by_source_year_weighted"] = { + str(year): ( + float( + weights[(years == year) & nonzero].sum() + / weights[years == year].sum() + ) + if weights[years == year].sum() + else 0.0 + ) + for year in sorted(set(years.tolist())) + } + shares[column] = entry + return { + "weights": ( + "household_weight resolved to persons" if weights is not None else None + ), + "nonzero_shares": shares, + "worked_last_year_rows": int(worked.sum()), + "worked_rows_with_worker_industry": int((worked & worker).sum()), + "worker_industry_rows_without_weeks_worked": int((worker & ~worked).sum()), + "detailed_industry_recode_counts": { + str(code): int((detailed == code).sum()) for code in range(24) + }, + "major_industry_recode_counts": { + str(code): int((major == code).sum()) for code in range(16) + }, + } + + +def asec_work_column_step(sources: AsecPersonSources | None = None) -> PatchStep: + """Restore ``ASEC_WORK_COLUMNS`` from the pinned ASEC person files. + + The #719 work columns, valued as the #720 restoration and the fiscal + ``org_wages`` carry value them (the route 2 step reviewed on #1647): + + - Each donor person's ``source_year`` is its ASEC income year; its member + is the survey-year ``source_year + 1`` file (``_resolve_pin`` refuses + any other pairing). Only the donor's income years are read, through + ``read_pinned_asec_person_columns``, which refuses a file whose size or + SHA-256 is not the pin's. + - ``WEIND`` and ``WEMIND`` join by exact ``(source_year, PERIDNUM)`` text. + A donor repeats a key within a year for an ASEC row and its PUF-support + clone, so many donor rows join one member row. A donor person with no + member row is refused, and so is a member that repeats a ``PERIDNUM`` + (a donor person would match more than one row). On every row the + :data:`ASEC_IDENTITY_COLUMNS` must equal the member's. + - The restoration's domains and work-experience identities are checked on + each member and on the joined rows. The columns are the output of + ``derive_us_org_occupation_inputs`` (int16, int16, bool); its other + outputs must equal the donor's own columns. + - A work column already on another entity is refused; one already on + ``person`` must equal the restored values (the tool's rule). + + ``run`` returns one :class:`ColumnPatch` per column on ``person``, with + its source item in ``record``, and the files, their digests, the match + counts, the clone counts, the carry checks and the nonzero shares in the + step ``receipt``. R1's ``_require_donor_work_experience`` then passes on + the copy. + """ + + sources = sources or AsecPersonSources() + + def run(tables: Mapping[str, pd.DataFrame]) -> PatchStepResult: + for entity, table in tables.items(): + elsewhere = sorted( + column for column in ASEC_WORK_COLUMNS if column in table.columns + ) + if entity != "person" and elsewhere: + raise ValueError( + f"The donor already carries work column(s) {elsewhere} on " + f"{entity}; refusing to duplicate them on person." + ) + person = tables["person"] + missing = [c for c in _ASEC_REQUIRED_PERSON_COLUMNS if c not in person] + if missing: + raise ValueError( + f"The donor person table lacks {missing}, which the ASEC work " + "column join needs." + ) + years, income_years = _asec_income_years(person) + pins = { + year: _resolve_pin(year, (sources.pins or {}).get(year)) + for year in income_years + } + paths = resolve_asec_person_files(pins, sources) + keys = _exact_person_keys(person["PERIDNUM"], "Donor person table").to_numpy() + members: dict[int, pd.DataFrame] = {} + files: dict[str, dict[str, object]] = {} + for year in income_years: + members[year], files[str(year)] = read_asec_work_member( + paths[year], pins[year] + ) + weind, wemind, per_year = join_asec_work_codes(person, years, keys, members) + del members + gc.collect() + clones = asec_clone_summary(person, years, keys) + derived, carry = carry_asec_work_columns(person, weind, wemind) + summary = asec_work_summary(_person_weights(tables), years, derived) + patches = tuple( + ColumnPatch( + entity="person", + column=column, + values=pd.Series(derived[column], index=person.index, name=column), + record={ + "source_item": ASEC_WORK_SOURCE_ITEMS[column], + "source": ( + "pinned ASEC person member of the row's income year, " + "joined on (source_year, PERIDNUM)" + ), + "derivation": carry["function"], + }, + ) + for column in ASEC_WORK_COLUMNS + ) + receipt = { + "source": ( + "pinned Census ASEC person members " + "(spm_role_source.ASEC_SPM_ROLE_SOURCES), read through " + "spm_role_source.read_pinned_asec_person_columns" + ), + "vintage_rule": ( + "source_year is the ASEC income year; its member is survey year " + "source_year + 1 (asec_census_person_columns._resolve_pin)" + ), + "files": files, + "join": { + "key": "(source_year, PERIDNUM as exact 22-digit text)", + "identity_columns": dict(ASEC_IDENTITY_COLUMNS), + "donor_rows": int(len(person)), + "donor_rows_matched_once": int(len(person)), + "unmatched_donor_rows": 0, + "multiply_matched_donor_rows": 0, + "by_income_year": per_year, + }, + "clones": clones, + "carry": carry, + "work_experience": summary, + } + return PatchStepResult(patches=patches, receipt=receipt) + + return PatchStep(name=ASEC_WORK_STEP, run=run) @dataclass(frozen=True) @@ -434,14 +996,18 @@ def build_patch_steps( *, zero_columns: Sequence[str], engine: Any, + asec_sources: AsecPersonSources | None = None, ) -> list[PatchStep]: """The steps the command runs, in order. - The ASEC work-column restore step (:func:`asec_work_column_step`) goes - first when it lands, then the reviewed zero columns. + With ``asec_sources``, the ASEC work-column restore step + (:func:`asec_work_column_step`) goes first, then the reviewed zero + columns. The command always passes ``asec_sources``. """ - return [reviewed_zero_column_step(zero_columns, engine=engine)] + steps = [] if asec_sources is None else [asec_work_column_step(asec_sources)] + steps.append(reviewed_zero_column_step(zero_columns, engine=engine)) + return steps def patch_donor_h5( @@ -875,6 +1441,23 @@ def _parse_args(argv: Sequence[str] | None = None) -> argparse.Namespace: "more than one (default: every reviewed column)." ), ) + parser.add_argument( + "--asec-source-cache", + type=Path, + help=( + "Directory holding the pinned ASEC person members (pppubYY.csv) or " + "their official archives (asecpubYYcsv.zip), for the work-column " + f"restore (default: {DEFAULT_ASEC_SOURCE_CACHE})." + ), + ) + parser.add_argument( + "--asec-fetch", + action="store_true", + help=( + "Download a pinned ASEC archive absent from the cache (verified " + "against its pin) instead of refusing." + ), + ) parser.add_argument( "--input-release-manifest", type=Path, @@ -922,6 +1505,9 @@ def main(argv: Sequence[str] | None = None) -> int: steps = build_patch_steps( zero_columns=args.zero_column or list(REVIEWED_ZERO_COLUMNS), engine=PolicyEngineUSEngine(), + asec_sources=AsecPersonSources( + cache=args.asec_source_cache, fetch=args.asec_fetch + ), ) release_manifest = ( None From 3b28e315c9c0e753590f13e359e1d87a057ebecd Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mar=C3=ADa=20Juaristi?= <127882282+juaristi22@users.noreply.github.com> Date: Tue, 17 Nov 2026 14:11:27 +0000 Subject: [PATCH 10/31] Compute the county AGI pre-check with the engine, as R2 stores it The check counted a household when any person held a nonzero gross-income input. policyengine-us 2.2.1 adds only the positive sources of a tax unit's head and spouse to irs_gross_income, and only an adult can be either, so a household whose income sits on a dependent, or on a tax unit without an adult, has an AGI of 0. A county of such households passed the check, and R2 would refuse its empty AGI row after the engine pass (#1660 review). The check now loads the staging frame and summary as R2's materialize stage does, holds back the formula-owned columns, fills the reviewed nulls with R2's own fill step, and runs the engine for the household sum of adjusted_gross_income in household chunks. An engine-tier test checks that sum against the production SOI materializer's AGI measure on six households, the dependent and no-adult cases included. Null take-up flags that R2's own stages fill are held back, as the AGI does not read them; a null never-default column that the AGI reads is refused, as R2 refuses it. Part of #922. Co-Authored-By: Claude Opus 5.5 --- ...-acs-county-agi-support-check-922.added.md | 2 +- .../us/test_us_acs_county_agi_support.py | 260 +++++----- .../test_us_acs_county_agi_support_engine.py | 140 ++++++ tools/check_us_acs_county_agi_support.py | 448 +++++++++--------- 4 files changed, 485 insertions(+), 365 deletions(-) create mode 100644 packages/microcosm-build/tests/engine_workflow/us/test_us_acs_county_agi_support_engine.py diff --git a/changelog.d/us-acs-county-agi-support-check-922.added.md b/changelog.d/us-acs-county-agi-support-check-922.added.md index aa8837ad26..208260516e 100644 --- a/changelog.d/us-acs-county-agi-support-check-922.added.md +++ b/changelog.d/us-acs-county-agi-support-check-922.added.md @@ -1 +1 @@ -`tools/check_us_acs_county_agi_support.py` lists, before the ACS local release (R2) runs, the counties whose county IRS SOI AGI row R2 would build empty: counties with households but none that can carry a nonzero AGI (microcosm#922; microcosm#1630 review, finding 1). The state AGI row stores no zero, so such a county makes `attach_surface` refuse the run after the materialize engine pass. The check reads the staging H5's household table and only the AGI income columns, which it takes from policyengine-us's `irs_gross_income` inputs without importing the engine (Social Security and deductions are left out, so it errs towards listing a county). With `--puma-ladder` it applies R2's own minimum-support moves first. It exits 2 when a county is at risk. +`tools/check_us_acs_county_agi_support.py` lists, before the ACS local release (R2) runs, the counties whose county IRS SOI AGI row R2 would build empty: counties with households but none with a nonzero AGI (microcosm#922; microcosm#1630 review, finding 1). The state AGI row stores no zero, so such a county makes `attach_surface` refuse the run after the materialize engine pass. The check computes the value R2 stores: it loads the staging frame and its summary as R2 does, holds back the formula-owned columns, fills the reviewed nulls with R2's own functions, and runs policyengine-us for the household sum of `adjusted_gross_income` in household chunks. That sum is the production SOI materializer's AGI measure (an engine-tier test compares them), so income held by a dependent, or by a tax unit without an adult, counts as the engine counts it: not at all. A null take-up flag that R2's own stages fill is held back, since the AGI does not read it; a null in a never-default column that the AGI reads is refused, as R2 refuses it. With `--puma-ladder` it applies R2's own minimum-support moves first. It exits 2 when a county is at risk. diff --git a/packages/microcosm-build/tests/engine_free/us/test_us_acs_county_agi_support.py b/packages/microcosm-build/tests/engine_free/us/test_us_acs_county_agi_support.py index dd02ef50cb..f78f6c62ff 100644 --- a/packages/microcosm-build/tests/engine_free/us/test_us_acs_county_agi_support.py +++ b/packages/microcosm-build/tests/engine_free/us/test_us_acs_county_agi_support.py @@ -1,9 +1,10 @@ """The pre-R2 check for counties whose SOI AGI row would be empty (microcosm#922). ``tools/check_us_acs_county_agi_support.py`` lists counties that have -households but none that can carry a nonzero AGI: R2's ``attach_surface`` -refuses such a county after the engine pass. These tests use small fixture -H5 files and a stand-in engine index, so no country engine is imported. +households but none with a nonzero AGI: R2's ``attach_surface`` refuses such +a county after the engine pass. These tests stub the engine pass (the +household AGI), so no country engine is imported; the engine-tier test +``engine_workflow/us/test_us_acs_county_agi_support_engine.py`` runs it. """ from __future__ import annotations @@ -13,13 +14,13 @@ import sys from dataclasses import dataclass from pathlib import Path +from types import SimpleNamespace import numpy as np import pandas as pd import pytest -from microcosm.build.us_runtime.h5_io import write_nullable_us_h5 -from microcosm.frame import US_SCHEMA, Frame, VariableMetadata, WeightKind, Weights +from microcosm.frame import US_SCHEMA, Frame, WeightKind, Weights from test_support.paths import paths_for _TEST_PATHS = paths_for("microcosm-build") @@ -36,44 +37,11 @@ def check(): return module -@dataclass(frozen=True) -class _Closure: - input_leaves: tuple[str, ...] - engine_version: str = "fixture" - sha256: str = "c" * 64 - - -class _Index: - """Stand-in for PolicyEngineUSVariableMetadataIndex.""" - - leaves = { - "employment_income_before_lsr": ("person", "float", "currency-USD"), - "taxable_interest_income": ("person", "float", "currency-USD"), - "social_security_retirement": ("person", "float", "currency-USD"), - "student_loan_interest": ("person", "float", "currency-USD"), - "other_net_gain": ("tax_unit", "float", "currency-USD"), - "age": ("person", "float", None), - "is_blind": ("person", "bool", None), - } - - def variable_dependency_closure(self, name): - assert name == "irs_gross_income" - return _Closure(tuple(sorted(self.leaves))) - - def variable_metadata(self, name): - entity, dtype, _unit = self.leaves[name] - return VariableMetadata(name=name, entity=entity, dtype=dtype, period="year") - - def variable_unit(self, name): - return self.leaves[name][2] - - -def _frame(person_income: dict[str, list[float]], unit_income=None) -> Frame: +def _frame(person_columns: dict[str, list] | None = None) -> Frame: """Six households in three counties of state 01, one person each. - 01001: two households with income. 01003: two households, the first with - Social Security only, the second with a null wage. 01005: two ACS - households, one a group-quarters record. + 01001 and 01003 hold two donor households each; 01005 holds two ACS + households, the second a group-quarters record. """ n = 6 @@ -83,10 +51,9 @@ def _frame(person_income: dict[str, list[float]], unit_income=None) -> Frame: "person_id": ids, **{f"person_{entity}_id": ids for entity in US_SCHEMA.group_entities}, "age": np.full(n, 40.0), + **(person_columns or {}), } ) - for column, values in person_income.items(): - person[column] = values tables = {"person": person} for entity in US_SCHEMA.group_entities: tables[entity] = pd.DataFrame({f"{entity}_id": ids}) @@ -98,8 +65,6 @@ def _frame(person_income: dict[str, list[float]], unit_income=None) -> Frame: ["asec_puf"] * 4 + ["acs_2024_1yr"] * 2, dtype=object ) household["TYPEHUGQ"] = [np.nan] * 4 + [1.0, 3.0] - for column, values in (unit_income or {}).items(): - tables["tax_unit"][column] = values return Frame( tables, US_SCHEMA, @@ -107,65 +72,13 @@ def _frame(person_income: dict[str, list[float]], unit_income=None) -> Frame: ) -_INCOME = { - "employment_income_before_lsr": [100.0, 0.0, 0.0, np.nan, 0.0, 0.0], - "taxable_interest_income": [0.0, 5.0, 0.0, 0.0, 0.0, 0.0], - "social_security_retirement": [0.0, 0.0, 900.0, 0.0, 0.0, 0.0], - "student_loan_interest": [0.0, 0.0, 0.0, 0.0, 300.0, 0.0], -} - - -def test_agi_income_columns_drop_social_security_and_deductions(check) -> None: - sources = check.agi_income_columns(_Index()) - - assert sources["person"] == [ - "employment_income_before_lsr", - "taxable_interest_income", - ] - assert sources["tax_unit"] == ["other_net_gain"] - assert sources["excluded"] == { - "social_security_retirement": "social_security_taxable_share_only", - "student_loan_interest": "deduction_expense_or_contribution", - } - assert sources["engine_version"] == "fixture" - - -def test_households_without_agi_income_are_found(check) -> None: - frame = _frame(_INCOME) - - flags = check.household_income_flags( - frame.table("household"), - frame.table("person"), - frame.table("tax_unit"), - person_columns=["employment_income_before_lsr", "taxable_interest_income"], - ) - - # Social Security only, a null wage, a deduction only: no AGI income. - assert flags.tolist() == [True, True, False, False, False, False] - - -def test_tax_unit_income_reaches_its_household(check) -> None: - frame = _frame(_INCOME, unit_income={"other_net_gain": [0, 0, 0, 0, 0, 7.0]}) - - flags = check.household_income_flags( - frame.table("household"), - frame.table("person"), - frame.table("tax_unit"), - person_columns=["employment_income_before_lsr"], - tax_unit_columns=["other_net_gain"], - ) - - assert flags.tolist() == [True, False, False, False, False, True] - - -def test_report_lists_counties_with_households_but_no_agi_income(check) -> None: - frame = _frame(_INCOME) - households = frame.table("household") - income = np.asarray([True, True, False, False, False, True]) +def test_report_lists_counties_with_households_but_no_nonzero_agi(check) -> None: + households = _frame().table("household") + nonzero = np.asarray([True, True, False, False, False, True]) report = check.county_agi_report( households, - income, + nonzero, county_column="county_fips_2023", county_populations={1001: 10.0, 1003: 5.0, 1005: 5.0, 1007: 3.0}, ) @@ -184,55 +97,134 @@ def test_report_lists_counties_with_households_but_no_agi_income(check) -> None: assert report["counties_outside_ladder"] == [] -@pytest.mark.parametrize("layout", ["fixed", "table"]) -def test_read_columns_reads_only_the_named_columns( - check, tmp_path: Path, layout: str -) -> None: - frame = _frame(_INCOME) - path = tmp_path / f"{layout}.h5" - if layout == "fixed": - write_nullable_us_h5(frame, path, period=2024, artifact_kind="fixture") - else: - with pd.HDFStore(path, mode="w") as store: - store.put("person", frame.table("person"), format="table") - - read = check.read_columns( - path, - "person", - ["person_household_id", "taxable_interest_income", "not_a_column"], +_NEVER_DEFAULT = frozenset( + { + ("person", "takes_up_ssi_if_eligible"), + ("person", "is_blind"), + ("spm_unit", "takes_up_snap_if_eligible"), + } +) + + +def test_null_runtime_columns_outside_the_agi_are_held_back(check) -> None: + frame = _frame( + { + "takes_up_ssi_if_eligible": [True, np.nan, True, True, False, True], + "is_blind": [False] * 6, + } ) - assert list(read.columns) == ["person_household_id", "taxable_interest_income"] - np.testing.assert_array_equal( - read["taxable_interest_income"].to_numpy(), _INCOME["taxable_interest_income"] + held_frame, held = check.hold_back_null_runtime_columns( + frame, never_default_filled=_NEVER_DEFAULT, agi_inputs={"is_blind", "age"} ) - np.testing.assert_array_equal( - read["person_household_id"].to_numpy(), np.arange(1, 7) + + assert held == {"person": ["takes_up_ssi_if_eligible"]} + assert "takes_up_ssi_if_eligible" not in held_frame.table("person").columns + assert "is_blind" in held_frame.table("person").columns + assert held_frame.n("household") == frame.n("household") + + +def test_a_null_never_default_agi_input_is_refused(check) -> None: + frame = _frame({"is_blind": [False, np.nan, False, False, False, False]}) + + with pytest.raises(SystemExit, match=r"person\.is_blind"): + check.hold_back_null_runtime_columns( + frame, never_default_filled=_NEVER_DEFAULT, agi_inputs={"is_blind"} + ) + + +def test_a_frame_without_null_runtime_columns_is_returned_as_is(check) -> None: + frame = _frame({"takes_up_ssi_if_eligible": [True] * 6}) + + held_frame, held = check.hold_back_null_runtime_columns( + frame, never_default_filled=_NEVER_DEFAULT, agi_inputs={"age"} ) + assert held == {} + assert held_frame is frame + + +@dataclass(frozen=True) +class _Closure: + input_leaves: tuple[str, ...] + + +def test_agi_engine_inputs_are_the_static_closure_of_agi(check) -> None: + class _Index: + def variable_dependency_closure(self, name): + assert name == "adjusted_gross_income" + return _Closure(("age", "employment_income_before_lsr")) + + assert check.agi_engine_inputs(_Index()) == {"age", "employment_income_before_lsr"} + + +def _stub_release(frame: Frame) -> SimpleNamespace: + return SimpleNamespace(_load_staging_frame=lambda path: frame) + def test_command_exits_2_and_reports_an_at_risk_county( check, tmp_path: Path, monkeypatch: pytest.MonkeyPatch ) -> None: - import microcosm.frame.adapters.policyengine_us as adapter - - monkeypatch.setattr(adapter, "PolicyEngineUSVariableMetadataIndex", _Index) staging = tmp_path / "staging.h5" - write_nullable_us_h5(_frame(_INCOME), staging, period=2024, artifact_kind="fixture") + staging.write_bytes(b"") + (tmp_path / "staging.summary.json").write_text("{}") out = tmp_path / "report.json" + monkeypatch.setattr(check, "_release_tool", lambda: _stub_release(_frame())) + calls = [] + + def agi(frame, summary_path, *, release, hh_chunk): + calls.append((summary_path, hh_chunk)) + # 01003's households have an AGI of 0; a negative AGI is stored. + return np.asarray([100.0, 0.0, 0.0, 0.0, -5.0, 0.0]), {"stub": True} + + monkeypatch.setattr(check, "household_agi", agi) status = check.main(["--h5", str(staging), "--out", str(out)]) report = json.loads(out.read_text()) assert status == check.EXIT_AT_RISK - assert report["at_risk"] == ["01003", "01005"] - assert report["agi_income_columns"]["person_present"] == [ - "employment_income_before_lsr", - "taxable_interest_income", - ] - assert report["agi_income_columns"]["tax_unit_present"] == [] + assert report["at_risk"] == ["01003"] + assert report["households_with_agi_income"] == 2 + assert report["agi_engine"] == {"stub": True} assert report["minimum_support"] is None + # The summary path defaults as R2's does: the H5 with .summary.json. + assert calls == [(tmp_path / "staging.summary.json", check.DEFAULT_HH_CHUNK)] + + def healthy(frame, summary_path, *, release, hh_chunk): + return np.asarray([1.0, 0.0, 0.0, 2.0, 0.0, 3.0]), {} - healthy = dict(_INCOME, taxable_interest_income=[0.0, 5.0, 1.0, 0.0, 2.0, 0.0]) - write_nullable_us_h5(_frame(healthy), staging, period=2024, artifact_kind="fixture") + monkeypatch.setattr(check, "household_agi", healthy) assert check.main(["--h5", str(staging), "--county-column", "county_fips"]) == 0 + + +def test_an_agi_below_float32_resolution_is_stored_as_zero( + check, tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + staging = tmp_path / "staging.h5" + staging.write_bytes(b"") + summary = tmp_path / "other.summary.json" + summary.write_text("{}") + monkeypatch.setattr(check, "_release_tool", lambda: _stub_release(_frame())) + monkeypatch.setattr( + check, + "household_agi", + lambda frame, path, *, release, hh_chunk: ( + np.asarray([1.0, 0.0, 1e-50, 0.0, 1.0, 0.0]), + {}, + ), + ) + + status = check.main(["--h5", str(staging), "--staging-summary", str(summary)]) + + assert status == check.EXIT_AT_RISK + + +def test_command_refuses_without_a_staging_summary( + check, tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + staging = tmp_path / "staging.h5" + staging.write_bytes(b"") + monkeypatch.setattr(check, "_release_tool", lambda: _stub_release(_frame())) + + with pytest.raises(SystemExit, match="Staging summary not found"): + check.main(["--h5", str(staging)]) diff --git a/packages/microcosm-build/tests/engine_workflow/us/test_us_acs_county_agi_support_engine.py b/packages/microcosm-build/tests/engine_workflow/us/test_us_acs_county_agi_support_engine.py new file mode 100644 index 0000000000..45515f95dd --- /dev/null +++ b/packages/microcosm-build/tests/engine_workflow/us/test_us_acs_county_agi_support_engine.py @@ -0,0 +1,140 @@ +"""The pre-R2 county AGI check against R2's SOI AGI measure (microcosm#922). + +``tools/check_us_acs_county_agi_support.py`` computes each household's AGI +with R2's projection, reviewed-null fill and dataset builder, in household +chunks. The engine counts only the positive income sources of a tax unit's +head and spouse (``irs_gross_income``), and only an adult can be a head or a +spouse, so income held by a dependent, or by a tax unit without an adult, +adds nothing. This test runs the check's engine pass on six households and +compares it with the production SOI materializer's AGI measure, the value +R2's state AGI row stores (#1660 review). +""" + +from __future__ import annotations + +import importlib.util +import json +import sys + +import numpy as np +import pandas as pd + +from microcosm.frame import US_SCHEMA, Frame, WeightKind, Weights +from test_support.microcosm_build.us_batched_target_materialization import ( + _load_builder_module, + _soi, +) +from test_support.paths import paths_for + +_TEST_PATHS = paths_for("microcosm-build") +#: Household AGI: a dependent's wages (1), a head's wages (2), a retiree's +#: interest beside a dependent's wages (3), a spouse's wages (4), a tax unit +#: of one 16-year-old with wages (5), and a capital loss alone (6). +_EXPECTED_AGI = [0.0, 30_000.0, 100.0, 20_000.0, 0.0, -2_000.0] + + +def _check(): + path = _TEST_PATHS.repository / "tools" / "check_us_acs_county_agi_support.py" + spec = importlib.util.spec_from_file_location("check_us_county_agi_engine", path) + module = importlib.util.module_from_spec(spec) + assert spec.loader is not None + sys.modules[spec.name] = module + spec.loader.exec_module(module) + return module + + +def _frame(*, with_nulls: bool) -> Frame: + household = np.asarray([1, 1, 2, 3, 3, 4, 4, 5, 6, 6], "int64") + tax_unit = np.asarray([10, 10, 20, 30, 30, 40, 40, 50, 60, 60], "int64") + interest = [0.0, 0.0, 0.0, 100.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0] + if with_nulls: + # A registered null: the fill step gives it the engine default, 0. + interest[0] = np.nan + persons = pd.DataFrame( + { + "person_id": np.arange(1, 11, dtype="int64"), + "person_household_id": household, + "person_tax_unit_id": tax_unit, + "person_spm_unit_id": tax_unit * 10, + "person_family_id": tax_unit * 100, + "person_marital_unit_id": np.asarray( + [1, 2, 3, 4, 5, 6, 6, 7, 8, 9], "int64" + ) + * 10_000, + "age": np.asarray( + [40.0, 10.0, 40.0, 70.0, 16.0, 40.0, 38.0, 16.0, 50.0, 12.0] + ), + "employment_income_before_lsr": np.asarray( + [0.0, 5_000.0, 30_000.0, 0.0, 8_000.0, 0.0, 20_000.0, 6_000.0, 0.0, 0.0] + ), + "taxable_interest_income": np.asarray(interest), + "short_term_capital_gains": np.asarray( + [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, -2_000.0, 0.0] + ), + } + ) + tables = {"person": persons} + for entity in ("tax_unit", "spm_unit", "family", "marital_unit"): + ids = np.unique(persons[f"person_{entity}_id"].to_numpy()) + tables[entity] = pd.DataFrame({f"{entity}_id": ids}) + if with_nulls: + # A runtime-owned take-up flag that R2's stages fill on ACS rows and + # the AGI does not read: the check holds it back while it is null. + tables["spm_unit"]["takes_up_snap_if_eligible"] = pd.Series( + [True, None, True, True, True, True], dtype=object + ) + tables["household"] = pd.DataFrame( + { + "household_id": np.arange(1, 7, dtype="int64"), + "state_fips": np.full(6, 6, dtype="int64"), + } + ) + return Frame( + tables, + US_SCHEMA, + {"household": Weights(np.ones(6), WeightKind.DESIGN)}, + ) + + +def test_household_agi_counts_only_heads_and_spouses_as_the_soi_row_does( + tmp_path, +) -> None: + check = _check() + release = check._release_tool() + summary = tmp_path / "staging.summary.json" + summary.write_text( + json.dumps( + { + "reviewed_engine_input_nulls": [ + { + "entity": "person", + "column": "taxable_interest_income", + "missing_rows": 1, + "rows": 10, + } + ] + } + ) + ) + + agi, receipt = check.household_agi( + _frame(with_nulls=True), summary, release=release, hh_chunk=2 + ) + + np.testing.assert_array_equal(agi, _EXPECTED_AGI) + assert receipt["chunks"] == 3 + assert receipt["reviewed_fill_columns"] == 1 + assert receipt["null_runtime_columns_held_back"] == { + "spm_unit": ["takes_up_snap_if_eligible"] + } + + builder = _load_builder_module() + target_frame, _registry, compilation = builder._materialize_target_frame( + _frame(with_nulls=False), + (_soi("agi_amount", "adjusted_gross_income"),), + maximum_microsim_batch_size=None, + ) + assert compilation["dropped_target_names"] == [] + np.testing.assert_array_equal( + target_frame.table("household")["agi_amount"].to_numpy(dtype=np.float64), agi + ) diff --git a/tools/check_us_acs_county_agi_support.py b/tools/check_us_acs_county_agi_support.py index 138bf672f0..03de9b0d15 100644 --- a/tools/check_us_acs_county_agi_support.py +++ b/tools/check_us_acs_county_agi_support.py @@ -9,27 +9,35 @@ finding 1). Minimum county support fills only counties with no household, so it does not help here. -This check runs on the staging H5 (R1's output) before R2, with no engine -pass and in minutes: - -- It reads the household table, and only the AGI income columns of the - person and tax-unit tables. -- The AGI income columns are the money inputs behind policyengine-us's - ``irs_gross_income`` (its gross income sources), read from the installed - engine's source without importing it, less the leaves that cannot make - gross income nonzero on their own: Social Security (only its taxable share - counts, which is 0 without other income) and deductions, expenses and - contributions (``NOT_INCOME_LEAVES``). -- A household can carry a nonzero AGI when any of its persons or tax units - has a nonzero, non-null value in one of those columns. R2 fills a null - income cell with the engine default, 0. +This check runs on the staging H5 (R1's output) and its summary, before R2. +It computes the value R2 stores, with R2's own functions and the engine: + +- It loads the staging frame as R2's materialize stage does + (``_load_staging_frame``), holds back the formula-owned columns + (``project_input_only``) and fills the reviewed nulls with the engine + defaults (``fill_reviewed_nulls``, which refuses what R2 refuses). +- It builds each household chunk's policyengine-us dataset as R2's engine + pass does (``_dataset_from_frame``) and computes the household sum of + ``adjusted_gross_income``. That is the value R2's SOI materializer stores + in the state AGI row: it counts every tax unit, filer or not (the + engine-tier test compares the two). +- The engine counts only the positive income sources of a tax unit's head + and spouse (``irs_gross_income``), and only an adult can be a head or a + spouse. A household whose income is all on dependents, or on a tax unit + without an adult, has an AGI of 0 unless a deduction makes it negative. +- R2's take-up stages fill some ``NEVER_DEFAULT_FILLED`` columns on the ACS + rows before its fill step. The check holds back such a column while it is + null; the AGI does not read it. A null in one that the AGI reads is + refused, as R2 refuses it. - With ``--puma-ladder`` it applies R2's own minimum-support moves (``plan_minimum_support`` with ``--county-min-support``, default R2's 3) and takes the county list from the ladder, as R2 does. -- A county is **at risk** when it has households but none can carry a - nonzero AGI. The check is conservative: a household whose only income is - Social Security counts as zero, so a listed county may still pass. - Return-count rows count every tax unit, so they are never empty. +- A county is **at risk** when it has households but none with a nonzero AGI + as R2 stores it (float32). Return-count rows count every tax unit, so they + are never empty. + +The check needs memory for the full staging frame, as R2's materialize stage +does, and runs the engine for the AGI alone (minutes, not R2's full pass). Exit status 0: no county at risk. Exit status 2: at least one county at risk; the JSON report (``--out``) lists them. Each needs a ruling before R2 @@ -42,20 +50,24 @@ --county-column county_fips_2023 \\ --puma-ladder build/us/us_puma_ladder_2020.npz \\ --out /county_agi_support.json + +``--staging-summary`` defaults to the H5 path with ``.summary.json``, as in +R2. """ # No ``from __future__ import annotations``: test loaders run this file # without registering it in ``sys.modules``. import argparse +import gc +import importlib.util import json import sys import time from collections import defaultdict -from collections.abc import Mapping, Sequence +from collections.abc import Collection, Mapping, Sequence from pathlib import Path from typing import Any -import h5py import numpy as np import pandas as pd @@ -65,212 +77,191 @@ import us_acs_local_county_surface as county_surface # noqa: E402 -from microcosm.frame import read_frame_table # noqa: E402 +from microcosm.frame import Frame # noqa: E402 TOOL = "tools/check_us_acs_county_agi_support.py" ISSUE = "microcosm#922" -#: The engine variable whose input leaves are the AGI income columns. -GROSS_INCOME_ROOT = "irs_gross_income" -#: Social Security enters gross income only through its taxable share, which -#: is 0 for a household without enough other income. -SOCIAL_SECURITY_LEAVES = frozenset( - { - "social_security_dependents", - "social_security_disability", - "social_security_retirement", - "social_security_survivors", - } -) -#: Money leaves of the ``irs_gross_income`` closure that are deductions, -#: expenses, contributions or tax-exempt amounts: none makes gross income -#: nonzero on its own. -NOT_INCOME_LEAVES = frozenset( - { - "alimony_expense", - "domestic_production_ald", - "early_withdrawal_penalty", - "educator_expense", - "health_insurance_premiums", - "health_savings_account_ald", - "health_savings_account_payroll_contributions", - "pre_tax_health_insurance_premiums", - "qualified_adoption_assistance_expense", - "qualified_tuition_expenses", - "roth_401k_contributions_desired", - "roth_403b_contributions_desired", - "roth_ira_contributions_desired", - "self_employed_pension_contributions_desired", - "student_loan_interest", - "tax_exempt_interest_income", - "traditional_401k_contributions_desired", - "traditional_403b_contributions_desired", - "traditional_ira_contributions_desired", - "us_bonds_for_higher_ed", - } -) +#: The engine variable whose household sum R2's state SOI AGI row stores. +AGI_VARIABLE = "adjusted_gross_income" EXIT_AT_RISK = 2 -_ROW_CHUNK = 250_000 +#: Households per engine chunk; the AGI closure alone is light. +DEFAULT_HH_CHUNK = 100_000 +_RELEASE_TOOL = _TOOLS / "build_us_acs_local_release.py" + + +def _release_tool(): + """R2's module, for its loader, projection, fill and constants.""" + + spec = importlib.util.spec_from_file_location( + "build_us_acs_local_release_for_agi_check", _RELEASE_TOOL + ) + module = importlib.util.module_from_spec(spec) + assert spec.loader is not None + sys.modules[spec.name] = module + spec.loader.exec_module(module) + return module -def agi_income_columns(index: Any) -> dict[str, Any]: - """The AGI income columns by entity, from the engine's static index. +def agi_engine_inputs(index: Any) -> frozenset[str]: + """The engine inputs ``adjusted_gross_income`` can read (static closure). ``index`` is a ``PolicyEngineUSVariableMetadataIndex`` (or a stand-in - with ``variable_dependency_closure``, ``variable_metadata`` and - ``variable_unit``). Returns the person and tax-unit columns, the leaves - left out and why, and the closure's engine version and digest. + with ``variable_dependency_closure``). """ - closure = index.variable_dependency_closure(GROSS_INCOME_ROOT) - columns: dict[str, list[str]] = defaultdict(list) - excluded: dict[str, str] = {} - for leaf in closure.input_leaves: - metadata = index.variable_metadata(leaf) - if metadata.dtype != "float" or index.variable_unit(leaf) != "currency-USD": - continue - if leaf in SOCIAL_SECURITY_LEAVES: - excluded[leaf] = "social_security_taxable_share_only" - elif leaf in NOT_INCOME_LEAVES: - excluded[leaf] = "deduction_expense_or_contribution" - else: - columns[metadata.entity].append(leaf) - unexpected = sorted(set(columns) - {"person", "tax_unit"}) - if unexpected: - raise ValueError( - f"{GROSS_INCOME_ROOT} money leaves on entities {unexpected}; the " - "check reads person and tax-unit columns only." - ) - return { - "root": GROSS_INCOME_ROOT, - "engine_version": closure.engine_version, - "closure_sha256": closure.sha256, - "person": sorted(columns.get("person", [])), - "tax_unit": sorted(columns.get("tax_unit", [])), - "excluded": dict(sorted(excluded.items())), - } - + return frozenset(index.variable_dependency_closure(AGI_VARIABLE).input_leaves) -def read_columns(path: Path, key: str, columns: Sequence[str]) -> pd.DataFrame: - """Read only ``columns`` (those present) of one pandas H5 table. - A table-format table is read with ``select``. A fixed-format table's - numeric blocks are streamed in row chunks, so memory holds only the - requested columns; a requested column in an object block is read through - the shared frame-table reader instead. +def hold_back_null_runtime_columns( + frame: Frame, + *, + never_default_filled: Collection[tuple[str, str]], + agi_inputs: Collection[str], +) -> tuple[Frame, dict[str, list[str]]]: + """Drop the null never-default columns the AGI does not read. + + R2's take-up stages fill such columns on the ACS rows before its fill + step, and its fill step refuses any null left in one. For the AGI alone + a column outside the AGI's inputs does not matter, so the check holds it + back. A null in a never-default column that the AGI reads is refused: + R2 refuses it too. """ - with pd.HDFStore(path, mode="r") as store: - if store.get_storer(key).is_table: - names = set(store.select(key, start=0, stop=0).columns) - present = list(dict.fromkeys(c for c in columns if c in names)) - return store.select(key, columns=present) - wanted = list(dict.fromkeys(columns)) - result: dict[str, np.ndarray] = {} - slow: list[str] = [] - with h5py.File(path, "r") as handle: - group = handle[key] - names = [_text(name) for name in group["axis0"][:]] - rows = int(group["axis1"].shape[0]) - for block in range(int(group.attrs["nblocks"])): - items = [_text(name) for name in group[f"block{block}_items"][:]] - values = group[f"block{block}_values"] - hits = [ - (position, item) - for position, item in enumerate(items) - if item in wanted - ] - if not hits: - continue - if values.dtype == object or values.ndim != 2: - slow.extend(item for _position, item in hits) - continue - parts: dict[str, list[np.ndarray]] = {item: [] for _p, item in hits} - for start in range(0, rows, _ROW_CHUNK): - chunk = values[start : start + _ROW_CHUNK] - for position, item in hits: - parts[item].append(np.asarray(chunk[:, position])) - for item, chunks in parts.items(): - result[item] = np.concatenate(chunks) if chunks else np.empty(0) - del names - if slow: - with pd.HDFStore(path, mode="r") as store: - table = read_frame_table(store, key) - for column in slow: - result[column] = table[column].to_numpy() - del table - return pd.DataFrame({c: result[c] for c in wanted if c in result}) - - -def _text(value: object) -> str: - return value.decode("utf-8") if isinstance(value, bytes) else str(value) - - -def household_income_flags( - households: pd.DataFrame, - person: pd.DataFrame, - tax_unit: pd.DataFrame | None, + agi_inputs = frozenset(agi_inputs) + held: dict[str, list[str]] = {} + tables = {} + refused = [] + for entity in frame.entities: + table = frame.table(entity) + null = sorted( + column + for owner, column in never_default_filled + if owner == entity + and column in table.columns + and table[column].isna().any() + ) + refused.extend(f"{entity}.{column}" for column in null if column in agi_inputs) + if null: + held[entity] = null + table = table.drop(columns=null) + tables[entity] = table + if refused: + raise SystemExit( + f"Null never-default-filled column(s) that the AGI reads: {refused}. " + "R2's materialize stage refuses these nulls too (fill_reviewed_nulls)." + ) + if not held: + return frame, held + weights = {entity: frame.weights_for(entity) for entity in frame.weighted_entities} + held_frame = Frame( + tables, frame.schema, weights, frame.strata, mass_log=frame.mass_log + ) + return held_frame, held + + +def household_agi( + frame: Frame, + summary_path: Path, *, - person_columns: Sequence[str], - tax_unit_columns: Sequence[str] = (), -) -> np.ndarray: - """Per household (in ``households`` order): can it carry a nonzero AGI? - - True when any of its persons, or any tax unit one of its persons belongs - to, has a nonzero, non-null value in an AGI income column. A null cell - counts as 0, the engine default R2 fills. + release: Any, + period: int | None = None, + hh_chunk: int = DEFAULT_HH_CHUNK, +) -> tuple[np.ndarray, dict[str, Any]]: + """Each household's AGI as R2's SOI materializer stores it. + + Returns the household sum of ``adjusted_gross_income`` in the order of + ``frame``'s household table, and a JSON-ready receipt. ``release`` is + R2's module (``_release_tool()``). """ - household_ids = households["household_id"].to_numpy() - position = pd.Index(household_ids) - if not position.is_unique: + import build_us_fiscal_refresh_release as fiscal + from policyengine_us import Microsimulation + + from microcosm.frame.adapters.policyengine_us import ( + PolicyEngineUSVariableMetadataIndex, + ) + + period = release.PERIOD if period is None else int(period) + projected, formula_owned = release.project_input_only(frame, period=period) + projected, held = hold_back_null_runtime_columns( + projected, + never_default_filled=release.NEVER_DEFAULT_FILLED, + agi_inputs=agi_engine_inputs(PolicyEngineUSVariableMetadataIndex()), + ) + fills, drift = release.fill_reviewed_nulls( + projected, summary_path, manifest_path=None, period=period + ) + household_ids = projected.table("household")["household_id"].to_numpy() + n_households = len(household_ids) + positions = pd.Index(household_ids) + if not positions.is_unique: raise ValueError("Household ids must be unique.") - person_household = person["person_household_id"].to_numpy() - person_rows = position.get_indexer(person_household) - if (person_rows < 0).any(): + person_position = positions.get_indexer( + projected.table("person")["person_household_id"].to_numpy() + ) + if (person_position < 0).any(): raise ValueError("Persons name households the household table lacks.") - person_income = np.zeros(len(person), dtype=bool) - for column in person_columns: - if column in person.columns: - values = pd.to_numeric(person[column], errors="coerce").to_numpy(float) - person_income |= np.nan_to_num(values, nan=0.0) != 0.0 - flags = np.zeros(len(households), dtype=bool) - np.logical_or.at(flags, person_rows, person_income) - present = [ - column - for column in tax_unit_columns - if tax_unit is not None and column in tax_unit.columns - ] - if present: - unit_income = np.zeros(len(tax_unit), dtype=bool) - for column in present: - values = pd.to_numeric(tax_unit[column], errors="coerce").to_numpy(float) - unit_income |= np.nan_to_num(values, nan=0.0) != 0.0 - units = pd.Index(tax_unit["tax_unit_id"].to_numpy()) - person_units = units.get_indexer(person["person_tax_unit_id"].to_numpy()) - if (person_units < 0).any(): - raise ValueError("Persons name tax units the tax-unit table lacks.") - np.logical_or.at(flags, person_rows, unit_income[person_units]) - return flags + if n_households > hh_chunk: + # A chunk keeps every group its persons reference, so a group across + # two chunks would be simulated twice, each time in part. + fiscal._assert_group_entities_nest_in_households(projected) + agi = np.zeros(n_households, dtype=np.float64) + chunks = 0 + for low in range(0, n_households, hh_chunk): + high = min(low + hh_chunk, n_households) + chunk = projected.select((person_position >= low) & (person_position < high)) + simulation = Microsimulation( + dataset=fiscal._dataset_from_frame( + chunk, assert_no_formula_owned_columns=False, period_only=True + ) + ) + got = np.asarray(simulation.calculate("household_id", period).values) + if not np.array_equal(got, household_ids[low:high]): + raise RuntimeError( + f"Engine chunk {chunks} does not carry its households in frame " + "order; refusing to place its AGI." + ) + agi[low:high] = np.asarray( + simulation.calculate(AGI_VARIABLE, period, map_to="household").values, + dtype=np.float64, + ) + chunks += 1 + del simulation, chunk + gc.collect() + return agi, { + "variable": AGI_VARIABLE, + "aggregation": "household sum over tax units", + "period": period, + "engine_version": release._installed_engine_version(), + "households_per_chunk": int(hh_chunk), + "chunks": chunks, + "formula_owned_columns_held_back": sum(len(c) for c in formula_owned.values()), + "null_runtime_columns_held_back": held, + "reviewed_fill_columns": len(fills), + "reviewed_fill_count_drift": len(drift), + } def county_agi_report( households: pd.DataFrame, - income: np.ndarray, + nonzero_agi: np.ndarray, *, county_column: str, county_populations: Mapping[int, float] | None = None, ) -> dict[str, Any]: """Per-county household counts and the counties at risk. - ``county_populations`` (the ladder's, as R2 uses) sets the county list; - without it the list is the counties the households name. + ``nonzero_agi`` flags the households (in ``households`` order) whose AGI + R2 would store as nonzero; the ``households_with_agi_income`` keys count + them. ``county_populations`` (the ladder's, as R2 uses) sets the county + list; without it the list is the counties the households name. """ codes = county_surface.county_codes(households, county_column=county_column) support = county_surface.support_universe(households) totals, supporting, with_income = (defaultdict(int) for _ in range(3)) for code, supports, earns in zip( - codes.tolist(), support.tolist(), income.tolist(), strict=True + codes.tolist(), support.tolist(), np.asarray(nonzero_agi).tolist(), strict=True ): totals[code] += 1 supporting[code] += int(supports) @@ -306,7 +297,7 @@ def county_agi_report( "county_column": county_column, "counties": len(counties), "households": int(len(households)), - "households_with_agi_income": int(income.sum()), + "households_with_agi_income": int(np.asarray(nonzero_agi).sum()), "at_risk": at_risk, "at_risk_detail": {code: rows[code] for code in at_risk}, "no_household": no_household, @@ -320,12 +311,21 @@ def _parse_args(argv: Sequence[str] | None = None) -> argparse.Namespace: parser = argparse.ArgumentParser( description=( "List counties whose county SOI AGI row R2 would build empty: " - "counties with households but none that can carry a nonzero AGI." + "counties with households but none with a nonzero AGI, computed " + "with R2's own fill and engine path." ) ) parser.add_argument( "--h5", required=True, type=Path, help="Staging H5 (R1 output)." ) + parser.add_argument( + "--staging-summary", + type=Path, + help=( + "R1's staging summary, for the reviewed-null fills (default: the " + "H5 path with .summary.json, as in R2)." + ), + ) parser.add_argument( "--county-column", default=county_surface.COUNTY_COLUMN_2023, @@ -349,6 +349,12 @@ def _parse_args(argv: Sequence[str] | None = None) -> argparse.Namespace: f"{county_surface.DEFAULT_COUNTY_MIN_SUPPORT}); used only with --puma-ladder." ), ) + parser.add_argument( + "--hh-chunk", + type=int, + default=DEFAULT_HH_CHUNK, + help=f"Households per engine chunk (default {DEFAULT_HH_CHUNK:,}).", + ) parser.add_argument("--out", type=Path, help="JSON report path.") return parser.parse_args(argv) @@ -356,38 +362,22 @@ def _parse_args(argv: Sequence[str] | None = None) -> argparse.Namespace: def main(argv: Sequence[str] | None = None) -> int: args = _parse_args(argv) started = time.time() - from microcosm.frame.adapters.policyengine_us import ( - PolicyEngineUSVariableMetadataIndex, - ) - - sources = agi_income_columns(PolicyEngineUSVariableMetadataIndex()) - with pd.HDFStore(args.h5, mode="r") as store: - households = read_frame_table(store, "household") - person = read_columns( - args.h5, - "person", - ["person_household_id", "person_tax_unit_id", *sources["person"]], - ) - tax_unit = ( - read_columns(args.h5, "tax_unit", ["tax_unit_id", *sources["tax_unit"]]) - if sources["tax_unit"] - else None - ) - present_person = [ - column for column in sources["person"] if column in person.columns - ] - present_unit = [ - column - for column in sources["tax_unit"] - if tax_unit is not None and column in tax_unit.columns - ] - income = household_income_flags( - households, - person, - tax_unit, - person_columns=present_person, - tax_unit_columns=present_unit, + summary_path = args.staging_summary or args.h5.with_suffix(".summary.json") + if not summary_path.exists(): + raise SystemExit( + f"Staging summary not found at {summary_path}; the reviewed-null " + "fills need its reviewed_engine_input_nulls register." + ) + release = _release_tool() + frame = release._load_staging_frame(args.h5) + households = frame.table("household") + agi, engine = household_agi( + frame, summary_path, release=release, hh_chunk=args.hh_chunk ) + del frame + gc.collect() + # R2 stores the household measures as float32 and keeps only nonzeros. + nonzero = agi.astype(np.float32) != 0 populations = None support = None if args.puma_ladder is not None: @@ -419,7 +409,7 @@ def main(argv: Sequence[str] | None = None) -> int: ) report = county_agi_report( households, - income, + nonzero, county_column=args.county_column, county_populations=populations, ) @@ -428,11 +418,8 @@ def main(argv: Sequence[str] | None = None) -> int: "tool": TOOL, "issue": ISSUE, "h5": str(args.h5), - "agi_income_columns": { - **sources, - "person_present": present_person, - "tax_unit_present": present_unit, - }, + "staging_summary": str(summary_path), + "agi_engine": engine, "minimum_support": ( None if support is None @@ -456,6 +443,7 @@ def main(argv: Sequence[str] | None = None) -> int: "county_column", "counties", "households", + "households_with_agi_income", "at_risk", "at_risk_detail", "no_household", From f96ff8e1b0b4eb429518003680e6f68f1c212422 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mar=C3=ADa=20Juaristi?= <127882282+juaristi22@users.noreply.github.com> Date: Tue, 17 Nov 2026 14:30:57 +0000 Subject: [PATCH 11/31] Mark the drop flag and the donor allowance as proof-of-concept only MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit María ruled that tonight's County Files proof of concept passes --county-drop-empty-soi-rows on every run (#1647 comment 6950739270), and asked that the code say clearly that this is a temporary setup. The help text of --county-drop-empty-soi-rows and --allow-default-donor-column now says: temporary for the County Files proof of concept (#1647); do not use for the final County Files build. There every county must be supported well: a county whose AGI row would be empty needs a real fix (more household support, or a declared cell with its own ruling), not a dropped target, and the donor is a new national build. The county rung doc now describes the drop flag with the same note, and R1's module docstring, the agent guide and both changelog fragments carry it too. Help text and docs only; no logic changes. Part of #922. Co-Authored-By: Claude Opus 5.5 --- ...us-acs-county-drop-empty-soi-rows-922.added.md | 2 +- ...taging-allow-default-donor-column-922.added.md | 2 +- docs/agent-guide.md | 4 +++- docs/us-acs-local-county-rung.md | 15 +++++++++++++++ tools/_legacy/build_us_acs_multispine_base.py | 9 +++++++-- tools/us_acs_local_county_surface.py | 6 +++++- 6 files changed, 32 insertions(+), 6 deletions(-) diff --git a/changelog.d/us-acs-county-drop-empty-soi-rows-922.added.md b/changelog.d/us-acs-county-drop-empty-soi-rows-922.added.md index 9420d127ce..de31b223bc 100644 --- a/changelog.d/us-acs-county-drop-empty-soi-rows-922.added.md +++ b/changelog.d/us-acs-county-drop-empty-soi-rows-922.added.md @@ -1 +1 @@ -The ACS local release takes `--county-drop-empty-soi-rows` (microcosm#922). With it, a county IRS SOI row that is empty although the county has households (every household's measure, for example AGI, is 0, and the state row stores no zero) is dropped with a receipt in `county_surface.json` (`zero_measure_soi_rows_dropped`), the run identity and the reliability report, instead of refusing the run after the engine pass. A county without households is refused as before. The flag is off by default, and passing it is a reviewed decision; the refresh recipe repeats it. +The ACS local release takes `--county-drop-empty-soi-rows` (microcosm#922). With it, a county IRS SOI row that is empty although the county has households (every household's measure, for example AGI, is 0, and the state row stores no zero) is dropped with a receipt in `county_surface.json` (`zero_measure_soi_rows_dropped`), the run identity and the reliability report, instead of refusing the run after the engine pass. A county without households is refused as before. The flag is off by default, and passing it is a reviewed decision; the refresh recipe repeats it. It is temporary for the County Files proof of concept (microcosm#1647): do not use it for the final County Files build, where a county whose row would be empty needs a real fix (more household support, or a declared cell with its own ruling), not a dropped target. diff --git a/changelog.d/us-acs-staging-allow-default-donor-column-922.added.md b/changelog.d/us-acs-staging-allow-default-donor-column-922.added.md index 3da47c7eb3..bb5e9b3fba 100644 --- a/changelog.d/us-acs-staging-allow-default-donor-column-922.added.md +++ b/changelog.d/us-acs-staging-allow-default-donor-column-922.added.md @@ -1 +1 @@ -The legacy ACS staging builder (`tools/_legacy/build_us_acs_multispine_base.py`) takes `--allow-default-donor-column COLUMN=REASON` (repeatable) for the County Files proof of concept's patched donor (microcosm#922). The dense-donor coverage gate then accepts that transfer-consumed column although every donor value equals the engine default; it still refuses an absent, unknown or not transfer-consumed column, and an allowance for a column with donor signal. The staging summary records each allowance and its reason (`allowed_default_donor_columns`, `orchestration.allow_default_donor_columns`) and adds the reviewed limitation `allowed_default_valued_donor_columns`, which the release carries forward. Modal staging plans never pass the flag. Without the flag, the gate, the outputs and the summary are unchanged. +The legacy ACS staging builder (`tools/_legacy/build_us_acs_multispine_base.py`) takes `--allow-default-donor-column COLUMN=REASON` (repeatable) for the County Files proof of concept's patched donor (microcosm#922). The dense-donor coverage gate then accepts that transfer-consumed column although every donor value equals the engine default; it still refuses an absent, unknown or not transfer-consumed column, and an allowance for a column with donor signal. The staging summary records each allowance and its reason (`allowed_default_donor_columns`, `orchestration.allow_default_donor_columns`) and adds the reviewed limitation `allowed_default_valued_donor_columns`, which the release carries forward. Modal staging plans never pass the flag. Without the flag, the gate, the outputs and the summary are unchanged. The flag is temporary for the County Files proof of concept (microcosm#1647): do not use it for the final County Files build, whose donor is a new national build. diff --git a/docs/agent-guide.md b/docs/agent-guide.md index 97d8db0bdd..4b1fdc9662 100644 --- a/docs/agent-guide.md +++ b/docs/agent-guide.md @@ -549,7 +549,9 @@ build-folder release manifest for the copy, for `--donor-release-manifest`), and the staging builder's `--allow-default-donor-column COLUMN=REASON` accepts named all-default donor columns and records each one in the staging summary. Neither changes a -default. +default. Both are temporary for the County Files proof of concept +(microcosm#1647): do not use them for the final County Files build, whose +donor is a new national build. US household ladders carry both `county_fips` (2020 counties for the locked policyengine-us rules) and `county_fips_2023` (3,144 county-equivalents for calibration, including Connecticut's nine planning regions). The latter is diff --git a/docs/us-acs-local-county-rung.md b/docs/us-acs-local-county-rung.md index 99c0dcd94f..64000293c0 100644 --- a/docs/us-acs-local-county-rung.md +++ b/docs/us-acs-local-county-rung.md @@ -105,6 +105,21 @@ are also reported and refused outside that smoke exception. The exception does not excuse missing source facts or mismatched county boundaries, and development samples cannot be packaged as releases. +`--county-drop-empty-soi-rows` (off by default) drops, instead of refusing, a +county IRS SOI row that is empty although the county has households: every +household's measure is 0 (for example AGI), and the state row stores no zero. +Each dropped row is recorded in `county_surface.json` +(`zero_measure_soi_rows_dropped`), the run identity and the reliability report, +and the refresh recipe repeats the flag. A county with no household is refused +either way. `tools/check_us_acs_county_agi_support.py` lists, before R2, the +counties whose AGI row would be empty. + +**Temporary for the County Files proof of concept (microcosm#1647). Do not use +for the final County Files build.** There every county must be supported well: +a county whose AGI row would be empty needs a real fix, for example more +household support (minimum support that also covers counties whose SOI rows +would be empty) or a declared cell with its own ruling, not a dropped target. + Calibration writes schema-3 `county_reliability.json` and a flat `county_reliability.csv` next to its calibration outputs, and packaging publishes both (the CSV is refused unless it is the flattening of the bound diff --git a/tools/_legacy/build_us_acs_multispine_base.py b/tools/_legacy/build_us_acs_multispine_base.py index 5609e48c4e..0d91c18e0c 100644 --- a/tools/_legacy/build_us_acs_multispine_base.py +++ b/tools/_legacy/build_us_acs_multispine_base.py @@ -25,7 +25,10 @@ allowance and its reason (``allowed_default_donor_columns``, ``orchestration.allow_default_donor_columns``) and a reviewed limitation. It exists for the County Files proof of concept's patched donor (microcosm#922); -without it the gate, the outputs and the summary are unchanged. +without it the gate, the outputs and the summary are unchanged. Temporary for +the County Files proof of concept (microcosm#1647). Do not use for the final +County Files build: its donor is a new national build that carries these +columns. Telemetry: after parsing its arguments the builder starts the emitter (``microcosm.build.program_telemetry``, pipeline ``us_acs_multispine_staging``), @@ -349,7 +352,9 @@ def _parse_args(argv: list[str] | None = None) -> argparse.Namespace: "none). Only that failure is skipped: an absent, unknown or not " "transfer-consumed column is still refused, and so is an allowance " "for a column with donor signal. Each allowance and its reason is " - "recorded in the summary (microcosm#922)." + "recorded in the summary (microcosm#922). Temporary for the County " + "Files proof of concept (microcosm#1647). Do not use for the final " + "County Files build." ), ) return parser.parse_args(argv) diff --git a/tools/us_acs_local_county_surface.py b/tools/us_acs_local_county_surface.py index d230aa70f5..7791d5ea26 100644 --- a/tools/us_acs_local_county_surface.py +++ b/tools/us_acs_local_county_surface.py @@ -2452,7 +2452,11 @@ def add_arguments(parser): "and the state row stores no zero. Without the flag such a row " "refuses the run after the engine pass. A county with no household " "is refused either way. Off by default; passing it is a reviewed " - "decision (microcosm#922)." + "decision (microcosm#922). Temporary for the County Files proof " + "of concept (microcosm#1647). Do not use for the final County " + "Files build: there a county whose row would be empty needs a " + "real fix (more household support or a declared cell with its " + "own ruling), not a dropped target." ), ) From 65b2155c0409d6a7f3734defa32791a9acc60f52 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mar=C3=ADa=20Juaristi?= <127882282+juaristi22@users.noreply.github.com> Date: Tue, 17 Nov 2026 14:35:02 +0000 Subject: [PATCH 12/31] Point the proof-of-concept notes at the removal issue, #1661 The removal of the County Files proof-of-concept setup now has its own tracking issue, #1661, a sub-issue of #922. Each note from the last commit now says "removal tracked in microcosm#1661": the help text of --county-drop-empty-soi-rows and --allow-default-donor-column, R1's module docstring, the agent guide, the county rung doc and both changelog fragments. This PR does not finish #1661. Help text and docs only; no logic changes. Part of #922. Co-Authored-By: Claude Opus 5.5 --- .../us-acs-county-drop-empty-soi-rows-922.added.md | 2 +- ...acs-staging-allow-default-donor-column-922.added.md | 2 +- docs/agent-guide.md | 4 ++-- docs/us-acs-local-county-rung.md | 5 +++-- tools/_legacy/build_us_acs_multispine_base.py | 10 +++++----- tools/us_acs_local_county_surface.py | 5 +++-- 6 files changed, 15 insertions(+), 13 deletions(-) diff --git a/changelog.d/us-acs-county-drop-empty-soi-rows-922.added.md b/changelog.d/us-acs-county-drop-empty-soi-rows-922.added.md index de31b223bc..9c427c99d2 100644 --- a/changelog.d/us-acs-county-drop-empty-soi-rows-922.added.md +++ b/changelog.d/us-acs-county-drop-empty-soi-rows-922.added.md @@ -1 +1 @@ -The ACS local release takes `--county-drop-empty-soi-rows` (microcosm#922). With it, a county IRS SOI row that is empty although the county has households (every household's measure, for example AGI, is 0, and the state row stores no zero) is dropped with a receipt in `county_surface.json` (`zero_measure_soi_rows_dropped`), the run identity and the reliability report, instead of refusing the run after the engine pass. A county without households is refused as before. The flag is off by default, and passing it is a reviewed decision; the refresh recipe repeats it. It is temporary for the County Files proof of concept (microcosm#1647): do not use it for the final County Files build, where a county whose row would be empty needs a real fix (more household support, or a declared cell with its own ruling), not a dropped target. +The ACS local release takes `--county-drop-empty-soi-rows` (microcosm#922). With it, a county IRS SOI row that is empty although the county has households (every household's measure, for example AGI, is 0, and the state row stores no zero) is dropped with a receipt in `county_surface.json` (`zero_measure_soi_rows_dropped`), the run identity and the reliability report, instead of refusing the run after the engine pass. A county without households is refused as before. The flag is off by default, and passing it is a reviewed decision; the refresh recipe repeats it. It is temporary for the County Files proof of concept (microcosm#1647; removal tracked in microcosm#1661): do not use it for the final County Files build, where a county whose row would be empty needs a real fix (more household support, or a declared cell with its own ruling), not a dropped target. diff --git a/changelog.d/us-acs-staging-allow-default-donor-column-922.added.md b/changelog.d/us-acs-staging-allow-default-donor-column-922.added.md index bb5e9b3fba..08bd4a9bd6 100644 --- a/changelog.d/us-acs-staging-allow-default-donor-column-922.added.md +++ b/changelog.d/us-acs-staging-allow-default-donor-column-922.added.md @@ -1 +1 @@ -The legacy ACS staging builder (`tools/_legacy/build_us_acs_multispine_base.py`) takes `--allow-default-donor-column COLUMN=REASON` (repeatable) for the County Files proof of concept's patched donor (microcosm#922). The dense-donor coverage gate then accepts that transfer-consumed column although every donor value equals the engine default; it still refuses an absent, unknown or not transfer-consumed column, and an allowance for a column with donor signal. The staging summary records each allowance and its reason (`allowed_default_donor_columns`, `orchestration.allow_default_donor_columns`) and adds the reviewed limitation `allowed_default_valued_donor_columns`, which the release carries forward. Modal staging plans never pass the flag. Without the flag, the gate, the outputs and the summary are unchanged. The flag is temporary for the County Files proof of concept (microcosm#1647): do not use it for the final County Files build, whose donor is a new national build. +The legacy ACS staging builder (`tools/_legacy/build_us_acs_multispine_base.py`) takes `--allow-default-donor-column COLUMN=REASON` (repeatable) for the County Files proof of concept's patched donor (microcosm#922). The dense-donor coverage gate then accepts that transfer-consumed column although every donor value equals the engine default; it still refuses an absent, unknown or not transfer-consumed column, and an allowance for a column with donor signal. The staging summary records each allowance and its reason (`allowed_default_donor_columns`, `orchestration.allow_default_donor_columns`) and adds the reviewed limitation `allowed_default_valued_donor_columns`, which the release carries forward. Modal staging plans never pass the flag. Without the flag, the gate, the outputs and the summary are unchanged. The flag is temporary for the County Files proof of concept (microcosm#1647; removal tracked in microcosm#1661): do not use it for the final County Files build, whose donor is a new national build. diff --git a/docs/agent-guide.md b/docs/agent-guide.md index 4b1fdc9662..6f463f648a 100644 --- a/docs/agent-guide.md +++ b/docs/agent-guide.md @@ -550,8 +550,8 @@ and the staging builder's `--allow-default-donor-column COLUMN=REASON` accepts named all-default donor columns and records each one in the staging summary. Neither changes a default. Both are temporary for the County Files proof of concept -(microcosm#1647): do not use them for the final County Files build, whose -donor is a new national build. +(microcosm#1647; removal tracked in microcosm#1661): do not use them for the +final County Files build, whose donor is a new national build. US household ladders carry both `county_fips` (2020 counties for the locked policyengine-us rules) and `county_fips_2023` (3,144 county-equivalents for calibration, including Connecticut's nine planning regions). The latter is diff --git a/docs/us-acs-local-county-rung.md b/docs/us-acs-local-county-rung.md index 64000293c0..deba988f31 100644 --- a/docs/us-acs-local-county-rung.md +++ b/docs/us-acs-local-county-rung.md @@ -114,8 +114,9 @@ and the refresh recipe repeats the flag. A county with no household is refused either way. `tools/check_us_acs_county_agi_support.py` lists, before R2, the counties whose AGI row would be empty. -**Temporary for the County Files proof of concept (microcosm#1647). Do not use -for the final County Files build.** There every county must be supported well: +**Temporary for the County Files proof of concept (microcosm#1647); removal +tracked in microcosm#1661. Do not use for the final County Files build.** There +every county must be supported well: a county whose AGI row would be empty needs a real fix, for example more household support (minimum support that also covers counties whose SOI rows would be empty) or a declared cell with its own ruling, not a dropped target. diff --git a/tools/_legacy/build_us_acs_multispine_base.py b/tools/_legacy/build_us_acs_multispine_base.py index 0d91c18e0c..261646b563 100644 --- a/tools/_legacy/build_us_acs_multispine_base.py +++ b/tools/_legacy/build_us_acs_multispine_base.py @@ -26,9 +26,9 @@ ``orchestration.allow_default_donor_columns``) and a reviewed limitation. It exists for the County Files proof of concept's patched donor (microcosm#922); without it the gate, the outputs and the summary are unchanged. Temporary for -the County Files proof of concept (microcosm#1647). Do not use for the final -County Files build: its donor is a new national build that carries these -columns. +the County Files proof of concept (microcosm#1647); removal tracked in +microcosm#1661. Do not use for the final County Files build: its donor is a +new national build that carries these columns. Telemetry: after parsing its arguments the builder starts the emitter (``microcosm.build.program_telemetry``, pipeline ``us_acs_multispine_staging``), @@ -353,8 +353,8 @@ def _parse_args(argv: list[str] | None = None) -> argparse.Namespace: "transfer-consumed column is still refused, and so is an allowance " "for a column with donor signal. Each allowance and its reason is " "recorded in the summary (microcosm#922). Temporary for the County " - "Files proof of concept (microcosm#1647). Do not use for the final " - "County Files build." + "Files proof of concept (microcosm#1647); removal tracked in " + "microcosm#1661. Do not use for the final County Files build." ), ) return parser.parse_args(argv) diff --git a/tools/us_acs_local_county_surface.py b/tools/us_acs_local_county_surface.py index 7791d5ea26..6f4e903443 100644 --- a/tools/us_acs_local_county_surface.py +++ b/tools/us_acs_local_county_surface.py @@ -2453,8 +2453,9 @@ def add_arguments(parser): "refuses the run after the engine pass. A county with no household " "is refused either way. Off by default; passing it is a reviewed " "decision (microcosm#922). Temporary for the County Files proof " - "of concept (microcosm#1647). Do not use for the final County " - "Files build: there a county whose row would be empty needs a " + "of concept (microcosm#1647); removal tracked in microcosm#1661. " + "Do not use for the final County Files build: there a county " + "whose row would be empty needs a " "real fix (more household support or a declared cell with its " "own ruling), not a dropped target." ), From a5ca4df65dd82ab60e64f8b8276dda7f1c560e05 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mar=C3=ADa=20Juaristi?= <127882282+juaristi22@users.noreply.github.com> Date: Tue, 17 Nov 2026 17:22:47 +0000 Subject: [PATCH 13/31] Give the counties R2 always refuses their own exit status in the AGI check The zero-AGI pre-check set its exit status from at_risk alone. R2's check_support refuses a county outside the ladder and a ladder county without a household-universe record, with or without --county-drop-empty-soi-rows, in materialize after the staging load and the SSI/Medicaid pre-pass. With --puma-ladder the check now lists both (counties_outside_ladder, unsupported_counties) with R2's set rules, moves no household when a county is outside the ladder (as R2 does), and exits 3, which takes precedence over 2. The report records its exit status. Part of #922; review of #1660 (comment 6955224433). Co-Authored-By: Claude Opus 5.5 --- ...-acs-county-agi-support-check-922.added.md | 2 +- .../us/test_us_acs_county_agi_support.py | 143 +++++++++++++++++- tools/check_us_acs_county_agi_support.py | 141 ++++++++++++----- 3 files changed, 248 insertions(+), 38 deletions(-) diff --git a/changelog.d/us-acs-county-agi-support-check-922.added.md b/changelog.d/us-acs-county-agi-support-check-922.added.md index 208260516e..993fb9a9b2 100644 --- a/changelog.d/us-acs-county-agi-support-check-922.added.md +++ b/changelog.d/us-acs-county-agi-support-check-922.added.md @@ -1 +1 @@ -`tools/check_us_acs_county_agi_support.py` lists, before the ACS local release (R2) runs, the counties whose county IRS SOI AGI row R2 would build empty: counties with households but none with a nonzero AGI (microcosm#922; microcosm#1630 review, finding 1). The state AGI row stores no zero, so such a county makes `attach_surface` refuse the run after the materialize engine pass. The check computes the value R2 stores: it loads the staging frame and its summary as R2 does, holds back the formula-owned columns, fills the reviewed nulls with R2's own functions, and runs policyengine-us for the household sum of `adjusted_gross_income` in household chunks. That sum is the production SOI materializer's AGI measure (an engine-tier test compares them), so income held by a dependent, or by a tax unit without an adult, counts as the engine counts it: not at all. A null take-up flag that R2's own stages fill is held back, since the AGI does not read it; a null in a never-default column that the AGI reads is refused, as R2 refuses it. With `--puma-ladder` it applies R2's own minimum-support moves first. It exits 2 when a county is at risk. +`tools/check_us_acs_county_agi_support.py` lists, before the ACS local release (R2) runs, the counties whose county IRS SOI AGI row R2 would build empty: counties with households but none with a nonzero AGI (microcosm#922; microcosm#1630 review, finding 1). The state AGI row stores no zero, so such a county makes `attach_surface` refuse the run after the materialize engine pass. The check computes the value R2 stores: it loads the staging frame and its summary as R2 does, holds back the formula-owned columns, fills the reviewed nulls with R2's own functions, and runs policyengine-us for the household sum of `adjusted_gross_income` in household chunks. That sum is the production SOI materializer's AGI measure (an engine-tier test compares them), so income held by a dependent, or by a tax unit without an adult, counts as the engine counts it: not at all. A null take-up flag that R2's own stages fill is held back, since the AGI does not read it; a null in a never-default column that the AGI reads is refused, as R2 refuses it. With `--puma-ladder` it applies R2's own minimum-support moves first, and lists the counties that R2's `check_support` refuses with or without `--county-drop-empty-soi-rows`: a county outside the ladder, and a ladder county without a household-universe record after the moves (as R2 does, it moves no household when a county is outside the ladder). It exits 2 when a county is at risk, and 3 when R2 would refuse the run (3 takes precedence). diff --git a/packages/microcosm-build/tests/engine_free/us/test_us_acs_county_agi_support.py b/packages/microcosm-build/tests/engine_free/us/test_us_acs_county_agi_support.py index f78f6c62ff..0ed560c5f4 100644 --- a/packages/microcosm-build/tests/engine_free/us/test_us_acs_county_agi_support.py +++ b/packages/microcosm-build/tests/engine_free/us/test_us_acs_county_agi_support.py @@ -89,12 +89,104 @@ def test_report_lists_counties_with_households_but_no_nonzero_agi(check) -> None "supporting_households": 2, "households_with_agi_income": 0, } - # 1007 has ladder population but no household: minimum support's case. + # 1007 has ladder population but no household after the minimum-support + # moves (the report's input), so R2's check_support refuses it. assert report["no_household"] == ["01007"] + assert report["unsupported_counties"] == ["01007"] # A group-quarters record counts for AGI but not for support. assert report["by_county"]["01005"]["supporting_households"] == 1 assert report["fewer_than_min_support_with_agi_income"] == ["01001", "01005"] assert report["counties_outside_ladder"] == [] + assert check.exit_status(report) == check.EXIT_R2_REFUSES + + +def test_report_lists_the_counties_r2_refuses_whatever_the_drop_flag(check) -> None: + households = _frame().table("household").copy() + # 01005 keeps only its group-quarters record, and one household names + # 01009, a county outside the ladder. + households["county_fips_2023"] = [1001, 1001, 1003, 1009, 1003, 1005] + nonzero = np.ones(len(households), dtype=bool) + + report = check.county_agi_report( + households, + nonzero, + county_column="county_fips_2023", + county_populations={1001: 10.0, 1003: 5.0, 1005: 5.0}, + ) + + assert report["at_risk"] == [] + assert report["no_household"] == [] + assert report["counties_outside_ladder"] == ["01009"] + assert report["unsupported_counties"] == ["01005"] + assert check.exit_status(report) == check.EXIT_R2_REFUSES + # Without the ladder neither list is checked. + unladdered = check.county_agi_report( + households, nonzero, county_column="county_fips_2023" + ) + assert unladdered["counties_outside_ladder"] is None + assert unladdered["unsupported_counties"] is None + assert check.exit_status(unladdered) == 0 + + +def test_exit_status_3_takes_precedence_over_2(check) -> None: + at_risk = {"at_risk": ["01003"], "counties_outside_ladder": []} + assert check.exit_status({**at_risk, "unsupported_counties": []}) == 2 + assert check.exit_status({**at_risk, "unsupported_counties": ["01005"]}) == 3 + assert ( + check.exit_status( + { + **at_risk, + "counties_outside_ladder": ["01009"], + "unsupported_counties": [], + } + ) + == 3 + ) + assert check.exit_status({"at_risk": [], "unsupported_counties": None}) == 0 + + +def test_ladder_support_moves_no_household_when_a_county_is_outside_the_ladder( + check, monkeypatch: pytest.MonkeyPatch +) -> None: + import microcosm.build.us_runtime.puma_ladder as puma_ladder + + households = _frame().table("household") + surface = check.county_surface + planned = [] + monkeypatch.setattr(puma_ladder, "load_us_puma_ladder", lambda path: "ladder") + monkeypatch.setattr(surface, "county_puma_overlaps", lambda path, column: {}) + + def plan(households, populations, overlaps, *, county_column, per_county): + planned.append(sorted(populations)) + return [], {"rewritten_columns": [county_column], "moves": []} + + monkeypatch.setattr(surface, "plan_minimum_support", plan) + for populations, expected in ( + # 01005 is outside this ladder: R2 refuses the run before any move. + ({1001: 10.0, 1003: 5.0, 1007: 3.0}, []), + # Every county is in the ladder and 01007 has no household: R2 plans + # its moves. + ({1001: 10.0, 1003: 5.0, 1005: 5.0, 1007: 3.0}, [[1001, 1003, 1005, 1007]]), + ): + planned.clear() + monkeypatch.setattr( + surface, + "with_county_populations", + lambda ladder, known, geographies, *, county_column, _p=populations: { + "county": _p + }, + ) + + _moved, ladder_populations, support = check.ladder_support( + households, + Path("ladder.npz"), + county_column="county_fips_2023", + county_min_support=3, + ) + + assert ladder_populations == populations + assert planned == expected + assert (support is None) is (not expected) _NEVER_DEFAULT = frozenset( @@ -183,7 +275,10 @@ def agi(frame, summary_path, *, release, hh_chunk): report = json.loads(out.read_text()) assert status == check.EXIT_AT_RISK + assert report["exit_status"] == check.EXIT_AT_RISK assert report["at_risk"] == ["01003"] + # Without --puma-ladder, R2's support refusals are not checked. + assert report["unsupported_counties"] is None assert report["households_with_agi_income"] == 2 assert report["agi_engine"] == {"stub": True} assert report["minimum_support"] is None @@ -197,6 +292,52 @@ def healthy(frame, summary_path, *, release, hh_chunk): assert check.main(["--h5", str(staging), "--county-column", "county_fips"]) == 0 +def test_command_exits_3_when_r2_refuses_whatever_the_drop_flag( + check, tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + staging = tmp_path / "staging.h5" + staging.write_bytes(b"") + (tmp_path / "staging.summary.json").write_text("{}") + out = tmp_path / "report.json" + monkeypatch.setattr(check, "_release_tool", lambda: _stub_release(_frame())) + # 01003's households have an AGI of 0, so it is also at risk. + monkeypatch.setattr( + check, + "household_agi", + lambda frame, path, *, release, hh_chunk: ( + np.asarray([1.0, 1.0, 0.0, 0.0, 1.0, 1.0]), + {}, + ), + ) + calls = [] + + def ladder(households, path, *, county_column, county_min_support): + calls.append((path, county_column, county_min_support)) + # 01005 is not in this ladder. + return households, {1001: 10.0, 1003: 5.0}, None + + monkeypatch.setattr(check, "ladder_support", ladder) + ladder_path = tmp_path / "ladder.npz" + + status = check.main( + ["--h5", str(staging), "--puma-ladder", str(ladder_path), "--out", str(out)] + ) + + report = json.loads(out.read_text()) + assert status == check.EXIT_R2_REFUSES + assert report["exit_status"] == check.EXIT_R2_REFUSES + assert report["at_risk"] == ["01003"] + assert report["counties_outside_ladder"] == ["01005"] + assert report["unsupported_counties"] == [] + assert calls == [ + ( + ladder_path, + check.county_surface.COUNTY_COLUMN_2023, + check.county_surface.DEFAULT_COUNTY_MIN_SUPPORT, + ) + ] + + def test_an_agi_below_float32_resolution_is_stored_as_zero( check, tmp_path: Path, monkeypatch: pytest.MonkeyPatch ) -> None: diff --git a/tools/check_us_acs_county_agi_support.py b/tools/check_us_acs_county_agi_support.py index 03de9b0d15..022c0f7739 100644 --- a/tools/check_us_acs_county_agi_support.py +++ b/tools/check_us_acs_county_agi_support.py @@ -35,13 +35,25 @@ - A county is **at risk** when it has households but none with a nonzero AGI as R2 stores it (float32). Return-count rows count every tax unit, so they are never empty. +- R2's ``check_support`` (materialize, after the staging load and the + SSI/Medicaid pre-pass) refuses the run, with or without + ``--county-drop-empty-soi-rows``, when a household names a county outside + the ladder or a ladder county has no household-universe record after the + minimum-support moves. With ``--puma-ladder`` the check lists both + (``counties_outside_ladder``, ``unsupported_counties``) with R2's set + rules, and, as R2 does, moves no household when a county is outside the + ladder. The check needs memory for the full staging frame, as R2's materialize stage does, and runs the engine for the AGI alone (minutes, not R2's full pass). -Exit status 0: no county at risk. Exit status 2: at least one county at -risk; the JSON report (``--out``) lists them. Each needs a ruling before R2 -(drop the county's AGI row with a receipt, or give it a declared SOI cell). +Exit status 0: no county at risk and none that R2 refuses. Exit status 2: at +least one county at risk; the JSON report (``--out``) lists them. Each needs +a ruling before R2 (drop the county's AGI row with a receipt, or give it a +declared SOI cell). Exit status 3: R2 would refuse the run in materialize +whatever the drop flag (a county outside the ladder, or without a +household-universe record); fix the staging file or the ladder first. Status +3 takes precedence over 2 and needs ``--puma-ladder``. Usage:: @@ -84,6 +96,8 @@ #: The engine variable whose household sum R2's state SOI AGI row stores. AGI_VARIABLE = "adjusted_gross_income" EXIT_AT_RISK = 2 +#: R2's ``check_support`` refuses the run whatever the drop flag. +EXIT_R2_REFUSES = 3 #: Households per engine chunk; the AGI closure alone is light. DEFAULT_HH_CHUNK = 100_000 _RELEASE_TOOL = _TOOLS / "build_us_acs_local_release.py" @@ -249,12 +263,16 @@ def county_agi_report( county_column: str, county_populations: Mapping[int, float] | None = None, ) -> dict[str, Any]: - """Per-county household counts and the counties at risk. + """Per-county household counts, the counties at risk and R2's refusals. ``nonzero_agi`` flags the households (in ``households`` order) whose AGI R2 would store as nonzero; the ``households_with_agi_income`` keys count them. ``county_populations`` (the ladder's, as R2 uses) sets the county - list; without it the list is the counties the households name. + list; without it the list is the counties the households name, and + ``counties_outside_ladder`` and ``unsupported_counties`` are None (not + checked). With it, they are what R2's ``check_support`` refuses: counties + the households name that are not in the ladder, and ladder counties + without a household-universe record (``support_universe``). """ codes = county_surface.county_codes(households, county_column=county_column) @@ -268,10 +286,12 @@ def county_agi_report( with_income[code] += int(earns) if county_populations is None: counties = sorted(totals) + ladder = None else: counties = sorted( int(code) for code, value in county_populations.items() if float(value) > 0 ) + ladder = {int(code) for code in county_populations} at_risk, no_household, thin = [], [], [] rows = {} for code in counties: @@ -290,9 +310,12 @@ def county_agi_report( < county_surface.DEFAULT_COUNTY_MIN_SUPPORT ): thin.append(f"{code:05d}") - outside = ( - sorted(set(totals) - set(counties)) if county_populations is not None else [] - ) + # R2's check_support compares with every ladder county, whatever its + # population. + outside = unsupported = None + if ladder is not None: + outside = sorted(set(totals) - ladder) + unsupported = sorted(ladder - {code for code, n in supporting.items() if n}) return { "county_column": county_column, "counties": len(counties), @@ -302,7 +325,12 @@ def county_agi_report( "at_risk_detail": {code: rows[code] for code in at_risk}, "no_household": no_household, "fewer_than_min_support_with_agi_income": thin, - "counties_outside_ladder": [f"{code:05d}" for code in outside], + "counties_outside_ladder": ( + None if outside is None else [f"{code:05d}" for code in outside] + ), + "unsupported_counties": ( + None if unsupported is None else [f"{code:05d}" for code in unsupported] + ), "by_county": rows, } @@ -337,7 +365,8 @@ def _parse_args(argv: Sequence[str] | None = None) -> argparse.Namespace: type=Path, help=( "R2's PUMA ladder. With it, the check takes the county list from " - "the ladder and applies R2's minimum-support moves first." + "the ladder, applies R2's minimum-support moves first and lists " + "the counties R2 refuses (exit status 3)." ), ) parser.add_argument( @@ -359,6 +388,61 @@ def _parse_args(argv: Sequence[str] | None = None) -> argparse.Namespace: return parser.parse_args(argv) +def ladder_support( + households: pd.DataFrame, + ladder_path: Path, + *, + county_column: str, + county_min_support: int, +) -> tuple[pd.DataFrame, dict[int, float], dict[str, Any] | None]: + """R2's ladder county populations and minimum-support moves. + + Returns ``(households, county_populations, support)``: the households + after the moves, as ``check_support`` rewrites them, and the moves' + receipt (None when nothing was planned). As in R2, no household moves + when one names a county outside the ladder; R2 then refuses the run. + """ + + from microcosm.build.us_runtime.puma_ladder import load_us_puma_ladder + + ladder = load_us_puma_ladder(ladder_path) + populations = county_surface.with_county_populations( + ladder, {}, {"county": True}, county_column=county_column + )["county"] + codes = county_surface.county_codes(households, county_column=county_column) + outside = {int(code) for code in codes.tolist()} - { + int(code) for code in populations + } + needed = county_surface.unsupported_counties( + households, populations, county_column=county_column + ) + support = None + if county_min_support > 0 and needed and not outside: + overlaps = county_surface.county_puma_overlaps(ladder_path, county_column) + moves, support = county_surface.plan_minimum_support( + households, + populations, + overlaps, + county_column=county_column, + per_county=county_min_support, + ) + households = county_surface.apply_support_moves( + households, + moves, + county_column=county_column, + columns=support["rewritten_columns"], + ) + return households, populations, support + + +def exit_status(report: Mapping[str, Any]) -> int: + """3 when R2 refuses whatever the drop flag, else 2 when a county is at risk.""" + + if report.get("counties_outside_ladder") or report.get("unsupported_counties"): + return EXIT_R2_REFUSES + return EXIT_AT_RISK if report["at_risk"] else 0 + + def main(argv: Sequence[str] | None = None) -> int: args = _parse_args(argv) started = time.time() @@ -381,32 +465,12 @@ def main(argv: Sequence[str] | None = None) -> int: populations = None support = None if args.puma_ladder is not None: - from microcosm.build.us_runtime.puma_ladder import load_us_puma_ladder - - ladder = load_us_puma_ladder(args.puma_ladder) - populations = county_surface.with_county_populations( - ladder, {}, {"county": True}, county_column=args.county_column - )["county"] - needed = county_surface.unsupported_counties( - households, populations, county_column=args.county_column + households, populations, support = ladder_support( + households, + args.puma_ladder, + county_column=args.county_column, + county_min_support=args.county_min_support, ) - if args.county_min_support > 0 and needed: - overlaps = county_surface.county_puma_overlaps( - args.puma_ladder, args.county_column - ) - moves, support = county_surface.plan_minimum_support( - households, - populations, - overlaps, - county_column=args.county_column, - per_county=args.county_min_support, - ) - households = county_surface.apply_support_moves( - households, - moves, - county_column=args.county_column, - columns=support["rewritten_columns"], - ) report = county_agi_report( households, nonzero, @@ -433,6 +497,8 @@ def main(argv: Sequence[str] | None = None) -> int: "seconds": round(time.time() - started, 1), } ) + status = exit_status(report) + report["exit_status"] = status rendered = json.dumps(report, indent=2, sort_keys=True) + "\n" if args.out is not None: args.out.parent.mkdir(parents=True, exist_ok=True) @@ -448,11 +514,14 @@ def main(argv: Sequence[str] | None = None) -> int: "at_risk_detail", "no_household", "fewer_than_min_support_with_agi_income", + "counties_outside_ladder", + "unsupported_counties", + "exit_status", "seconds", ) } print(json.dumps(summary, indent=2, sort_keys=True)) - return EXIT_AT_RISK if report["at_risk"] else 0 + return status if __name__ == "__main__": From e49d5399772c78cf6dfe265b9c55a06c34140775 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mar=C3=ADa=20Juaristi?= <127882282+juaristi22@users.noreply.github.com> Date: Tue, 17 Nov 2026 17:28:55 +0000 Subject: [PATCH 14/31] Name each dropped SOI row in its county's reliability cell and CSV row With --county-drop-empty-soi-rows, calibrate grades a county without its dropped row, and only the reliability report's top-level unsupported_targets named it. Materialize now records each dropped row's county cell in the run identity (zero_measure_soi_rows_dropped; only a flagged run has the key), and the bound report names the row in every member county's cell and in a zero_measure_soi_rows_dropped column of county_reliability.csv. A run without the flag keeps its identity, report and CSV bytes. A flagged identity from older code that dropped rows but lacks their cells is refused (re-run materialize), never left unmarked. The flag's test now runs on through calibration_evidence, write_reports and package_reports. Part of #922; review of #1660 (comment 6955224433). Co-Authored-By: Claude Opus 5.5 --- ...cs-county-drop-empty-soi-rows-922.added.md | 2 +- docs/us-acs-local-county-rung.md | 13 +- .../us/test_us_acs_local_county_surface.py | 130 +++++++++++++++++- tools/us_acs_local_county_surface.py | 66 ++++++++- 4 files changed, 199 insertions(+), 12 deletions(-) diff --git a/changelog.d/us-acs-county-drop-empty-soi-rows-922.added.md b/changelog.d/us-acs-county-drop-empty-soi-rows-922.added.md index 9c427c99d2..f69539dc51 100644 --- a/changelog.d/us-acs-county-drop-empty-soi-rows-922.added.md +++ b/changelog.d/us-acs-county-drop-empty-soi-rows-922.added.md @@ -1 +1 @@ -The ACS local release takes `--county-drop-empty-soi-rows` (microcosm#922). With it, a county IRS SOI row that is empty although the county has households (every household's measure, for example AGI, is 0, and the state row stores no zero) is dropped with a receipt in `county_surface.json` (`zero_measure_soi_rows_dropped`), the run identity and the reliability report, instead of refusing the run after the engine pass. A county without households is refused as before. The flag is off by default, and passing it is a reviewed decision; the refresh recipe repeats it. It is temporary for the County Files proof of concept (microcosm#1647; removal tracked in microcosm#1661): do not use it for the final County Files build, where a county whose row would be empty needs a real fix (more household support, or a declared cell with its own ruling), not a dropped target. +The ACS local release takes `--county-drop-empty-soi-rows` (microcosm#922). With it, a county IRS SOI row that is empty although the county has households (every household's measure, for example AGI, is 0, and the state row stores no zero) is dropped with a receipt in `county_surface.json` (`zero_measure_soi_rows_dropped`), the run identity and the reliability report, instead of refusing the run after the engine pass. Calibration grades such a county without the row, so the reliability report names each dropped row in its county cells (every member of a combined cell) and in a `zero_measure_soi_rows_dropped` column of `county_reliability.csv`; only a run with the flag has that key and column. A county without households is refused as before. The flag is off by default, and passing it is a reviewed decision; the refresh recipe repeats it. It is temporary for the County Files proof of concept (microcosm#1647; removal tracked in microcosm#1661): do not use it for the final County Files build, where a county whose row would be empty needs a real fix (more household support, or a declared cell with its own ruling), not a dropped target. diff --git a/docs/us-acs-local-county-rung.md b/docs/us-acs-local-county-rung.md index deba988f31..15114e06f9 100644 --- a/docs/us-acs-local-county-rung.md +++ b/docs/us-acs-local-county-rung.md @@ -110,9 +110,16 @@ county IRS SOI row that is empty although the county has households: every household's measure is 0 (for example AGI), and the state row stores no zero. Each dropped row is recorded in `county_surface.json` (`zero_measure_soi_rows_dropped`), the run identity and the reliability report, -and the refresh recipe repeats the flag. A county with no household is refused -either way. `tools/check_us_acs_county_agi_support.py` lists, before R2, the -counties whose AGI row would be empty. +and the refresh recipe repeats the flag. Calibration grades such a county +without the row, so the reliability report also names each dropped row in its +county cells (`zero_measure_soi_rows_dropped`; a combined cell's row marks +every member county) and in a `zero_measure_soi_rows_dropped` column of +`county_reliability.csv`. Only a run with the flag has that key and column. A +county with no household is refused either way. +`tools/check_us_acs_county_agi_support.py` lists, before R2, the counties whose +AGI row would be empty (exit status 2), and exits 3 when R2 would refuse the run +whatever the flag: a county outside the ladder, or a ladder county without a +household-universe record after minimum support. **Temporary for the County Files proof of concept (microcosm#1647); removal tracked in microcosm#1661. Do not use for the final County Files build.** There diff --git a/packages/microcosm-build/tests/engine_free/us/test_us_acs_local_county_surface.py b/packages/microcosm-build/tests/engine_free/us/test_us_acs_local_county_surface.py index 946a8a280d..c10e552da9 100644 --- a/packages/microcosm-build/tests/engine_free/us/test_us_acs_local_county_surface.py +++ b/packages/microcosm-build/tests/engine_free/us/test_us_acs_local_county_surface.py @@ -2,9 +2,11 @@ from __future__ import annotations +import csv import dataclasses import hashlib import importlib.util +import io import json import math import shlex @@ -1135,9 +1137,13 @@ def test_county_hooks_materialize_a_fixture_and_preserve_configured_geography( written = json.loads((args.checkpoint_dir / "county_reliability.json").read_text()) assert written["county_column"] == "planning_region" assert written["counties"]["01001"]["distinct_source_households"] == 1 - assert (args.checkpoint_dir / "county_reliability.csv").read_text() == ( - county.reliability_csv(written) - ) + csv_text = (args.checkpoint_dir / "county_reliability.csv").read_text() + assert csv_text == county.reliability_csv(written) + # Without --county-drop-empty-soi-rows, no drop mark and no CSV column. + assert "county_drop_empty_soi_rows" not in identity + assert county.ZERO_MEASURE_SOI_ROWS_DROPPED not in written + assert county.ZERO_MEASURE_SOI_ROWS_DROPPED not in written["counties"]["01001"] + assert csv_text.splitlines()[0].split(",") == county.reliability_csv_columns() def _export_county_fixture(module, monkeypatch, run, out_h5, weights): @@ -1814,13 +1820,129 @@ def test_a_county_whose_households_all_have_zero_agi_refuses_or_drops_its_row( assert run.county.refresh_recipe("release", identity).endswith( " --county-drop-empty-soi-rows" ) - _loaded, _design, registry, _records, matrix = run.module.load_checkpoint_surface( + assert identity["zero_measure_soi_rows_dropped"] == [ + { + "target": agi_row, + "county_fips": "01003", + "cell_members": ["01003"], + "concept": "adjusted_gross_income", + } + ] + loaded, design, registry, records, matrix = run.module.load_checkpoint_surface( checkpoint, identity ) # The default fixture's 12 rows less the dropped AGI row. assert matrix.shape == (11, 3) assert agi_row not in {spec.name for spec in registry} + # Calibrate grades 01003 without its AGI row; the packaged report and its + # CSV name the row in 01003's cell (review of #1660). + for record in records: + if record.get("state_county_parent_target_name"): + record["role"] = "holdout" + evidence = run.module.calibration_evidence( + frame=loaded, + roles=records, + matrix=matrix, + design_weights=design, + weights=np.asarray([10.0, 75.0, 15.0]), + target_loss_cap=1.0, + checkpoint_dir=checkpoint, + identity=identity, + ) + assert agi_row not in {record["name"] for record in records} + summary = { + "county_reliability": evidence["county_reliability"], + "run_identity_sha256": hashlib.sha256( + json.dumps(identity, sort_keys=True, separators=(",", ":")).encode() + ).hexdigest(), + "weights_sha256": "fixture-weights", + } + run.county.write_reports(checkpoint, summary, identity=identity) + (checkpoint / "calibration_summary.json").write_text(json.dumps(summary)) + files = {} + packaged = run.county.package_reports(files, checkpoint, identity) + report = files["county_reliability.json"] + assert report["unsupported_targets"] == [agi_row] + assert ( + report["zero_measure_soi_rows_dropped"] + == (identity["zero_measure_soi_rows_dropped"]) + ) + cells = report["counties"] + assert cells["01003"]["zero_measure_soi_rows_dropped"] == [agi_row] + assert cells["01001"]["zero_measure_soi_rows_dropped"] == [] + # 01003 is still graded, from its other rows and validation families. + assert cells["01003"]["grade"] in {"A", "B", "C", "D"} + rows = { + row["county_fips"]: row + for row in csv.DictReader(io.StringIO(packaged["county_reliability.csv"])) + } + assert rows["01003"]["zero_measure_soi_rows_dropped"] == agi_row + assert rows["01001"]["zero_measure_soi_rows_dropped"] == "" + + +def test_the_reliability_report_marks_every_member_of_a_dropped_combined_cell( + tmp_path, +) -> None: + county = _county() + row = { + "target": "county_15009__soi_agi", + "county_fips": "15009", + "cell_members": ["15005", "15009"], + "concept": "adjusted_gross_income", + } + identity = { + "geographies": "state,county", + "county_column": "county_fips_2023", + "county_targets_dropped": [row["target"]], + "county_drop_empty_soi_rows": True, + "zero_measure_soi_rows_dropped": [row], + } + summary = { + "county_reliability": { + "schema_version": 3, + "counties": { + code: {"grade": "B", "status": "supported"} + for code in ("15001", "15005", "15009") + }, + }, + "run_identity_sha256": "stamp", + "weights_sha256": "weights", + } + + county.write_reports(tmp_path, summary, identity=identity) + + report = json.loads((tmp_path / "county_reliability.json").read_text()) + marks = { + code: cell["zero_measure_soi_rows_dropped"] + for code, cell in report["counties"].items() + } + assert marks == {"15001": [], "15005": [row["target"]], "15009": [row["target"]]} + rows = list( + csv.DictReader(io.StringIO((tmp_path / "county_reliability.csv").read_text())) + ) + assert [row_["zero_measure_soi_rows_dropped"] for row_ in rows] == [ + "", + row["target"], + row["target"], + ] + # A flagged identity from older code names dropped targets but not their + # cells: refused, never an unmarked report. + older = { + key: value + for key, value in identity.items() + if key != "zero_measure_soi_rows_dropped" + } + with pytest.raises(SystemExit, match="re-run --stage materialize"): + county.write_reports(tmp_path, summary, identity=older) + # With nothing dropped, the older identity needs no cells. + county.write_reports( + tmp_path, summary, identity={**older, "county_targets_dropped": []} + ) + report = json.loads((tmp_path / "county_reliability.json").read_text()) + assert report["zero_measure_soi_rows_dropped"] == [] + assert report["counties"]["15005"]["zero_measure_soi_rows_dropped"] == [] + def test_dropping_empty_soi_rows_never_drops_a_county_without_households() -> None: county = _county() diff --git a/tools/us_acs_local_county_surface.py b/tools/us_acs_local_county_surface.py index 6f4e903443..3458ef90af 100644 --- a/tools/us_acs_local_county_surface.py +++ b/tools/us_acs_local_county_surface.py @@ -33,6 +33,12 @@ RELIABILITY_CSV_FILENAME = "county_reliability.csv" SUPPORT_FILENAME = "county_support.json" SURFACE_FILENAME = "county_surface.json" +#: Where --county-drop-empty-soi-rows records each dropped SOI row: the +#: county_surface.json receipt, the run identity, and the reliability report's +#: top level, county cells and CSV column (microcosm#922). +ZERO_MEASURE_SOI_ROWS_DROPPED = "zero_measure_soi_rows_dropped" +#: The fields of a dropped row that the run identity keeps. +_DROPPED_ROW_IDENTITY_FIELDS = ("target", "county_fips", "cell_members", "concept") #: Materialize-time validation inputs (microcosm#922): the public county #: design and the household measures it is scored on. Neither is a target: #: they never enter the registry, roles, matrix or loss. @@ -1921,7 +1927,7 @@ def reliability_report( #: Columns of the flat per-county reliability CSV, in order. -def reliability_csv_columns(): +def reliability_csv_columns(*, zero_measure_soi_rows=False): columns = [ "county_fips", "state_fips", @@ -1947,6 +1953,10 @@ def reliability_csv_columns(): "median_household_income_public", "median_household_income_estimate", ] + # Only a --county-drop-empty-soi-rows run has this column, so every other + # run's CSV keeps its bytes. + if zero_measure_soi_rows: + columns.append(ZERO_MEASURE_SOI_ROWS_DROPPED) return columns @@ -1956,9 +1966,12 @@ def reliability_csv(report): import io provisional = bool(report.get("grade_rule", {}).get("provisional", True)) + dropped = ZERO_MEASURE_SOI_ROWS_DROPPED in report stream = io.StringIO() writer = csv.DictWriter( - stream, fieldnames=reliability_csv_columns(), lineterminator="\n" + stream, + fieldnames=reliability_csv_columns(zero_measure_soi_rows=dropped), + lineterminator="\n", ) writer.writeheader() @@ -2003,6 +2016,10 @@ def cell_value(value): entry = families.get(name) or {} row[f"{name}_abs_rel_error"] = entry.get("abs_rel_error") row[f"{name}_pro_rata_abs_rel_error"] = entry.get("pro_rata_abs_rel_error") + if dropped: + row[ZERO_MEASURE_SOI_ROWS_DROPPED] = ";".join( + cell.get(ZERO_MEASURE_SOI_ROWS_DROPPED) or [] + ) writer.writerow({key: cell_value(value) for key, value in row.items()}) return stream.getvalue() @@ -2446,7 +2463,8 @@ def add_arguments(parser): "--county-drop-empty-soi-rows", action="store_true", help=( - "Drop, with a receipt in county_surface.json and the run identity, " + "Drop, with a receipt in county_surface.json, the run identity and " + "the county reliability report (its cells and CSV), " "a county IRS SOI row that is empty although the county has " "households: every household's measure is 0 (for example AGI), " "and the state row stores no zero. Without the flag such a row " @@ -2769,7 +2787,8 @@ def attach_surface(surface, materialized, frame, populations, args): dropped = zero_measure_soi_rows( county.specs, households, empty, county_column=column ) - receipt["zero_measure_soi_rows_dropped"] = dropped + receipt[ZERO_MEASURE_SOI_ROWS_DROPPED] = dropped + args.zero_measure_soi_rows_dropped = dropped names = {row["target"] for row in dropped} refused = [name for name in empty if name not in names] (args.checkpoint_dir / SURFACE_FILENAME).write_text(json.dumps(receipt, indent=2)) @@ -2835,6 +2854,12 @@ def run_metadata(args, county_holdout): # Recorded only when set, so every other run identity keeps its bytes. if getattr(args, "county_drop_empty_soi_rows", False): metadata["county_drop_empty_soi_rows"] = True + # Each dropped row's county cell, for the reliability report: the + # calibrate stage grades those counties without the row. + metadata[ZERO_MEASURE_SOI_ROWS_DROPPED] = [ + {field: row[field] for field in _DROPPED_ROW_IDENTITY_FIELDS} + for row in getattr(args, "zero_measure_soi_rows_dropped", []) + ] # Only a run that read county facts (or ran the county support step) # records them, so a no-county run identity keeps its pre-county bytes. for key, attribute in ( @@ -3011,9 +3036,42 @@ def _bound_report(summary, identity): report["unsupported_targets"] = identity.get("county_targets_dropped", []) if identity.get("county_support"): report["minimum_support"] = identity["county_support"] + if identity.get("county_drop_empty_soi_rows"): + _mark_dropped_soi_rows(report, identity) return report +def _mark_dropped_soi_rows(report, identity): + """Name each SOI row --county-drop-empty-soi-rows dropped in its cells. + + Calibration grades such a county without the row, so its cell and the CSV + say which rows it lacks; a combined cell's row marks every member county. + Every cell gets the list, empty when no row of its own was dropped. + """ + rows = identity.get(ZERO_MEASURE_SOI_ROWS_DROPPED) + if rows is None: + if identity.get("county_targets_dropped"): + raise SystemExit( + "The run identity records --county-drop-empty-soi-rows and " + "dropped county targets, but not the dropped rows' county " + "cells (materialized by older code); re-run --stage " + "materialize with this code." + ) + rows = [] + cells = report["counties"] + for cell in cells.values(): + cell[ZERO_MEASURE_SOI_ROWS_DROPPED] = [] + for row in rows: + for member in row["cell_members"]: + if member not in cells: + raise SystemExit( + f"Dropped SOI row {row['target']} covers county {member}, " + "which the county reliability report does not grade." + ) + cells[member][ZERO_MEASURE_SOI_ROWS_DROPPED].append(row["target"]) + report[ZERO_MEASURE_SOI_ROWS_DROPPED] = json.loads(json.dumps(rows)) + + def feed_path(feed): """The hashable facts file for either supported Ledger artifact form.""" path = Path(feed) From 28e7b7ce6bd2da7238160e147a1fcc3513460955 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mar=C3=ADa=20Juaristi?= <127882282+juaristi22@users.noreply.github.com> Date: Tue, 17 Nov 2026 17:31:37 +0000 Subject: [PATCH 15/31] Accept an ACS-only never-default null only where an R2 stage fills it The reviewed-fill pre-check filed any ACS-only null in a never-default column under natively_filled. R2's stages fill only the take-up stage's SPM-unit take-up flags and engine-free fills and the SSI and Medicaid take-up flags; R2's reasons for the immigration, disability, income transfer and SSI disability-criteria columns say to re-run staging, so such a null passed the pre-check and then stopped materialize. The check now takes the stage-filled set from R2's own constants (stage_filled_never_default), refuses every other never-default null on any spine with a re-run-staging message, and records the set in its report. A test ties the set to R2's own reasons. Part of #922; review of #1660 (comment 6955224433). Co-Authored-By: Claude Opus 5.5 --- ...s-acs-reviewed-fills-precheck-922.added.md | 2 +- .../test_us_acs_local_reviewed_fills_check.py | 67 ++++++++++++++-- tools/check_us_acs_local_reviewed_fills.py | 76 ++++++++++++++++--- 3 files changed, 126 insertions(+), 19 deletions(-) diff --git a/changelog.d/us-acs-reviewed-fills-precheck-922.added.md b/changelog.d/us-acs-reviewed-fills-precheck-922.added.md index c81e708a75..ee88b6cd91 100644 --- a/changelog.d/us-acs-reviewed-fills-precheck-922.added.md +++ b/changelog.d/us-acs-reviewed-fills-precheck-922.added.md @@ -1 +1 @@ -`tools/check_us_acs_local_reviewed_fills.py` grades a staging summary's reviewed engine-input nulls against the ACS local release's fill rules in seconds, before the release runs (microcosm#922). It refuses what materialize would refuse (a null in a never-default-filled column off the ACS spine, a null ESI premium), builds the fill records the release would write with the engine defaults the release resolves, and runs the release's own finalize gate (`acs_local_reviewed_fill_consumer_gate`) on them, which otherwise refuses an unregistered fill hours into the run. It exits 2 when the release would refuse. +`tools/check_us_acs_local_reviewed_fills.py` grades a staging summary's reviewed engine-input nulls against the ACS local release's fill rules in seconds, before the release runs (microcosm#922). It refuses what materialize would refuse (a null in a never-default-filled column, unless the null is on the ACS spine alone and in a column that one of the release's own stages fills there first: the take-up stage's SPM-unit take-up flags and engine-free fills, or the SSI and Medicaid take-up flags; a null ESI premium), builds the fill records the release would write with the engine defaults the release resolves, and runs the release's own finalize gate (`acs_local_reviewed_fill_consumer_gate`) on them, which otherwise refuses an unregistered fill hours into the run. It exits 2 when the release would refuse. diff --git a/packages/microcosm-build/tests/engine_free/us/test_us_acs_local_reviewed_fills_check.py b/packages/microcosm-build/tests/engine_free/us/test_us_acs_local_reviewed_fills_check.py index e0f8df3b3f..18a1f90799 100644 --- a/packages/microcosm-build/tests/engine_free/us/test_us_acs_local_reviewed_fills_check.py +++ b/packages/microcosm-build/tests/engine_free/us/test_us_acs_local_reviewed_fills_check.py @@ -54,30 +54,54 @@ def _resolve(column): return 0, "int" +def test_stage_filled_columns_are_the_never_default_columns_r2_stages_fill( + check, release +) -> None: + filled = check.stage_filled_never_default(release) + + assert filled < set(release.NEVER_DEFAULT_FILLED) + # R2's own reasons agree: a stage-filled column's reason says to run an + # R2 stage first; every other one says to re-run staging. + for key, reason in release._NEVER_DEFAULT_FILLED_REASONS.items(): + assert ("stage first" in reason) is (key in filled), key + assert ("re-run staging" in reason) is (key not in filled), key + + def test_staged_nulls_split_as_r2_fill_step_treats_them(check, release) -> None: - never_entity, never_column = sorted(release.NEVER_DEFAULT_FILLED)[0] + stage_filled = check.stage_filled_never_default(release) + stage_entity, stage_column = sorted(stage_filled)[0] + staging_entity, staging_column = sorted( + set(release.NEVER_DEFAULT_FILLED) - stage_filled + )[0] nulls = [ _null("strike_benefits", {_ACS: 7}), - _null(never_column, {_ACS: 3}, entity=never_entity), - _null(never_column, {"asec_puf": 2}, entity=never_entity), + _null(stage_column, {_ACS: 3}, entity=stage_entity), + _null(stage_column, {"asec_puf": 2}, entity=stage_entity), + # An R2 stage never fills this column: staging must. + _null(staging_column, {_ACS: 5}, entity=staging_entity), _null(US_ESI_EMPLOYER_PREMIUM_COLUMN, {_ACS: 4}), ] split = check.expected_fills( nulls, never_default_filled=release.NEVER_DEFAULT_FILLED, + stage_filled=stage_filled, resolve_default=_resolve, ) assert [fill["column"] for fill in split["fills"]] == ["strike_benefits"] assert split["fills"][0]["fill_value"] == "0" assert split["fills"][0]["missing_rows_by_spine"] == {_ACS: 7} + assert [item["column"] for item in split["natively_filled"]] == [ + f"{stage_entity}.{stage_column}" + ] assert [item["missing_rows_by_spine"] for item in split["natively_filled"]] == [ {_ACS: 3} ] - assert [item["missing_rows_by_spine"] for item in split["denied"]] == [ - {"asec_puf": 2} - ] + assert [ + (item["missing_rows_by_spine"], item["r2_stage_fills"]) + for item in split["denied"] + ] == [({"asec_puf": 2}, True), ({_ACS: 5}, False)] assert [item["column"] for item in split["esi"]] == [ f"person.{US_ESI_EMPLOYER_PREMIUM_COLUMN}" ] @@ -108,6 +132,7 @@ def test_r2_gate_grades_the_expected_fills( split = check.expected_fills( nulls, never_default_filled=release.NEVER_DEFAULT_FILLED, + stage_filled=check.stage_filled_never_default(release), resolve_default=_resolve, ) @@ -123,6 +148,36 @@ def test_r2_gate_grades_the_expected_fills( assert any(message in refusal for refusal in report["refusals"]) +def test_an_acs_only_null_that_staging_should_have_filled_is_refused( + check, release +) -> None: + stage_filled = check.stage_filled_never_default(release) + staging_filled = sorted(set(release.NEVER_DEFAULT_FILLED) - stage_filled) + assert staging_filled + for entity, column in staging_filled: + split = check.expected_fills( + [_null(column, {_ACS: 3}, entity=entity)], + never_default_filled=release.NEVER_DEFAULT_FILLED, + stage_filled=stage_filled, + resolve_default=_resolve, + ) + + report = check.grade( + split, + manifest_names=release.REVIEWED_FILL_MANIFESTS, + never_default_filled=release.NEVER_DEFAULT_FILLED, + installed_engine_version="2.2.1", + ) + + assert report["passed"] is False + assert report["natively_filled"] == [] + assert any( + refusal.startswith(f"{entity}.{column}: null on ['{_ACS}']") + and "re-run staging" in refusal + for refusal in report["refusals"] + ), (entity, column) + + def test_command_exits_2_on_an_unregistered_fill( check, tmp_path: Path, monkeypatch: pytest.MonkeyPatch ) -> None: diff --git a/tools/check_us_acs_local_reviewed_fills.py b/tools/check_us_acs_local_reviewed_fills.py index 6e74108935..af9cf07a59 100644 --- a/tools/check_us_acs_local_reviewed_fills.py +++ b/tools/check_us_acs_local_reviewed_fills.py @@ -14,8 +14,13 @@ - It reads the staging summary's ``reviewed_engine_input_nulls`` (column names and null counts by spine; no row values). -- A null in a ``NEVER_DEFAULT_FILLED`` column on any spine but the ACS one - is refused, as materialize refuses it; R2's own stages fill the ACS cells. +- A null in a ``NEVER_DEFAULT_FILLED`` column is refused, as materialize + refuses it, unless it is on the ACS spine alone and in a column that one of + R2's own stages fills on the ACS rows first (``stage_filled_never_default``: + the take-up stage's SPM-unit take-up flags and engine-free fills, and the + SSI and Medicaid take-up flags). R2 expects staging to fill every other + never-default column (immigration, disability, income transfers, SSI + disability criteria); its reason for those says to re-run staging. - A null in an ESI premium output is refused, as materialize refuses it. - Every other null becomes the fill record R2 writes, with the fill value R2 resolves from the installed engine, and R2's own gate grades the records. @@ -72,21 +77,53 @@ def _release_tool(): return module +def stage_filled_never_default(release: Any) -> frozenset[tuple[str, str]]: + """The ``NEVER_DEFAULT_FILLED`` columns that R2's own stages fill on ACS rows. + + Materialize's ACS take-up stage fills the SPM-unit take-up flags and the + engine-free fills; its SSI/Medicaid take-up stage fills those two flags. + R2's reasons for every other never-default column (immigration, + disability, income transfers, SSI disability criteria) say to re-run + staging, and a null there stops materialize on any spine. + """ + + filled = frozenset( + { + *(("spm_unit", column) for column in release.ACS_LOCAL_TAKE_UP_COLUMNS), + *(tuple(key) for key in release.ACS_LOCAL_ENGINE_FREE_FILL_COLUMNS), + *( + ("person", column) + for column in release.ACS_LOCAL_SSI_MEDICAID_TAKE_UP_COLUMNS + ), + } + ) + unknown = sorted(filled - set(release.NEVER_DEFAULT_FILLED)) + if unknown: + raise SystemExit( + f"R2's stage-filled columns {unknown} are not in NEVER_DEFAULT_FILLED." + ) + return filled + + def expected_fills( nulls: Sequence[Mapping[str, Any]], *, never_default_filled: Collection[tuple[str, str]], + stage_filled: Collection[tuple[str, str]], resolve_default: Callable[[str], tuple[object, str]], ) -> dict[str, list]: """Split the staged nulls as R2's fill step treats them. Returns ``fills`` (the records R2 writes, in its manifest's shape), - ``denied`` (never-default nulls off the ACS spine), ``esi`` (null ESI - premium outputs) and ``natively_filled`` (never-default nulls on the ACS - spine only, which R2's stages fill). + ``denied`` (never-default nulls that materialize refuses), ``esi`` (null + ESI premium outputs) and ``natively_filled`` (never-default nulls on the + ACS spine only, in a ``stage_filled`` column: one that R2's stages fill + there). Each denied record says whether an R2 stage fills its column + (``r2_stage_fills``). """ never = set(never_default_filled) + by_stage = set(stage_filled) result: dict[str, list] = { "fills": [], "denied": [], @@ -108,8 +145,12 @@ def expected_fills( off_acs = { spine: rows for spine, rows in by_spine.items() if spine != ACS_SPINE } - target = "denied" if off_acs or not by_spine else "natively_filled" - result[target].append({"column": name, "missing_rows_by_spine": by_spine}) + stage = (entity, column) in by_stage + record = {"column": name, "missing_rows_by_spine": by_spine} + if stage and by_spine and not off_acs: + result["natively_filled"].append(record) + else: + result["denied"].append({**record, "r2_stage_fills": stage}) continue fill_value, kind = resolve_default(column) missing = int(item["missing_rows"]) @@ -148,11 +189,7 @@ def grade( installed_engine_version=installed_engine_version, ) refusals = [ - *( - f"{item['column']}: null on {sorted(item['missing_rows_by_spine'])}, " - "a column R2 never default-fills (materialize refuses it)" - for item in split["denied"] - ), + *(_denied_refusal(item) for item in split["denied"]), *( f"{item['column']}: null ESI employer premium (materialize refuses it)" for item in split["esi"] @@ -172,6 +209,16 @@ def grade( } +def _denied_refusal(item: Mapping[str, Any]) -> str: + where = f"{item['column']}: null on {sorted(item['missing_rows_by_spine'])}" + if item.get("r2_stage_fills", True): + return f"{where}, a column R2 never default-fills (materialize refuses it)" + return ( + f"{where}, a never-default column that staging fills and no R2 stage " + "does (materialize refuses it; re-run staging)" + ) + + def _parse_args(argv: Sequence[str] | None = None) -> argparse.Namespace: parser = argparse.ArgumentParser( description=( @@ -204,9 +251,11 @@ def main(argv: Sequence[str] | None = None) -> int: ) release = _release_tool() system = _tax_benefit_system() + stage_filled = stage_filled_never_default(release) split = expected_fills( nulls, never_default_filled=release.NEVER_DEFAULT_FILLED, + stage_filled=stage_filled, resolve_default=lambda column: release._resolve_engine_default(system, column), ) report = { @@ -214,6 +263,9 @@ def main(argv: Sequence[str] | None = None) -> int: "issue": ISSUE, "staging_summary": str(args.staging_summary), "staged_null_columns": len(nulls), + "r2_stage_filled_never_default": sorted( + f"{entity}.{column}" for entity, column in stage_filled + ), **grade( split, manifest_names=release.REVIEWED_FILL_MANIFESTS, From 2e9bf301d469c09e8edcf492d275a509634761ed Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mar=C3=ADa=20Juaristi?= <127882282+juaristi22@users.noreply.github.com> Date: Tue, 17 Nov 2026 17:34:00 +0000 Subject: [PATCH 16/31] Refuse to replace an existing patched copy unless --overwrite is passed The donor-patch tool never tested whether --output-h5, the receipt or the copy release manifest existed, so a second run replaced them. Two runs give different file hashes (the HDF5 object headers record write times), so a re-run after R1 left the staging summary's base.sha256 naming bytes no longer at its path. The tool now refuses an existing output before any work, and --overwrite allows the replacement; its help says to re-run R1 on the new copy. Part of #922; review of #1660 (comment 6955224433). Co-Authored-By: Claude Opus 5.5 --- .../us-acs-poc-donor-patch-922.added.md | 2 +- .../us/test_us_acs_donor_column_patch.py | 55 +++++++++++++++++++ tools/patch_us_acs_donor_columns.py | 42 +++++++++++++- 3 files changed, 97 insertions(+), 2 deletions(-) diff --git a/changelog.d/us-acs-poc-donor-patch-922.added.md b/changelog.d/us-acs-poc-donor-patch-922.added.md index ee20b274b4..57ac5264a6 100644 --- a/changelog.d/us-acs-poc-donor-patch-922.added.md +++ b/changelog.d/us-acs-poc-donor-patch-922.added.md @@ -1 +1 @@ -`tools/patch_us_acs_donor_columns.py` writes a patched copy of a published US national donor H5 for the County Files proof of concept's ACS staging (microcosm#922, plan microcosm#1647). It adds reviewed all-zero columns on the entity the US engine gives them (`strike_benefits`: no donor or ASEC pppub23–26 row has `OI_OFF` 12; `passive_partnership_s_corp_income`: the donor holds partnership and S-corp income as one combined `partnership_income`), refuses a column that is already present with any other value, keeps every other table, column, dtype and root attribute, and writes a receipt with both SHA-256 digests, the row counts, each added column with its reason, and the tool's commit. It first restores the three ASEC work columns (`detailed_industry_recode`, `major_industry_recode`, `worked_last_year`) on `person`, valued as the #720 restoration and the `org_wages` carry value them: it reads each donor income year's pinned ASEC person member (refusing a file whose SHA-256 is not pinned), joins `WEIND` and `WEMIND` on source year and exact `PERIDNUM`, refuses a donor person with no member row or more than one, checks eight Census identity columns on every row, and records the files, their digests and the match counts in the receipt. It reads the members from `--asec-source-cache` (default `~/.cache/microcosm/cps/asec_education`) and downloads a missing pinned archive only with `--asec-fetch`. The published donor is read only, and no default changes. With `--input-release-manifest` it checks the input against the published donor's release manifest and records that build in the receipt. With `--release-manifest`, `--manifest-release` and `--manifest-build` it also writes a build-folder release manifest for the copy (in `policyengine/populace-us-staging` by default), so the ACS staging can take it as `--donor-release-manifest` and record the copy's build as `donor_release`, which the local-area release contract requires before publication. +`tools/patch_us_acs_donor_columns.py` writes a patched copy of a published US national donor H5 for the County Files proof of concept's ACS staging (microcosm#922, plan microcosm#1647). It adds reviewed all-zero columns on the entity the US engine gives them (`strike_benefits`: no donor or ASEC pppub23–26 row has `OI_OFF` 12; `passive_partnership_s_corp_income`: the donor holds partnership and S-corp income as one combined `partnership_income`), refuses a column that is already present with any other value, keeps every other table, column, dtype and root attribute, and writes a receipt with both SHA-256 digests, the row counts, each added column with its reason, and the tool's commit. It first restores the three ASEC work columns (`detailed_industry_recode`, `major_industry_recode`, `worked_last_year`) on `person`, valued as the #720 restoration and the `org_wages` carry value them: it reads each donor income year's pinned ASEC person member (refusing a file whose SHA-256 is not pinned), joins `WEIND` and `WEMIND` on source year and exact `PERIDNUM`, refuses a donor person with no member row or more than one, checks eight Census identity columns on every row, and records the files, their digests and the match counts in the receipt. It reads the members from `--asec-source-cache` (default `~/.cache/microcosm/cps/asec_education`) and downloads a missing pinned archive only with `--asec-fetch`. The published donor is read only, and no default changes. It refuses an existing output copy, receipt or copy release manifest unless `--overwrite` is passed: a re-run writes a copy with another SHA-256 (the HDF5 object headers record write times), so a staging summary built on the first copy would no longer match it. With `--input-release-manifest` it checks the input against the published donor's release manifest and records that build in the receipt. With `--release-manifest`, `--manifest-release` and `--manifest-build` it also writes a build-folder release manifest for the copy (in `policyengine/populace-us-staging` by default), so the ACS staging can take it as `--donor-release-manifest` and record the copy's build as `donor_release`, which the local-area release contract requires before publication. diff --git a/packages/microcosm-build/tests/engine_free/us/test_us_acs_donor_column_patch.py b/packages/microcosm-build/tests/engine_free/us/test_us_acs_donor_column_patch.py index a216bd9c8b..a7ef708b2b 100644 --- a/packages/microcosm-build/tests/engine_free/us/test_us_acs_donor_column_patch.py +++ b/packages/microcosm-build/tests/engine_free/us/test_us_acs_donor_column_patch.py @@ -420,6 +420,61 @@ def test_command_writes_the_default_receipt_beside_the_copy( tool.main(["--input-h5", str(donor), "--output-h5", str(donor)]) +def test_an_existing_copy_receipt_or_manifest_is_replaced_only_when_asked( + tool, asec, tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + """Review of #1660: a re-run writes another SHA-256, so a staging summary + that pinned the first copy would name bytes no longer at its path.""" + + import microcosm.frame.adapters.policyengine_us as adapter + + donor = _write_asec_donor(tmp_path / "donor.h5") + monkeypatch.setattr(adapter, "PolicyEngineUSEngine", _Engine) + monkeypatch.setattr( + tool, "current_tool_identity", lambda: {"commit": "c" * 40, "tool_dirty": False} + ) + output = tmp_path / "patched.h5" + receipt_path = tmp_path / "patched.receipt.json" + base = ["--input-h5", str(donor), "--output-h5", str(output)] + assert tool.main(base) == 0 + first = (output.read_bytes(), receipt_path.read_bytes()) + + with pytest.raises(SystemExit, match="already exist.*--overwrite"): + tool.main(base) + assert (output.read_bytes(), receipt_path.read_bytes()) == first + + # An existing receipt alone is refused too. + output.unlink() + with pytest.raises(SystemExit, match="already exist"): + tool.main(base) + assert not output.exists() + + assert tool.main([*base, "--overwrite"]) == 0 + assert json.loads(receipt_path.read_text())["output"]["sha256"] == _sha256(output) + + # So is an existing copy release manifest, before any work. + manifest_path = tmp_path / "release_manifest.json" + manifest_path.write_text("{}") + fresh = tmp_path / "fresh.h5" + with pytest.raises(SystemExit, match="release_manifest.json"): + tool.main( + [ + "--input-h5", + str(donor), + "--output-h5", + str(fresh), + "--release-manifest", + str(manifest_path), + "--manifest-release", + _COPY_RELEASE, + "--manifest-build", + _COPY_BUILD, + ] + ) + assert manifest_path.read_text() == "{}" + assert not fresh.exists() + + def test_table_format_donor_keeps_its_layout(tool, builder, tmp_path: Path) -> None: """A donor stored like BuildP: compound tables, every column a data column.""" diff --git a/tools/patch_us_acs_donor_columns.py b/tools/patch_us_acs_donor_columns.py index 9f5cd43d8e..df0b51c6c0 100644 --- a/tools/patch_us_acs_donor_columns.py +++ b/tools/patch_us_acs_donor_columns.py @@ -1020,6 +1020,7 @@ def patch_donor_h5( engine_identity: Mapping[str, object] | None = None, input_release_manifest: Path | None = None, release_manifest: CopyReleaseManifest | None = None, + overwrite: bool = False, ) -> dict[str, object]: """Write the patched copy and its receipt; return the receipt. @@ -1028,7 +1029,9 @@ def patch_donor_h5( tables a step changes are rewritten, through the shared frame-table codec, in their stored HDF format. The copy is verified before it replaces ``output_h5``. ``input_release_manifest`` is checked before any - work; ``release_manifest`` is written last, after the receipt. + work; ``release_manifest`` is written last, after the receipt. An + existing ``output_h5``, receipt or ``release_manifest`` is refused unless + ``overwrite``: a re-run writes a copy with another SHA-256. """ input_h5, output_h5 = Path(input_h5), Path(output_h5) @@ -1040,6 +1043,14 @@ def patch_donor_h5( *(() if input_release_manifest is None else (Path(input_release_manifest),)), *(() if release_manifest is None else (Path(release_manifest.path),)), ) + _refuse_existing_outputs( + ( + output_h5, + receipt_path, + *(() if release_manifest is None else (Path(release_manifest.path),)), + ), + overwrite=overwrite, + ) input_sha256 = refuse_denied_pool_h5(input_h5, consumer=_CONSUMER) input_release = ( None @@ -1377,6 +1388,24 @@ def _validate_paths( ) +def _refuse_existing_outputs(paths: Sequence[Path], *, overwrite: bool) -> None: + """Refuse to replace an existing output unless asked. + + A re-run writes a copy with another SHA-256 (the HDF5 object headers + record write times), so a staging summary that pinned the first copy + (``base.sha256``) would name bytes no longer at its path. + """ + + existing = [str(path) for path in paths if path.exists()] + if existing and not overwrite: + raise ValueError( + f"Output(s) already exist: {existing}. A re-run writes a copy with " + "another SHA-256, so a staging summary built on the first copy " + "would no longer match it. Write to a new path, or pass --overwrite " + "and re-run R1 on the new copy." + ) + + def _sha256(path: Path) -> str: digest = hashlib.sha256() with path.open("rb") as file: @@ -1485,6 +1514,16 @@ def _parse_args(argv: Sequence[str] | None = None) -> argparse.Namespace: ) parser.add_argument("--manifest-release", help="Release folder name of the copy.") parser.add_argument("--manifest-build", help="Build folder name of the copy.") + parser.add_argument( + "--overwrite", + action="store_true", + help=( + "Replace an existing --output-h5, receipt and --release-manifest " + "(refused by default). The new copy has another SHA-256 (the HDF5 " + "object headers record write times), so re-run R1 on it: a staging " + "summary built on the old copy no longer matches." + ), + ) args = parser.parse_args(argv) names = (args.manifest_release, args.manifest_build) if args.release_manifest is None and any(name is not None for name in names): @@ -1528,6 +1567,7 @@ def main(argv: Sequence[str] | None = None) -> int: engine_identity=_engine_identity(), input_release_manifest=args.input_release_manifest, release_manifest=release_manifest, + overwrite=args.overwrite, ) except ValueError as error: raise SystemExit(f"Donor patch refused: {error}") from error From f8b1039f0099454da2b3e3d3ba17b674c5a488d9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mar=C3=ADa=20Juaristi?= <127882282+juaristi22@users.noreply.github.com> Date: Tue, 17 Nov 2026 18:02:55 +0000 Subject: [PATCH 17/31] Hold back a null never-default column only where an R2 stage fills it The zero-AGI check held back every null NEVER_DEFAULT_FILLED column that the AGI does not read, on either spine. Run alone, it passed a file that R2's first fill refuses. It now takes the stage-filled set from the reviewed-fill pre-check (stage_filled_never_default) and holds back a null column only when an R2 stage fills it, every null is on an ACS row (the _spine tag) and the AGI does not read it. It refuses every other never-default null, as R2's fill step does: a null on a donor row, in a column no R2 stage fills, in one the AGI reads, or without a spine tag to place it. An engine-tier test checks that no stage-filled column is an input of the AGI closure, so an engine release that changes that fails in CI. Part of #922; review of #1660 (comment 6956136956). Co-Authored-By: Claude Opus 5.5 --- ...-acs-county-agi-support-check-922.added.md | 2 +- .../us/test_us_acs_county_agi_support.py | 79 +++++++++++++++---- .../test_us_acs_county_agi_support_engine.py | 23 +++++- tools/check_us_acs_county_agi_support.py | 58 ++++++++++---- 4 files changed, 130 insertions(+), 32 deletions(-) diff --git a/changelog.d/us-acs-county-agi-support-check-922.added.md b/changelog.d/us-acs-county-agi-support-check-922.added.md index 993fb9a9b2..fcd1b5fd27 100644 --- a/changelog.d/us-acs-county-agi-support-check-922.added.md +++ b/changelog.d/us-acs-county-agi-support-check-922.added.md @@ -1 +1 @@ -`tools/check_us_acs_county_agi_support.py` lists, before the ACS local release (R2) runs, the counties whose county IRS SOI AGI row R2 would build empty: counties with households but none with a nonzero AGI (microcosm#922; microcosm#1630 review, finding 1). The state AGI row stores no zero, so such a county makes `attach_surface` refuse the run after the materialize engine pass. The check computes the value R2 stores: it loads the staging frame and its summary as R2 does, holds back the formula-owned columns, fills the reviewed nulls with R2's own functions, and runs policyengine-us for the household sum of `adjusted_gross_income` in household chunks. That sum is the production SOI materializer's AGI measure (an engine-tier test compares them), so income held by a dependent, or by a tax unit without an adult, counts as the engine counts it: not at all. A null take-up flag that R2's own stages fill is held back, since the AGI does not read it; a null in a never-default column that the AGI reads is refused, as R2 refuses it. With `--puma-ladder` it applies R2's own minimum-support moves first, and lists the counties that R2's `check_support` refuses with or without `--county-drop-empty-soi-rows`: a county outside the ladder, and a ladder county without a household-universe record after the moves (as R2 does, it moves no household when a county is outside the ladder). It exits 2 when a county is at risk, and 3 when R2 would refuse the run (3 takes precedence). +`tools/check_us_acs_county_agi_support.py` lists, before the ACS local release (R2) runs, the counties whose county IRS SOI AGI row R2 would build empty: counties with households but none with a nonzero AGI (microcosm#922; microcosm#1630 review, finding 1). The state AGI row stores no zero, so such a county makes `attach_surface` refuse the run after the materialize engine pass. The check computes the value R2 stores: it loads the staging frame and its summary as R2 does, holds back the formula-owned columns, fills the reviewed nulls with R2's own functions, and runs policyengine-us for the household sum of `adjusted_gross_income` in household chunks. That sum is the production SOI materializer's AGI measure (an engine-tier test compares them), so income held by a dependent, or by a tax unit without an adult, counts as the engine counts it: not at all. A null in a never-default column that one of R2's own stages fills (the set the reviewed-fill pre-check uses) is held back only while its nulls are on ACS rows and the AGI does not read it; every other never-default null is refused, as R2's fill step refuses it: a null on a donor row, in a column no R2 stage fills, or in one the AGI reads. An engine-tier test checks that no stage-filled column is an AGI input. With `--puma-ladder` it applies R2's own minimum-support moves first, and lists the counties that R2's `check_support` refuses with or without `--county-drop-empty-soi-rows`: a county outside the ladder, and a ladder county without a household-universe record after the moves (as R2 does, it moves no household when a county is outside the ladder). It exits 2 when a county is at risk, and 3 when R2 would refuse the run (3 takes precedence). diff --git a/packages/microcosm-build/tests/engine_free/us/test_us_acs_county_agi_support.py b/packages/microcosm-build/tests/engine_free/us/test_us_acs_county_agi_support.py index 0ed560c5f4..361269badf 100644 --- a/packages/microcosm-build/tests/engine_free/us/test_us_acs_county_agi_support.py +++ b/packages/microcosm-build/tests/engine_free/us/test_us_acs_county_agi_support.py @@ -198,17 +198,39 @@ def plan(households, populations, overlaps, *, county_column, per_county): ) -def test_null_runtime_columns_outside_the_agi_are_held_back(check) -> None: +#: The columns of ``_NEVER_DEFAULT`` that an R2 stage fills on ACS rows; +#: ``is_blind`` stands in for one that staging must fill. +_STAGE_FILLED = frozenset( + { + ("person", "takes_up_ssi_if_eligible"), + ("spm_unit", "takes_up_snap_if_eligible"), + } +) +#: One person per household: persons 5 and 6 are ACS rows. +_PERSON_SPINE = ["asec_puf"] * 4 + ["acs_2024_1yr"] * 2 + + +def _hold_back(check, frame, agi_inputs): + return check.hold_back_null_runtime_columns( + frame, + never_default_filled=_NEVER_DEFAULT, + stage_filled=_STAGE_FILLED, + agi_inputs=agi_inputs, + ) + + +def test_null_stage_filled_columns_on_acs_rows_outside_the_agi_are_held_back( + check, +) -> None: frame = _frame( { - "takes_up_ssi_if_eligible": [True, np.nan, True, True, False, True], + "person_spine": _PERSON_SPINE, + "takes_up_ssi_if_eligible": [True, True, True, True, np.nan, True], "is_blind": [False] * 6, } ) - held_frame, held = check.hold_back_null_runtime_columns( - frame, never_default_filled=_NEVER_DEFAULT, agi_inputs={"is_blind", "age"} - ) + held_frame, held = _hold_back(check, frame, {"is_blind", "age"}) assert held == {"person": ["takes_up_ssi_if_eligible"]} assert "takes_up_ssi_if_eligible" not in held_frame.table("person").columns @@ -216,21 +238,50 @@ def test_null_runtime_columns_outside_the_agi_are_held_back(check) -> None: assert held_frame.n("household") == frame.n("household") -def test_a_null_never_default_agi_input_is_refused(check) -> None: - frame = _frame({"is_blind": [False, np.nan, False, False, False, False]}) +@pytest.mark.parametrize( + ("columns", "agi_inputs", "message"), + [ + # An R2 stage fills it on the ACS rows, but the AGI reads it. + ( + {"takes_up_ssi_if_eligible": [True] * 4 + [np.nan, True]}, + {"takes_up_ssi_if_eligible"}, + r"person\.takes_up_ssi_if_eligible: the AGI reads it", + ), + # R2's stages fill the ACS rows only; this null is on a donor row. + ( + {"takes_up_ssi_if_eligible": [np.nan] + [True] * 4 + [np.nan]}, + {"age"}, + r"person\.takes_up_ssi_if_eligible: null on 1 non-ACS row", + ), + # No R2 stage fills it, so staging must, on any spine. + ( + {"is_blind": [False] * 4 + [np.nan, False]}, + {"age"}, + r"person\.is_blind: no R2 stage fills it", + ), + ], + ids=["agi-input", "donor-row", "staging-filled"], +) +def test_never_default_nulls_r2_refuses_are_refused( + check, columns, agi_inputs, message +) -> None: + frame = _frame({"person_spine": _PERSON_SPINE, **columns}) + + with pytest.raises(SystemExit, match=message): + _hold_back(check, frame, agi_inputs) - with pytest.raises(SystemExit, match=r"person\.is_blind"): - check.hold_back_null_runtime_columns( - frame, never_default_filled=_NEVER_DEFAULT, agi_inputs={"is_blind"} - ) + +def test_a_null_stage_filled_column_without_a_spine_tag_is_refused(check) -> None: + frame = _frame({"takes_up_ssi_if_eligible": [True] * 4 + [np.nan, True]}) + + with pytest.raises(SystemExit, match="no person_spine column"): + _hold_back(check, frame, {"age"}) def test_a_frame_without_null_runtime_columns_is_returned_as_is(check) -> None: frame = _frame({"takes_up_ssi_if_eligible": [True] * 6}) - held_frame, held = check.hold_back_null_runtime_columns( - frame, never_default_filled=_NEVER_DEFAULT, agi_inputs={"age"} - ) + held_frame, held = _hold_back(check, frame, {"age"}) assert held == {} assert held_frame is frame diff --git a/packages/microcosm-build/tests/engine_workflow/us/test_us_acs_county_agi_support_engine.py b/packages/microcosm-build/tests/engine_workflow/us/test_us_acs_county_agi_support_engine.py index 45515f95dd..b732e8cca5 100644 --- a/packages/microcosm-build/tests/engine_workflow/us/test_us_acs_county_agi_support_engine.py +++ b/packages/microcosm-build/tests/engine_workflow/us/test_us_acs_county_agi_support_engine.py @@ -79,10 +79,12 @@ def _frame(*, with_nulls: bool) -> Frame: tables[entity] = pd.DataFrame({f"{entity}_id": ids}) if with_nulls: # A runtime-owned take-up flag that R2's stages fill on ACS rows and - # the AGI does not read: the check holds it back while it is null. + # the AGI does not read: the check holds it back while its nulls are + # on ACS rows only. tables["spm_unit"]["takes_up_snap_if_eligible"] = pd.Series( [True, None, True, True, True, True], dtype=object ) + tables["spm_unit"]["spm_unit_spine"] = "acs_2024_1yr" tables["household"] = pd.DataFrame( { "household_id": np.arange(1, 7, dtype="int64"), @@ -96,6 +98,25 @@ def _frame(*, with_nulls: bool) -> Frame: ) +def test_no_column_an_r2_stage_fills_is_an_agi_input() -> None: + """The check holds back a null stage-filled column on ACS rows because + the AGI does not read it; an engine release whose AGI read one would make + the check refuse a staging file R2 accepts (review of #1660).""" + + from microcosm.frame.adapters.policyengine_us import ( + PolicyEngineUSVariableMetadataIndex, + ) + + check = _check() + release = check._release_tool() + inputs = check.agi_engine_inputs(PolicyEngineUSVariableMetadataIndex()) + stage_filled = check.reviewed_fills.stage_filled_never_default(release) + + assert "employment_income_before_lsr" in inputs + assert stage_filled + assert inputs.isdisjoint(column for _entity, column in stage_filled) + + def test_household_agi_counts_only_heads_and_spouses_as_the_soi_row_does( tmp_path, ) -> None: diff --git a/tools/check_us_acs_county_agi_support.py b/tools/check_us_acs_county_agi_support.py index 022c0f7739..905ac73c26 100644 --- a/tools/check_us_acs_county_agi_support.py +++ b/tools/check_us_acs_county_agi_support.py @@ -25,10 +25,13 @@ and spouse (``irs_gross_income``), and only an adult can be a head or a spouse. A household whose income is all on dependents, or on a tax unit without an adult, has an AGI of 0 unless a deduction makes it negative. -- R2's take-up stages fill some ``NEVER_DEFAULT_FILLED`` columns on the ACS - rows before its fill step. The check holds back such a column while it is - null; the AGI does not read it. A null in one that the AGI reads is - refused, as R2 refuses it. +- R2's stages fill some ``NEVER_DEFAULT_FILLED`` columns on the ACS rows + before its fill step (``stage_filled_never_default``, shared with the + reviewed-fill pre-check). The check holds back such a column while its + nulls are on ACS rows only and the AGI does not read it. It refuses every + other null in a never-default column, as R2's fill step does: a null on a + donor row, a null in a column that no R2 stage fills, and a null the AGI + reads. - With ``--puma-ladder`` it applies R2's own minimum-support moves (``plan_minimum_support`` with ``--county-min-support``, default R2's 3) and takes the county list from the ladder, as R2 does. @@ -87,6 +90,7 @@ if str(_TOOLS) not in sys.path: sys.path.insert(0, str(_TOOLS)) +import check_us_acs_local_reviewed_fills as reviewed_fills # noqa: E402 import us_acs_local_county_surface as county_surface # noqa: E402 from microcosm.frame import Frame # noqa: E402 @@ -130,39 +134,60 @@ def hold_back_null_runtime_columns( frame: Frame, *, never_default_filled: Collection[tuple[str, str]], + stage_filled: Collection[tuple[str, str]], agi_inputs: Collection[str], ) -> tuple[Frame, dict[str, list[str]]]: - """Drop the null never-default columns the AGI does not read. - - R2's take-up stages fill such columns on the ACS rows before its fill - step, and its fill step refuses any null left in one. For the AGI alone - a column outside the AGI's inputs does not matter, so the check holds it - back. A null in a never-default column that the AGI reads is refused: - R2 refuses it too. + """Drop the null never-default columns that R2's stages fill first. + + R2's stages fill the ``stage_filled`` columns on the ACS rows before its + fill step, and the fill step refuses any null left in a never-default + column. So the check holds back a null column only when an R2 stage fills + it, every null is on an ACS row (the ``_spine`` tag) and the AGI + does not read it. Every other null in a never-default column is refused, + as R2 refuses it. """ + from microcosm.build.us_runtime.base_pool import spine_column + agi_inputs = frozenset(agi_inputs) + stage_filled = frozenset(stage_filled) held: dict[str, list[str]] = {} tables = {} refused = [] for entity in frame.entities: table = frame.table(entity) - null = sorted( + tag = spine_column(entity) + null = [] + for column in sorted( column for owner, column in never_default_filled if owner == entity and column in table.columns and table[column].isna().any() - ) - refused.extend(f"{entity}.{column}" for column in null if column in agi_inputs) + ): + name = f"{entity}.{column}" + missing = table[column].isna() + if (entity, column) not in stage_filled: + refused.append(f"{name}: no R2 stage fills it (re-run staging)") + elif tag not in table.columns: + refused.append(f"{name}: no {tag} column places its null rows") + elif off := int((missing & table[tag].ne(county_surface.ACS_SPINE)).sum()): + refused.append( + f"{name}: null on {off} non-ACS row(s); R2's stages fill " + "the ACS rows only" + ) + elif column in agi_inputs: + refused.append(f"{name}: the AGI reads it") + else: + null.append(column) if null: held[entity] = null table = table.drop(columns=null) tables[entity] = table if refused: raise SystemExit( - f"Null never-default-filled column(s) that the AGI reads: {refused}. " - "R2's materialize stage refuses these nulls too (fill_reviewed_nulls)." + "Null never-default-filled column(s) that R2's materialize stage " + f"refuses too (fill_reviewed_nulls): {'; '.join(refused)}." ) if not held: return frame, held @@ -200,6 +225,7 @@ def household_agi( projected, held = hold_back_null_runtime_columns( projected, never_default_filled=release.NEVER_DEFAULT_FILLED, + stage_filled=reviewed_fills.stage_filled_never_default(release), agi_inputs=agi_engine_inputs(PolicyEngineUSVariableMetadataIndex()), ) fills, drift = release.fill_reviewed_nulls( From c990afa5652b7f441401b83db38468e4887836eb Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mar=C3=ADa=20Juaristi?= <127882282+juaristi22@users.noreply.github.com> Date: Wed, 18 Nov 2026 18:08:36 +0000 Subject: [PATCH 18/31] Add the first draft of the County Files PoC report for LWI Draft v0.1 of the proof-of-concept report: the fit and the limits of the 2024 county file from the 17-18 November run. It is pe-doc Markdown, with the numbers from the run report on #1647 and the release's own reports, and three placeholders still open (the methods link twice, the schema documentation). Part of #922. Co-Authored-By: Claude Opus 5.5 --- experiments/us-county-poc-20261117/README.md | 10 + .../us-county-poc-20261117/lwi-poc-report.md | 208 ++++++++++++++++++ 2 files changed, 218 insertions(+) create mode 100644 experiments/us-county-poc-20261117/README.md create mode 100644 experiments/us-county-poc-20261117/lwi-poc-report.md diff --git a/experiments/us-county-poc-20261117/README.md b/experiments/us-county-poc-20261117/README.md new file mode 100644 index 0000000000..c5f922fd2b --- /dev/null +++ b/experiments/us-county-poc-20261117/README.md @@ -0,0 +1,10 @@ +# US County Files proof of concept: the report (2026-11-17 run) + +Tracking issue: microcosm#922, the LWI County Files. Plan: microcosm#1647. + +`lwi-poc-report.md` is the first draft (v0.1, 18 November 2026) of the proof-of-concept report for the Living Wage Institute. It states the fit and the limits of the 2024 county file that the 17–18 November run built: build `populace-us-2024-buildo-acs-local-f8b1039f00-20261118T011728Z`, SHA-256 `82314a3b5a6a95762faf6eb4f5b499ce56608ad6a39a27b75e11c75b4945bd3c`. The draft is under review and has not been sent. + +- **Format.** The draft is `pe-doc` Markdown (PolicyEngine/document-templates). It has the front matter, the three-line title block, `[[placeholders]]` that `pe-doc check` refuses, and source notes after the last rule. `pe-doc` has no report kind, so the draft uses `kind: proposal` with `psl_foundation: false`. +- **Sources.** The numbers come from the run report on microcosm#1647 (comments 6982547034 and 6982549060) and from the release's own reports: `county_reliability.json` and `.csv`, `calibration_diagnostics.json` and `gate_summary.json`. The loader result comes from a test on 18 November with policyengine-us 2.2.1. +- **Delivery.** The file is shared through the private Hugging Face dataset `policyengine/lwi-county-files`. +- **Still open.** The link to the methods documentation, the schema documentation, and the review. diff --git a/experiments/us-county-poc-20261117/lwi-poc-report.md b/experiments/us-county-poc-20261117/lwi-poc-report.md new file mode 100644 index 0000000000..de462b45bc --- /dev/null +++ b/experiments/us-county-poc-20261117/lwi-poc-report.md @@ -0,0 +1,208 @@ +--- +kind: proposal +client: "Living Wage Institute" +status: "draft v0.1 (2026-11-18): for María and Max to review, not for sending" +pe-doc: + psl_foundation: false + split_tables: true + pdf_name: "PolicyEngine - County Files proof of concept report" +--- + +# County Files proof of concept: the 2024 county file + +**What we built, how well it matches official county statistics, and what comes next** + +A PolicyEngine report · for the Living Wage Institute · November 2026 + +## Summary + +- **We are delivering a 2024 county file.** It is one microdata file of synthetic households that covers all 3,144 US counties and county-equivalents. It is weighted to represent about 122.5 million households and 331 million people, and it runs in PolicyEngine's US tax-benefit model (policyengine-us 2.2.1). +- **State results are strong.** After calibration, 96% of the 4,227 IRS state tax targets are within 10% of their official value, and every SNAP, Medicaid and state population target is within 10%. +- **County totals are useful, but county distributions are not yet reliable.** Two-thirds of the county targets used in calibration are within 10%. Against county statistics the calibration never saw, the file estimates total earnings and total household income better than a simple population-share split. It is worse than that split for the number of households with earnings and for the income distribution. +- **The main limit is the effective sample in each county.** In the median county, the weights behave like a sample of about 6 households. National donor households make up 3.6% of the records but carry 77% of the weight, so a few of them dominate each county. +- **Use the file for county totals and for ranking counties,** with care. Do not yet use it for distributions inside a county, such as income brackets, poverty rates or the share of households with earnings. +- **Next, we will raise the effective sample in each county,** balance how much cloned records contribute to the calibration, and improve the calibration fit. We will also produce the 2026 and 2027 files, the household measures and the schema manifest. + +## What we are delivering + +| Item | In the agreement | Status for Monday | +|---|---|---| +| The 2024 county file | Yes | Built on 18 November 2026. All automated checks passed. Shared in a private Hugging Face repository, `policyengine/lwi-county-files`, with a read-only access token. | +| A written delivery notice | Yes | Max Ghenis sends it. | +| This report: the fit and the limits | For the proof of concept | This document. | +| Methods documentation | Yes | A draft is ready: [[link to the methods draft]] | +| Schema documentation | Yes | [[Schema documentation for Monday, or moved to the stretch goals]] | +| The 2026 and 2027 county files | Stretch goal | Not yet produced. | +| Household measures (earnings, gross income and net income for each household) | Stretch goal | Not yet produced. | +| The schema manifest (every table and column, with types and counts) | Stretch goal | Not yet produced. | + +## The 2024 county file + +| Feature | Value | +|---|---| +| Year | 2024 | +| Geography | 3,144 counties and county-equivalents on the 2023 county codes, including Connecticut's nine planning regions; 436 congressional districts. Puerto Rico is not included. | +| Household records | 1,586,908: 1,529,668 from the 2024 American Community Survey (ACS) and 57,240 national donor households | +| Person records | 3,587,263: 3,420,942 ACS and 166,321 donor | +| Weighted totals | About 122.5 million households and 331 million people | +| Model | policyengine-us 2.2.1 | +| File | `populace_us_2024_acs_local.h5`, 10.6 GB (HDF5) | + +Every county has at least one household record. The median county has 144 records, and the largest has 35,707. Ten very small counties have only one or two records. Three counties had no records of their own, so we moved three households into each of them from other counties in the same PUMA (Public Use Microdata Area, the smallest area the ACS microdata identifies). + +## How we built it + +The method has four steps. The methods documentation gives the detail ([[link to the methods draft]]), and our working papers explain the main choices. + +1. **Households and their counties.** We start from the 2024 ACS 1-year public-use microdata. The ACS gives each household's PUMA, not its county. So we assign each ACS household a county within its PUMA, in proportion to the population each county shares with that PUMA. +2. **National donor households.** The ACS does not collect detailed tax items. We add 57,240 national donor households from the Current Population Survey (CPS ASEC) with tax detail from the IRS public-use file, from PolicyEngine's published national data. These households keep the county that the national data gives them. +3. **Imputation.** We give ACS households the characteristics the ACS lacks, such as detailed tax items, from the donor households, with quantile regression forests (working paper: [microcosm.institute/support/paper](https://microcosm.institute/support/paper)). Imputation gives records their characteristics. It does not change how many households each record represents. +4. **Calibration.** We then adjust the household weights so that the file matches 16,440 official statistics at once: 4,482 for states, 436 for congressional districts and 11,522 for counties. A cap keeps each household's final weight at most five times its starting weight. A paper on this calibration method is in preparation. + +The targets come from IRS Statistics of Income (county tax returns and adjusted gross income; state detail on income items, deductions and credits, by income band), USDA SNAP (state households and benefits, fiscal year 2024), CMS Medicaid enrollment (state, 2024), Census population (state, district and county) and ACS households (state and county). + +To test the file, we held out 1,052 county targets, about one in ten, from the calibration. We also kept five ACS county tables out of the calibration completely: total earnings, households with earnings, total household income, the household income distribution, and median household income. + +## How well the file fits + +We measure each target's error as the difference between the file's estimate and the official value, divided by the official value. "Within 10%" means an error of 10% or less in either direction. + +### States and the nation + +| Targets | Number | Within 10% | Median error | +|---|---|---|---| +| IRS tax statistics, by state | 4,227 | 96.0% | 0.12% | +| SNAP households and benefits, by state | 102 | 100% | 0.11% | +| Medicaid enrollment, by state | 51 | 100% | 0.08% | +| Population, by state | 51 | 100% | 0.07% | +| ACS households, by state | 51 | 94.1% | 4.2% | +| Population, by congressional district | 436 | 92.2% | 0.58% | + +National totals are the sum of the state estimates. Most national tax totals are within 4.5% of the official value. A few groups are further off: + +- tax returns with adjusted gross income of $1 million or more: 129% too high; +- returns with capital gains: 32% too low; +- taxable interest on returns with adjusted gross income below $1: 29% too low; +- returns with taxable interest and adjusted gross income of $500,000 or more: 13% too high; +- the total number of households: 5.2% too low. + +### Counties: targets used in calibration + +| County targets | Number | Within 10% | Median error | +|---|---|---|---| +| Population | 3,144 | 67.5% | 3.7% | +| IRS tax returns | 2,702 | 70.8% | 3.6% | +| IRS adjusted gross income | 2,846 | 82.3% | 0.4% | +| ACS households | 2,830 | 47.6% | 10.8% | +| **All county targets** | **11,522** | **67.1%** | **3.4%** | + +In 856 counties (27%), every county target used in calibration is within 10%. Before calibration, only 15% of county targets were within 10%. + +### Counties: targets held out of calibration + +For the 1,052 held-out county targets, we compare the file with a simple baseline: each state's total split across its counties by population. + +| Held-out county targets | Number | Median error: file | Median error: baseline | Within 10%: file | Within 10%: baseline | +|---|---|---|---|---|---| +| IRS tax returns | 441 | 14.8% | 5.7% | 36.7% | 73.0% | +| IRS adjusted gross income | 297 | 32.8% | 39.2% | 13.5% | 11.8% | +| ACS households | 314 | 19.6% | 5.4% | 26.1% | 76.4% | +| **All** | **1,052** | **20.5%** | **8.1%** | **27.0%** | **56.8%** | + +The file beats the baseline for county adjusted gross income, but not for counts of tax returns or households. + +### Counties: ACS statistics never used in calibration + +| ACS county statistic | Median error: file | Median error: baseline | Counties where the file is closer | +|---|---|---|---| +| Total earnings | 19.3% | 28.8% | 61% | +| Total household income (approximate) | 13.8% | 21.3% | 63% | +| Households with earnings | 15.8% | 7.2% | 30% | +| Household income distribution (16 brackets) | 101%¹ | 25%¹ | 0.4% | + +The file also ranks counties better than the baseline by earnings per person and by household income per person. The rank correlation with the official values is 0.57 for the file against 0.37 for the baseline for earnings, and 0.68 against 0.46 for household income. For households with earnings, the two are about equal (0.28 and 0.27). Within a state, the population-share split cannot rank counties at all; there, the file's median rank correlation is 0.49 for earnings and 0.64 for household income. + +The file's median household income is too high in most counties: in the median county it is 17% above the published ACS value. Its rank correlation with the published county medians is 0.30. + +### Compared with the earlier state-and-district file + +PolicyEngine's published 2024 state-and-district file did not have county targets. On the 4,459 targets that both files used, the share within 10% is almost the same: 97.0% before and 96.9% now. Adding the county targets did lower two things: congressional district population fell from 97.0% to 92.2% within 10%, and the national effective sample fell from about 12,100 to about 7,900. + +## How reliable each county is + +Each county gets a provisional reliability grade from two measures: its effective sample and its largest error. The largest error is taken over the county's calibration targets, its held-out targets and its ACS checks. + +| Grade | Rule | Counties | +|---|---|---| +| A | Effective sample at least 400, and largest error at most 10% | 0 | +| B | Effective sample at least 100, and largest error at most 20% | 3 | +| C | Effective sample at least 30, and largest error at most 50% | 103 | +| D | Lower than C, with test evidence | 3,038 | +| U | No test evidence | 0 | + +The effective sample is the number of equally weighted households that would give the same precision as the county's actual weights. It is small in almost every county: + +- The median county's effective sample is about 6. The largest is about 146. +- Only 167 counties reach an effective sample of 30. Together they hold 22.6% of the US population. +- Of the 279 counties with 250,000 people or more, 246 have an effective sample below 30. + +Most D grades have both causes: 2,905 counties have an effective sample below 30 and a largest error above 50%. The largest error comes from the household income distribution in almost every county. + +**Why the effective samples are small.** There are three reasons: + +1. **Donor households carry most of the weight.** The 57,240 national donor households are 3.6% of the records, but they carry 77% of the household weight. Before calibration they carried half. In each county, a few of them hold most of the weight. +2. **Calibration concentrates the weight further.** After calibration, 1% of the household records hold 81% of the weight. Before calibration, they held 51%. +3. **The calibration gives most of its attention to state targets.** State and district targets make up 94% of the calibration's weighting, and county targets 6%. So the calibration fits state totals closely and county targets more loosely. + +## Limits: how to use the file + +**Group results by county** with the household table's `county_fips_2023` column. The reliability files use the same county codes. The model does not read this column, so join it to model results by `household_id`. The repository's README shows how. + +**Use with care:** + +- county totals of population, tax returns, adjusted gross income, earnings and household income; +- rankings of counties by earnings or income per person; +- state results, and national results other than the tax groups listed above. + +**Do not use yet:** + +- distributions within a county, such as income brackets, poverty rates, or the share of households with earnings; +- county median household income, which the file overstates; +- results for single small counties. Ten counties have only one or two household records. + +**Other limits of this proof of concept:** + +- **County assignment within a PUMA.** We assign ACS households to counties by population share within their PUMA. Many PUMAs, especially in rural areas, cover several counties. Inside such a PUMA, differences between counties come only from the calibration to county targets, not from the survey itself. +- **Donor households are national records.** They keep the county that PolicyEngine's national data gives them, and their characteristics come from national surveys, not from the county. +- **The grades are provisional.** The grade rule will change as the method improves. +- **Temporary data shortcuts.** For this proof of concept, strike benefits are zero for every household, because no household in the source surveys reports them. S-corporation income is not separated from partnership income: the national data holds both as one combined partnership amount, so the separate S-corporation items are zero. +- **Model use.** The file loads with policyengine-us 2.2.1's standard dataset loader. On a computer with 32 GB of memory, the national simulation built in 90 seconds and used at most 18 GB, and it computed 2024 totals of population, employment income and adjusted gross income. For one state, the model also computed income tax, SNAP and household net income, with no missing values. We have not run full-model calculations, such as household net income, for the whole country at once. On a 32 GB computer, run them state by state or in chunks, or use a larger machine. The model ignores 254 extra columns: raw survey fields and build identifiers. +- **One year only.** The file is for 2024. The 2026 and 2027 files are a stretch goal. + +## Next steps + +1. **Raise the effective sample in each county.** Spread each county's weight over more households, mainly by lowering the share of the weight that donor households carry. We will measure progress with the effective sample per county and the share of the population in counties at grade C or better. +2. **Balance the contribution of cloned records to the calibration.** Keep any single source household, together with its copies, from dominating the weights that the calibration chooses. +3. **Improve the calibration fit.** Give the county targets more weight, so that held-out county targets beat the population-share baseline, and fix the national tax outliers listed above. We will also bring district population back to its earlier fit. +4. **Complete the stretch goals.** Produce the 2026 and 2027 county files, the household measures and the schema manifest. +5. **Build the final County Files.** Rebuild from PolicyEngine's certified national data and remove the shortcuts this proof of concept uses. + +## Appendix: file provenance + +| Item | Value | +|---|---| +| Build | `populace-us-2024-buildo-acs-local-f8b1039f00-20261118T011728Z` | +| File | `populace_us_2024_acs_local.h5`, 10,637,811,669 bytes | +| SHA-256 | `82314a3b5a6a95762faf6eb4f5b499ce56608ad6a39a27b75e11c75b4945bd3c` | +| Built | 17–18 November 2026 | +| Code | Microcosm, commits `72b7072bf` (ACS staging) and `f8b1039f0` (calibration and packaging) | +| Model | policyengine-us 2.2.1 | +| Checks | All 23 automated release checks passed. | +| Loader test | On 18 November 2026, `Microsimulation(dataset=)` in policyengine-us 2.2.1 built the national simulation in 90 seconds, with a peak of 18 GB of memory | +| Reliability files | `county_reliability.csv` and `county_reliability.json`, one record per county, with its grade, effective sample and errors | + +--- + +¹ The income distribution error is the sum, over the 16 ACS income brackets, of the differences between the estimated and published numbers of households, divided by the county's number of households. When the estimated and published totals agree, an error of 100% means that half of the households fall in the wrong bracket. + +Sources: US Census Bureau, American Community Survey 2024 1-year public-use microdata and county tables B11001, B19001, B19013, B19025, B19051 and B19061; IRS Statistics of Income, state and county data; USDA Food and Nutrition Service, SNAP state participation and benefits, fiscal year 2024; CMS Medicaid enrollment, 2024; US Census Bureau population data; US Census Bureau and Bureau of Labor Statistics, Current Population Survey Annual Social and Economic Supplement, and the IRS Statistics of Income public-use file, both through PolicyEngine's national data. From 0ca8f6d4da8cf30599dbcb29855c85ff584d9897 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mar=C3=ADa=20Juaristi?= <127882282+juaristi22@users.noreply.github.com> Date: Thu, 19 Nov 2026 20:16:29 +0000 Subject: [PATCH 19/31] Revise the County Files PoC report for LWI (v0.2) Takes the corrections that part 2 of the methods draft lists (#1647 comment 7005741386). The ACS county tables are 2020-2024 5-year; only some targets equal published figures; the ACS checks compare with the file's state totals split in the ACS county proportions; county counts are of households in housing units; and the report now names three temporary shortcuts. The checks line says what gate_summary.json records: all 17 blocking checks passed, and the district evidence check flagged 275 of the 436 districts. The schema documentation is a deliverable, not a stretch goal, and the placeholders are gone: the report names the methods and schema documents instead of linking into the private repository. Part of #922. Co-Authored-By: Claude Opus 5.5 --- experiments/us-county-poc-20261117/README.md | 8 +-- .../us-county-poc-20261117/lwi-poc-report.md | 64 ++++++++++--------- 2 files changed, 38 insertions(+), 34 deletions(-) diff --git a/experiments/us-county-poc-20261117/README.md b/experiments/us-county-poc-20261117/README.md index c5f922fd2b..4ed8982299 100644 --- a/experiments/us-county-poc-20261117/README.md +++ b/experiments/us-county-poc-20261117/README.md @@ -2,9 +2,9 @@ Tracking issue: microcosm#922, the LWI County Files. Plan: microcosm#1647. -`lwi-poc-report.md` is the first draft (v0.1, 18 November 2026) of the proof-of-concept report for the Living Wage Institute. It states the fit and the limits of the 2024 county file that the 17–18 November run built: build `populace-us-2024-buildo-acs-local-f8b1039f00-20261118T011728Z`, SHA-256 `82314a3b5a6a95762faf6eb4f5b499ce56608ad6a39a27b75e11c75b4945bd3c`. The draft is under review and has not been sent. +`lwi-poc-report.md` is draft v0.2 (19 November 2026) of the proof-of-concept report for the Living Wage Institute. It states the fit and the limits of the 2024 county file that the 17–18 November run built: build `populace-us-2024-buildo-acs-local-f8b1039f00-20261118T011728Z`, SHA-256 `82314a3b5a6a95762faf6eb4f5b499ce56608ad6a39a27b75e11c75b4945bd3c`. The draft is under review and has not been sent. v0.2 takes the corrections that part 2 of the methods draft lists (microcosm#1647 comment 7005741386) and describes the 23 release checks as `gate_summary.json` records them. -- **Format.** The draft is `pe-doc` Markdown (PolicyEngine/document-templates). It has the front matter, the three-line title block, `[[placeholders]]` that `pe-doc check` refuses, and source notes after the last rule. `pe-doc` has no report kind, so the draft uses `kind: proposal` with `psl_foundation: false`. +- **Format.** The draft is `pe-doc` Markdown (PolicyEngine/document-templates). It has the front matter, the three-line title block and source notes after the last rule. `pe-doc` has no report kind, so the draft uses `kind: proposal` with `psl_foundation: false`. - **Sources.** The numbers come from the run report on microcosm#1647 (comments 6982547034 and 6982549060) and from the release's own reports: `county_reliability.json` and `.csv`, `calibration_diagnostics.json` and `gate_summary.json`. The loader result comes from a test on 18 November with policyengine-us 2.2.1. -- **Delivery.** The file is shared through the private Hugging Face dataset `policyengine/lwi-county-files`. -- **Still open.** The link to the methods documentation, the schema documentation, and the review. +- **Delivery.** The file, this report, the methods documentation and the schema documentation are shared through the private Hugging Face dataset `policyengine/lwi-county-files`. The report refers to the other two documents by name, because a link into a private repository does not open for a reader who has only a download token. +- **Still open.** The methods documentation and the schema documentation, which go next to this report (microcosm#1647 comment 7006535601), and the review. diff --git a/experiments/us-county-poc-20261117/lwi-poc-report.md b/experiments/us-county-poc-20261117/lwi-poc-report.md index de462b45bc..89c42c1b88 100644 --- a/experiments/us-county-poc-20261117/lwi-poc-report.md +++ b/experiments/us-county-poc-20261117/lwi-poc-report.md @@ -1,7 +1,7 @@ --- kind: proposal client: "Living Wage Institute" -status: "draft v0.1 (2026-11-18): for María and Max to review, not for sending" +status: "draft v0.2 (2026-11-19): for María and Max to review, not for sending" pe-doc: psl_foundation: false split_tables: true @@ -17,24 +17,23 @@ A PolicyEngine report · for the Living Wage Institute · November 2026 ## Summary - **We are delivering a 2024 county file.** It is one microdata file of synthetic households that covers all 3,144 US counties and county-equivalents. It is weighted to represent about 122.5 million households and 331 million people, and it runs in PolicyEngine's US tax-benefit model (policyengine-us 2.2.1). -- **State results are strong.** After calibration, 96% of the 4,227 IRS state tax targets are within 10% of their official value, and every SNAP, Medicaid and state population target is within 10%. +- **State results are strong.** After calibration, 96% of the 4,227 IRS state tax targets are within 10% of their target value, and every SNAP, Medicaid and state population target is within 10%. - **County totals are useful, but county distributions are not yet reliable.** Two-thirds of the county targets used in calibration are within 10%. Against county statistics the calibration never saw, the file estimates total earnings and total household income better than a simple population-share split. It is worse than that split for the number of households with earnings and for the income distribution. - **The main limit is the effective sample in each county.** In the median county, the weights behave like a sample of about 6 households. National donor households make up 3.6% of the records but carry 77% of the weight, so a few of them dominate each county. - **Use the file for county totals and for ranking counties,** with care. Do not yet use it for distributions inside a county, such as income brackets, poverty rates or the share of households with earnings. -- **Next, we will raise the effective sample in each county,** balance how much cloned records contribute to the calibration, and improve the calibration fit. We will also produce the 2026 and 2027 files, the household measures and the schema manifest. +- **Next, we will raise the effective sample in each county,** balance how much cloned records contribute to the calibration, and improve the calibration fit. We will also produce the 2026 and 2027 files and the household measures. ## What we are delivering | Item | In the agreement | Status for Monday | |---|---|---| -| The 2024 county file | Yes | Built on 18 November 2026. All automated checks passed. Shared in a private Hugging Face repository, `policyengine/lwi-county-files`, with a read-only access token. | +| The 2024 county file | Yes | Built on 18 November 2026. Every check that can stop the build passed (see the appendix). Shared in a private Hugging Face repository, `policyengine/lwi-county-files`, with a read-only access token. | | A written delivery notice | Yes | Max Ghenis sends it. | | This report: the fit and the limits | For the proof of concept | This document. | -| Methods documentation | Yes | A draft is ready: [[link to the methods draft]] | -| Schema documentation | Yes | [[Schema documentation for Monday, or moved to the stretch goals]] | +| Methods documentation | Yes | Delivered with this report, in the same repository. | +| Schema documentation | Yes | Delivered with this report, in the same repository: every table and column of the file, with its type and its missing values, and the changes from the sample column list sent with the agreement. | | The 2026 and 2027 county files | Stretch goal | Not yet produced. | | Household measures (earnings, gross income and net income for each household) | Stretch goal | Not yet produced. | -| The schema manifest (every table and column, with types and counts) | Stretch goal | Not yet produced. | ## The 2024 county file @@ -42,30 +41,30 @@ A PolicyEngine report · for the Living Wage Institute · November 2026 |---|---| | Year | 2024 | | Geography | 3,144 counties and county-equivalents on the 2023 county codes, including Connecticut's nine planning regions; 436 congressional districts. Puerto Rico is not included. | -| Household records | 1,586,908: 1,529,668 from the 2024 American Community Survey (ACS) and 57,240 national donor households | +| Household records | 1,586,908: 1,529,668 from the 2024 American Community Survey (ACS), of which 181,260 are one-person group-quarters records (for example, in nursing homes or college dormitories), and 57,240 national donor households | | Person records | 3,587,263: 3,420,942 ACS and 166,321 donor | | Weighted totals | About 122.5 million households and 331 million people | | Model | policyengine-us 2.2.1 | | File | `populace_us_2024_acs_local.h5`, 10.6 GB (HDF5) | -Every county has at least one household record. The median county has 144 records, and the largest has 35,707. Ten very small counties have only one or two records. Three counties had no records of their own, so we moved three households into each of them from other counties in the same PUMA (Public Use Microdata Area, the smallest area the ACS microdata identifies). +Every county has at least one household. Counting households in housing units (ACS housing-unit records and donor households, without group-quarters records), the median county has 144, and the largest has 35,707. Ten very small counties have only one or two. Three counties had no households after the county draw, so we moved three ACS households into each of them from other counties in the same PUMA (Public Use Microdata Area, the smallest area the ACS microdata identifies). ## How we built it -The method has four steps. The methods documentation gives the detail ([[link to the methods draft]]), and our working papers explain the main choices. +The method has four steps. The methods documentation, delivered with this report, gives the detail, and our working papers explain the main choices. -1. **Households and their counties.** We start from the 2024 ACS 1-year public-use microdata. The ACS gives each household's PUMA, not its county. So we assign each ACS household a county within its PUMA, in proportion to the population each county shares with that PUMA. -2. **National donor households.** The ACS does not collect detailed tax items. We add 57,240 national donor households from the Current Population Survey (CPS ASEC) with tax detail from the IRS public-use file, from PolicyEngine's published national data. These households keep the county that the national data gives them. -3. **Imputation.** We give ACS households the characteristics the ACS lacks, such as detailed tax items, from the donor households, with quantile regression forests (working paper: [microcosm.institute/support/paper](https://microcosm.institute/support/paper)). Imputation gives records their characteristics. It does not change how many households each record represents. -4. **Calibration.** We then adjust the household weights so that the file matches 16,440 official statistics at once: 4,482 for states, 436 for congressional districts and 11,522 for counties. A cap keeps each household's final weight at most five times its starting weight. A paper on this calibration method is in preparation. +1. **Households and their counties.** We start from the 2024 ACS 1-year public-use microdata. The ACS gives each household's PUMA, not its county. So we draw a county for each ACS household within its PUMA, with odds in proportion to the population each county shares with that PUMA. Each household keeps its whole weight in the county it draws. +2. **National donor households.** The ACS does not collect detailed tax items. We add 57,240 donor households from PolicyEngine's published national file, which combines the Current Population Survey (CPS ASEC) with tax detail imputed from the IRS public-use file. For this proof of concept, we patched a copy of that file: we added three work columns from the CPS ASEC and two columns of zeros, and kept every record. These households keep the county that the national file gives them. +3. **Imputation.** We give ACS households most of the characteristics the ACS lacks, such as detailed tax items, from the donor households, with quantile regression forests (working paper: [microcosm.institute/support/paper](https://microcosm.institute/support/paper)). A few come from elsewhere: the household's own ACS answer sets SNAP receipt, a model trained on the Survey of Income and Program Participation sets SSI disability status, and rules and seeded random draws set immigration status and program take-up. Inputs still blank after that take the model's default values, such as zero tips and zero net worth. Imputation gives records their characteristics. It does not change how many households each record represents. +4. **Calibration.** We then adjust the household weights so that the file comes close to 16,440 targets at once: 4,482 for states, 436 for congressional districts and 11,522 for counties. The targets come from official statistics, but not all of them equal a published figure: we age IRS dollar amounts to 2024, split each state's IRS totals of returns and adjusted gross income across its counties by the counties' shares in the IRS county data, and take every population target from 2020 Census block populations. A cap keeps each household's final weight at most five times its starting weight. A paper on this calibration method is in preparation. -The targets come from IRS Statistics of Income (county tax returns and adjusted gross income; state detail on income items, deductions and credits, by income band), USDA SNAP (state households and benefits, fiscal year 2024), CMS Medicaid enrollment (state, 2024), Census population (state, district and county) and ACS households (state and county). +The targets come from IRS Statistics of Income (county tax returns and adjusted gross income; state totals of income items, deductions, credits and tax; the earned income tax credit by number of children; taxable interest in nine income bands; and returns and adjusted gross income in four bands from $100,000 up), USDA SNAP (state households and benefits, fiscal year 2024), CMS Medicaid enrollment (state, December 2024), 2020 Census population (state, district and county) and ACS households (state and county). -To test the file, we held out 1,052 county targets, about one in ten, from the calibration. We also kept five ACS county tables out of the calibration completely: total earnings, households with earnings, total household income, the household income distribution, and median household income. +To test the file, we held out 1,052 county targets from the calibration, about one in ten. We held them out in whole groups, each one state's county targets for one measure, so that a state total cannot give a held-out county away. We also kept five ACS county tables out of the calibration completely: total earnings, households with earnings, total household income, the household income distribution, and median household income. ## How well the file fits -We measure each target's error as the difference between the file's estimate and the official value, divided by the official value. "Within 10%" means an error of 10% or less in either direction. +We measure each target's error as the difference between the file's estimate and the target, divided by the target. "Within 10%" means an error of 10% or less in either direction. ### States and the nation @@ -78,7 +77,7 @@ We measure each target's error as the difference between the file's estimate and | ACS households, by state | 51 | 94.1% | 4.2% | | Population, by congressional district | 436 | 92.2% | 0.58% | -National totals are the sum of the state estimates. Most national tax totals are within 4.5% of the official value. A few groups are further off: +National totals are the sum of the state estimates, compared with the sum of the state targets; no national target takes part in the calibration. Most national tax totals are within 4.5%. A few groups are further off: - tax returns with adjusted gross income of $1 million or more: 129% too high; - returns with capital gains: 32% too low; @@ -113,6 +112,8 @@ The file beats the baseline for county adjusted gross income, but not for counts ### Counties: ACS statistics never used in calibration +For these checks, a county's comparison value is the file's own state total, split across the state's counties in the published ACS county proportions. The checks therefore test how the file divides each state among its counties, not its state totals. The baseline splits the same state total by population. + | ACS county statistic | Median error: file | Median error: baseline | Counties where the file is closer | |---|---|---|---| | Total earnings | 19.3% | 28.8% | 61% | @@ -120,13 +121,13 @@ The file beats the baseline for county adjusted gross income, but not for counts | Households with earnings | 15.8% | 7.2% | 30% | | Household income distribution (16 brackets) | 101%¹ | 25%¹ | 0.4% | -The file also ranks counties better than the baseline by earnings per person and by household income per person. The rank correlation with the official values is 0.57 for the file against 0.37 for the baseline for earnings, and 0.68 against 0.46 for household income. For households with earnings, the two are about equal (0.28 and 0.27). Within a state, the population-share split cannot rank counties at all; there, the file's median rank correlation is 0.49 for earnings and 0.64 for household income. +The file also ranks counties better than the baseline by earnings per person and by household income per person. The rank correlation with the published ACS values is 0.57 for the file against 0.37 for the baseline for earnings, and 0.68 against 0.46 for household income. For households with earnings, the two are about equal (0.28 and 0.27). Within a state, the population-share split cannot rank counties at all; there, the file's median rank correlation is 0.49 for earnings and 0.64 for household income. The file's median household income is too high in most counties: in the median county it is 17% above the published ACS value. Its rank correlation with the published county medians is 0.30. ### Compared with the earlier state-and-district file -PolicyEngine's published 2024 state-and-district file did not have county targets. On the 4,459 targets that both files used, the share within 10% is almost the same: 97.0% before and 96.9% now. Adding the county targets did lower two things: congressional district population fell from 97.0% to 92.2% within 10%, and the national effective sample fell from about 12,100 to about 7,900. +PolicyEngine's published 2024 state-and-district file did not have county targets. On the 4,459 targets that both files used, the share within 10% is almost the same: 97.0% before and 96.9% now. Two things are lower in the county file: congressional district population fell from 97.0% to 92.2% within 10%, and the national effective sample fell from about 12,100 to about 7,900. The two files also differ in some of their other targets, so we cannot yet say how much of either change comes from the county targets. ## How reliable each county is @@ -138,9 +139,9 @@ Each county gets a provisional reliability grade from two measures: its effectiv | B | Effective sample at least 100, and largest error at most 20% | 3 | | C | Effective sample at least 30, and largest error at most 50% | 103 | | D | Lower than C, with test evidence | 3,038 | -| U | No test evidence | 0 | +| U | No test evidence, or no record of the survey household each record comes from | 0 | -The effective sample is the number of equally weighted households that would give the same precision as the county's actual weights. It is small in almost every county: +The effective sample is the number of equally weighted households that would give the same precision as the county's actual weights. It counts records that come from the same survey household once, and it leaves out group-quarters records. It is small in almost every county: - The median county's effective sample is about 6. The largest is about 146. - Only 167 counties reach an effective sample of 30. Together they hold 22.6% of the US population. @@ -152,7 +153,7 @@ Most D grades have both causes: 2,905 counties have an effective sample below 30 1. **Donor households carry most of the weight.** The 57,240 national donor households are 3.6% of the records, but they carry 77% of the household weight. Before calibration they carried half. In each county, a few of them hold most of the weight. 2. **Calibration concentrates the weight further.** After calibration, 1% of the household records hold 81% of the weight. Before calibration, they held 51%. -3. **The calibration gives most of its attention to state targets.** State and district targets make up 94% of the calibration's weighting, and county targets 6%. So the calibration fits state totals closely and county targets more loosely. +3. **The calibration gives most of its weight to state targets.** Before the solve, state and district targets make up 94% of the calibration's weighting and county targets 6%. At the final weights, county targets carry 27% of the remaining error. The fit is close for state totals and looser for counties. We have not yet tested other weightings. ## Limits: how to use the file @@ -168,14 +169,17 @@ Most D grades have both causes: 2,905 counties have an effective sample below 30 - distributions within a county, such as income brackets, poverty rates, or the share of households with earnings; - county median household income, which the file overstates; -- results for single small counties. Ten counties have only one or two household records. +- results for single small counties. Ten counties have only one or two households in housing units. **Other limits of this proof of concept:** -- **County assignment within a PUMA.** We assign ACS households to counties by population share within their PUMA. Many PUMAs, especially in rural areas, cover several counties. Inside such a PUMA, differences between counties come only from the calibration to county targets, not from the survey itself. +- **County assignment within a PUMA.** We draw each ACS household's county at random within its PUMA, by population share. Many PUMAs, especially in rural areas, cover several counties. Inside such a PUMA, the ACS does not say which county a household lives in: its counties differ only through the random draw, the donor households placed in them and the calibration to county targets. - **Donor households are national records.** They keep the county that PolicyEngine's national data gives them, and their characteristics come from national surveys, not from the county. - **The grades are provisional.** The grade rule will change as the method improves. -- **Temporary data shortcuts.** For this proof of concept, strike benefits are zero for every household, because no household in the source surveys reports them. S-corporation income is not separated from partnership income: the national data holds both as one combined partnership amount, so the separate S-corporation items are zero. +- **Temporary data shortcuts.** This proof of concept takes three: + - Strike benefits are zero for every household. No donor record reports them, and ACS households take the model's default of zero. + - S-corporation income is not separated from partnership income. The national data holds both as one combined partnership amount, so the separate S-corporation items are zero. + - We left out the 1,946 ACS group-quarters records of children under 15, which carry 0.04% of the ACS household weight. Each would form a poverty-measure unit with no adult, and one such unit stops the model version we use from computing poverty measures for the whole file. - **Model use.** The file loads with policyengine-us 2.2.1's standard dataset loader. On a computer with 32 GB of memory, the national simulation built in 90 seconds and used at most 18 GB, and it computed 2024 totals of population, employment income and adjusted gross income. For one state, the model also computed income tax, SNAP and household net income, with no missing values. We have not run full-model calculations, such as household net income, for the whole country at once. On a 32 GB computer, run them state by state or in chunks, or use a larger machine. The model ignores 254 extra columns: raw survey fields and build identifiers. - **One year only.** The file is for 2024. The 2026 and 2027 files are a stretch goal. @@ -184,7 +188,7 @@ Most D grades have both causes: 2,905 counties have an effective sample below 30 1. **Raise the effective sample in each county.** Spread each county's weight over more households, mainly by lowering the share of the weight that donor households carry. We will measure progress with the effective sample per county and the share of the population in counties at grade C or better. 2. **Balance the contribution of cloned records to the calibration.** Keep any single source household, together with its copies, from dominating the weights that the calibration chooses. 3. **Improve the calibration fit.** Give the county targets more weight, so that held-out county targets beat the population-share baseline, and fix the national tax outliers listed above. We will also bring district population back to its earlier fit. -4. **Complete the stretch goals.** Produce the 2026 and 2027 county files, the household measures and the schema manifest. +4. **Complete the stretch goals.** Produce the 2026 and 2027 county files and the household measures. 5. **Build the final County Files.** Rebuild from PolicyEngine's certified national data and remove the shortcuts this proof of concept uses. ## Appendix: file provenance @@ -197,12 +201,12 @@ Most D grades have both causes: 2,905 counties have an effective sample below 30 | Built | 17–18 November 2026 | | Code | Microcosm, commits `72b7072bf` (ACS staging) and `f8b1039f0` (calibration and packaging) | | Model | policyengine-us 2.2.1 | -| Checks | All 23 automated release checks passed. | +| Checks | The build ran 23 automated checks. All 17 that can stop the build passed. The other 6 record evidence. One of them, on congressional districts, flagged 275 of the 436 districts: their effective sample fell below a quarter of its value before calibration, or below 15. | | Loader test | On 18 November 2026, `Microsimulation(dataset=)` in policyengine-us 2.2.1 built the national simulation in 90 seconds, with a peak of 18 GB of memory | | Reliability files | `county_reliability.csv` and `county_reliability.json`, one record per county, with its grade, effective sample and errors | --- -¹ The income distribution error is the sum, over the 16 ACS income brackets, of the differences between the estimated and published numbers of households, divided by the county's number of households. When the estimated and published totals agree, an error of 100% means that half of the households fall in the wrong bracket. +¹ The income distribution error is the sum, over the 16 ACS income brackets, of the absolute differences between the file's number of households and the comparison value, divided by the sum of the county's comparison values. Each bracket's comparison value is the file's state total for that bracket, split across counties in the published ACS proportions. When the two totals agree, an error of 100% means that half of the households fall in the wrong bracket. -Sources: US Census Bureau, American Community Survey 2024 1-year public-use microdata and county tables B11001, B19001, B19013, B19025, B19051 and B19061; IRS Statistics of Income, state and county data; USDA Food and Nutrition Service, SNAP state participation and benefits, fiscal year 2024; CMS Medicaid enrollment, 2024; US Census Bureau population data; US Census Bureau and Bureau of Labor Statistics, Current Population Survey Annual Social and Economic Supplement, and the IRS Statistics of Income public-use file, both through PolicyEngine's national data. +Sources: US Census Bureau, American Community Survey 2024 1-year public-use microdata and 2020–2024 5-year county tables B11001, B19001, B19013, B19025, B19051 and B19061; US Census Bureau, 2020 Census block populations and the 2020 tract-to-PUMA and block-to-congressional-district files; IRS Statistics of Income, state, county and congressional district data and national totals (Publication 1304); Congressional Budget Office, revenue projections, February 2026; USDA Food and Nutrition Service, SNAP state participation and benefits, fiscal year 2024, and the SNAP participation rate; CMS, Medicaid and CHIP enrollment data, December 2024; Social Security Administration, SSI Monthly Statistics, December 2024; HHS Office of the Assistant Secretary for Planning and Evaluation, Welfare Indicators report; US Census Bureau, Survey of Income and Program Participation 2023 public-use file; Pew Research Center and the Higher Ed Immigration Portal; US Census Bureau and Bureau of Labor Statistics, Current Population Survey Annual Social and Economic Supplement 2023–2025, through PolicyEngine's national data and directly for three work columns; the IRS Statistics of Income public-use file (tax year 2015), through PolicyEngine's national data. The methods documentation gives each source's vintage and use. From 35e3863f620c3319ce574da81d73085efd078ae2 Mon Sep 17 00:00:00 2001 From: Max Ghenis Date: Thu, 19 Nov 2026 21:30:25 +0000 Subject: [PATCH 20/31] Add the schema manifest and methods document for the County Files PoC Adds, next to the PoC report, the three documents microcosm#1647 comment 7006535601 asks for: - schema_manifest.json, as tools/us_release_schema_manifest.py wrote it for the 2024 county file (SHA-256 82314a3b...bd3c); - schema_manifest.md, the tool's output with a notes section added at the top. The notes say that six household geography columns hold empty strings, not nulls, for all 1,529,668 ACS households (and for some donors, including every Connecticut donor's cbsa_code); which columns are raw CPS ASEC or ACS fields, build identifiers or derived columns, and which 198 policyengine-us 2.2.1 reads; and why three columns were removed and 134 dtypes changed; - lwi-poc-methods.md, part 1 of the methods draft as posted in #1647 comment 7005740491, without the comment's preamble. Part of #922. Co-Authored-By: Claude Opus 5.5 --- .../us-county-poc-20261117/lwi-poc-methods.md | 360 ++ .../schema_manifest.json | 3575 +++++++++++++++++ .../us-county-poc-20261117/schema_manifest.md | 798 ++++ 3 files changed, 4733 insertions(+) create mode 100644 experiments/us-county-poc-20261117/lwi-poc-methods.md create mode 100644 experiments/us-county-poc-20261117/schema_manifest.json create mode 100644 experiments/us-county-poc-20261117/schema_manifest.md diff --git a/experiments/us-county-poc-20261117/lwi-poc-methods.md b/experiments/us-county-poc-20261117/lwi-poc-methods.md new file mode 100644 index 0000000000..a6364c7f38 --- /dev/null +++ b/experiments/us-county-poc-20261117/lwi-poc-methods.md @@ -0,0 +1,360 @@ +# Methods: the 2024 county file + +This document describes how we built the 2024 county file for the County Files proof of concept (PoC), as the build ran on 17–18 November 2026. We ran the build at two commits of PolicyEngine's Microcosm code: + +- **Staging, at `72b7072bf`:** builds the household records from the American Community Survey (ACS) and a national donor file, gives each household a county, and imputes the inputs the ACS lacks. +- **The release build, at `f8b1039f0`:** runs seven stages in order. `fills` and `agi` check the staged file first: its blank inputs, and each county's households and income. `materialize` sets program take-up, moves nine ACS households into three counties that the county draws left empty, fills reviewed defaults, and builds the targets and the holdout. Take-up means whether an eligible person or household receives a benefit. `calibrate` sets the weights. `qa` runs PolicyEngine's tax-benefit model on the calibrated file. `finalize` and `package` write the release files and run the last checks. + +The PoC report gives the results. The run report on microcosm#1647 ([part 1](https://github.com/PolicyEngine/microcosm/issues/1647#issuecomment-6982547034) and [part 2](https://github.com/PolicyEngine/microcosm/issues/1647#issuecomment-6982549060)) gives the commands, environments and file digests, and the [schema manifest](https://github.com/PolicyEngine/microcosm/issues/1647#issuecomment-6990728184) lists the file's tables and columns. We have not yet produced the 2026 and 2027 files or the household measures the agreement lists (earnings, gross income and net income for each household), so this document covers neither. + +## Data sources and years + +We built the 2024 county file from two sets of household records and from published statistics, with PolicyEngine's US tax-benefit model. We list each source at the vintage the build read on 17–18 November 2026. The run files record the SHA-256 digests of the input files, among them the target feed `consumer_facts_us_41b2fb2.jsonl` (`1d45a89c…`) and the county facts `consumer_facts_us_county_3e9d3a0.jsonl` (`67b0998a…`) (run report, part 2, section 11). + +| Source | Vintage | What the build uses it for | +|---|---|---| +| ACS public-use microdata, household and person files | 2024 1-year | 1,529,668 ACS household records with 3,420,942 people. Of these, 181,260 are group-quarters records: one person each, living in a place such as a nursing home or college dormitory rather than a housing unit, and counting as a household of one. These counts come after staging drops group-quarters records of children under 15 (see "What we impute onto ACS households, and from which donors") | +| PolicyEngine's national donor file, release `populace-us-2024-spm-receipts-20260923`, in a copy we patched | See "Donor households" below the table | 57,240 donor household records with 166,321 person records; we train the imputation on their person records, tax units (the people on one tax return) and SPM units (the family unit of the Supplemental Poverty Measure) | +| Current Population Survey Annual Social and Economic Supplement (CPS ASEC), person files `pppub23`–`pppub25` | Survey years 2023–2025 (income years 2022–2024) | The donor households' survey records; three work columns our patch adds | +| Internal Revenue Service (IRS) Statistics of Income (SOI) public-use file (PUF), in PolicyEngine's processed version 1.8.0 | Tax year 2015, scaled forward to 2024 | An input of the donor file's national build, as that build's records name it; we did not trace what the donor records take from it | +| Census 2020 tract-to-PUMA (Public Use Microdata Area) relationship file; 2020 Census redistricting (P.L. 94-171) block populations; the Census file of each block's 119th Congress district | 2020 Census; 119th Congress districts | The PUMA ladder (see "Population" below): the county and district draws within each PUMA, and every population target | +| SOI Historic Table 2, state data | Tax year 2022; tax year 2023 for 408 rows | 4,227 state tax targets, and the state totals we split into county tax targets | +| SOI county file (`22incyallnoagi.csv`) | Tax year 2022 | Each county's share of the sum of its state's county rows, for returns and for adjusted gross income (AGI). Each of the two has 3,143 county targets (Kalawao and Maui share one); we hold out 441 return targets and 297 AGI targets and train on the rest | +| SOI national totals: Publication 1304 Tables 1.1, 1.4 and 4.3; the SOI congressional district file `22incd.csv` | Tax years 2022 and 2023; see "Tax targets" for the district file | Growth from 2022 to 2023, for aging SOI dollar amounts; national totals for rescaling some state rows | +| Congressional Budget Office (CBO) revenue projections by income source | February 2026 | Growth from 2023 to 2024, for aging SOI dollar amounts | +| US Department of Agriculture (USDA), Supplemental Nutrition Assistance Program (SNAP) state participation and benefits | Fiscal year 2024 | 102 state targets | +| Centers for Medicare & Medicaid Services (CMS), state Medicaid enrollment from its Medicaid and Children's Health Insurance Program (CHIP) enrollment data, April 2026 release | December 2024 (Rhode Island: November 2024) | 51 state targets; Medicaid take-up on ACS households | +| ACS county table B11001 (households) | 2020–2024 5-year | 51 state household targets, and 3,144 county household targets, of which we train on 2,830 and hold out 314 | +| ACS county tables B19061, B19051, B19025 and B19001; B19013 (median household income) | 2020–2024 5-year | Checks that never enter calibration; B19013 serves only as a diagnostic | +| Social Security Administration (SSA), Supplemental Security Income (SSI) Monthly Statistics, Table 1 | December 2024 | SSI take-up on ACS households | +| Census Survey of Income and Program Participation (SIPP) public-use file | 2023 file | SSI disability status on ACS households | +| Pew Research Center; Higher Ed Immigration Portal | Pages published July 2024 and March 2021 | National counts that set immigration status on ACS households | +| USDA SNAP participation rate; the Department of Health and Human Services (HHS) Office of the Assistant Secretary for Planning and Evaluation (ASPE) take-up rate for Temporary Assistance for Needy Families (TANF), from its 24th Welfare Indicators report | The run records no year | SNAP and TANF take-up on ACS households | +| policyengine-us; policyengine-core | 2.2.1; 3.32.5 | The model the build ran; the release manifest records both versions | + +**Donor households.** Donor households are survey households from PolicyEngine's national donor file. We add them to the ACS households and train the imputation on their person records, tax units and SPM units. The file comes from three releases in the public Hugging Face dataset `policyengine/populace-us`: a national build and two later releases that add columns to it. + +- The national build, `populace-us-2024-buildp-sparse-rmloss100-cae8640-20260728T011454Z` of 28 July 2026, chose 57,240 household records from 337,704 candidates. Its records name its inputs as the CPS ASEC for income years 2022–2024 and PolicyEngine's processed PUF, version 1.8.0. In that build's code, version 1.8.0 is the 2015 public-use file, scaled forward to 2024. +- Release `populace-us-2024-spm-20260915` added an SPM role flag. Release `populace-us-2024-spm-receipts-20260923` added reported receipt of SNAP, TANF and WIC (the Special Supplemental Nutrition Program for Women, Infants, and Children). Both drew on the same ASEC person files, and neither changed an existing column. + +For this PoC we patched a copy of the last release. We added two industry columns and a worked-last-year column from the ASEC person files. We also added two columns that hold only zeros: strike benefits, and passive partnership and S-corporation income. We kept every household and person record. + +**Population.** A PUMA is the smallest area the ACS microdata identifies. The PUMA ladder is a table of each 2020 PUMA's population, summed from 2020 Census block populations and split across census tracts, counties and congressional districts. For the county targets, we group the tracts by their 2023 county code; under those codes, Connecticut's tracts fall into its nine planning regions. We then scale each state's counties to the state's PUMA total. Every population target comes from this ladder, so states, districts and counties each sum to 331,449,281, the ladder's total of 2020 Census block populations. The county facts file also holds the Census Bureau's 2024 county population estimates and ACS table B01003 (total population); no target or check uses either. + +**Tax targets.** Most state tax targets come from tax year 2022: + +- 2,397 totals across all income levels, for income items, deductions, credits, tax, returns and AGI; +- 510 earned income tax credit (EITC) rows, in total and by number of children; +- 912 rows of taxable interest, amount and returns, in nine AGI bands. + +The other 408 come from tax year 2023: returns and AGI in the four AGI bands from $100,000 up. + +Before aging, we rescale some rows across tax years. Each 2023 AGI-band row keeps its share of its state's 2023 total, applied to the state's 2022 total of returns or AGI. We scale other 2022 rows to an SOI national total for tax year 2023: taxable interest (1,014 rows, in total and by AGI band) and net capital gains (102 rows, amount and returns). For the 51 net capital gains return rows, that total comes from the SOI congressional district file `22incd.csv`. In the target feed, that file carries the label tax year 2023 but the title "Congressional District Data 2022", so we could not pin its tax year. + +We then age every SOI dollar amount to 2024 with national growth. A dollar row that we rescaled to a 2023 national total ages from 2023; every other dollar row ages from 2022. SOI's national totals for 2022 and 2023 give the growth from 2022 to 2023, and CBO's February 2026 projections give the growth from 2023 to 2024. Most dollar amounts grow with total AGI; wages and net capital gains grow with their own series. We do not age counts. + +We split two state totals into county tax targets: returns, and AGI after aging. Each county's target equals its state's total times the county's share of the sum of its state's county rows in the 2022 SOI county file. The 2022 SOI county file and the ACS 2020–2024 county tables both already list Connecticut by its nine planning regions (09110 to 09190), so the build uses their rows as published, with no crosswalk. The SOI county file has no row for Kalawao County, Hawaii. The build's code cites the IRS guide to the county file, which says the IRS leaves out items with fewer than 20 returns for a county. Kalawao shares one cell with Maui County for these two targets. Apart from that cell, the build stops unless each state's county rows in the SOI county file and in ACS table B11001 match the 2023 counties of the population targets one for one. + +**Program targets.** The SNAP targets are each state's average monthly households and total benefits in fiscal year 2024. The Medicaid targets are each state's total Medicaid enrollment in December 2024. CMS reports Rhode Island's December 2024 enrollment as zero, with a footnote that the state could not provide the data, so we use Rhode Island's November 2024 figure (273,400). + +**ACS county tables.** These 5-year estimates cover survey responses from 2020 through 2024, with dollar amounts in 2024 inflation-adjusted dollars. Each county's household target equals its published B11001 estimate, and each state's household target equals the sum of its counties' estimates. + +## How households get their counties + +The 2024 county file holds 1,529,668 household records from the 2024 ACS 1-year public-use microdata and 57,240 national donor household records. Of the ACS records, 181,260 are group-quarters records, each for one person. These counts come after staging drops 1,946 group-quarters records of children under 15 (see "What we impute onto ACS households, and from which donors"). The two kinds of household get their geography in different ways. + +### ACS households + +Each ACS household record carries its state and its PUMA. We keep both. A PUMA can span several counties and congressional districts, so we assign those from the PUMA ladder (see "Population" under "Data sources and years"). + +We built the ladder from 2020 Census block populations (the P.L. 94-171 redistricting file) and the Census file of each block's congressional district. Blocks nest in tracts, and each 2020 tract lies in one 2020 PUMA. Summing block populations therefore gives the number of people each PUMA shares with each 2020 county and with each district. We call that number the population overlap. Of the ladder's 2,462 PUMAs, 610 overlap more than one county and 1,276 overlap more than one district. + +Within its PUMA, each ACS household gets a district from one random draw, with odds proportional to the PUMA's population overlap with each district. It gets a county from a separate draw, with odds proportional to the PUMA's population overlap with each county. One random-number generator with a fixed seed (0) makes every draw. With the same inputs, row order and software versions, the code makes the same draws; we did not rebuild to check. Each household gets one district and one county and keeps its whole weight: the draw does not split a household across counties. + +The draws use only the PUMA's population overlaps, not the household's survey answers, and the district draw does not depend on the county draw. The code checks only that the PUMA, district and county lie in the household's state. We found no check that a household's district and county overlap. + +Staging gives ACS households no tract or block. In the file, the tract and block columns hold empty values for every ACS household. + +The file carries two county codes. `county_fips` holds 2020 counties, which divide Connecticut into its eight former counties. `county_fips_2023` holds 2023 county-equivalents, which divide Connecticut into its nine planning regions (09110 to 09190). The county targets and the minimum-support step below use `county_fips_2023`. Outside Connecticut the two codes agree. For a Connecticut ACS household, staging also draws a 2020 tract within the household's PUMA and the county it drew, again by population, and records that tract's planning region. It does not keep the tract. + +### Donor households + +Donor households keep the district, county, tract and block stored in the donor file. Staging checks that each stored district and county lies in the household's state and that the county matches the tract's county. It sets the household's PUMA from the tract and takes `county_fips_2023` from the tract. + +We made the donor file from a copy of PolicyEngine's national release `populace-us-2024-spm-receipts-20260923`: for the PoC, we added person columns and left the household table as it was. In that release we added three variables, and in the release it came from, `populace-us-2024-spm-20260915`, we added one; none of the four is a household variable. By the two releases' published records, we left every existing column unchanged in both, so the stored geography predates both. We could not establish how the donor households got their districts, counties and tracts. + +### Counties without households + +Staging draws each ACS household's county at random and sets no minimum number of households per county. After the draws, three counties had no household of any kind: Kalawao County, Hawaii (15005), Blaine County, Nebraska (31009) and Loving County, Texas (48301). The 2020 Census counted 82, 431 and 64 residents in them. Before calibration, the `materialize` stage runs a minimum-support step. In this run, the step moved three households into each of the three counties. Its rules: + +- It applies only to a county with residents in the ladder and no supporting household. Every household supports its county except ACS group-quarters records. A county with one or two supporting households does not qualify. +- It looks for movers first in the PUMA that shares the most people with the county, then in the next. +- A mover must be a supporting household with no stored tract or block, so donor households never move. Its two county codes must agree, and its own county must keep at least three supporting households. +- It ranks candidates by a hash of a fixed key (`acs-local-county-support-v1`), the destination county and the household ID, so row order does not matter. It moves the top three, or none if fewer than three qualify. +- A move rewrites the two county codes and nothing else. The household keeps its state, PUMA, weight and the district it drew. + +The `materialize` stage records each move in `county_support.json`. When the `calibrate` stage writes the calibrated file, it reloads the staged file and applies the same recorded moves again. + +Each county took its three households from its one overlapping PUMA: + +| County | PUMA | Moved from (county: households) | +|---|---|---| +| 15005 Kalawao, HI | 1500100 | 15007: 1; 15009: 2 | +| 31009 Blaine, NE | 3100300 | 31079: 2; 31081: 1 | +| 48301 Loving, TX | 4807300 | 48165: 1; 48377: 1; 48389: 1 | + +All nine are ACS households. After the step, all 3,144 counties have at least one supporting household: 1,405,648 in all, with a median of 144 per county and 35,707 in the largest county. Ten counties have only one or two, and the step does not apply to them. Counting every household record, group quarters included (1,586,908), the median county has 165 records, the largest has 39,788, and six counties have one or two. + +## What we impute onto ACS households, and from which donors + +Staging loads 1,531,614 household records with 3,422,888 people from the 2024 ACS 1-year public-use file; it skips the file's 100,355 vacant housing units. Before it imputes anything, it drops the 1,946 group-quarters records of children under 15. These records carry 0.04% of the ACS household weight, and the build records the drop as an interim exclusion. The build's recorded reason: each such child forms a one-person SPM unit with no adult. The PolicyEngine model version the build ran measures every SPM unit, so a single such unit makes it refuse every SPM measurement on the file. + +That leaves 1,529,668 household records with 3,420,942 people. Of these, 181,260 are group-quarters records of one person each. The ACS records each person's age, sex, wages, self-employment income, reported SSI, disabilities, work hours, industry and occupation, and each household's tenure and property tax. PolicyEngine's model needs many more inputs, such as income by tax type, deductions, health coverage and program receipt. + +We fill most of the missing inputs from PolicyEngine's national donor file: 57,240 household records with 166,321 person records. Staging runs the imputation. The release build's `materialize` stage then sets program take-up and gives the remaining blanks the model's default values. + +### Method + +We use quantile regression forests in Microcosm's own form, with sign classifiers, chained draws and donor weights. A quantile regression forest predicts the whole distribution of a value, not only its average. Staging runs three imputation passes in order. The first imputes usual weekly hours. The second imputes child support, retirement-account distributions, and work and disability income. The third imputes everything else. In each pass: + +- **Training records.** Donor person records, tax units or SPM units. The first two passes train on the donors' ASEC person records and the third on their tax-detail copies (both defined below). Each forest resamples the donors in proportion to their weights in the donor file. The sign classifier below uses the same weights directly. +- **Predictors.** Age, sex and state, plus, where the ACS record has them, wages, self-employment income, Social Security, retirement income, interest, dividend and rental income, household-head status and housing tenure. Tax-unit and SPM-unit fits use the unit's number of people, of women and of household heads, its summed ages, state, housing tenure and summed incomes. Each pattern of available predictors gets its own fit, on donors that have those predictors and all of the family's columns, so the build never reads a blank as a zero. +- **Second-pass predictors.** For child support, the second pass adds the ACS's "all other income" amount. For retirement-account distributions and for work and disability income, it swaps the donors' retirement-income measure for one closer to the ACS's definition. +- **Joint within a family.** In this run, each family holds at most eight columns. The build splits a wider group of columns into batches, and each batch counts as its own family (the `__batch_1`, `__batch_2` names in the table below). The forests draw a family's columns in sequence, each conditioned on the predictors and on the columns already drawn. One family's draws do not enter another family's fit. For example, the forests draw the 54 person-level tax columns jointly only within each of their seven batches. +- **Random draws.** For each amount, a classifier picks the sign (negative, zero or positive), and the forest returns a value at a random quantile. The draws therefore follow the donors' distribution rather than an average. The run seed, 0, combined with each family's name and pattern of predictors, fixes every draw. Each forest in these passes has 32 trees. +- **Blanks only.** The forests fill only blank cells. Where the ACS reports a model input, its value stays as it is. Where the ACS reports only a combined amount, the build uses that amount as a predictor and draws the model's inputs from donors (next paragraph). +- **Weights unchanged.** Imputation passes the ACS household weights through unchanged. After imputation, staging pools the ACS and donor records and gives each group half of the donor file's household weight, 61.27 million each, before calibration. + +The ACS reports Social Security, retirement income, and interest, dividend and rental income as one amount each per person. The build uses these amounts only as predictors. The model's inputs for these items, such as Social Security by type, pensions, individual retirement account (IRA) distributions, interest and dividends by tax treatment, and rent received, come from donor draws. No build step makes the draws add up to the ACS amount. + +### What the run imputed + +In the table below, "ASEC" and "PUF" name the two roles a donor person record can hold. An "ASEC" record holds a person as the CPS ASEC recorded them. A "PUF" record holds a tax-detail copy of such a person; the build code names this role `puf_tax_detail`. We did not trace how the donor file made these copies (see "Data sources and years" for the donor build's inputs). + +The staging summary records 101 imputed columns in 25 families: + +| What staging imputes (family) | Columns | Unit | ACS records filled | Donor records trained on | +|---|---:|---|---:|---:| +| Usual weekly hours (`source_operator_hours_worked`) | 1 | person | 39,800 | 50,490 ASEC | +| Child support received and paid (`acs_local_child_support`) | 2 | person | 3,420,942 | 66,001 ASEC | +| Retirement-account distributions: 401(k), 403(b), simplified employee pension (SEP), Keogh and Roth IRA (`acs_local_retirement_distributions`) | 5 | person | 3,420,942 | 66,001 ASEC | +| Workers' compensation and disability benefits (`acs_local_work_disability_income`) | 2 | person | 3,420,942 | 66,001 ASEC | +| Interest, dividends, capital gains, pensions, Social Security by type, and business and deduction items (`puf_tax_itemization__batch_1` to `_7`) | 54 | person | 3,420,942 | 100,320 PUF | +| Mortgage, health savings account deduction and two other tax items (`puf_tax_itemization`) | 6 | tax unit | 2,095,799 | 48,755 PUF | +| Health coverage, full-time student, pregnancy and WIC (`model_required_boolean__batch_1` to `_4`) | 12 | person | 3,420,942 | 100,320 PUF | +| Assets, medical costs, tax-exempt pensions, unemployment and veterans' benefits, and hours last week (`model_required_numeric__batch_1` to `_2`) | 10 | person | 3,420,942 | 100,320 PUF | +| Own children in household (`model_required_discrete`) | 1 | person | 3,420,942 | 100,320 PUF | +| Care need and adult-care spending (`adult_care`) | 2 | person | 3,420,942 | 100,320 PUF | +| Pre-subsidy rent (`housing`) | 1 | person | 3,239,682 (all but the 181,260 in group quarters) | 100,320 PUF | +| SNAP and TANF receipt, housing assistance take-up and childcare costs (`model_required_boolean`, `benefit_participation`, `model_required_numeric`) | 4 | SPM unit | 1,529,668 | 36,614 PUF | +| Capital gain distributions, a fixed share of imputed long-term gains, with no forest (`capital_gain_details`) | 1 | person | 3,420,942 | none | + +Three rules limit or replace forest draws: + +- **Pregnancy.** Only women aged 15 to 44 get a forest draw (603,628 people). The build sets everyone else to not pregnant (2,817,314 people). +- **Adult care.** The build keeps adult-care spending only on people who qualify, at most one per tax unit. It removed the spending of 12,926 people who did not qualify and of 40 extra people in a tax unit; 6,348 people keep it. +- **SNAP receipt.** The ACS household's own answer replaces the forest's draw on every ACS SPM unit (see "Take-up and other assigned values"). + +### Self-employment, partnership and S-corporation income + +The ACS reports one self-employment amount per person (SEMP). The 2024 ACS subject definitions, as the build code cites them, count farm income and income from a person's own partnership in SEMP, but not profit from an incorporated business. So: + +- We keep each person's ACS self-employment amount. The forests still draw its three parts (farm operations, partnership self-employment earnings and specified-service business income). The build then sets all three to zero for all 3,420,942 ACS people. Of those draws, 44,478, 73,164 and 114,327 had a nonzero value. A gate, one of the build's automated checks (see "Automated gates"), found no ACS person whose self-employment differs by more than $1 from SEMP in 2024 dollars. +- The build sets partnership-income draws to zero for three groups. The first is people who report nonzero SEMP (171,732). The second is a head or spouse whose tax-unit partner reports nonzero SEMP (84,177). The 2024 ACS form asks people to report jointly received income under one person (item 43, as the code cites it). The third is people with blank SEMP, all aged under 15 (508,152). That removed 16,571 nonzero draws. At the ACS's own household weights, before pooling rescales them, they came to $159.4 billion of income and $13.9 billion of losses. Partnership income stays nonzero on 139,930 ACS records. +- S-corporation income and passive partnership and S-corporation income stay zero on every ACS and donor record. Both columns hold only zeros in the donor file, so the forests have nothing to learn from and draw zero. S-corporation income comes unchanged from the published donor file; our patch added the passive column (see "What donor records carry"). The recorded reason for both: the donor file holds partnership and S-corporation income as one combined partnership amount, with no record of the split. +- A staging check refuses any donor column that the third pass reads and that holds only default values, unless the staging command lists it. The command listed these two columns. Strike benefits, which also hold only zeros in the donor file, needed no listing, because the third pass does not read them. + +### Take-up and other assigned values + +Rules, seeded draws and other models set these values on ACS records. One of them, housing assistance receipt, copies a forest draw. + +**Staging:** + +- **SNAP receipt.** The ACS household's answer to the food stamp question replaces the forest's draw on every ACS SPM unit. It sets 137,941 units to true and the other 1,210,467 housing units to false. The 181,260 people in group quarters get false. +- **SSI disability criteria.** An archived quantile regression forest, trained on the 2023 SIPP with 100 trees and 9,346 training records, runs on ACS people. The code describes it as the donor file's own SSI model. ACS people under 65 who report SSI meet the criteria. In all, 303,302 ACS people meet them. +- **Immigration status.** The build reads ACS citizenship and exact year of entry. It maps other ACS fields, such as place of birth, health coverage at interview, class of worker, and Social Security and SSI receipt, onto the ASEC's legal-status indicators. Seeded draws then aim at national counts of undocumented workers (8.3 million, Pew Research Center) and undocumented students (408,000, Higher Ed Immigration Portal), minus what the donor records already carry. +- **Usual weekly hours.** 547,952 ACS people lacked them. The build gives the 508,152 children under 15 zero hours, and the forest imputes the other 39,800. + +**The release build's `materialize` stage, before calibration:** + +- **SNAP take-up.** The flag means a unit would take up SNAP if eligible; PolicyEngine's model decides eligibility. Units that report SNAP get the flag. Other units draw it at 79.8%, so that 82% of ACS SPM units, by weight, carry it: USDA's national SNAP participation rate. +- **TANF take-up.** Units draw the flag at 21.9%, the rate in HHS's 24th Welfare Indicators report. The draw ignores imputed TANF receipt: 10,559 of the 13,536 ACS units with imputed TANF receipt drew no take-up. +- **SSI and Medicaid take-up.** PolicyEngine's model first runs on the donor and ACS households to find who could get SSI or Medicaid. ACS people who report SSI then take up SSI, and people with ACS Medicaid or other means-tested coverage take up Medicaid. The rest draw toward SSA counts by age band and CMS enrollment counts by state, minus what the donor records already carry. The run's take-up file (`acs_local_ssi_medicaid_take_up.npz`) records the flags: 1,835,876 ACS people take up SSI if eligible, and 3,359,039 take up Medicaid if eligible. The model applies eligibility. +- **Other flags.** Medicare take-up follows ACS Medicare coverage. Children aged 3 to 5 draw Head Start take-up at the donor records' weighted take-up share, 4.9%. Housing assistance receipt copies the imputed housing-assistance take-up, a forest draw, and stays false in group quarters. Adults aged 18 to 64 draw an exemption from SNAP's work time limit at 8%, the statutory cap. + +When the `calibrate` stage writes the calibrated file, it applies these assignments again and stops if they differ from the ones the `materialize` stage recorded. + +### Reviewed null fills + +After these steps, 58 model inputs still have blank cells: 143,641,752 on ACS records, and 166,321 on donor records (every donor person record's reported SSI). The build writes the model's own default value into each of these 143,808,073 blanks. A reviewed list of 66 model inputs governs this step. Its other 8 entries cover the release build's assignments above: six take-up flags, housing assistance receipt and the SNAP work time limit exemption. The calibrated file stores these defaults. For example, every ACS person gets zero strike benefits, tips and hourly wage, no Hispanic flag, race code 0 and no self-employed flag. Every ACS household gets zero net worth, and every ACS tax unit takes up the EITC. A blank model input missing from the list stops the build. + +### What donor records carry + +The donor file's 166,321 person records come from the CPS ASEC for income years 2022, 2023 and 2024 (54,464, 54,654 and 57,203 records). Of these, 66,001 are ASEC person records and 100,320 are tax-detail copies. They hold 135,833 distinct people, each counted once per income year: 30,488 people appear twice, once in each role. In the county file, the 57,240 donor household records hold 47,277 distinct source households (see "Copies" under "The reliability grade"). + +For this PoC we used a patched copy of PolicyEngine's published donor file. The patch added three ASEC work columns (detailed industry, major industry and whether the person worked last year). It matched each of the 166,321 donor person records to its ASEC record exactly once, with no identity mismatches. It re-derived eight existing columns and found them equal on every record. It also added strike benefits and passive partnership and S-corporation income as zeros, and changed no column the published file already held. The patch tool's code gives a fixed reason for strike benefits: no donor record, and no record in the ASEC person files for survey years 2023 to 2026, reports them. The patch run itself read only the files for survey years 2023 to 2025, for the work columns. + +## Calibration: the targets, how we weight them, and the weight cap + +Calibration sets each household record's weight: the number of US households (for a group-quarters record, people) that the record stands for. Each record starts from its design weight (see "Design weights and the solver"). The `calibrate` stage then moves the 1,586,908 weights so that the file's totals come close to 16,440 targets: 4,482 for states, 436 for congressional districts and 11,522 for counties. No national target takes part. + +Only some targets equal published figures. The state SNAP and Medicaid targets equal published state figures. The state SOI targets start from published state tables; we age SOI dollar amounts to 2024 and rescale some rows across tax years (see "Tax targets" under "Data sources and years"). Each county ACS household target equals the county's published B11001 estimate, and each state household target equals the sum of its counties' estimates. Each county SOI target splits a state target by the county's share in the SOI county file. It matches the county's own figure in that file only where the state target matches the sum of the state's county rows. In this run that holds for the county return counts of Utah (29 trained targets) and Vermont (14 held-out targets). Every population target, at every level, comes from the PUMA ladder. + +### The targets + +| Targets | Level | Trained | Held out | Source | +|---|---|---:|---:|---| +| SOI, all returns: the return count, AGI, and 45 return counts and dollar amounts for 23 income, deduction, credit and tax items | State | 2,397 | 0 | SOI Historic Table 2, tax year 2022 | +| SOI taxable interest: returns and dollars in 9 AGI bands | State | 912 | 0 | SOI Historic Table 2, tax year 2022 (the band under $1 has no row for 3 states) | +| SOI EITC: claims and dollars, in total and by number of children | State | 510 | 0 | SOI Historic Table 2, tax year 2022 | +| SOI return count and AGI in four AGI bands from $100,000 up | State | 408 | 0 | SOI Historic Table 2, tax year 2023 | +| SNAP: average monthly households and total benefits | State | 102 | 0 | USDA, fiscal year 2024 | +| Medicaid enrollment | State | 51 | 0 | CMS, December 2024 (Rhode Island: November 2024) | +| ACS households | State | 51 | 0 | Sum of the state's county estimates from ACS 2020–2024 5-year table B11001 | +| Population | State; district; county | 51; 436; 3,144 | 0 | The PUMA ladder | +| SOI return count; SOI AGI | County | 2,702; 2,846 | 441; 297 | SOI Historic Table 2 state totals, tax year 2022, split by shares from the SOI county file (`22incyallnoagi.csv`), tax year 2022 | +| ACS households | County | 2,830 | 314 | ACS 2020–2024 5-year table B11001 county estimates | +| **All** | | **16,440** | **1,052** | | + +**County targets.** Each county target splits a state target in proportion to a county figure: + +```text +county target = state target × county figure ÷ sum of the county figures in the state +``` + +- **SOI:** the state target is the state's all-returns count for tax year 2022, or its tax year 2022 AGI aged to 2024. The county figures come from the SOI county file (`22incyallnoagi.csv`), also tax year 2022. +- **ACS households:** the state target is the sum of the state's county estimates, so each county target equals the county's own published estimate. When the build counts the file's households for these targets, it leaves out ACS group-quarters records. +- **Population:** for each county, we add up the population it shares with each PUMA in the PUMA ladder. We then scale the state's counties so that they add up to the state's ladder population. + +So each concept's county targets add up to their state target; the largest county takes any rounding remainder. + +The SOI county file has no row for Kalawao County, Hawaii (15005), and neither does the county facts file the run read. The build's code cites the IRS guide to the county file, which says the IRS leaves out items with fewer than 20 returns for a county. For the two SOI concepts, one target covers Kalawao and Maui (15009) together, with Maui's published share. Kalawao keeps its own population and household targets. + +The run dropped no target. It passed `--county-drop-empty-soi-rows`, which drops a county SOI target when every household in that county has a zero value for it; no target met that rule. + +### How we weight the targets + +For each target, the solver computes a scaled error: (estimate − target) ÷ max(|target|, 1). Every trained target's value is 27 or more, so the scaled error equals the relative error. The loss is the weighted average of the absolute scaled errors, with each one capped at 10 (an error of 1,000%). One cap covers every target at every level. At the design weights, 20 targets had an error over 10; at the final weights, 9 did. + +A target's loss weight sets how much its error counts in that average. It comes from five steps: + +1. Each target is a count (people, households, returns, enrollees) or a dollar amount. +2. Its base weight is the square root of its value, divided by the average square root over targets of the same kind. A larger target weighs more, but less than in proportion to its size. +3. Some targets share a budget. The county targets of one concept in one state together weigh as much as the largest of them alone. The district population targets of one state share a budget the same way. Each state target has its own budget. +4. Counts and dollar amounts each get half of the total weight. +5. The code rescales the weights to an average of 1. No group of targets got an extra multiplier in this run. + +Two shares describe each group of targets. Its loss weight share is its share of the summed loss weights, which the build fixes before the solve. Its realized loss share is its share of the loss at the final weights, where the loss comes to 0.0159: + +| Targets | Loss weight share | Realized loss share | +|---|---:|---:| +| State SOI | 83.50% | 64.08% | +| All state and district targets, state SOI included | 94.01% | 72.91% | +| All county targets | 5.99% | 27.09% | + +### Design weights and the solver + +The solve starts from the design weights. Staging builds them when it pools the ACS and donor records. It takes each ACS household's housing-unit weight (WGTP; a group-quarters record takes its person weight) and each donor household's weight in the donor file. It then scales each group to half of the donor file's household weight total: 61.27 million each, 122.5 million in all. These scaled weights are the design weights. The solve keeps their total fixed. The weight cap, every weight ratio below and the loss at the design weights all use them. + +The solver, Adam (a standard gradient method), works on the logarithm of each weight, so every weight stays positive. It takes 800 steps at a learning rate of 0.02, in two runs of 400 steps, with seed 0. Each step uses every trained target and every household record. The second run starts from the first run's weights, with a fresh optimizer state. No penalty pulls weights toward their design values. The file keeps the weights from the last step. + +The loss comes to 0.173 at the design weights, 0.0208 after the first 400 steps and 0.0159 after all 800. The run files record an `initial_loss` of 0.020786: the loss at the start of the second run, not at the design weights. + +### The weight cap + +No household record's final weight may exceed 5 times its design weight (`--county-max-weight-ratio 5`). A donor household's design weight equals exactly half its weight in the donor file, so its limit equals 2.5 times that weight. The cap acts on each record as a hard limit, not a penalty. After every step, the solver lowers any weight over its limit to the limit. It then rescales all weights by one factor to the fixed total and applies the limit again. Both runs measure the limit against the design weights. + +A rescale factor below 1 leaves the records at the limit under it, at 5 times the factor. The largest final ratio is 4.9297, not 5, and 44,083 records end within 0.01% of it. So the last step's factor came to about 0.986 (4.9297 ÷ 5). The cap has no lower counterpart: 1,246,252 records (78.5% of 1,586,908) end with less than 1% of their design weight. + +### The holdout + +We hold out county targets in whole holdout groups. A holdout group covers one state's county targets for one concept: SOI returns, SOI AGI or ACS households. The 153 holdout groups cover 9,430 county targets. For each group, the build hashes the group's name with a fixed key, `acs-local-county-v1`, using SHA-256, and turns the result into a number from 0 to 1. It leaves the group out of the solve when that number falls under 0.1 (`--county-holdout-fraction 0.1`). The draw depends only on the group's name and the key, never on the other groups. County population targets belong to no holdout group and always train. + +The code gives its reason for holding out whole groups: "to prevent sibling leakage". A group's county targets add up to its state target, which trains. If the group's other counties trained, the state target minus their sum would give away the held-out county. + +The run held out 18 of the 153 holdout groups: 1,052 of the 9,430 eligible county targets (11.2%), or 8.4% of all 12,574 county targets. The 1,052 break down into 441 SOI return-count targets, 297 SOI AGI targets and 314 ACS household targets. The run held out no state or district target. + +The solver never sees a held-out target; after the solve, the build scores them (see "How we test the file"). The ACS county tables for earnings and income (B19061, B19051, B19025 and B19001) and for median household income (B19013) never enter the loss either. After calibration, the build scores the first four as checks and reports B19013 as a diagnostic only. + +## How we test the file + +We test the 2024 county file in four ways: county targets held out of the calibration, ACS county tables the calibration never uses, a reliability grade for each county, and 23 gates. For the results, see the PoC report. + +### Held-out county targets + +We hold county targets out of the calibration in whole holdout groups. We give the rule under "The holdout" in the calibration section. This run held out 18 of the 153 holdout groups: 1,052 of the 9,430 eligible county targets (441 SOI return counts, 297 SOI AGI and 314 ACS households). County population targets belong to no holdout group, and the run held out no state or district target, so all of these trained. + +For each held-out target, the error is |estimate − target| / max(|target|, 1), where the estimate is the file's weighted total for that county and concept. A target counts as within 10% when its error is 0.10 or less. We compare the file with a pro-rata baseline: the state target times the county's share of the state's population in the PUMA ladder. The build also scores the design weights the same way. + +### ACS county tables the calibration never uses + +Four ACS 2020–2024 5-year county tables never enter the calibration's targets, its loss or its weights: + +- B19061: aggregate household earnings; +- B19051: households with earnings; +- B19025: aggregate household income; +- B19001: households in 16 income brackets. + +After calibration, we score all four tables in all 3,144 counties. We also compare each county's weighted median household income in the file with ACS table B19013. That comparison serves as a diagnostic only and never enters a grade. + +These checks test how the file splits each state's total among its counties. Each county's target splits the file's own state total, under the final weights, in the ACS county proportions: + +``` +target(county) = file's state total × ACS county value ÷ sum of ACS values over the state's counties +``` + +So if the file's earnings or income sum differs from the ACS concept by the same proportion in every county of a state, that difference cancels. The pro-rata baseline splits the same state total by population: the file's state total × county population ÷ state population. It uses the same PUMA ladder county populations as the held-out targets' baseline. + +For B19061, B19051 and B19025, the error is |estimate − target| / max(|target|, 1). For B19001, the error adds |estimate − target| over the 16 brackets and divides the sum by max(sum of the county's bracket targets, 1). For each table, the build also records the share of counties where the file's error falls below the baseline's. + +The build computes household earnings and income sums from stored inputs, not from model outputs, and uses them only for these checks and the B19013 comparison. For each household, it adds up its people's values, and a missing value counts as zero. The code describes the ACS household tables as leaving out group quarters, both institutional and noninstitutional, so the checks leave out ACS group-quarters records too; every donor household counts. + +- **Earnings for the checks:** wages, self-employment income and farm income, plus partnership self-employment earnings on donor records. +- **Household income for the checks:** wages, self-employment and farm income, plus the stored income inputs. Those inputs cover interest, dividends, rent, estate income, Social Security, SSI, pensions, IRA distributions, unemployment compensation, veterans' benefits, workers' compensation, alimony, child support and miscellaneous income. +- On donor records, the build also adds partnership and S-corporation income to the income sum. On ACS records it leaves both out; the code's stated reason is that the ACS self-employment answer "already counts partnership income". The income sum also leaves out donor partnership self-employment earnings, which partnership income mostly holds already. +- In this run, S-corporation income is zero, so it adds nothing. TANF receipt (`receives_tanf`) appears in the file only as a yes/no flag, and the stored inputs have no column for TANF or public assistance dollars (`tanf_reported`, `public_assistance_income`). So the income sum includes neither. +- The build marks the two income tables, B19025 and B19001, `approximate: true`. The code describes the income sum as an approximation of the ACS household income concept. + +### The reliability grade + +The build writes each county's provisional grade to `county_reliability.json` and `county_reliability.csv`, and records the rule in the JSON: + +``` +"provisional": true, +"A": "source ESS >=400 and max error <=0.10", +"B": "source ESS >=100 and max error <=0.20", +"C": "source ESS >=30 and max error <=0.50", +"D": "otherwise with holdout or validation evidence", +"U": "no county holdout or validation evidence (no household support) or source household identity unavailable", +"error": "maximum absolute relative error over the county's training and holdout targets and its validation families (the income distribution as its bracket L1 error); denominator max(abs(target),1)" +``` + +- **Effective sample size (ESS).** The number of equally weighted households that would carry the same information as the actual weights: (sum of the weights)² ÷ (sum of the squared weights). For the grade's "source ESS" (`kish_ess`), the build first adds up the final weights of rows that share one source household: "final weights summed within county by (household_spine, household_source_id), excluding ACS group quarters". `household_spine` marks a row as ACS (`acs_2024_1yr`) or donor (`asec_puf`); `household_source_id` holds the ID of the household the row came from. +- **Support.** The build counts support as in "Counties without households": ACS group-quarters records count toward neither support nor ESS. +- **Copies.** Staging sets each ACS household's source ID to its ACS household ID from before pooling, so no two ACS rows share one. A donor household can appear twice under one source ID, as its ASEC record and as its tax-detail copy. The file's 57,240 donor household records hold 47,277 distinct source households. The source ESS counts a household and its copy as one only when both sit in the same county. Across all counties, the 1,405,648 supporting rows count as 1,404,416 source households, and 240 counties hold at least one such pair. +- **Row ESS.** The build also reports `kish_ess_rows`, which counts each row on its own, copies included, and likewise leaves out ACS group quarters. The grade does not use it. +- **Error.** The largest error over the county's training targets, its held-out targets and the four ACS tables, with B19001 as its bracket error. In the CSV, `grade_driver` holds the target or table that set it. +- **Evidence.** A county gets a grade from A to D only if it has a supporting household and either a held-out target or a scored ACS table. + +The code returns U when a county lacks that evidence or its source household identity. Otherwise it tries A, then B, then C, and returns the first grade whose two limits the county meets; failing all three, it returns D. At a fixed error, a higher ESS therefore cannot lower a grade. In the CSV, `grade_provisional` reads true for every county. + +### Automated gates + +The build ran 23 gates and recorded each in the release's `gate_summary.json`; all 23 recorded `passed: true`. Seventeen stop the build when they fail: + +- **Geography (1):** each household's PUMA, congressional district and county must be present and must agree with its state. New York City must keep a plausible share of the weight. +- **Household inputs (12):** the build assigns some inputs to ACS records: hours worked, program take-up, immigration status, disability, transferred income, SSI disability criteria, SSI and Medicaid take-up, and SNAP receipt. Each must be complete and must vary. Where a gate checks them against native ACS answers or plausibility ranges, they must agree. Every input left at a model default must appear on a reviewed list. ACS self-employment income must count once. Occupation, industry and worked-last-year inputs must be complete. +- **Calibration (1):** the final loss must fall under 10, the same setting that caps each target's scaled error in the loss. It must also fall under the run files' `initial_loss` (0.020786): the loss at the start of the second 400-step run, not the loss at the design weights. The final weights must sum to within 0.1% of the design weights' sum. +- **Model readiness (3):** the file stores no input that policyengine-us 2.2.1 lacks, outside a reviewed list. Every SPM unit the model measures has an adult, so the SPM calculation cannot stop on a unit without one. The build wrote its consumer export, and the `qa` stage loaded the calibrated file as stored, with no added fills. + +Six gates record evidence. Five of them record `passed: true` whatever they measure: + +- `cd_holdout`: held-out district targets; none in this run. In the `calibration` gate's breakdown, the build uses the same label, `cd_holdout`, for the 1,052 held-out county targets. +- `weight_origin`: the weight share and ESS of ACS and donor households. +- `input_coverage`: a note that staging checks donor inputs; the gate itself checks nothing. +- `spine_composition`: households and weight of ACS and donor records. +- `spine_ssi_qa`: the `qa` stage's load and its SSI and SNAP figures. + +The sixth, `district_ess_collapse`, flags congressional districts whose ESS under the final weights fell under a quarter of their ESS under the design weights, or under 15. It stops the build only when the build runs with `--district-ess-gate-blocking`; this run did not use that flag. In this run, 271 of the 436 districts fell under the quarter floor and 155 under 15, so the gate recorded `criteria_met: false` and still recorded `passed: true`. + +The `qa` stage loaded the calibrated file with Microcosm's own loader, not policyengine-us's dataset loader. It then ran policyengine-us 2.2.1 for 2024, with no reform, in 80 chunks of 20,000 households, for eight variables: SSI, six SNAP-related variables and the state code. For a separate test on 18 November that loaded the file with policyengine-us's standard loader, see the PoC report. diff --git a/experiments/us-county-poc-20261117/schema_manifest.json b/experiments/us-county-poc-20261117/schema_manifest.json new file mode 100644 index 0000000000..2586567de3 --- /dev/null +++ b/experiments/us-county-poc-20261117/schema_manifest.json @@ -0,0 +1,3575 @@ +{ + "diff": { + "added": [ + { + "column": "family_spine", + "dtype": "str", + "table": "family" + }, + { + "column": "ADJHSG", + "dtype": "float64", + "table": "household" + }, + { + "column": "FS", + "dtype": "float64", + "table": "household" + }, + { + "column": "GRNTP", + "dtype": "float64", + "table": "household" + }, + { + "column": "NP", + "dtype": "float64", + "table": "household" + }, + { + "column": "PUMA", + "dtype": "str", + "table": "household" + }, + { + "column": "RNTP", + "dtype": "float64", + "table": "household" + }, + { + "column": "SERIALNO", + "dtype": "str", + "table": "household" + }, + { + "column": "ST", + "dtype": "str", + "table": "household" + }, + { + "column": "TAXAMT", + "dtype": "float64", + "table": "household" + }, + { + "column": "TEN", + "dtype": "float64", + "table": "household" + }, + { + "column": "TYPEHUGQ", + "dtype": "float64", + "table": "household" + }, + { + "column": "VEH", + "dtype": "float64", + "table": "household" + }, + { + "column": "acs_annual_property_tax", + "dtype": "float64", + "table": "household" + }, + { + "column": "acs_monthly_contract_rent", + "dtype": "float64", + "table": "household" + }, + { + "column": "acs_monthly_gross_rent", + "dtype": "float64", + "table": "household" + }, + { + "column": "county_fips_2023", + "dtype": "str", + "table": "household" + }, + { + "column": "household_spine", + "dtype": "str", + "table": "household" + }, + { + "column": "puma", + "dtype": "str", + "table": "household" + }, + { + "column": "puma_geoid", + "dtype": "str", + "table": "household" + }, + { + "column": "marital_unit_spine", + "dtype": "str", + "table": "marital_unit" + }, + { + "column": "ACS_MIL", + "dtype": "float64", + "table": "person" + }, + { + "column": "ADJINC", + "dtype": "float64", + "table": "person" + }, + { + "column": "AGEP", + "dtype": "float64", + "table": "person" + }, + { + "column": "CIT", + "dtype": "float64", + "table": "person" + }, + { + "column": "COW", + "dtype": "float64", + "table": "person" + }, + { + "column": "DDRS", + "dtype": "float64", + "table": "person" + }, + { + "column": "DEAR", + "dtype": "float64", + "table": "person" + }, + { + "column": "DEYE", + "dtype": "float64", + "table": "person" + }, + { + "column": "DOUT", + "dtype": "float64", + "table": "person" + }, + { + "column": "DPHY", + "dtype": "float64", + "table": "person" + }, + { + "column": "DREM", + "dtype": "float64", + "table": "person" + }, + { + "column": "ESR", + "dtype": "float64", + "table": "person" + }, + { + "column": "FWKHP", + "dtype": "float64", + "table": "person" + }, + { + "column": "HINS3", + "dtype": "float64", + "table": "person" + }, + { + "column": "HINS4", + "dtype": "float64", + "table": "person" + }, + { + "column": "HINS5", + "dtype": "float64", + "table": "person" + }, + { + "column": "HINS6", + "dtype": "float64", + "table": "person" + }, + { + "column": "HINS7", + "dtype": "float64", + "table": "person" + }, + { + "column": "INDP", + "dtype": "float64", + "table": "person" + }, + { + "column": "INTP", + "dtype": "float64", + "table": "person" + }, + { + "column": "MAR", + "dtype": "float64", + "table": "person" + }, + { + "column": "OCCP", + "dtype": "float64", + "table": "person" + }, + { + "column": "OIP", + "dtype": "float64", + "table": "person" + }, + { + "column": "PAP", + "dtype": "float64", + "table": "person" + }, + { + "column": "POBP", + "dtype": "float64", + "table": "person" + }, + { + "column": "PWGTP", + "dtype": "float64", + "table": "person" + }, + { + "column": "RELSHIPP", + "dtype": "float64", + "table": "person" + }, + { + "column": "RETP", + "dtype": "float64", + "table": "person" + }, + { + "column": "SCHG", + "dtype": "float64", + "table": "person" + }, + { + "column": "SEMP", + "dtype": "float64", + "table": "person" + }, + { + "column": "SEX", + "dtype": "float64", + "table": "person" + }, + { + "column": "SPORDER", + "dtype": "float64", + "table": "person" + }, + { + "column": "SSIP", + "dtype": "float64", + "table": "person" + }, + { + "column": "SSP", + "dtype": "float64", + "table": "person" + }, + { + "column": "WAGP", + "dtype": "float64", + "table": "person" + }, + { + "column": "WKHP", + "dtype": "float64", + "table": "person" + }, + { + "column": "WKL", + "dtype": "float64", + "table": "person" + }, + { + "column": "WKWN", + "dtype": "float64", + "table": "person" + }, + { + "column": "YOEP", + "dtype": "float64", + "table": "person" + }, + { + "column": "acs_interest_dividend_rental_income", + "dtype": "float64", + "table": "person" + }, + { + "column": "acs_retirement_income", + "dtype": "float64", + "table": "person" + }, + { + "column": "acs_social_security_income", + "dtype": "float64", + "table": "person" + }, + { + "column": "detailed_industry_recode", + "dtype": "int16", + "table": "person" + }, + { + "column": "is_spm_independent_minor_role", + "dtype": "bool", + "table": "person" + }, + { + "column": "major_industry_recode", + "dtype": "int16", + "table": "person" + }, + { + "column": "parent_1_id", + "dtype": "float64", + "table": "person" + }, + { + "column": "parent_2_id", + "dtype": "float64", + "table": "person" + }, + { + "column": "passive_partnership_s_corp_income", + "dtype": "float64", + "table": "person" + }, + { + "column": "person_spine", + "dtype": "str", + "table": "person" + }, + { + "column": "receives_wic", + "dtype": "bool", + "table": "person" + }, + { + "column": "ssi_reported", + "dtype": "float64", + "table": "person" + }, + { + "column": "strike_benefits", + "dtype": "float64", + "table": "person" + }, + { + "column": "worked_last_year", + "dtype": "bool", + "table": "person" + }, + { + "column": "years_since_us_entry", + "dtype": "float64", + "table": "person" + }, + { + "column": "receives_snap", + "dtype": "bool", + "table": "spm_unit" + }, + { + "column": "receives_tanf", + "dtype": "bool", + "table": "spm_unit" + }, + { + "column": "spm_unit_spine", + "dtype": "str", + "table": "spm_unit" + }, + { + "column": "tax_unit_spine", + "dtype": "str", + "table": "tax_unit" + } + ], + "declared_renames_not_applied": [], + "dtype_changed": [ + { + "column": "H_TENURE", + "dtype_after": "float64", + "dtype_before": "int64", + "table": "household" + }, + { + "column": "household_vehicles_owned", + "dtype_after": "int64", + "dtype_before": "int32", + "table": "household" + }, + { + "column": "household_vehicles_value", + "dtype_after": "float64", + "dtype_before": "float32", + "table": "household" + }, + { + "column": "ACTC_CRD", + "dtype_after": "float64", + "dtype_before": "int64", + "table": "person" + }, + { + "column": "AGI", + "dtype_after": "float64", + "dtype_before": "int64", + "table": "person" + }, + { + "column": "ANN_VAL", + "dtype_after": "float64", + "dtype_before": "int64", + "table": "person" + }, + { + "column": "A_FNLWGT", + "dtype_after": "float64", + "dtype_before": "int64", + "table": "person" + }, + { + "column": "A_HRS1", + "dtype_after": "float64", + "dtype_before": "int64", + "table": "person" + }, + { + "column": "A_HSCOL", + "dtype_after": "float64", + "dtype_before": "int64", + "table": "person" + }, + { + "column": "A_MJOCC", + "dtype_after": "float64", + "dtype_before": "int64", + "table": "person" + }, + { + "column": "A_SEX", + "dtype_after": "float64", + "dtype_before": "int64", + "table": "person" + }, + { + "column": "CAID", + "dtype_after": "float64", + "dtype_before": "int64", + "table": "person" + }, + { + "column": "CAP_VAL", + "dtype_after": "float64", + "dtype_before": "int64", + "table": "person" + }, + { + "column": "CHAMPVA", + "dtype_after": "float64", + "dtype_before": "int64", + "table": "person" + }, + { + "column": "CHSP_VAL", + "dtype_after": "float64", + "dtype_before": "int64", + "table": "person" + }, + { + "column": "CSP_VAL", + "dtype_after": "float64", + "dtype_before": "int64", + "table": "person" + }, + { + "column": "CTC_CRD", + "dtype_after": "float64", + "dtype_before": "int64", + "table": "person" + }, + { + "column": "DIS_SC1", + "dtype_after": "float64", + "dtype_before": "int64", + "table": "person" + }, + { + "column": "DIS_SC2", + "dtype_after": "float64", + "dtype_before": "int64", + "table": "person" + }, + { + "column": "DIS_VAL1", + "dtype_after": "float64", + "dtype_before": "int64", + "table": "person" + }, + { + "column": "DIS_VAL2", + "dtype_after": "float64", + "dtype_before": "int64", + "table": "person" + }, + { + "column": "DIV_VAL", + "dtype_after": "float64", + "dtype_before": "int64", + "table": "person" + }, + { + "column": "DST_SC1", + "dtype_after": "float64", + "dtype_before": "int64", + "table": "person" + }, + { + "column": "DST_SC1_YNG", + "dtype_after": "float64", + "dtype_before": "int64", + "table": "person" + }, + { + "column": "DST_SC2", + "dtype_after": "float64", + "dtype_before": "int64", + "table": "person" + }, + { + "column": "DST_SC2_YNG", + "dtype_after": "float64", + "dtype_before": "int64", + "table": "person" + }, + { + "column": "DST_VAL1", + "dtype_after": "float64", + "dtype_before": "int64", + "table": "person" + }, + { + "column": "DST_VAL1_YNG", + "dtype_after": "float64", + "dtype_before": "int64", + "table": "person" + }, + { + "column": "DST_VAL2", + "dtype_after": "float64", + "dtype_before": "int64", + "table": "person" + }, + { + "column": "DST_VAL2_YNG", + "dtype_after": "float64", + "dtype_before": "int64", + "table": "person" + }, + { + "column": "EIT_CRED", + "dtype_after": "float64", + "dtype_before": "int64", + "table": "person" + }, + { + "column": "FEDTAX_AC", + "dtype_after": "float64", + "dtype_before": "int64", + "table": "person" + }, + { + "column": "FEDTAX_BC", + "dtype_after": "float64", + "dtype_before": "int64", + "table": "person" + }, + { + "column": "FRSE_VAL", + "dtype_after": "float64", + "dtype_before": "int64", + "table": "person" + }, + { + "column": "HRSWK", + "dtype_after": "float64", + "dtype_before": "int64", + "table": "person" + }, + { + "column": "IHSFLG", + "dtype_after": "float64", + "dtype_before": "int64", + "table": "person" + }, + { + "column": "INT_VAL", + "dtype_after": "float64", + "dtype_before": "int64", + "table": "person" + }, + { + "column": "I_ERNVAL", + "dtype_after": "float64", + "dtype_before": "int64", + "table": "person" + }, + { + "column": "I_SEVAL", + "dtype_after": "float64", + "dtype_before": "int64", + "table": "person" + }, + { + "column": "MARG_TAX", + "dtype_after": "float64", + "dtype_before": "int64", + "table": "person" + }, + { + "column": "MCARE", + "dtype_after": "float64", + "dtype_before": "int64", + "table": "person" + }, + { + "column": "MIL", + "dtype_after": "float64", + "dtype_before": "int64", + "table": "person" + }, + { + "column": "MOOP", + "dtype_after": "float64", + "dtype_before": "int64", + "table": "person" + }, + { + "column": "NOW_GRP", + "dtype_after": "float64", + "dtype_before": "int64", + "table": "person" + }, + { + "column": "NOW_MRK", + "dtype_after": "float64", + "dtype_before": "int64", + "table": "person" + }, + { + "column": "OI_OFF", + "dtype_after": "float64", + "dtype_before": "int64", + "table": "person" + }, + { + "column": "OI_VAL", + "dtype_after": "float64", + "dtype_before": "int64", + "table": "person" + }, + { + "column": "PAW_VAL", + "dtype_after": "float64", + "dtype_before": "int64", + "table": "person" + }, + { + "column": "PEAFEVER", + "dtype_after": "float64", + "dtype_before": "int64", + "table": "person" + }, + { + "column": "PEDISDRS", + "dtype_after": "float64", + "dtype_before": "int64", + "table": "person" + }, + { + "column": "PEDISEAR", + "dtype_after": "float64", + "dtype_before": "int64", + "table": "person" + }, + { + "column": "PEDISEYE", + "dtype_after": "float64", + "dtype_before": "int64", + "table": "person" + }, + { + "column": "PEDISOUT", + "dtype_after": "float64", + "dtype_before": "int64", + "table": "person" + }, + { + "column": "PEDISPHY", + "dtype_after": "float64", + "dtype_before": "int64", + "table": "person" + }, + { + "column": "PEDISREM", + "dtype_after": "float64", + "dtype_before": "int64", + "table": "person" + }, + { + "column": "PEINUSYR", + "dtype_after": "float64", + "dtype_before": "int64", + "table": "person" + }, + { + "column": "PEIO1COW", + "dtype_after": "float64", + "dtype_before": "int64", + "table": "person" + }, + { + "column": "PEIOOCC", + "dtype_after": "float64", + "dtype_before": "int64", + "table": "person" + }, + { + "column": "PEMCPREM", + "dtype_after": "float64", + "dtype_before": "int64", + "table": "person" + }, + { + "column": "PENATVTY", + "dtype_after": "float64", + "dtype_before": "int64", + "table": "person" + }, + { + "column": "PEN_SC1", + "dtype_after": "float64", + "dtype_before": "int64", + "table": "person" + }, + { + "column": "PEN_SC2", + "dtype_after": "float64", + "dtype_before": "int64", + "table": "person" + }, + { + "column": "PF_SEQ", + "dtype_after": "float64", + "dtype_before": "int64", + "table": "person" + }, + { + "column": "PHIP_VAL", + "dtype_after": "float64", + "dtype_before": "int64", + "table": "person" + }, + { + "column": "PMED_VAL", + "dtype_after": "float64", + "dtype_before": "int64", + "table": "person" + }, + { + "column": "PNSN_VAL", + "dtype_after": "float64", + "dtype_before": "int64", + "table": "person" + }, + { + "column": "POCCU2", + "dtype_after": "float64", + "dtype_before": "int64", + "table": "person" + }, + { + "column": "POTC_VAL", + "dtype_after": "float64", + "dtype_before": "int64", + "table": "person" + }, + { + "column": "PRCITSHP", + "dtype_after": "float64", + "dtype_before": "int64", + "table": "person" + }, + { + "column": "PRDTHSP", + "dtype_after": "float64", + "dtype_before": "int64", + "table": "person" + }, + { + "column": "PRDTRACE", + "dtype_after": "float64", + "dtype_before": "int64", + "table": "person" + }, + { + "column": "P_SEQ", + "dtype_after": "float64", + "dtype_before": "int64", + "table": "person" + }, + { + "column": "RESNSS1", + "dtype_after": "float64", + "dtype_before": "int64", + "table": "person" + }, + { + "column": "RESNSS2", + "dtype_after": "float64", + "dtype_before": "int64", + "table": "person" + }, + { + "column": "RESNSSI1", + "dtype_after": "float64", + "dtype_before": "int64", + "table": "person" + }, + { + "column": "RESNSSI2", + "dtype_after": "float64", + "dtype_before": "int64", + "table": "person" + }, + { + "column": "RETCB_VAL", + "dtype_after": "float64", + "dtype_before": "int64", + "table": "person" + }, + { + "column": "RNT_VAL", + "dtype_after": "float64", + "dtype_before": "int64", + "table": "person" + }, + { + "column": "SEMP_VAL", + "dtype_after": "float64", + "dtype_before": "int64", + "table": "person" + }, + { + "column": "SPM_ACTC", + "dtype_after": "float64", + "dtype_before": "int64", + "table": "person" + }, + { + "column": "SPM_BBSUBVAL", + "dtype_after": "float64", + "dtype_before": "int64", + "table": "person" + }, + { + "column": "SPM_CAPHOUSESUB", + "dtype_after": "float64", + "dtype_before": "int64", + "table": "person" + }, + { + "column": "SPM_CAPWKCCXPNS", + "dtype_after": "float64", + "dtype_before": "int64", + "table": "person" + }, + { + "column": "SPM_CHILDCAREXPNS", + "dtype_after": "float64", + "dtype_before": "int64", + "table": "person" + }, + { + "column": "SPM_CHILDSUPPD", + "dtype_after": "float64", + "dtype_before": "int64", + "table": "person" + }, + { + "column": "SPM_EITC", + "dtype_after": "float64", + "dtype_before": "int64", + "table": "person" + }, + { + "column": "SPM_ENGVAL", + "dtype_after": "float64", + "dtype_before": "int64", + "table": "person" + }, + { + "column": "SPM_FAMTYPE", + "dtype_after": "float64", + "dtype_before": "int64", + "table": "person" + }, + { + "column": "SPM_FEDTAX", + "dtype_after": "float64", + "dtype_before": "int64", + "table": "person" + }, + { + "column": "SPM_FEDTAXBC", + "dtype_after": "float64", + "dtype_before": "int64", + "table": "person" + }, + { + "column": "SPM_FICA", + "dtype_after": "float64", + "dtype_before": "int64", + "table": "person" + }, + { + "column": "SPM_HAGE", + "dtype_after": "float64", + "dtype_before": "int64", + "table": "person" + }, + { + "column": "SPM_HHISP", + "dtype_after": "float64", + "dtype_before": "int64", + "table": "person" + }, + { + "column": "SPM_HMARITALSTATUS", + "dtype_after": "float64", + "dtype_before": "int64", + "table": "person" + }, + { + "column": "SPM_HRACE", + "dtype_after": "float64", + "dtype_before": "int64", + "table": "person" + }, + { + "column": "SPM_ID", + "dtype_after": "float64", + "dtype_before": "int64", + "table": "person" + }, + { + "column": "SPM_MEDXPNS", + "dtype_after": "float64", + "dtype_before": "int64", + "table": "person" + }, + { + "column": "SPM_NUMADULTS", + "dtype_after": "float64", + "dtype_before": "int64", + "table": "person" + }, + { + "column": "SPM_NUMKIDS", + "dtype_after": "float64", + "dtype_before": "int64", + "table": "person" + }, + { + "column": "SPM_NUMPER", + "dtype_after": "float64", + "dtype_before": "int64", + "table": "person" + }, + { + "column": "SPM_POOR", + "dtype_after": "float64", + "dtype_before": "int64", + "table": "person" + }, + { + "column": "SPM_POVTHRESHOLD", + "dtype_after": "float64", + "dtype_before": "int64", + "table": "person" + }, + { + "column": "SPM_RESOURCES", + "dtype_after": "float64", + "dtype_before": "int64", + "table": "person" + }, + { + "column": "SPM_SCHLUNCH", + "dtype_after": "float64", + "dtype_before": "int64", + "table": "person" + }, + { + "column": "SPM_SNAPSUB", + "dtype_after": "float64", + "dtype_before": "int64", + "table": "person" + }, + { + "column": "SPM_STTAX", + "dtype_after": "float64", + "dtype_before": "int64", + "table": "person" + }, + { + "column": "SPM_TENMORTSTATUS", + "dtype_after": "float64", + "dtype_before": "int64", + "table": "person" + }, + { + "column": "SPM_TOTVAL", + "dtype_after": "float64", + "dtype_before": "int64", + "table": "person" + }, + { + "column": "SPM_WCOHABIT", + "dtype_after": "float64", + "dtype_before": "int64", + "table": "person" + }, + { + "column": "SPM_WEIGHT", + "dtype_after": "float64", + "dtype_before": "int64", + "table": "person" + }, + { + "column": "SPM_WFOSTER22", + "dtype_after": "float64", + "dtype_before": "int64", + "table": "person" + }, + { + "column": "SPM_WICVAL", + "dtype_after": "float64", + "dtype_before": "int64", + "table": "person" + }, + { + "column": "SPM_WKXPNS", + "dtype_after": "float64", + "dtype_before": "int64", + "table": "person" + }, + { + "column": "SPM_WNEWHEAD", + "dtype_after": "float64", + "dtype_before": "int64", + "table": "person" + }, + { + "column": "SPM_WNEWPARENT", + "dtype_after": "float64", + "dtype_before": "int64", + "table": "person" + }, + { + "column": "SPM_WUI_LT15", + "dtype_after": "float64", + "dtype_before": "int64", + "table": "person" + }, + { + "column": "SSI_VAL", + "dtype_after": "float64", + "dtype_before": "int64", + "table": "person" + }, + { + "column": "SSI_YN", + "dtype_after": "float64", + "dtype_before": "int64", + "table": "person" + }, + { + "column": "SS_VAL", + "dtype_after": "float64", + "dtype_before": "int64", + "table": "person" + }, + { + "column": "SS_YN", + "dtype_after": "float64", + "dtype_before": "int64", + "table": "person" + }, + { + "column": "STATETAX_A", + "dtype_after": "float64", + "dtype_before": "int64", + "table": "person" + }, + { + "column": "STATETAX_B", + "dtype_after": "float64", + "dtype_before": "int64", + "table": "person" + }, + { + "column": "TAX_ID", + "dtype_after": "float64", + "dtype_before": "int64", + "table": "person" + }, + { + "column": "TAX_INC", + "dtype_after": "float64", + "dtype_before": "int64", + "table": "person" + }, + { + "column": "UC_VAL", + "dtype_after": "float64", + "dtype_before": "int64", + "table": "person" + }, + { + "column": "VET_VAL", + "dtype_after": "float64", + "dtype_before": "int64", + "table": "person" + }, + { + "column": "WC_VAL", + "dtype_after": "float64", + "dtype_before": "int64", + "table": "person" + }, + { + "column": "WICYN", + "dtype_after": "float64", + "dtype_before": "int64", + "table": "person" + }, + { + "column": "WKSWORK", + "dtype_after": "float64", + "dtype_before": "int64", + "table": "person" + }, + { + "column": "WSAL_VAL", + "dtype_after": "float64", + "dtype_before": "int64", + "table": "person" + }, + { + "column": "cps_race", + "dtype_after": "int64", + "dtype_before": "int16", + "table": "person" + }, + { + "column": "fsla_overtime_premium", + "dtype_after": "float64", + "dtype_before": "float32", + "table": "person" + }, + { + "column": "treasury_tipped_occupation_code", + "dtype_after": "int64", + "dtype_before": "int16", + "table": "person" + }, + { + "column": "second_home_mortgage_origination_year", + "dtype_after": "int64", + "dtype_before": "float64", + "table": "tax_unit" + } + ], + "prior": { + "files": [ + { + "name": "prior_sample_columns.csv", + "sha256": "759e72a029a4fe0723d6009da574d79636b3172468bf5cf1d9e24def3f6ed159" + } + ], + "label": "the sample column list sent with the County Files agreement" + }, + "removed": [ + { + "column": "has_marketplace_health_coverage", + "dtype": "bool", + "table": "person" + }, + { + "column": "medicare_part_b_premiums", + "dtype": "float64", + "table": "person" + }, + { + "column": "weeks_worked", + "dtype": "float64", + "table": "person" + } + ], + "renamed": [ + { + "dtype_after": "bool", + "dtype_before": "bool", + "from": "would_claim_wic", + "reason": "policyengine-us names the WIC take-up input takes_up_wic_if_eligible; it defines no would_claim_wic.", + "table": "person", + "to": "takes_up_wic_if_eligible" + } + ], + "tables_added": [], + "tables_removed": [] + }, + "files": [ + { + "format": "hdf5", + "name": "populace_us_2024_acs_local.h5", + "other_keys": [ + { + "key": "_populace_staging_metadata", + "pandas_type": "series_table", + "rows": 1, + "value": "{\"artifact_kind\": \"calibrated_local_area_artifact\", \"entity_hdf_format\": \"fixed_nullable\", \"household_weight_kind\": \"calibrated\"}" + }, + { + "key": "_time_period", + "pandas_type": "series_table", + "rows": 1, + "value": 2024 + } + ], + "root_attributes": {}, + "sha256": "82314a3b5a6a95762faf6eb4f5b499ce56608ad6a39a27b75e11c75b4945bd3c", + "size_bytes": 10637811669, + "tables": [ + { + "columns": [ + { + "dtype": "str", + "name": "PERIDNUM", + "null_count": 3420942 + }, + { + "dtype": "int64", + "name": "PH_SEQ", + "null_count": 0 + }, + { + "dtype": "float64", + "name": "P_SEQ", + "null_count": 3420942 + }, + { + "dtype": "int64", + "name": "A_LINENO", + "null_count": 0 + }, + { + "dtype": "float64", + "name": "PF_SEQ", + "null_count": 3420942 + }, + { + "dtype": "float64", + "name": "PEAFEVER", + "null_count": 3420942 + }, + { + "dtype": "float64", + "name": "PENATVTY", + "null_count": 3420942 + }, + { + "dtype": "float64", + "name": "PEINUSYR", + "null_count": 3420942 + }, + { + "dtype": "int64", + "name": "PEPAR1", + "null_count": 0 + }, + { + "dtype": "int64", + "name": "PEPAR2", + "null_count": 0 + }, + { + "dtype": "float64", + "name": "PRDTHSP", + "null_count": 3420942 + }, + { + "dtype": "float64", + "name": "PRDTRACE", + "null_count": 3420942 + }, + { + "dtype": "float64", + "name": "PRCITSHP", + "null_count": 3420942 + }, + { + "dtype": "float64", + "name": "PECOHAB", + "null_count": 3530060 + }, + { + "dtype": "float64", + "name": "PEIO1COW", + "null_count": 3420942 + }, + { + "dtype": "float64", + "name": "PEDISEAR", + "null_count": 3420942 + }, + { + "dtype": "float64", + "name": "PEDISEYE", + "null_count": 3420942 + }, + { + "dtype": "float64", + "name": "PEDISREM", + "null_count": 3420942 + }, + { + "dtype": "float64", + "name": "PEDISPHY", + "null_count": 3420942 + }, + { + "dtype": "float64", + "name": "PEDISDRS", + "null_count": 3420942 + }, + { + "dtype": "float64", + "name": "PEDISOUT", + "null_count": 3420942 + }, + { + "dtype": "int64", + "name": "A_AGE", + "null_count": 0 + }, + { + "dtype": "float64", + "name": "A_SEX", + "null_count": 3420942 + }, + { + "dtype": "float64", + "name": "A_ENRLW", + "null_count": 3530060 + }, + { + "dtype": "float64", + "name": "A_MJOCC", + "null_count": 3420942 + }, + { + "dtype": "float64", + "name": "A_HSCOL", + "null_count": 3420942 + }, + { + "dtype": "float64", + "name": "A_FTPT", + "null_count": 3530060 + }, + { + "dtype": "float64", + "name": "A_FNLWGT", + "null_count": 3420942 + }, + { + "dtype": "float64", + "name": "A_FAMREL", + "null_count": 3530060 + }, + { + "dtype": "float64", + "name": "A_FAMTYP", + "null_count": 3530060 + }, + { + "dtype": "int64", + "name": "A_SPOUSE", + "null_count": 0 + }, + { + "dtype": "int64", + "name": "A_MARITL", + "null_count": 0 + }, + { + "dtype": "float64", + "name": "A_HRS1", + "null_count": 3420942 + }, + { + "dtype": "int64", + "name": "A_EXPRRP", + "null_count": 0 + }, + { + "dtype": "float64", + "name": "ACTC_CRD", + "null_count": 3420942 + }, + { + "dtype": "float64", + "name": "AGI", + "null_count": 3420942 + }, + { + "dtype": "float64", + "name": "ANN_VAL", + "null_count": 3420942 + }, + { + "dtype": "float64", + "name": "CAID", + "null_count": 3420942 + }, + { + "dtype": "float64", + "name": "CAP_VAL", + "null_count": 3420942 + }, + { + "dtype": "float64", + "name": "CHAMPVA", + "null_count": 3420942 + }, + { + "dtype": "float64", + "name": "CHSP_VAL", + "null_count": 3420942 + }, + { + "dtype": "float64", + "name": "CSP_VAL", + "null_count": 3420942 + }, + { + "dtype": "float64", + "name": "CTC_CRD", + "null_count": 3420942 + }, + { + "dtype": "float64", + "name": "DIS_SC1", + "null_count": 3420942 + }, + { + "dtype": "float64", + "name": "DIS_SC2", + "null_count": 3420942 + }, + { + "dtype": "float64", + "name": "DIS_VAL1", + "null_count": 3420942 + }, + { + "dtype": "float64", + "name": "DIS_VAL2", + "null_count": 3420942 + }, + { + "dtype": "float64", + "name": "DIV_VAL", + "null_count": 3420942 + }, + { + "dtype": "float64", + "name": "DST_SC1", + "null_count": 3420942 + }, + { + "dtype": "float64", + "name": "DST_SC2", + "null_count": 3420942 + }, + { + "dtype": "float64", + "name": "DST_SC1_YNG", + "null_count": 3420942 + }, + { + "dtype": "float64", + "name": "DST_SC2_YNG", + "null_count": 3420942 + }, + { + "dtype": "float64", + "name": "DST_VAL1", + "null_count": 3420942 + }, + { + "dtype": "float64", + "name": "DST_VAL2", + "null_count": 3420942 + }, + { + "dtype": "float64", + "name": "DST_VAL1_YNG", + "null_count": 3420942 + }, + { + "dtype": "float64", + "name": "DST_VAL2_YNG", + "null_count": 3420942 + }, + { + "dtype": "float64", + "name": "EIT_CRED", + "null_count": 3420942 + }, + { + "dtype": "float64", + "name": "FEDTAX_AC", + "null_count": 3420942 + }, + { + "dtype": "float64", + "name": "FEDTAX_BC", + "null_count": 3420942 + }, + { + "dtype": "float64", + "name": "FRSE_VAL", + "null_count": 3420942 + }, + { + "dtype": "float64", + "name": "HRSWK", + "null_count": 3420942 + }, + { + "dtype": "float64", + "name": "IHSFLG", + "null_count": 3420942 + }, + { + "dtype": "float64", + "name": "INT_VAL", + "null_count": 3420942 + }, + { + "dtype": "float64", + "name": "I_ERNVAL", + "null_count": 3420942 + }, + { + "dtype": "float64", + "name": "I_SEVAL", + "null_count": 3420942 + }, + { + "dtype": "float64", + "name": "LKWEEKS", + "null_count": 3420942 + }, + { + "dtype": "float64", + "name": "MARG_TAX", + "null_count": 3420942 + }, + { + "dtype": "float64", + "name": "MCARE", + "null_count": 3420942 + }, + { + "dtype": "float64", + "name": "MIL", + "null_count": 3420942 + }, + { + "dtype": "float64", + "name": "MOOP", + "null_count": 3420942 + }, + { + "dtype": "float64", + "name": "NOW_CAID", + "null_count": 3530060 + }, + { + "dtype": "float64", + "name": "NOW_CHAMPVA", + "null_count": 3530060 + }, + { + "dtype": "float64", + "name": "NOW_COV", + "null_count": 3530060 + }, + { + "dtype": "float64", + "name": "NOW_DIR", + "null_count": 3530060 + }, + { + "dtype": "float64", + "name": "NOW_GRP", + "null_count": 3420942 + }, + { + "dtype": "float64", + "name": "NOW_IHSFLG", + "null_count": 3530060 + }, + { + "dtype": "float64", + "name": "NOW_MCAID", + "null_count": 3530060 + }, + { + "dtype": "float64", + "name": "NOW_MCARE", + "null_count": 3530060 + }, + { + "dtype": "float64", + "name": "NOW_MIL", + "null_count": 3530060 + }, + { + "dtype": "float64", + "name": "NOW_MRK", + "null_count": 3420942 + }, + { + "dtype": "float64", + "name": "NOW_MRKS", + "null_count": 3530060 + }, + { + "dtype": "float64", + "name": "NOW_MRKUN", + "null_count": 3530060 + }, + { + "dtype": "float64", + "name": "NOW_NONM", + "null_count": 3530060 + }, + { + "dtype": "float64", + "name": "NOW_OTHMT", + "null_count": 3530060 + }, + { + "dtype": "float64", + "name": "NOW_PCHIP", + "null_count": 3530060 + }, + { + "dtype": "float64", + "name": "NOW_PRIV", + "null_count": 3530060 + }, + { + "dtype": "float64", + "name": "NOW_PUB", + "null_count": 3530060 + }, + { + "dtype": "float64", + "name": "NOW_VACARE", + "null_count": 3530060 + }, + { + "dtype": "float64", + "name": "OI_OFF", + "null_count": 3420942 + }, + { + "dtype": "float64", + "name": "OI_VAL", + "null_count": 3420942 + }, + { + "dtype": "float64", + "name": "PAW_VAL", + "null_count": 3420942 + }, + { + "dtype": "float64", + "name": "PEMCPREM", + "null_count": 3420942 + }, + { + "dtype": "float64", + "name": "PEN_SC1", + "null_count": 3420942 + }, + { + "dtype": "float64", + "name": "PEN_SC2", + "null_count": 3420942 + }, + { + "dtype": "float64", + "name": "PHIP_VAL", + "null_count": 3420942 + }, + { + "dtype": "float64", + "name": "PMED_VAL", + "null_count": 3420942 + }, + { + "dtype": "float64", + "name": "PNSN_VAL", + "null_count": 3420942 + }, + { + "dtype": "float64", + "name": "POCCU2", + "null_count": 3420942 + }, + { + "dtype": "float64", + "name": "POTC_VAL", + "null_count": 3420942 + }, + { + "dtype": "float64", + "name": "PTOTVAL", + "null_count": 3530060 + }, + { + "dtype": "float64", + "name": "RESNSS1", + "null_count": 3420942 + }, + { + "dtype": "float64", + "name": "RESNSS2", + "null_count": 3420942 + }, + { + "dtype": "float64", + "name": "RESNSSI1", + "null_count": 3420942 + }, + { + "dtype": "float64", + "name": "RESNSSI2", + "null_count": 3420942 + }, + { + "dtype": "float64", + "name": "RETCB_VAL", + "null_count": 3420942 + }, + { + "dtype": "float64", + "name": "RNT_VAL", + "null_count": 3420942 + }, + { + "dtype": "float64", + "name": "SEMP_VAL", + "null_count": 3420942 + }, + { + "dtype": "float64", + "name": "SPM_ACTC", + "null_count": 3420942 + }, + { + "dtype": "float64", + "name": "SPM_BBSUBVAL", + "null_count": 3420942 + }, + { + "dtype": "float64", + "name": "SPM_CAPHOUSESUB", + "null_count": 3420942 + }, + { + "dtype": "float64", + "name": "SPM_CAPWKCCXPNS", + "null_count": 3420942 + }, + { + "dtype": "float64", + "name": "SPM_CHILDCAREXPNS", + "null_count": 3420942 + }, + { + "dtype": "float64", + "name": "SPM_CHILDSUPPD", + "null_count": 3420942 + }, + { + "dtype": "float64", + "name": "SPM_EITC", + "null_count": 3420942 + }, + { + "dtype": "float64", + "name": "SPM_ENGVAL", + "null_count": 3420942 + }, + { + "dtype": "float64", + "name": "SPM_EQUIVSCALE", + "null_count": 3420942 + }, + { + "dtype": "float64", + "name": "SPM_FAMTYPE", + "null_count": 3420942 + }, + { + "dtype": "float64", + "name": "SPM_FEDTAX", + "null_count": 3420942 + }, + { + "dtype": "float64", + "name": "SPM_FEDTAXBC", + "null_count": 3420942 + }, + { + "dtype": "float64", + "name": "SPM_FICA", + "null_count": 3420942 + }, + { + "dtype": "float64", + "name": "SPM_GEOADJ", + "null_count": 3420942 + }, + { + "dtype": "float64", + "name": "SPM_HAGE", + "null_count": 3420942 + }, + { + "dtype": "float64", + "name": "SPM_HHISP", + "null_count": 3420942 + }, + { + "dtype": "float64", + "name": "SPM_HMARITALSTATUS", + "null_count": 3420942 + }, + { + "dtype": "float64", + "name": "SPM_HRACE", + "null_count": 3420942 + }, + { + "dtype": "float64", + "name": "SPM_ID", + "null_count": 3420942 + }, + { + "dtype": "float64", + "name": "SPM_MEDXPNS", + "null_count": 3420942 + }, + { + "dtype": "float64", + "name": "SPM_NUMADULTS", + "null_count": 3420942 + }, + { + "dtype": "float64", + "name": "SPM_NUMKIDS", + "null_count": 3420942 + }, + { + "dtype": "float64", + "name": "SPM_NUMPER", + "null_count": 3420942 + }, + { + "dtype": "float64", + "name": "SPM_POOR", + "null_count": 3420942 + }, + { + "dtype": "float64", + "name": "SPM_POVTHRESHOLD", + "null_count": 3420942 + }, + { + "dtype": "float64", + "name": "SPM_RESOURCES", + "null_count": 3420942 + }, + { + "dtype": "float64", + "name": "SPM_SCHLUNCH", + "null_count": 3420942 + }, + { + "dtype": "float64", + "name": "SPM_SNAPSUB", + "null_count": 3420942 + }, + { + "dtype": "float64", + "name": "SPM_STTAX", + "null_count": 3420942 + }, + { + "dtype": "float64", + "name": "SPM_TENMORTSTATUS", + "null_count": 3420942 + }, + { + "dtype": "float64", + "name": "SPM_TOTVAL", + "null_count": 3420942 + }, + { + "dtype": "float64", + "name": "SPM_WCOHABIT", + "null_count": 3420942 + }, + { + "dtype": "float64", + "name": "SPM_WEIGHT", + "null_count": 3420942 + }, + { + "dtype": "float64", + "name": "SPM_WFOSTER22", + "null_count": 3420942 + }, + { + "dtype": "float64", + "name": "SPM_WICVAL", + "null_count": 3420942 + }, + { + "dtype": "float64", + "name": "SPM_WKXPNS", + "null_count": 3420942 + }, + { + "dtype": "float64", + "name": "SPM_WNEWHEAD", + "null_count": 3420942 + }, + { + "dtype": "float64", + "name": "SPM_WNEWPARENT", + "null_count": 3420942 + }, + { + "dtype": "float64", + "name": "SPM_WUI_LT15", + "null_count": 3420942 + }, + { + "dtype": "float64", + "name": "SSI_VAL", + "null_count": 3420942 + }, + { + "dtype": "float64", + "name": "SSI_YN", + "null_count": 3420942 + }, + { + "dtype": "float64", + "name": "SS_VAL", + "null_count": 3420942 + }, + { + "dtype": "float64", + "name": "SS_YN", + "null_count": 3420942 + }, + { + "dtype": "float64", + "name": "STATETAX_A", + "null_count": 3420942 + }, + { + "dtype": "float64", + "name": "STATETAX_B", + "null_count": 3420942 + }, + { + "dtype": "float64", + "name": "TAX_INC", + "null_count": 3420942 + }, + { + "dtype": "float64", + "name": "UC_VAL", + "null_count": 3420942 + }, + { + "dtype": "float64", + "name": "VET_VAL", + "null_count": 3420942 + }, + { + "dtype": "float64", + "name": "WC_VAL", + "null_count": 3420942 + }, + { + "dtype": "float64", + "name": "WICYN", + "null_count": 3420942 + }, + { + "dtype": "float64", + "name": "WKSWORK", + "null_count": 3420942 + }, + { + "dtype": "float64", + "name": "WSAL_VAL", + "null_count": 3420942 + }, + { + "dtype": "float64", + "name": "TAX_ID", + "null_count": 3420942 + }, + { + "dtype": "float64", + "name": "PEIOOCC", + "null_count": 3420942 + }, + { + "dtype": "float64", + "name": "CENSUS_TAX_ID", + "null_count": 3530060 + }, + { + "dtype": "int64", + "name": "source_year", + "null_count": 0 + }, + { + "dtype": "int64", + "name": "source_household_id", + "null_count": 0 + }, + { + "dtype": "str", + "name": "source_person_id", + "null_count": 0 + }, + { + "dtype": "int64", + "name": "source_row_id", + "null_count": 0 + }, + { + "dtype": "int64", + "name": "person_tax_unit_id", + "null_count": 0 + }, + { + "dtype": "str", + "name": "tax_unit_role_input", + "null_count": 0 + }, + { + "dtype": "bool", + "name": "is_related_to_head_or_spouse", + "null_count": 0 + }, + { + "dtype": "int64", + "name": "person_spm_unit_id", + "null_count": 0 + }, + { + "dtype": "int64", + "name": "person_family_id", + "null_count": 0 + }, + { + "dtype": "int64", + "name": "person_marital_unit_id", + "null_count": 0 + }, + { + "dtype": "int64", + "name": "person_household_id", + "null_count": 0 + }, + { + "dtype": "int64", + "name": "person_id", + "null_count": 0 + }, + { + "dtype": "float64", + "name": "age", + "null_count": 0 + }, + { + "dtype": "bool", + "name": "is_female", + "null_count": 0 + }, + { + "dtype": "float64", + "name": "employment_income_before_lsr", + "null_count": 0 + }, + { + "dtype": "float64", + "name": "self_employment_income_before_lsr", + "null_count": 0 + }, + { + "dtype": "float64", + "name": "taxable_interest_income", + "null_count": 0 + }, + { + "dtype": "float64", + "name": "qualified_dividend_income", + "null_count": 0 + }, + { + "dtype": "float64", + "name": "non_qualified_dividend_income", + "null_count": 0 + }, + { + "dtype": "float64", + "name": "long_term_capital_gains_before_response", + "null_count": 0 + }, + { + "dtype": "float64", + "name": "short_term_capital_gains", + "null_count": 0 + }, + { + "dtype": "float64", + "name": "social_security_retirement", + "null_count": 0 + }, + { + "dtype": "float64", + "name": "social_security_disability", + "null_count": 0 + }, + { + "dtype": "float64", + "name": "social_security_survivors", + "null_count": 0 + }, + { + "dtype": "float64", + "name": "social_security_dependents", + "null_count": 0 + }, + { + "dtype": "float64", + "name": "taxable_private_pension_income", + "null_count": 0 + }, + { + "dtype": "float64", + "name": "tax_exempt_private_pension_income", + "null_count": 0 + }, + { + "dtype": "float64", + "name": "taxable_ira_distributions", + "null_count": 0 + }, + { + "dtype": "float64", + "name": "alimony_income", + "null_count": 0 + }, + { + "dtype": "float64", + "name": "miscellaneous_income", + "null_count": 0 + }, + { + "dtype": "float64", + "name": "rental_income", + "null_count": 0 + }, + { + "dtype": "float64", + "name": "farm_operations_income", + "null_count": 0 + }, + { + "dtype": "float64", + "name": "unemployment_compensation", + "null_count": 0 + }, + { + "dtype": "float64", + "name": "health_insurance_premiums_without_medicare_part_b", + "null_count": 0 + }, + { + "dtype": "float64", + "name": "other_medical_expenses", + "null_count": 0 + }, + { + "dtype": "float64", + "name": "over_the_counter_health_expenses", + "null_count": 0 + }, + { + "dtype": "bool", + "name": "has_marketplace_health_coverage_at_interview", + "null_count": 0 + }, + { + "dtype": "bool", + "name": "has_non_marketplace_direct_purchase_health_coverage_at_interview", + "null_count": 0 + }, + { + "dtype": "bool", + "name": "has_medicaid_health_coverage_at_interview", + "null_count": 0 + }, + { + "dtype": "bool", + "name": "has_esi", + "null_count": 0 + }, + { + "dtype": "bool", + "name": "has_champva_health_coverage_at_interview", + "null_count": 0 + }, + { + "dtype": "bool", + "name": "has_tricare_health_coverage_at_interview", + "null_count": 0 + }, + { + "dtype": "bool", + "name": "has_va_health_coverage_at_interview", + "null_count": 0 + }, + { + "dtype": "bool", + "name": "has_other_means_tested_health_coverage_at_interview", + "null_count": 0 + }, + { + "dtype": "bool", + "name": "has_indian_health_service_coverage_at_interview", + "null_count": 0 + }, + { + "dtype": "float64", + "name": "self_employment_income_last_year", + "null_count": 0 + }, + { + "dtype": "bool", + "name": "previous_year_income_available", + "null_count": 0 + }, + { + "dtype": "bool", + "name": "is_household_head", + "null_count": 0 + }, + { + "dtype": "bool", + "name": "is_separated", + "null_count": 0 + }, + { + "dtype": "bool", + "name": "is_surviving_spouse", + "null_count": 0 + }, + { + "dtype": "bool", + "name": "takes_up_medicare_if_eligible", + "null_count": 0 + }, + { + "dtype": "float64", + "name": "pre_subsidy_rent", + "null_count": 0 + }, + { + "dtype": "bool", + "name": "is_disabled", + "null_count": 0 + }, + { + "dtype": "bool", + "name": "is_blind", + "null_count": 0 + }, + { + "dtype": "bool", + "name": "is_full_time_college_student", + "null_count": 0 + }, + { + "dtype": "float64", + "name": "own_children_in_household", + "null_count": 0 + }, + { + "dtype": "float64", + "name": "veterans_benefits", + "null_count": 0 + }, + { + "dtype": "bool", + "name": "is_pregnant", + "null_count": 0 + }, + { + "dtype": "float64", + "name": "child_support_received", + "null_count": 0 + }, + { + "dtype": "float64", + "name": "child_support_expense", + "null_count": 0 + }, + { + "dtype": "float64", + "name": "disability_benefits", + "null_count": 0 + }, + { + "dtype": "float64", + "name": "workers_compensation", + "null_count": 0 + }, + { + "dtype": "float64", + "name": "weeks_unemployed", + "null_count": 0 + }, + { + "dtype": "float64", + "name": "traditional_401k_contributions_desired", + "null_count": 0 + }, + { + "dtype": "float64", + "name": "roth_401k_contributions_desired", + "null_count": 0 + }, + { + "dtype": "float64", + "name": "traditional_ira_contributions_desired", + "null_count": 0 + }, + { + "dtype": "float64", + "name": "roth_ira_contributions_desired", + "null_count": 0 + }, + { + "dtype": "float64", + "name": "self_employed_pension_contributions_desired", + "null_count": 0 + }, + { + "dtype": "float64", + "name": "taxable_401k_distributions", + "null_count": 0 + }, + { + "dtype": "float64", + "name": "taxable_403b_distributions", + "null_count": 0 + }, + { + "dtype": "float64", + "name": "tax_exempt_ira_distributions", + "null_count": 0 + }, + { + "dtype": "float64", + "name": "keogh_distributions", + "null_count": 0 + }, + { + "dtype": "float64", + "name": "taxable_sep_distributions", + "null_count": 0 + }, + { + "dtype": "str", + "name": "ssn_card_type", + "null_count": 0 + }, + { + "dtype": "str", + "name": "immigration_status_str", + "null_count": 0 + }, + { + "dtype": "int64", + "name": "person_source_id", + "null_count": 0 + }, + { + "dtype": "str", + "name": "person_support_channel", + "null_count": 0 + }, + { + "dtype": "int64", + "name": "person_support_clone_index", + "null_count": 0 + }, + { + "dtype": "float64", + "name": "tax_exempt_interest_income", + "null_count": 0 + }, + { + "dtype": "float64", + "name": "long_term_capital_gains_on_collectibles", + "null_count": 0 + }, + { + "dtype": "float64", + "name": "non_sch_d_capital_gains", + "null_count": 0 + }, + { + "dtype": "float64", + "name": "alimony_expense", + "null_count": 0 + }, + { + "dtype": "float64", + "name": "salt_refund_income", + "null_count": 0 + }, + { + "dtype": "float64", + "name": "charitable_cash_donations", + "null_count": 0 + }, + { + "dtype": "float64", + "name": "charitable_non_cash_donations", + "null_count": 0 + }, + { + "dtype": "float64", + "name": "real_estate_taxes", + "null_count": 0 + }, + { + "dtype": "float64", + "name": "home_mortgage_interest", + "null_count": 0 + }, + { + "dtype": "float64", + "name": "investment_interest_expense", + "null_count": 0 + }, + { + "dtype": "float64", + "name": "investment_income_elected_form_4952", + "null_count": 0 + }, + { + "dtype": "float64", + "name": "student_loan_interest", + "null_count": 0 + }, + { + "dtype": "float64", + "name": "educator_expense", + "null_count": 0 + }, + { + "dtype": "float64", + "name": "qualified_tuition_expenses", + "null_count": 0 + }, + { + "dtype": "float64", + "name": "casualty_loss", + "null_count": 0 + }, + { + "dtype": "float64", + "name": "unreimbursed_business_employee_expenses", + "null_count": 0 + }, + { + "dtype": "float64", + "name": "estate_income", + "null_count": 0 + }, + { + "dtype": "float64", + "name": "farm_income", + "null_count": 0 + }, + { + "dtype": "float64", + "name": "farm_rent_income", + "null_count": 0 + }, + { + "dtype": "float64", + "name": "partnership_income", + "null_count": 0 + }, + { + "dtype": "float64", + "name": "s_corp_income", + "null_count": 0 + }, + { + "dtype": "float64", + "name": "partnership_self_employment_net_earnings", + "null_count": 0 + }, + { + "dtype": "bool", + "name": "estate_income_would_be_qualified", + "null_count": 0 + }, + { + "dtype": "bool", + "name": "farm_operations_income_would_be_qualified", + "null_count": 0 + }, + { + "dtype": "bool", + "name": "farm_rent_income_would_be_qualified", + "null_count": 0 + }, + { + "dtype": "bool", + "name": "partnership_s_corp_income_would_be_qualified", + "null_count": 0 + }, + { + "dtype": "bool", + "name": "rental_income_would_be_qualified", + "null_count": 0 + }, + { + "dtype": "bool", + "name": "self_employment_income_would_be_qualified", + "null_count": 0 + }, + { + "dtype": "bool", + "name": "sstb_self_employment_income_would_be_qualified", + "null_count": 0 + }, + { + "dtype": "bool", + "name": "business_is_sstb", + "null_count": 0 + }, + { + "dtype": "float64", + "name": "qualified_bdc_income", + "null_count": 0 + }, + { + "dtype": "float64", + "name": "qualified_reit_and_ptp_income", + "null_count": 0 + }, + { + "dtype": "float64", + "name": "sstb_self_employment_income_before_lsr", + "null_count": 0 + }, + { + "dtype": "float64", + "name": "sstb_unadjusted_basis_qualified_property", + "null_count": 0 + }, + { + "dtype": "float64", + "name": "sstb_w2_wages_from_qualified_business", + "null_count": 0 + }, + { + "dtype": "float64", + "name": "unadjusted_basis_qualified_property", + "null_count": 0 + }, + { + "dtype": "float64", + "name": "w2_wages_from_qualified_business", + "null_count": 0 + }, + { + "dtype": "float64", + "name": "schedule_d_capital_gain_distributions", + "null_count": 0 + }, + { + "dtype": "bool", + "name": "is_incapable_of_self_care", + "null_count": 0 + }, + { + "dtype": "float64", + "name": "pre_subsidy_care_expenses", + "null_count": 0 + }, + { + "dtype": "float64", + "name": "educational_assistance", + "null_count": 0 + }, + { + "dtype": "bool", + "name": "is_pursuing_credential_for_american_opportunity_credit", + "null_count": 0 + }, + { + "dtype": "bool", + "name": "attends_eligible_educational_institution_for_american_opportunity_credit", + "null_count": 0 + }, + { + "dtype": "bool", + "name": "is_enrolled_at_least_half_time_for_american_opportunity_credit", + "null_count": 0 + }, + { + "dtype": "bool", + "name": "has_american_opportunity_credit_1098_t_or_exception", + "null_count": 0 + }, + { + "dtype": "bool", + "name": "has_american_opportunity_credit_institution_ein", + "null_count": 0 + }, + { + "dtype": "float64", + "name": "weekly_hours_worked_before_lsr", + "null_count": 0 + }, + { + "dtype": "float64", + "name": "hours_worked_last_week", + "null_count": 0 + }, + { + "dtype": "bool", + "name": "is_snap_abawd_discretionary_exempt", + "null_count": 0 + }, + { + "dtype": "float64", + "name": "bank_account_assets", + "null_count": 0 + }, + { + "dtype": "float64", + "name": "stock_assets", + "null_count": 0 + }, + { + "dtype": "float64", + "name": "bond_assets", + "null_count": 0 + }, + { + "dtype": "bool", + "name": "meets_ssi_disability_criteria", + "null_count": 0 + }, + { + "dtype": "bool", + "name": "takes_up_head_start_if_eligible", + "null_count": 0 + }, + { + "dtype": "bool", + "name": "takes_up_ssi_if_eligible", + "null_count": 0 + }, + { + "dtype": "float64", + "name": "tip_income", + "null_count": 0 + }, + { + "dtype": "int64", + "name": "treasury_tipped_occupation_code", + "null_count": 0 + }, + { + "dtype": "int64", + "name": "cps_race", + "null_count": 0 + }, + { + "dtype": "bool", + "name": "is_hispanic", + "null_count": 0 + }, + { + "dtype": "int16", + "name": "detailed_occupation_recode", + "null_count": 0 + }, + { + "dtype": "bool", + "name": "has_never_worked", + "null_count": 0 + }, + { + "dtype": "bool", + "name": "is_military", + "null_count": 0 + }, + { + "dtype": "bool", + "name": "is_computer_scientist", + "null_count": 0 + }, + { + "dtype": "bool", + "name": "is_farmer_fisher", + "null_count": 0 + }, + { + "dtype": "bool", + "name": "is_executive_administrative_professional", + "null_count": 0 + }, + { + "dtype": "float64", + "name": "hourly_wage", + "null_count": 0 + }, + { + "dtype": "bool", + "name": "is_paid_hourly", + "null_count": 0 + }, + { + "dtype": "bool", + "name": "is_union_member_or_covered", + "null_count": 0 + }, + { + "dtype": "float64", + "name": "fsla_overtime_premium", + "null_count": 0 + }, + { + "dtype": "bool", + "name": "takes_up_medicaid_if_eligible", + "null_count": 0 + }, + { + "dtype": "float64", + "name": "other_health_insurance_premiums", + "null_count": 0 + }, + { + "dtype": "float64", + "name": "health_insurance_premiums", + "null_count": 0 + }, + { + "dtype": "bool", + "name": "is_self_employed", + "null_count": 0 + }, + { + "dtype": "bool", + "name": "is_spm_independent_minor_role", + "null_count": 0 + }, + { + "dtype": "bool", + "name": "receives_wic", + "null_count": 0 + }, + { + "dtype": "int16", + "name": "detailed_industry_recode", + "null_count": 0 + }, + { + "dtype": "int16", + "name": "major_industry_recode", + "null_count": 0 + }, + { + "dtype": "bool", + "name": "worked_last_year", + "null_count": 0 + }, + { + "dtype": "float64", + "name": "strike_benefits", + "null_count": 0 + }, + { + "dtype": "float64", + "name": "passive_partnership_s_corp_income", + "null_count": 0 + }, + { + "dtype": "str", + "name": "person_spine", + "null_count": 0 + }, + { + "dtype": "float64", + "name": "SPORDER", + "null_count": 166321 + }, + { + "dtype": "float64", + "name": "ADJINC", + "null_count": 166321 + }, + { + "dtype": "float64", + "name": "PWGTP", + "null_count": 166321 + }, + { + "dtype": "float64", + "name": "AGEP", + "null_count": 166321 + }, + { + "dtype": "float64", + "name": "CIT", + "null_count": 166321 + }, + { + "dtype": "float64", + "name": "COW", + "null_count": 1542526 + }, + { + "dtype": "float64", + "name": "DDRS", + "null_count": 317477 + }, + { + "dtype": "float64", + "name": "DEAR", + "null_count": 166321 + }, + { + "dtype": "float64", + "name": "DEYE", + "null_count": 166321 + }, + { + "dtype": "float64", + "name": "DOUT", + "null_count": 674473 + }, + { + "dtype": "float64", + "name": "DPHY", + "null_count": 317477 + }, + { + "dtype": "float64", + "name": "DREM", + "null_count": 317477 + }, + { + "dtype": "float64", + "name": "HINS3", + "null_count": 166321 + }, + { + "dtype": "float64", + "name": "HINS4", + "null_count": 166321 + }, + { + "dtype": "float64", + "name": "HINS5", + "null_count": 166321 + }, + { + "dtype": "float64", + "name": "HINS6", + "null_count": 166321 + }, + { + "dtype": "float64", + "name": "HINS7", + "null_count": 166321 + }, + { + "dtype": "float64", + "name": "INTP", + "null_count": 674473 + }, + { + "dtype": "float64", + "name": "MAR", + "null_count": 166321 + }, + { + "dtype": "float64", + "name": "ACS_MIL", + "null_count": 755441 + }, + { + "dtype": "float64", + "name": "OIP", + "null_count": 674473 + }, + { + "dtype": "float64", + "name": "PAP", + "null_count": 674473 + }, + { + "dtype": "float64", + "name": "RELSHIPP", + "null_count": 166321 + }, + { + "dtype": "float64", + "name": "RETP", + "null_count": 674473 + }, + { + "dtype": "float64", + "name": "SCHG", + "null_count": 2850008 + }, + { + "dtype": "float64", + "name": "SEMP", + "null_count": 674473 + }, + { + "dtype": "float64", + "name": "SEX", + "null_count": 166321 + }, + { + "dtype": "float64", + "name": "SSIP", + "null_count": 674473 + }, + { + "dtype": "float64", + "name": "SSP", + "null_count": 674473 + }, + { + "dtype": "float64", + "name": "WAGP", + "null_count": 674473 + }, + { + "dtype": "float64", + "name": "WKHP", + "null_count": 1820131 + }, + { + "dtype": "float64", + "name": "WKL", + "null_count": 714273 + }, + { + "dtype": "float64", + "name": "WKWN", + "null_count": 1820131 + }, + { + "dtype": "float64", + "name": "YOEP", + "null_count": 3104761 + }, + { + "dtype": "float64", + "name": "ESR", + "null_count": 714273 + }, + { + "dtype": "float64", + "name": "INDP", + "null_count": 1542526 + }, + { + "dtype": "float64", + "name": "OCCP", + "null_count": 1542526 + }, + { + "dtype": "float64", + "name": "POBP", + "null_count": 166321 + }, + { + "dtype": "float64", + "name": "FWKHP", + "null_count": 166321 + }, + { + "dtype": "float64", + "name": "ssi_reported", + "null_count": 0 + }, + { + "dtype": "float64", + "name": "acs_social_security_income", + "null_count": 674473 + }, + { + "dtype": "float64", + "name": "acs_retirement_income", + "null_count": 674473 + }, + { + "dtype": "float64", + "name": "acs_interest_dividend_rental_income", + "null_count": 674473 + }, + { + "dtype": "float64", + "name": "parent_1_id", + "null_count": 166321 + }, + { + "dtype": "float64", + "name": "parent_2_id", + "null_count": 166321 + }, + { + "dtype": "float64", + "name": "years_since_us_entry", + "null_count": 0 + }, + { + "dtype": "bool", + "name": "takes_up_wic_if_eligible", + "null_count": 0 + } + ], + "name": "person", + "rows": 3587263, + "storage": "fixed" + }, + { + "columns": [ + { + "dtype": "int64", + "name": "household_id", + "null_count": 0 + }, + { + "dtype": "int64", + "name": "state_fips", + "null_count": 0 + }, + { + "dtype": "float64", + "name": "H_TENURE", + "null_count": 1529668 + }, + { + "dtype": "str", + "name": "tenure_type", + "null_count": 0 + }, + { + "dtype": "int64", + "name": "household_source_id", + "null_count": 0 + }, + { + "dtype": "str", + "name": "household_support_channel", + "null_count": 0 + }, + { + "dtype": "int64", + "name": "household_support_clone_index", + "null_count": 0 + }, + { + "dtype": "int64", + "name": "congressional_district_geoid", + "null_count": 0 + }, + { + "dtype": "str", + "name": "block_geoid", + "null_count": 0 + }, + { + "dtype": "str", + "name": "tract_geoid", + "null_count": 0 + }, + { + "dtype": "str", + "name": "county_fips", + "null_count": 0 + }, + { + "dtype": "str", + "name": "place_fips", + "null_count": 0 + }, + { + "dtype": "str", + "name": "sldu", + "null_count": 0 + }, + { + "dtype": "str", + "name": "sldl", + "null_count": 0 + }, + { + "dtype": "str", + "name": "cbsa_code", + "null_count": 0 + }, + { + "dtype": "float64", + "name": "net_worth", + "null_count": 0 + }, + { + "dtype": "float64", + "name": "auto_loan_balance", + "null_count": 0 + }, + { + "dtype": "float64", + "name": "auto_loan_interest", + "null_count": 0 + }, + { + "dtype": "float64", + "name": "qualified_passenger_vehicle_loan_interest", + "null_count": 0 + }, + { + "dtype": "int64", + "name": "household_vehicles_owned", + "null_count": 0 + }, + { + "dtype": "float64", + "name": "household_vehicles_value", + "null_count": 0 + }, + { + "dtype": "str", + "name": "household_spine", + "null_count": 0 + }, + { + "dtype": "str", + "name": "SERIALNO", + "null_count": 57240 + }, + { + "dtype": "str", + "name": "ST", + "null_count": 57240 + }, + { + "dtype": "str", + "name": "PUMA", + "null_count": 57240 + }, + { + "dtype": "str", + "name": "puma_geoid", + "null_count": 57240 + }, + { + "dtype": "str", + "name": "puma", + "null_count": 0 + }, + { + "dtype": "float64", + "name": "NP", + "null_count": 57240 + }, + { + "dtype": "float64", + "name": "ADJHSG", + "null_count": 57240 + }, + { + "dtype": "float64", + "name": "TEN", + "null_count": 238500 + }, + { + "dtype": "float64", + "name": "RNTP", + "null_count": 1250798 + }, + { + "dtype": "float64", + "name": "GRNTP", + "null_count": 1250798 + }, + { + "dtype": "float64", + "name": "TAXAMT", + "null_count": 598224 + }, + { + "dtype": "float64", + "name": "TYPEHUGQ", + "null_count": 57240 + }, + { + "dtype": "float64", + "name": "FS", + "null_count": 57240 + }, + { + "dtype": "float64", + "name": "VEH", + "null_count": 238500 + }, + { + "dtype": "float64", + "name": "acs_monthly_contract_rent", + "null_count": 1250798 + }, + { + "dtype": "float64", + "name": "acs_monthly_gross_rent", + "null_count": 1250798 + }, + { + "dtype": "float64", + "name": "acs_annual_property_tax", + "null_count": 598224 + }, + { + "dtype": "str", + "name": "county_fips_2023", + "null_count": 0 + }, + { + "dtype": "float64", + "name": "household_weight", + "null_count": 0 + } + ], + "name": "household", + "rows": 1586908, + "storage": "fixed" + }, + { + "columns": [ + { + "dtype": "int64", + "name": "tax_unit_id", + "null_count": 0 + }, + { + "dtype": "str", + "name": "filing_status_input", + "null_count": 0 + }, + { + "dtype": "int64", + "name": "tax_unit_source_id", + "null_count": 0 + }, + { + "dtype": "str", + "name": "tax_unit_support_channel", + "null_count": 0 + }, + { + "dtype": "int64", + "name": "tax_unit_support_clone_index", + "null_count": 0 + }, + { + "dtype": "float64", + "name": "domestic_production_ald", + "null_count": 0 + }, + { + "dtype": "float64", + "name": "unrecaptured_section_1250_gain", + "null_count": 0 + }, + { + "dtype": "float64", + "name": "first_home_mortgage_balance", + "null_count": 0 + }, + { + "dtype": "float64", + "name": "second_home_mortgage_balance", + "null_count": 0 + }, + { + "dtype": "float64", + "name": "first_home_mortgage_interest", + "null_count": 0 + }, + { + "dtype": "float64", + "name": "second_home_mortgage_interest", + "null_count": 0 + }, + { + "dtype": "float64", + "name": "first_home_mortgage_origination_year", + "null_count": 0 + }, + { + "dtype": "int64", + "name": "second_home_mortgage_origination_year", + "null_count": 0 + }, + { + "dtype": "float64", + "name": "health_savings_account_ald", + "null_count": 0 + }, + { + "dtype": "bool", + "name": "takes_up_eitc", + "null_count": 0 + }, + { + "dtype": "bool", + "name": "would_file_taxes_voluntarily", + "null_count": 0 + }, + { + "dtype": "bool", + "name": "takes_up_aca_if_eligible", + "null_count": 0 + }, + { + "dtype": "float64", + "name": "selected_marketplace_plan_benchmark_ratio", + "null_count": 0 + }, + { + "dtype": "str", + "name": "tax_unit_spine", + "null_count": 0 + } + ], + "name": "tax_unit", + "rows": 2175528, + "storage": "fixed" + }, + { + "columns": [ + { + "dtype": "int64", + "name": "spm_unit_id", + "null_count": 0 + }, + { + "dtype": "float64", + "name": "spm_unit_pre_subsidy_childcare_expenses", + "null_count": 0 + }, + { + "dtype": "bool", + "name": "receives_housing_assistance", + "null_count": 0 + }, + { + "dtype": "bool", + "name": "takes_up_housing_assistance_if_eligible", + "null_count": 0 + }, + { + "dtype": "str", + "name": "spm_unit_tenure_type", + "null_count": 0 + }, + { + "dtype": "float64", + "name": "spm_unit_energy_subsidy", + "null_count": 0 + }, + { + "dtype": "int64", + "name": "spm_unit_source_id", + "null_count": 0 + }, + { + "dtype": "str", + "name": "spm_unit_support_channel", + "null_count": 0 + }, + { + "dtype": "int64", + "name": "spm_unit_support_clone_index", + "null_count": 0 + }, + { + "dtype": "bool", + "name": "takes_up_tanf_if_eligible", + "null_count": 0 + }, + { + "dtype": "bool", + "name": "takes_up_snap_if_eligible", + "null_count": 0 + }, + { + "dtype": "bool", + "name": "receives_snap", + "null_count": 0 + }, + { + "dtype": "bool", + "name": "receives_tanf", + "null_count": 0 + }, + { + "dtype": "str", + "name": "spm_unit_spine", + "null_count": 0 + } + ], + "name": "spm_unit", + "rows": 1589568, + "storage": "fixed" + }, + { + "columns": [ + { + "dtype": "int64", + "name": "family_id", + "null_count": 0 + }, + { + "dtype": "int64", + "name": "family_source_id", + "null_count": 0 + }, + { + "dtype": "str", + "name": "family_support_channel", + "null_count": 0 + }, + { + "dtype": "int64", + "name": "family_support_clone_index", + "null_count": 0 + }, + { + "dtype": "str", + "name": "family_spine", + "null_count": 0 + } + ], + "name": "family", + "rows": 1594874, + "storage": "fixed" + }, + { + "columns": [ + { + "dtype": "int64", + "name": "marital_unit_id", + "null_count": 0 + }, + { + "dtype": "int64", + "name": "marital_unit_source_id", + "null_count": 0 + }, + { + "dtype": "str", + "name": "marital_unit_support_channel", + "null_count": 0 + }, + { + "dtype": "int64", + "name": "marital_unit_support_clone_index", + "null_count": 0 + }, + { + "dtype": "str", + "name": "marital_unit_spine", + "null_count": 0 + } + ], + "name": "marital_unit", + "rows": 2867105, + "storage": "fixed" + } + ] + } + ], + "kind": "microcosm_us_release_schema_manifest", + "schema_version": 1 +} diff --git a/experiments/us-county-poc-20261117/schema_manifest.md b/experiments/us-county-poc-20261117/schema_manifest.md new file mode 100644 index 0000000000..26ed0cb6bc --- /dev/null +++ b/experiments/us-county-poc-20261117/schema_manifest.md @@ -0,0 +1,798 @@ +# Schema manifest: the 2024 county file (County Files proof of concept) + +Manifest kind `microcosm_us_release_schema_manifest`, schema version 1. Dtypes are as pandas reads each file; null counts count missing values in every row. + +## Notes + +These notes cover what the tables below do not show. Apart from this section, the file is the manifest tool's output, unchanged, and `schema_manifest.json` is as the tool wrote it. + +### Empty strings in six household columns + +`block_geoid`, `tract_geoid`, `place_fips`, `sldu`, `sldl` and `cbsa_code` hold an empty string, not a null, for all 1,529,668 ACS households. That is why the Nulls column shows 0 for them. The ACS public-use file locates a household only to its PUMA, and the build does not place ACS households below the PUMA, so the release fills these columns with `''` on ACS rows. Read `''` as missing. + +The 57,240 donor households take all six from the census block each was placed in. Some donors are blank as well: + +| Column | Blank donor households | Why | +| --- | ---: | --- | +| `block_geoid`, `tract_geoid`, `sldu` | 0 | | +| `place_fips` | 15,382 | The block is in no incorporated place or census-designated place. | +| `sldl` | 1,435 | Nebraska (884) and DC (551) have no lower-house districts. | +| `cbsa_code` | 5,343 | Outside Connecticut (4,435), the household's county is in no metropolitan or micropolitan area. All 908 Connecticut donor households are blank (below). | + +In Connecticut, a blank `cbsa_code` does not mean the household is outside a metropolitan or micropolitan area. The donor households got their geography before 30 September 2026, from code that looked a block's CBSA up by its 2020 county. The 2023 delineations list Connecticut by its nine planning regions instead, so no Connecticut block found a CBSA. The build has used the planning regions since that date, but the donor households keep their earlier geography. + +### Which columns the model reads + +policyengine-us 2.2.1 sets a column as an input only if its name is a model variable. It loads the other columns and ignores them; these are the 254 ignored columns the README and the report mention. In this file the split follows letter case: the model reads every lowercase column except 40 build identifiers and derived columns, and no uppercase column. + +| Kind | Columns | Which | +| --- | ---: | --- | +| Read by the model | 198 | 153 person, 19 household, 14 tax_unit, 10 spm_unit, 1 family, 1 marital_unit | +| Raw CPS ASEC fields | 162 | Uppercase, under their Census names: 161 person and household `H_TENURE`. Null on ACS rows, except eight (below). | +| Raw ACS 2024 PUMS fields | 51 | Uppercase; null on donor rows. `ST` is the Census `STATE` and `ACS_MIL` the Census `MIL`. Listed below. | +| Build identifiers | 29 | For each of the six tables, `{table}_source_id`, `{table}_support_channel`, `{table}_support_clone_index` and `{table}_spine`; plus `source_year`, `source_household_id`, `source_person_id`, `source_row_id` and the uppercase `CENSUS_TAX_ID`. `household_spine` is `acs_2024_1yr` for ACS households and `asec_puf` for donor households. | +| Derived columns | 12 | `county_fips_2023`, `puma_geoid`, `acs_social_security_income`, `acs_retirement_income`, `acs_interest_dividend_rental_income`, `acs_monthly_contract_rent`, `acs_monthly_gross_rent`, `acs_annual_property_tax`, `tax_unit_role_input`, `filing_status_input`, `parent_1_id`, `parent_2_id` | + +The 51 ACS fields are, for persons, `SPORDER`, `ADJINC`, `PWGTP`, `AGEP`, `CIT`, `COW`, `DDRS`, `DEAR`, `DEYE`, `DOUT`, `DPHY`, `DREM`, `HINS3`, `HINS4`, `HINS5`, `HINS6`, `HINS7`, `INTP`, `MAR`, `ACS_MIL`, `OIP`, `PAP`, `RELSHIPP`, `RETP`, `SCHG`, `SEMP`, `SEX`, `SSIP`, `SSP`, `WAGP`, `WKHP`, `WKL`, `WKWN`, `YOEP`, `ESR`, `INDP`, `OCCP`, `POBP` and `FWKHP`, and for households `SERIALNO`, `ST`, `PUMA`, `NP`, `ADJHSG`, `TEN`, `RNTP`, `GRNTP`, `TAXAMT`, `TYPEHUGQ`, `FS` and `VEH`. + +Three more points: + +- Eight CPS ASEC names have no nulls: `PH_SEQ`, `A_LINENO`, `A_AGE`, `A_MARITL`, `A_SPOUSE`, `PEPAR1`, `PEPAR2` and `A_EXPRRP`. On ACS rows the build fills them from ACS fields so that it can form tax units. +- The model reads raw survey values only under its own names. On ACS rows, for example, `employment_income_before_lsr` is `WAGP` times `ADJINC`. +- The model reads `county_fips` (2020 counties). It does not read `county_fips_2023`. + +### Removed columns, the rename and the dtype changes + +These compare the file with the sample column list sent with the County Files agreement. + +- `has_marketplace_health_coverage` and `weeks_worked`: policyengine-us 2.2.1 has a formula for each, and the release leaves out any column the model can compute with a formula in some year. It keeps id columns, and inputs that policyengine-us says the data must supply even though it has a fallback formula, such as `is_spm_independent_minor_role`. The formula for `has_marketplace_health_coverage` returns `has_marketplace_health_coverage_at_interview`, which the file keeps. The formula for `weeks_worked` applies from 2025. +- `medicare_part_b_premiums`, the CPS ASEC Part B premium (`PEMCPREM`): policyengine-us 2.2.1 has no variable by this name, so the release no longer stores it. It held values for the 166,321 donor persons only. +- 128 dtype changes are int64 to float64: 127 person columns and household `H_TENURE`. All are CPS ASEC fields with no value on ACS rows. An int64 column cannot hold a missing value, so when the build stacks donor and ACS rows, pandas stores these columns as float64. Only the storage type changes. The sample file had no ACS rows. +- The other six are columns that are null on ACS rows, where the release fills the model's default, 0, and stores the model's type, int64 or float64: household `household_vehicles_owned` (int32 to int64) and `household_vehicles_value` (float32 to float64); person `cps_race` (int16 to int64), `fsla_overtime_premium` (float32 to float64) and `treasury_tipped_occupation_code` (int16 to int64); and tax_unit `second_home_mortgage_origination_year` (float64 to int64). + +## Files + +| File | Format | Size (bytes) | SHA-256 | +| --- | --- | ---: | --- | +| populace_us_2024_acs_local.h5 | hdf5 | 10,637,811,669 | 82314a3b5a6a95762faf6eb4f5b499ce56608ad6a39a27b75e11c75b4945bd3c | + +## Metadata + +| File | Item | Value | +| --- | --- | --- | +| populace_us_2024_acs_local.h5 | key `_populace_staging_metadata` | {"artifact_kind": "calibrated_local_area_artifact", "entity_hdf_format": "fixed_nullable", "household_weight_kind": "calibrated"} | +| populace_us_2024_acs_local.h5 | key `_time_period` | 2024 | + +## Tables + +| Table | File | Storage | Rows | Columns | +| --- | --- | --- | ---: | ---: | +| person | populace_us_2024_acs_local.h5 | fixed | 3,587,263 | 368 | +| household | populace_us_2024_acs_local.h5 | fixed | 1,586,908 | 41 | +| tax_unit | populace_us_2024_acs_local.h5 | fixed | 2,175,528 | 19 | +| spm_unit | populace_us_2024_acs_local.h5 | fixed | 1,589,568 | 14 | +| family | populace_us_2024_acs_local.h5 | fixed | 1,594,874 | 5 | +| marital_unit | populace_us_2024_acs_local.h5 | fixed | 2,867,105 | 5 | + +### `person` + +| Column | Dtype | Logical dtype | Nulls | +| --- | --- | --- | ---: | +| `PERIDNUM` | str | | 3,420,942 | +| `PH_SEQ` | int64 | | 0 | +| `P_SEQ` | float64 | | 3,420,942 | +| `A_LINENO` | int64 | | 0 | +| `PF_SEQ` | float64 | | 3,420,942 | +| `PEAFEVER` | float64 | | 3,420,942 | +| `PENATVTY` | float64 | | 3,420,942 | +| `PEINUSYR` | float64 | | 3,420,942 | +| `PEPAR1` | int64 | | 0 | +| `PEPAR2` | int64 | | 0 | +| `PRDTHSP` | float64 | | 3,420,942 | +| `PRDTRACE` | float64 | | 3,420,942 | +| `PRCITSHP` | float64 | | 3,420,942 | +| `PECOHAB` | float64 | | 3,530,060 | +| `PEIO1COW` | float64 | | 3,420,942 | +| `PEDISEAR` | float64 | | 3,420,942 | +| `PEDISEYE` | float64 | | 3,420,942 | +| `PEDISREM` | float64 | | 3,420,942 | +| `PEDISPHY` | float64 | | 3,420,942 | +| `PEDISDRS` | float64 | | 3,420,942 | +| `PEDISOUT` | float64 | | 3,420,942 | +| `A_AGE` | int64 | | 0 | +| `A_SEX` | float64 | | 3,420,942 | +| `A_ENRLW` | float64 | | 3,530,060 | +| `A_MJOCC` | float64 | | 3,420,942 | +| `A_HSCOL` | float64 | | 3,420,942 | +| `A_FTPT` | float64 | | 3,530,060 | +| `A_FNLWGT` | float64 | | 3,420,942 | +| `A_FAMREL` | float64 | | 3,530,060 | +| `A_FAMTYP` | float64 | | 3,530,060 | +| `A_SPOUSE` | int64 | | 0 | +| `A_MARITL` | int64 | | 0 | +| `A_HRS1` | float64 | | 3,420,942 | +| `A_EXPRRP` | int64 | | 0 | +| `ACTC_CRD` | float64 | | 3,420,942 | +| `AGI` | float64 | | 3,420,942 | +| `ANN_VAL` | float64 | | 3,420,942 | +| `CAID` | float64 | | 3,420,942 | +| `CAP_VAL` | float64 | | 3,420,942 | +| `CHAMPVA` | float64 | | 3,420,942 | +| `CHSP_VAL` | float64 | | 3,420,942 | +| `CSP_VAL` | float64 | | 3,420,942 | +| `CTC_CRD` | float64 | | 3,420,942 | +| `DIS_SC1` | float64 | | 3,420,942 | +| `DIS_SC2` | float64 | | 3,420,942 | +| `DIS_VAL1` | float64 | | 3,420,942 | +| `DIS_VAL2` | float64 | | 3,420,942 | +| `DIV_VAL` | float64 | | 3,420,942 | +| `DST_SC1` | float64 | | 3,420,942 | +| `DST_SC2` | float64 | | 3,420,942 | +| `DST_SC1_YNG` | float64 | | 3,420,942 | +| `DST_SC2_YNG` | float64 | | 3,420,942 | +| `DST_VAL1` | float64 | | 3,420,942 | +| `DST_VAL2` | float64 | | 3,420,942 | +| `DST_VAL1_YNG` | float64 | | 3,420,942 | +| `DST_VAL2_YNG` | float64 | | 3,420,942 | +| `EIT_CRED` | float64 | | 3,420,942 | +| `FEDTAX_AC` | float64 | | 3,420,942 | +| `FEDTAX_BC` | float64 | | 3,420,942 | +| `FRSE_VAL` | float64 | | 3,420,942 | +| `HRSWK` | float64 | | 3,420,942 | +| `IHSFLG` | float64 | | 3,420,942 | +| `INT_VAL` | float64 | | 3,420,942 | +| `I_ERNVAL` | float64 | | 3,420,942 | +| `I_SEVAL` | float64 | | 3,420,942 | +| `LKWEEKS` | float64 | | 3,420,942 | +| `MARG_TAX` | float64 | | 3,420,942 | +| `MCARE` | float64 | | 3,420,942 | +| `MIL` | float64 | | 3,420,942 | +| `MOOP` | float64 | | 3,420,942 | +| `NOW_CAID` | float64 | | 3,530,060 | +| `NOW_CHAMPVA` | float64 | | 3,530,060 | +| `NOW_COV` | float64 | | 3,530,060 | +| `NOW_DIR` | float64 | | 3,530,060 | +| `NOW_GRP` | float64 | | 3,420,942 | +| `NOW_IHSFLG` | float64 | | 3,530,060 | +| `NOW_MCAID` | float64 | | 3,530,060 | +| `NOW_MCARE` | float64 | | 3,530,060 | +| `NOW_MIL` | float64 | | 3,530,060 | +| `NOW_MRK` | float64 | | 3,420,942 | +| `NOW_MRKS` | float64 | | 3,530,060 | +| `NOW_MRKUN` | float64 | | 3,530,060 | +| `NOW_NONM` | float64 | | 3,530,060 | +| `NOW_OTHMT` | float64 | | 3,530,060 | +| `NOW_PCHIP` | float64 | | 3,530,060 | +| `NOW_PRIV` | float64 | | 3,530,060 | +| `NOW_PUB` | float64 | | 3,530,060 | +| `NOW_VACARE` | float64 | | 3,530,060 | +| `OI_OFF` | float64 | | 3,420,942 | +| `OI_VAL` | float64 | | 3,420,942 | +| `PAW_VAL` | float64 | | 3,420,942 | +| `PEMCPREM` | float64 | | 3,420,942 | +| `PEN_SC1` | float64 | | 3,420,942 | +| `PEN_SC2` | float64 | | 3,420,942 | +| `PHIP_VAL` | float64 | | 3,420,942 | +| `PMED_VAL` | float64 | | 3,420,942 | +| `PNSN_VAL` | float64 | | 3,420,942 | +| `POCCU2` | float64 | | 3,420,942 | +| `POTC_VAL` | float64 | | 3,420,942 | +| `PTOTVAL` | float64 | | 3,530,060 | +| `RESNSS1` | float64 | | 3,420,942 | +| `RESNSS2` | float64 | | 3,420,942 | +| `RESNSSI1` | float64 | | 3,420,942 | +| `RESNSSI2` | float64 | | 3,420,942 | +| `RETCB_VAL` | float64 | | 3,420,942 | +| `RNT_VAL` | float64 | | 3,420,942 | +| `SEMP_VAL` | float64 | | 3,420,942 | +| `SPM_ACTC` | float64 | | 3,420,942 | +| `SPM_BBSUBVAL` | float64 | | 3,420,942 | +| `SPM_CAPHOUSESUB` | float64 | | 3,420,942 | +| `SPM_CAPWKCCXPNS` | float64 | | 3,420,942 | +| `SPM_CHILDCAREXPNS` | float64 | | 3,420,942 | +| `SPM_CHILDSUPPD` | float64 | | 3,420,942 | +| `SPM_EITC` | float64 | | 3,420,942 | +| `SPM_ENGVAL` | float64 | | 3,420,942 | +| `SPM_EQUIVSCALE` | float64 | | 3,420,942 | +| `SPM_FAMTYPE` | float64 | | 3,420,942 | +| `SPM_FEDTAX` | float64 | | 3,420,942 | +| `SPM_FEDTAXBC` | float64 | | 3,420,942 | +| `SPM_FICA` | float64 | | 3,420,942 | +| `SPM_GEOADJ` | float64 | | 3,420,942 | +| `SPM_HAGE` | float64 | | 3,420,942 | +| `SPM_HHISP` | float64 | | 3,420,942 | +| `SPM_HMARITALSTATUS` | float64 | | 3,420,942 | +| `SPM_HRACE` | float64 | | 3,420,942 | +| `SPM_ID` | float64 | | 3,420,942 | +| `SPM_MEDXPNS` | float64 | | 3,420,942 | +| `SPM_NUMADULTS` | float64 | | 3,420,942 | +| `SPM_NUMKIDS` | float64 | | 3,420,942 | +| `SPM_NUMPER` | float64 | | 3,420,942 | +| `SPM_POOR` | float64 | | 3,420,942 | +| `SPM_POVTHRESHOLD` | float64 | | 3,420,942 | +| `SPM_RESOURCES` | float64 | | 3,420,942 | +| `SPM_SCHLUNCH` | float64 | | 3,420,942 | +| `SPM_SNAPSUB` | float64 | | 3,420,942 | +| `SPM_STTAX` | float64 | | 3,420,942 | +| `SPM_TENMORTSTATUS` | float64 | | 3,420,942 | +| `SPM_TOTVAL` | float64 | | 3,420,942 | +| `SPM_WCOHABIT` | float64 | | 3,420,942 | +| `SPM_WEIGHT` | float64 | | 3,420,942 | +| `SPM_WFOSTER22` | float64 | | 3,420,942 | +| `SPM_WICVAL` | float64 | | 3,420,942 | +| `SPM_WKXPNS` | float64 | | 3,420,942 | +| `SPM_WNEWHEAD` | float64 | | 3,420,942 | +| `SPM_WNEWPARENT` | float64 | | 3,420,942 | +| `SPM_WUI_LT15` | float64 | | 3,420,942 | +| `SSI_VAL` | float64 | | 3,420,942 | +| `SSI_YN` | float64 | | 3,420,942 | +| `SS_VAL` | float64 | | 3,420,942 | +| `SS_YN` | float64 | | 3,420,942 | +| `STATETAX_A` | float64 | | 3,420,942 | +| `STATETAX_B` | float64 | | 3,420,942 | +| `TAX_INC` | float64 | | 3,420,942 | +| `UC_VAL` | float64 | | 3,420,942 | +| `VET_VAL` | float64 | | 3,420,942 | +| `WC_VAL` | float64 | | 3,420,942 | +| `WICYN` | float64 | | 3,420,942 | +| `WKSWORK` | float64 | | 3,420,942 | +| `WSAL_VAL` | float64 | | 3,420,942 | +| `TAX_ID` | float64 | | 3,420,942 | +| `PEIOOCC` | float64 | | 3,420,942 | +| `CENSUS_TAX_ID` | float64 | | 3,530,060 | +| `source_year` | int64 | | 0 | +| `source_household_id` | int64 | | 0 | +| `source_person_id` | str | | 0 | +| `source_row_id` | int64 | | 0 | +| `person_tax_unit_id` | int64 | | 0 | +| `tax_unit_role_input` | str | | 0 | +| `is_related_to_head_or_spouse` | bool | | 0 | +| `person_spm_unit_id` | int64 | | 0 | +| `person_family_id` | int64 | | 0 | +| `person_marital_unit_id` | int64 | | 0 | +| `person_household_id` | int64 | | 0 | +| `person_id` | int64 | | 0 | +| `age` | float64 | | 0 | +| `is_female` | bool | | 0 | +| `employment_income_before_lsr` | float64 | | 0 | +| `self_employment_income_before_lsr` | float64 | | 0 | +| `taxable_interest_income` | float64 | | 0 | +| `qualified_dividend_income` | float64 | | 0 | +| `non_qualified_dividend_income` | float64 | | 0 | +| `long_term_capital_gains_before_response` | float64 | | 0 | +| `short_term_capital_gains` | float64 | | 0 | +| `social_security_retirement` | float64 | | 0 | +| `social_security_disability` | float64 | | 0 | +| `social_security_survivors` | float64 | | 0 | +| `social_security_dependents` | float64 | | 0 | +| `taxable_private_pension_income` | float64 | | 0 | +| `tax_exempt_private_pension_income` | float64 | | 0 | +| `taxable_ira_distributions` | float64 | | 0 | +| `alimony_income` | float64 | | 0 | +| `miscellaneous_income` | float64 | | 0 | +| `rental_income` | float64 | | 0 | +| `farm_operations_income` | float64 | | 0 | +| `unemployment_compensation` | float64 | | 0 | +| `health_insurance_premiums_without_medicare_part_b` | float64 | | 0 | +| `other_medical_expenses` | float64 | | 0 | +| `over_the_counter_health_expenses` | float64 | | 0 | +| `has_marketplace_health_coverage_at_interview` | bool | | 0 | +| `has_non_marketplace_direct_purchase_health_coverage_at_interview` | bool | | 0 | +| `has_medicaid_health_coverage_at_interview` | bool | | 0 | +| `has_esi` | bool | | 0 | +| `has_champva_health_coverage_at_interview` | bool | | 0 | +| `has_tricare_health_coverage_at_interview` | bool | | 0 | +| `has_va_health_coverage_at_interview` | bool | | 0 | +| `has_other_means_tested_health_coverage_at_interview` | bool | | 0 | +| `has_indian_health_service_coverage_at_interview` | bool | | 0 | +| `self_employment_income_last_year` | float64 | | 0 | +| `previous_year_income_available` | bool | | 0 | +| `is_household_head` | bool | | 0 | +| `is_separated` | bool | | 0 | +| `is_surviving_spouse` | bool | | 0 | +| `takes_up_medicare_if_eligible` | bool | | 0 | +| `pre_subsidy_rent` | float64 | | 0 | +| `is_disabled` | bool | | 0 | +| `is_blind` | bool | | 0 | +| `is_full_time_college_student` | bool | | 0 | +| `own_children_in_household` | float64 | | 0 | +| `veterans_benefits` | float64 | | 0 | +| `is_pregnant` | bool | | 0 | +| `child_support_received` | float64 | | 0 | +| `child_support_expense` | float64 | | 0 | +| `disability_benefits` | float64 | | 0 | +| `workers_compensation` | float64 | | 0 | +| `weeks_unemployed` | float64 | | 0 | +| `traditional_401k_contributions_desired` | float64 | | 0 | +| `roth_401k_contributions_desired` | float64 | | 0 | +| `traditional_ira_contributions_desired` | float64 | | 0 | +| `roth_ira_contributions_desired` | float64 | | 0 | +| `self_employed_pension_contributions_desired` | float64 | | 0 | +| `taxable_401k_distributions` | float64 | | 0 | +| `taxable_403b_distributions` | float64 | | 0 | +| `tax_exempt_ira_distributions` | float64 | | 0 | +| `keogh_distributions` | float64 | | 0 | +| `taxable_sep_distributions` | float64 | | 0 | +| `ssn_card_type` | str | | 0 | +| `immigration_status_str` | str | | 0 | +| `person_source_id` | int64 | | 0 | +| `person_support_channel` | str | | 0 | +| `person_support_clone_index` | int64 | | 0 | +| `tax_exempt_interest_income` | float64 | | 0 | +| `long_term_capital_gains_on_collectibles` | float64 | | 0 | +| `non_sch_d_capital_gains` | float64 | | 0 | +| `alimony_expense` | float64 | | 0 | +| `salt_refund_income` | float64 | | 0 | +| `charitable_cash_donations` | float64 | | 0 | +| `charitable_non_cash_donations` | float64 | | 0 | +| `real_estate_taxes` | float64 | | 0 | +| `home_mortgage_interest` | float64 | | 0 | +| `investment_interest_expense` | float64 | | 0 | +| `investment_income_elected_form_4952` | float64 | | 0 | +| `student_loan_interest` | float64 | | 0 | +| `educator_expense` | float64 | | 0 | +| `qualified_tuition_expenses` | float64 | | 0 | +| `casualty_loss` | float64 | | 0 | +| `unreimbursed_business_employee_expenses` | float64 | | 0 | +| `estate_income` | float64 | | 0 | +| `farm_income` | float64 | | 0 | +| `farm_rent_income` | float64 | | 0 | +| `partnership_income` | float64 | | 0 | +| `s_corp_income` | float64 | | 0 | +| `partnership_self_employment_net_earnings` | float64 | | 0 | +| `estate_income_would_be_qualified` | bool | | 0 | +| `farm_operations_income_would_be_qualified` | bool | | 0 | +| `farm_rent_income_would_be_qualified` | bool | | 0 | +| `partnership_s_corp_income_would_be_qualified` | bool | | 0 | +| `rental_income_would_be_qualified` | bool | | 0 | +| `self_employment_income_would_be_qualified` | bool | | 0 | +| `sstb_self_employment_income_would_be_qualified` | bool | | 0 | +| `business_is_sstb` | bool | | 0 | +| `qualified_bdc_income` | float64 | | 0 | +| `qualified_reit_and_ptp_income` | float64 | | 0 | +| `sstb_self_employment_income_before_lsr` | float64 | | 0 | +| `sstb_unadjusted_basis_qualified_property` | float64 | | 0 | +| `sstb_w2_wages_from_qualified_business` | float64 | | 0 | +| `unadjusted_basis_qualified_property` | float64 | | 0 | +| `w2_wages_from_qualified_business` | float64 | | 0 | +| `schedule_d_capital_gain_distributions` | float64 | | 0 | +| `is_incapable_of_self_care` | bool | | 0 | +| `pre_subsidy_care_expenses` | float64 | | 0 | +| `educational_assistance` | float64 | | 0 | +| `is_pursuing_credential_for_american_opportunity_credit` | bool | | 0 | +| `attends_eligible_educational_institution_for_american_opportunity_credit` | bool | | 0 | +| `is_enrolled_at_least_half_time_for_american_opportunity_credit` | bool | | 0 | +| `has_american_opportunity_credit_1098_t_or_exception` | bool | | 0 | +| `has_american_opportunity_credit_institution_ein` | bool | | 0 | +| `weekly_hours_worked_before_lsr` | float64 | | 0 | +| `hours_worked_last_week` | float64 | | 0 | +| `is_snap_abawd_discretionary_exempt` | bool | | 0 | +| `bank_account_assets` | float64 | | 0 | +| `stock_assets` | float64 | | 0 | +| `bond_assets` | float64 | | 0 | +| `meets_ssi_disability_criteria` | bool | | 0 | +| `takes_up_head_start_if_eligible` | bool | | 0 | +| `takes_up_ssi_if_eligible` | bool | | 0 | +| `tip_income` | float64 | | 0 | +| `treasury_tipped_occupation_code` | int64 | | 0 | +| `cps_race` | int64 | | 0 | +| `is_hispanic` | bool | | 0 | +| `detailed_occupation_recode` | int16 | | 0 | +| `has_never_worked` | bool | | 0 | +| `is_military` | bool | | 0 | +| `is_computer_scientist` | bool | | 0 | +| `is_farmer_fisher` | bool | | 0 | +| `is_executive_administrative_professional` | bool | | 0 | +| `hourly_wage` | float64 | | 0 | +| `is_paid_hourly` | bool | | 0 | +| `is_union_member_or_covered` | bool | | 0 | +| `fsla_overtime_premium` | float64 | | 0 | +| `takes_up_medicaid_if_eligible` | bool | | 0 | +| `other_health_insurance_premiums` | float64 | | 0 | +| `health_insurance_premiums` | float64 | | 0 | +| `is_self_employed` | bool | | 0 | +| `is_spm_independent_minor_role` | bool | | 0 | +| `receives_wic` | bool | | 0 | +| `detailed_industry_recode` | int16 | | 0 | +| `major_industry_recode` | int16 | | 0 | +| `worked_last_year` | bool | | 0 | +| `strike_benefits` | float64 | | 0 | +| `passive_partnership_s_corp_income` | float64 | | 0 | +| `person_spine` | str | | 0 | +| `SPORDER` | float64 | | 166,321 | +| `ADJINC` | float64 | | 166,321 | +| `PWGTP` | float64 | | 166,321 | +| `AGEP` | float64 | | 166,321 | +| `CIT` | float64 | | 166,321 | +| `COW` | float64 | | 1,542,526 | +| `DDRS` | float64 | | 317,477 | +| `DEAR` | float64 | | 166,321 | +| `DEYE` | float64 | | 166,321 | +| `DOUT` | float64 | | 674,473 | +| `DPHY` | float64 | | 317,477 | +| `DREM` | float64 | | 317,477 | +| `HINS3` | float64 | | 166,321 | +| `HINS4` | float64 | | 166,321 | +| `HINS5` | float64 | | 166,321 | +| `HINS6` | float64 | | 166,321 | +| `HINS7` | float64 | | 166,321 | +| `INTP` | float64 | | 674,473 | +| `MAR` | float64 | | 166,321 | +| `ACS_MIL` | float64 | | 755,441 | +| `OIP` | float64 | | 674,473 | +| `PAP` | float64 | | 674,473 | +| `RELSHIPP` | float64 | | 166,321 | +| `RETP` | float64 | | 674,473 | +| `SCHG` | float64 | | 2,850,008 | +| `SEMP` | float64 | | 674,473 | +| `SEX` | float64 | | 166,321 | +| `SSIP` | float64 | | 674,473 | +| `SSP` | float64 | | 674,473 | +| `WAGP` | float64 | | 674,473 | +| `WKHP` | float64 | | 1,820,131 | +| `WKL` | float64 | | 714,273 | +| `WKWN` | float64 | | 1,820,131 | +| `YOEP` | float64 | | 3,104,761 | +| `ESR` | float64 | | 714,273 | +| `INDP` | float64 | | 1,542,526 | +| `OCCP` | float64 | | 1,542,526 | +| `POBP` | float64 | | 166,321 | +| `FWKHP` | float64 | | 166,321 | +| `ssi_reported` | float64 | | 0 | +| `acs_social_security_income` | float64 | | 674,473 | +| `acs_retirement_income` | float64 | | 674,473 | +| `acs_interest_dividend_rental_income` | float64 | | 674,473 | +| `parent_1_id` | float64 | | 166,321 | +| `parent_2_id` | float64 | | 166,321 | +| `years_since_us_entry` | float64 | | 0 | +| `takes_up_wic_if_eligible` | bool | | 0 | + +### `household` + +| Column | Dtype | Logical dtype | Nulls | +| --- | --- | --- | ---: | +| `household_id` | int64 | | 0 | +| `state_fips` | int64 | | 0 | +| `H_TENURE` | float64 | | 1,529,668 | +| `tenure_type` | str | | 0 | +| `household_source_id` | int64 | | 0 | +| `household_support_channel` | str | | 0 | +| `household_support_clone_index` | int64 | | 0 | +| `congressional_district_geoid` | int64 | | 0 | +| `block_geoid` | str | | 0 | +| `tract_geoid` | str | | 0 | +| `county_fips` | str | | 0 | +| `place_fips` | str | | 0 | +| `sldu` | str | | 0 | +| `sldl` | str | | 0 | +| `cbsa_code` | str | | 0 | +| `net_worth` | float64 | | 0 | +| `auto_loan_balance` | float64 | | 0 | +| `auto_loan_interest` | float64 | | 0 | +| `qualified_passenger_vehicle_loan_interest` | float64 | | 0 | +| `household_vehicles_owned` | int64 | | 0 | +| `household_vehicles_value` | float64 | | 0 | +| `household_spine` | str | | 0 | +| `SERIALNO` | str | | 57,240 | +| `ST` | str | | 57,240 | +| `PUMA` | str | | 57,240 | +| `puma_geoid` | str | | 57,240 | +| `puma` | str | | 0 | +| `NP` | float64 | | 57,240 | +| `ADJHSG` | float64 | | 57,240 | +| `TEN` | float64 | | 238,500 | +| `RNTP` | float64 | | 1,250,798 | +| `GRNTP` | float64 | | 1,250,798 | +| `TAXAMT` | float64 | | 598,224 | +| `TYPEHUGQ` | float64 | | 57,240 | +| `FS` | float64 | | 57,240 | +| `VEH` | float64 | | 238,500 | +| `acs_monthly_contract_rent` | float64 | | 1,250,798 | +| `acs_monthly_gross_rent` | float64 | | 1,250,798 | +| `acs_annual_property_tax` | float64 | | 598,224 | +| `county_fips_2023` | str | | 0 | +| `household_weight` | float64 | | 0 | + +### `tax_unit` + +| Column | Dtype | Logical dtype | Nulls | +| --- | --- | --- | ---: | +| `tax_unit_id` | int64 | | 0 | +| `filing_status_input` | str | | 0 | +| `tax_unit_source_id` | int64 | | 0 | +| `tax_unit_support_channel` | str | | 0 | +| `tax_unit_support_clone_index` | int64 | | 0 | +| `domestic_production_ald` | float64 | | 0 | +| `unrecaptured_section_1250_gain` | float64 | | 0 | +| `first_home_mortgage_balance` | float64 | | 0 | +| `second_home_mortgage_balance` | float64 | | 0 | +| `first_home_mortgage_interest` | float64 | | 0 | +| `second_home_mortgage_interest` | float64 | | 0 | +| `first_home_mortgage_origination_year` | float64 | | 0 | +| `second_home_mortgage_origination_year` | int64 | | 0 | +| `health_savings_account_ald` | float64 | | 0 | +| `takes_up_eitc` | bool | | 0 | +| `would_file_taxes_voluntarily` | bool | | 0 | +| `takes_up_aca_if_eligible` | bool | | 0 | +| `selected_marketplace_plan_benchmark_ratio` | float64 | | 0 | +| `tax_unit_spine` | str | | 0 | + +### `spm_unit` + +| Column | Dtype | Logical dtype | Nulls | +| --- | --- | --- | ---: | +| `spm_unit_id` | int64 | | 0 | +| `spm_unit_pre_subsidy_childcare_expenses` | float64 | | 0 | +| `receives_housing_assistance` | bool | | 0 | +| `takes_up_housing_assistance_if_eligible` | bool | | 0 | +| `spm_unit_tenure_type` | str | | 0 | +| `spm_unit_energy_subsidy` | float64 | | 0 | +| `spm_unit_source_id` | int64 | | 0 | +| `spm_unit_support_channel` | str | | 0 | +| `spm_unit_support_clone_index` | int64 | | 0 | +| `takes_up_tanf_if_eligible` | bool | | 0 | +| `takes_up_snap_if_eligible` | bool | | 0 | +| `receives_snap` | bool | | 0 | +| `receives_tanf` | bool | | 0 | +| `spm_unit_spine` | str | | 0 | + +### `family` + +| Column | Dtype | Logical dtype | Nulls | +| --- | --- | --- | ---: | +| `family_id` | int64 | | 0 | +| `family_source_id` | int64 | | 0 | +| `family_support_channel` | str | | 0 | +| `family_support_clone_index` | int64 | | 0 | +| `family_spine` | str | | 0 | + +### `marital_unit` + +| Column | Dtype | Logical dtype | Nulls | +| --- | --- | --- | ---: | +| `marital_unit_id` | int64 | | 0 | +| `marital_unit_source_id` | int64 | | 0 | +| `marital_unit_support_channel` | str | | 0 | +| `marital_unit_support_clone_index` | int64 | | 0 | +| `marital_unit_spine` | str | | 0 | + +## Changes from the prior schema + +Compared with the sample column list sent with the County Files agreement: `prior_sample_columns.csv`. + +### Columns added + +| Table | Column | Dtype | +| --- | --- | --- | +| family | `family_spine` | str | +| household | `ADJHSG` | float64 | +| household | `FS` | float64 | +| household | `GRNTP` | float64 | +| household | `NP` | float64 | +| household | `PUMA` | str | +| household | `RNTP` | float64 | +| household | `SERIALNO` | str | +| household | `ST` | str | +| household | `TAXAMT` | float64 | +| household | `TEN` | float64 | +| household | `TYPEHUGQ` | float64 | +| household | `VEH` | float64 | +| household | `acs_annual_property_tax` | float64 | +| household | `acs_monthly_contract_rent` | float64 | +| household | `acs_monthly_gross_rent` | float64 | +| household | `county_fips_2023` | str | +| household | `household_spine` | str | +| household | `puma` | str | +| household | `puma_geoid` | str | +| marital_unit | `marital_unit_spine` | str | +| person | `ACS_MIL` | float64 | +| person | `ADJINC` | float64 | +| person | `AGEP` | float64 | +| person | `CIT` | float64 | +| person | `COW` | float64 | +| person | `DDRS` | float64 | +| person | `DEAR` | float64 | +| person | `DEYE` | float64 | +| person | `DOUT` | float64 | +| person | `DPHY` | float64 | +| person | `DREM` | float64 | +| person | `ESR` | float64 | +| person | `FWKHP` | float64 | +| person | `HINS3` | float64 | +| person | `HINS4` | float64 | +| person | `HINS5` | float64 | +| person | `HINS6` | float64 | +| person | `HINS7` | float64 | +| person | `INDP` | float64 | +| person | `INTP` | float64 | +| person | `MAR` | float64 | +| person | `OCCP` | float64 | +| person | `OIP` | float64 | +| person | `PAP` | float64 | +| person | `POBP` | float64 | +| person | `PWGTP` | float64 | +| person | `RELSHIPP` | float64 | +| person | `RETP` | float64 | +| person | `SCHG` | float64 | +| person | `SEMP` | float64 | +| person | `SEX` | float64 | +| person | `SPORDER` | float64 | +| person | `SSIP` | float64 | +| person | `SSP` | float64 | +| person | `WAGP` | float64 | +| person | `WKHP` | float64 | +| person | `WKL` | float64 | +| person | `WKWN` | float64 | +| person | `YOEP` | float64 | +| person | `acs_interest_dividend_rental_income` | float64 | +| person | `acs_retirement_income` | float64 | +| person | `acs_social_security_income` | float64 | +| person | `detailed_industry_recode` | int16 | +| person | `is_spm_independent_minor_role` | bool | +| person | `major_industry_recode` | int16 | +| person | `parent_1_id` | float64 | +| person | `parent_2_id` | float64 | +| person | `passive_partnership_s_corp_income` | float64 | +| person | `person_spine` | str | +| person | `receives_wic` | bool | +| person | `ssi_reported` | float64 | +| person | `strike_benefits` | float64 | +| person | `worked_last_year` | bool | +| person | `years_since_us_entry` | float64 | +| spm_unit | `receives_snap` | bool | +| spm_unit | `receives_tanf` | bool | +| spm_unit | `spm_unit_spine` | str | +| tax_unit | `tax_unit_spine` | str | + +### Columns removed + +| Table | Column | Dtype | +| --- | --- | --- | +| person | `has_marketplace_health_coverage` | bool | +| person | `medicare_part_b_premiums` | float64 | +| person | `weeks_worked` | float64 | + +### Columns renamed + +| Table | From | To | Dtype | Why | +| --- | --- | --- | --- | --- | +| person | `would_claim_wic` | `takes_up_wic_if_eligible` | bool | policyengine-us names the WIC take-up input takes_up_wic_if_eligible; it defines no would_claim_wic. | + +### Dtypes changed + +| Table | Column | Before | After | +| --- | --- | --- | --- | +| household | `H_TENURE` | int64 | float64 | +| household | `household_vehicles_owned` | int32 | int64 | +| household | `household_vehicles_value` | float32 | float64 | +| person | `ACTC_CRD` | int64 | float64 | +| person | `AGI` | int64 | float64 | +| person | `ANN_VAL` | int64 | float64 | +| person | `A_FNLWGT` | int64 | float64 | +| person | `A_HRS1` | int64 | float64 | +| person | `A_HSCOL` | int64 | float64 | +| person | `A_MJOCC` | int64 | float64 | +| person | `A_SEX` | int64 | float64 | +| person | `CAID` | int64 | float64 | +| person | `CAP_VAL` | int64 | float64 | +| person | `CHAMPVA` | int64 | float64 | +| person | `CHSP_VAL` | int64 | float64 | +| person | `CSP_VAL` | int64 | float64 | +| person | `CTC_CRD` | int64 | float64 | +| person | `DIS_SC1` | int64 | float64 | +| person | `DIS_SC2` | int64 | float64 | +| person | `DIS_VAL1` | int64 | float64 | +| person | `DIS_VAL2` | int64 | float64 | +| person | `DIV_VAL` | int64 | float64 | +| person | `DST_SC1` | int64 | float64 | +| person | `DST_SC1_YNG` | int64 | float64 | +| person | `DST_SC2` | int64 | float64 | +| person | `DST_SC2_YNG` | int64 | float64 | +| person | `DST_VAL1` | int64 | float64 | +| person | `DST_VAL1_YNG` | int64 | float64 | +| person | `DST_VAL2` | int64 | float64 | +| person | `DST_VAL2_YNG` | int64 | float64 | +| person | `EIT_CRED` | int64 | float64 | +| person | `FEDTAX_AC` | int64 | float64 | +| person | `FEDTAX_BC` | int64 | float64 | +| person | `FRSE_VAL` | int64 | float64 | +| person | `HRSWK` | int64 | float64 | +| person | `IHSFLG` | int64 | float64 | +| person | `INT_VAL` | int64 | float64 | +| person | `I_ERNVAL` | int64 | float64 | +| person | `I_SEVAL` | int64 | float64 | +| person | `MARG_TAX` | int64 | float64 | +| person | `MCARE` | int64 | float64 | +| person | `MIL` | int64 | float64 | +| person | `MOOP` | int64 | float64 | +| person | `NOW_GRP` | int64 | float64 | +| person | `NOW_MRK` | int64 | float64 | +| person | `OI_OFF` | int64 | float64 | +| person | `OI_VAL` | int64 | float64 | +| person | `PAW_VAL` | int64 | float64 | +| person | `PEAFEVER` | int64 | float64 | +| person | `PEDISDRS` | int64 | float64 | +| person | `PEDISEAR` | int64 | float64 | +| person | `PEDISEYE` | int64 | float64 | +| person | `PEDISOUT` | int64 | float64 | +| person | `PEDISPHY` | int64 | float64 | +| person | `PEDISREM` | int64 | float64 | +| person | `PEINUSYR` | int64 | float64 | +| person | `PEIO1COW` | int64 | float64 | +| person | `PEIOOCC` | int64 | float64 | +| person | `PEMCPREM` | int64 | float64 | +| person | `PENATVTY` | int64 | float64 | +| person | `PEN_SC1` | int64 | float64 | +| person | `PEN_SC2` | int64 | float64 | +| person | `PF_SEQ` | int64 | float64 | +| person | `PHIP_VAL` | int64 | float64 | +| person | `PMED_VAL` | int64 | float64 | +| person | `PNSN_VAL` | int64 | float64 | +| person | `POCCU2` | int64 | float64 | +| person | `POTC_VAL` | int64 | float64 | +| person | `PRCITSHP` | int64 | float64 | +| person | `PRDTHSP` | int64 | float64 | +| person | `PRDTRACE` | int64 | float64 | +| person | `P_SEQ` | int64 | float64 | +| person | `RESNSS1` | int64 | float64 | +| person | `RESNSS2` | int64 | float64 | +| person | `RESNSSI1` | int64 | float64 | +| person | `RESNSSI2` | int64 | float64 | +| person | `RETCB_VAL` | int64 | float64 | +| person | `RNT_VAL` | int64 | float64 | +| person | `SEMP_VAL` | int64 | float64 | +| person | `SPM_ACTC` | int64 | float64 | +| person | `SPM_BBSUBVAL` | int64 | float64 | +| person | `SPM_CAPHOUSESUB` | int64 | float64 | +| person | `SPM_CAPWKCCXPNS` | int64 | float64 | +| person | `SPM_CHILDCAREXPNS` | int64 | float64 | +| person | `SPM_CHILDSUPPD` | int64 | float64 | +| person | `SPM_EITC` | int64 | float64 | +| person | `SPM_ENGVAL` | int64 | float64 | +| person | `SPM_FAMTYPE` | int64 | float64 | +| person | `SPM_FEDTAX` | int64 | float64 | +| person | `SPM_FEDTAXBC` | int64 | float64 | +| person | `SPM_FICA` | int64 | float64 | +| person | `SPM_HAGE` | int64 | float64 | +| person | `SPM_HHISP` | int64 | float64 | +| person | `SPM_HMARITALSTATUS` | int64 | float64 | +| person | `SPM_HRACE` | int64 | float64 | +| person | `SPM_ID` | int64 | float64 | +| person | `SPM_MEDXPNS` | int64 | float64 | +| person | `SPM_NUMADULTS` | int64 | float64 | +| person | `SPM_NUMKIDS` | int64 | float64 | +| person | `SPM_NUMPER` | int64 | float64 | +| person | `SPM_POOR` | int64 | float64 | +| person | `SPM_POVTHRESHOLD` | int64 | float64 | +| person | `SPM_RESOURCES` | int64 | float64 | +| person | `SPM_SCHLUNCH` | int64 | float64 | +| person | `SPM_SNAPSUB` | int64 | float64 | +| person | `SPM_STTAX` | int64 | float64 | +| person | `SPM_TENMORTSTATUS` | int64 | float64 | +| person | `SPM_TOTVAL` | int64 | float64 | +| person | `SPM_WCOHABIT` | int64 | float64 | +| person | `SPM_WEIGHT` | int64 | float64 | +| person | `SPM_WFOSTER22` | int64 | float64 | +| person | `SPM_WICVAL` | int64 | float64 | +| person | `SPM_WKXPNS` | int64 | float64 | +| person | `SPM_WNEWHEAD` | int64 | float64 | +| person | `SPM_WNEWPARENT` | int64 | float64 | +| person | `SPM_WUI_LT15` | int64 | float64 | +| person | `SSI_VAL` | int64 | float64 | +| person | `SSI_YN` | int64 | float64 | +| person | `SS_VAL` | int64 | float64 | +| person | `SS_YN` | int64 | float64 | +| person | `STATETAX_A` | int64 | float64 | +| person | `STATETAX_B` | int64 | float64 | +| person | `TAX_ID` | int64 | float64 | +| person | `TAX_INC` | int64 | float64 | +| person | `UC_VAL` | int64 | float64 | +| person | `VET_VAL` | int64 | float64 | +| person | `WC_VAL` | int64 | float64 | +| person | `WICYN` | int64 | float64 | +| person | `WKSWORK` | int64 | float64 | +| person | `WSAL_VAL` | int64 | float64 | +| person | `cps_race` | int16 | int64 | +| person | `fsla_overtime_premium` | float32 | float64 | +| person | `treasury_tipped_occupation_code` | int16 | int64 | +| tax_unit | `second_home_mortgage_origination_year` | float64 | int64 | From c82fa5ce6ea0cbfe3072f711f5376e27d736ad8b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mar=C3=ADa=20Juaristi?= <127882282+juaristi22@users.noreply.github.com> Date: Thu, 19 Nov 2026 21:39:07 +0000 Subject: [PATCH 21/31] Edit the County Files PoC methods document for LWI (draft v0.1) Max's agents committed part 1 of the methods draft as posted (#1647 comment 7005740491). This edits it for the Living Wage Institute: pe-doc front matter and title block; an appendix of build identifiers, settings and input digests in place of the links to GitHub comments, which a reader with only a download token cannot open; flags, run-file names and imputation family names out of the text; and the gate section reworded. The donor households' geography and tax-detail records are now described from the national build's code at cae8640, in place of "we could not establish". Max's agents are checking that account against the 28 July build's run logs (#1647 comment 7022836029). The experiments README lists the three documents. Part of #922. Co-Authored-By: Claude Opus 5.5 --- experiments/us-county-poc-20261117/README.md | 10 +- .../us-county-poc-20261117/lwi-poc-methods.md | 129 ++++++++++++------ 2 files changed, 93 insertions(+), 46 deletions(-) diff --git a/experiments/us-county-poc-20261117/README.md b/experiments/us-county-poc-20261117/README.md index 4ed8982299..c46a7c21ec 100644 --- a/experiments/us-county-poc-20261117/README.md +++ b/experiments/us-county-poc-20261117/README.md @@ -1,10 +1,14 @@ -# US County Files proof of concept: the report (2026-11-17 run) +# US County Files proof of concept: the documents for LWI (2026-11-17 run) Tracking issue: microcosm#922, the LWI County Files. Plan: microcosm#1647. `lwi-poc-report.md` is draft v0.2 (19 November 2026) of the proof-of-concept report for the Living Wage Institute. It states the fit and the limits of the 2024 county file that the 17–18 November run built: build `populace-us-2024-buildo-acs-local-f8b1039f00-20261118T011728Z`, SHA-256 `82314a3b5a6a95762faf6eb4f5b499ce56608ad6a39a27b75e11c75b4945bd3c`. The draft is under review and has not been sent. v0.2 takes the corrections that part 2 of the methods draft lists (microcosm#1647 comment 7005741386) and describes the 23 release checks as `gate_summary.json` records them. -- **Format.** The draft is `pe-doc` Markdown (PolicyEngine/document-templates). It has the front matter, the three-line title block and source notes after the last rule. `pe-doc` has no report kind, so the draft uses `kind: proposal` with `psl_foundation: false`. +`lwi-poc-methods.md` is draft v0.1 (19 November 2026) of the methods documentation. It is part 1 of the methods draft that Max's agents posted on microcosm#1647 (comment 7005740491), edited for LWI: an appendix of build identifiers, settings and input digests replaces the links to GitHub comments, and flags, run-file names and imputation family names are out of the text. Its account of how donor households got their geography and their tax-detail records comes from the national build's code at `cae8640`; Max's agents are checking it against that build's run logs. + +`schema_manifest.md` and `schema_manifest.json` are the schema documentation: `tools/us_release_schema_manifest.py`'s output for the file, with a notes section at the top of the Markdown (microcosm#1647 comment 7022836029). + +- **Format.** The report and the methods documentation are `pe-doc` Markdown (PolicyEngine/document-templates). Each has the front matter, the three-line title block and source notes after the last rule. `pe-doc` has no report kind, so both use `kind: proposal` with `psl_foundation: false`. - **Sources.** The numbers come from the run report on microcosm#1647 (comments 6982547034 and 6982549060) and from the release's own reports: `county_reliability.json` and `.csv`, `calibration_diagnostics.json` and `gate_summary.json`. The loader result comes from a test on 18 November with policyengine-us 2.2.1. - **Delivery.** The file, this report, the methods documentation and the schema documentation are shared through the private Hugging Face dataset `policyengine/lwi-county-files`. The report refers to the other two documents by name, because a link into a private repository does not open for a reader who has only a download token. -- **Still open.** The methods documentation and the schema documentation, which go next to this report (microcosm#1647 comment 7006535601), and the review. +- **Still open.** Max's agents' note on the 28 July national build (the donor geography, the tax-detail records and the targets the donor weights fit), the review, the PDF builds, and Max's go for the upload. diff --git a/experiments/us-county-poc-20261117/lwi-poc-methods.md b/experiments/us-county-poc-20261117/lwi-poc-methods.md index a6364c7f38..d0d46a432e 100644 --- a/experiments/us-county-poc-20261117/lwi-poc-methods.md +++ b/experiments/us-county-poc-20261117/lwi-poc-methods.md @@ -1,22 +1,36 @@ -# Methods: the 2024 county file +--- +kind: proposal +client: "Living Wage Institute" +status: "draft v0.1 (2026-11-19): for María and Max to review, not for sending" +pe-doc: + psl_foundation: false + split_tables: true + pdf_name: "PolicyEngine - County Files proof of concept methods" +--- -This document describes how we built the 2024 county file for the County Files proof of concept (PoC), as the build ran on 17–18 November 2026. We ran the build at two commits of PolicyEngine's Microcosm code: +# County Files proof of concept: methods -- **Staging, at `72b7072bf`:** builds the household records from the American Community Survey (ACS) and a national donor file, gives each household a county, and imputes the inputs the ACS lacks. -- **The release build, at `f8b1039f0`:** runs seven stages in order. `fills` and `agi` check the staged file first: its blank inputs, and each county's households and income. `materialize` sets program take-up, moves nine ACS households into three counties that the county draws left empty, fills reviewed defaults, and builds the targets and the holdout. Take-up means whether an eligible person or household receives a benefit. `calibrate` sets the weights. `qa` runs PolicyEngine's tax-benefit model on the calibrated file. `finalize` and `package` write the release files and run the last checks. +**How we built and tested the 2024 county file** -The PoC report gives the results. The run report on microcosm#1647 ([part 1](https://github.com/PolicyEngine/microcosm/issues/1647#issuecomment-6982547034) and [part 2](https://github.com/PolicyEngine/microcosm/issues/1647#issuecomment-6982549060)) gives the commands, environments and file digests, and the [schema manifest](https://github.com/PolicyEngine/microcosm/issues/1647#issuecomment-6990728184) lists the file's tables and columns. We have not yet produced the 2026 and 2027 files or the household measures the agreement lists (earnings, gross income and net income for each household), so this document covers neither. +A PolicyEngine methods note · for the Living Wage Institute · November 2026 + +This document describes how we built the 2024 county file for the County Files proof of concept (PoC), as the build ran on 17–18 November 2026. We ran the build in two parts with PolicyEngine's Microcosm code; the appendix gives the code versions, the settings and the digests of the inputs: + +- **Staging** builds the household records from the American Community Survey (ACS) and a national donor file, gives each household a county, and imputes the inputs the ACS lacks. +- **The release build** runs seven stages in order. `fills` and `agi` check the staged file first: its blank inputs, and each county's households and income. `materialize` sets program take-up, moves nine ACS households into three counties that the county draws left empty, fills reviewed defaults, and builds the targets and the holdout. Take-up means whether an eligible person or household receives a benefit. `calibrate` sets the weights. `qa` runs PolicyEngine's tax-benefit model on the calibrated file. `finalize` and `package` write the release files and run the last checks. + +The PoC report gives the results, and the schema documentation lists the file's tables and columns; both come with this document. We have not yet produced the 2026 and 2027 files or the household measures the agreement lists (earnings, gross income and net income for each household), so this document covers neither. ## Data sources and years -We built the 2024 county file from two sets of household records and from published statistics, with PolicyEngine's US tax-benefit model. We list each source at the vintage the build read on 17–18 November 2026. The run files record the SHA-256 digests of the input files, among them the target feed `consumer_facts_us_41b2fb2.jsonl` (`1d45a89c…`) and the county facts `consumer_facts_us_county_3e9d3a0.jsonl` (`67b0998a…`) (run report, part 2, section 11). +We built the 2024 county file from two sets of household records and from published statistics, with PolicyEngine's US tax-benefit model. We list each source at the vintage the build read on 17–18 November 2026. The build records the SHA-256 digest of every input file; the appendix lists the main ones. | Source | Vintage | What the build uses it for | |---|---|---| | ACS public-use microdata, household and person files | 2024 1-year | 1,529,668 ACS household records with 3,420,942 people. Of these, 181,260 are group-quarters records: one person each, living in a place such as a nursing home or college dormitory rather than a housing unit, and counting as a household of one. These counts come after staging drops group-quarters records of children under 15 (see "What we impute onto ACS households, and from which donors") | | PolicyEngine's national donor file, release `populace-us-2024-spm-receipts-20260923`, in a copy we patched | See "Donor households" below the table | 57,240 donor household records with 166,321 person records; we train the imputation on their person records, tax units (the people on one tax return) and SPM units (the family unit of the Supplemental Poverty Measure) | | Current Population Survey Annual Social and Economic Supplement (CPS ASEC), person files `pppub23`–`pppub25` | Survey years 2023–2025 (income years 2022–2024) | The donor households' survey records; three work columns our patch adds | -| Internal Revenue Service (IRS) Statistics of Income (SOI) public-use file (PUF), in PolicyEngine's processed version 1.8.0 | Tax year 2015, scaled forward to 2024 | An input of the donor file's national build, as that build's records name it; we did not trace what the donor records take from it | +| Internal Revenue Service (IRS) Statistics of Income (SOI) public-use file (PUF), in PolicyEngine's processed version 1.8.0 | Tax year 2015, scaled forward to 2024 | The tax items on the donor file's tax-detail records, through PolicyEngine's national build (see "Donor households" below the table) | | Census 2020 tract-to-PUMA (Public Use Microdata Area) relationship file; 2020 Census redistricting (P.L. 94-171) block populations; the Census file of each block's 119th Congress district | 2020 Census; 119th Congress districts | The PUMA ladder (see "Population" below): the county and district draws within each PUMA, and every population target | | SOI Historic Table 2, state data | Tax year 2022; tax year 2023 for 408 rows | 4,227 state tax targets, and the state totals we split into county tax targets | | SOI county file (`22incyallnoagi.csv`) | Tax year 2022 | Each county's share of the sum of its state's county rows, for returns and for adjusted gross income (AGI). Each of the two has 3,143 county targets (Kalawao and Maui share one); we hold out 441 return targets and 297 AGI targets and train on the rest | @@ -35,6 +49,7 @@ We built the 2024 county file from two sets of household records and from publis **Donor households.** Donor households are survey households from PolicyEngine's national donor file. We add them to the ACS households and train the imputation on their person records, tax units and SPM units. The file comes from three releases in the public Hugging Face dataset `policyengine/populace-us`: a national build and two later releases that add columns to it. - The national build, `populace-us-2024-buildp-sparse-rmloss100-cae8640-20260728T011454Z` of 28 July 2026, chose 57,240 household records from 337,704 candidates. Its records name its inputs as the CPS ASEC for income years 2022–2024 and PolicyEngine's processed PUF, version 1.8.0. In that build's code, version 1.8.0 is the 2015 public-use file, scaled forward to 2024. +- In PolicyEngine's national build code at that build's commit (`cae8640`), each CPS ASEC household appears as two records that share its weight equally. One keeps the household as the CPS ASEC recorded it. The other, a tax-detail record, takes its tax items from the PUF: quantile regression forests trained on the PUF's tax units draw them, given the tax unit's filing status, its number of people and its incomes (wages, self-employment income, taxable interest, dividends and capital gains). The code then spreads each tax unit's amounts over its members in their CPS shares. Because the national build then chose among these records, a donor household can appear in the donor file as one of its two records or as both (see "What donor records carry"). - Release `populace-us-2024-spm-20260915` added an SPM role flag. Release `populace-us-2024-spm-receipts-20260923` added reported receipt of SNAP, TANF and WIC (the Special Supplemental Nutrition Program for Women, Infants, and Children). Both drew on the same ASEC person files, and neither changed an existing column. For this PoC we patched a copy of the last release. We added two industry columns and a worked-last-year column from the ASEC person files. We also added two columns that hold only zeros: strike benefits, and passive partnership and S-corporation income. We kept every household and person record. @@ -49,7 +64,7 @@ For this PoC we patched a copy of the last release. We added two industry column The other 408 come from tax year 2023: returns and AGI in the four AGI bands from $100,000 up. -Before aging, we rescale some rows across tax years. Each 2023 AGI-band row keeps its share of its state's 2023 total, applied to the state's 2022 total of returns or AGI. We scale other 2022 rows to an SOI national total for tax year 2023: taxable interest (1,014 rows, in total and by AGI band) and net capital gains (102 rows, amount and returns). For the 51 net capital gains return rows, that total comes from the SOI congressional district file `22incd.csv`. In the target feed, that file carries the label tax year 2023 but the title "Congressional District Data 2022", so we could not pin its tax year. +Before aging, we rescale some rows across tax years. Each 2023 AGI-band row keeps its share of its state's 2023 total, applied to the state's 2022 total of returns or AGI. We scale other 2022 rows to an SOI national total for tax year 2023: taxable interest (1,014 rows, in total and by AGI band) and net capital gains (102 rows, amount and returns). For the 51 net capital gains return rows, that total comes from the SOI congressional district file `22incd.csv`. In the target feed, that file carries the label tax year 2023 but the title "Congressional District Data 2022", so its tax year is uncertain. We then age every SOI dollar amount to 2024 with national growth. A dollar row that we rescaled to a 2023 national total ages from 2023; every other dollar row ages from 2022. SOI's national totals for 2022 and 2023 give the growth from 2022 to 2023, and CBO's February 2026 projections give the growth from 2023 to 2024. Most dollar amounts grow with total AGI; wages and net capital gains grow with their own series. We do not age counts. @@ -69,7 +84,7 @@ Each ACS household record carries its state and its PUMA. We keep both. A PUMA c We built the ladder from 2020 Census block populations (the P.L. 94-171 redistricting file) and the Census file of each block's congressional district. Blocks nest in tracts, and each 2020 tract lies in one 2020 PUMA. Summing block populations therefore gives the number of people each PUMA shares with each 2020 county and with each district. We call that number the population overlap. Of the ladder's 2,462 PUMAs, 610 overlap more than one county and 1,276 overlap more than one district. -Within its PUMA, each ACS household gets a district from one random draw, with odds proportional to the PUMA's population overlap with each district. It gets a county from a separate draw, with odds proportional to the PUMA's population overlap with each county. One random-number generator with a fixed seed (0) makes every draw. With the same inputs, row order and software versions, the code makes the same draws; we did not rebuild to check. Each household gets one district and one county and keeps its whole weight: the draw does not split a household across counties. +Within its PUMA, each ACS household gets a district from one random draw, with odds proportional to the PUMA's population overlap with each district. It gets a county from a separate draw, with odds proportional to the PUMA's population overlap with each county. One random-number generator with a fixed seed (0) makes every draw. With the same inputs, row order and software versions, the code makes the same draws; we have not rebuilt the file to confirm this. Each household gets one district and one county and keeps its whole weight: the draw does not split a household across counties. The draws use only the PUMA's population overlaps, not the household's survey answers, and the district draw does not depend on the county draw. The code checks only that the PUMA, district and county lie in the household's state. We found no check that a household's district and county overlap. @@ -81,7 +96,9 @@ The file carries two county codes. `county_fips` holds 2020 counties, which divi Donor households keep the district, county, tract and block stored in the donor file. Staging checks that each stored district and county lies in the household's state and that the county matches the tract's county. It sets the household's PUMA from the tract and takes `county_fips_2023` from the tract. -We made the donor file from a copy of PolicyEngine's national release `populace-us-2024-spm-receipts-20260923`: for the PoC, we added person columns and left the household table as it was. In that release we added three variables, and in the release it came from, `populace-us-2024-spm-20260915`, we added one; none of the four is a household variable. By the two releases' published records, we left every existing column unchanged in both, so the stored geography predates both. We could not establish how the donor households got their districts, counties and tracts. +The donor file's household table comes unchanged from PolicyEngine's 28 July 2026 national build. Our patch added only person columns. By their published records, the two later releases added no household column and changed no existing column. The stored geography is therefore the national build's. + +In PolicyEngine's national build code at that build's commit (`cae8640`), each household gets its geography from two draws. The first draws a congressional district within the household's state, with odds in proportion to each district's number of tax returns in the IRS congressional district data. The second draws one 2020 census block within that district, in proportion to block population. The tract and the county follow from the block. A donor household's county therefore comes from these draws, not from the county its CPS ASEC record names. ### Counties without households @@ -93,7 +110,7 @@ Staging draws each ACS household's county at random and sets no minimum number o - It ranks candidates by a hash of a fixed key (`acs-local-county-support-v1`), the destination county and the household ID, so row order does not matter. It moves the top three, or none if fewer than three qualify. - A move rewrites the two county codes and nothing else. The household keeps its state, PUMA, weight and the district it drew. -The `materialize` stage records each move in `county_support.json`. When the `calibrate` stage writes the calibrated file, it reloads the staged file and applies the same recorded moves again. +The `materialize` stage records each move. When the `calibrate` stage writes the calibrated file, it reloads the staged file and applies the same recorded moves again. Each county took its three households from its one overlapping PUMA: @@ -120,7 +137,7 @@ We use quantile regression forests in Microcosm's own form, with sign classifier - **Training records.** Donor person records, tax units or SPM units. The first two passes train on the donors' ASEC person records and the third on their tax-detail copies (both defined below). Each forest resamples the donors in proportion to their weights in the donor file. The sign classifier below uses the same weights directly. - **Predictors.** Age, sex and state, plus, where the ACS record has them, wages, self-employment income, Social Security, retirement income, interest, dividend and rental income, household-head status and housing tenure. Tax-unit and SPM-unit fits use the unit's number of people, of women and of household heads, its summed ages, state, housing tenure and summed incomes. Each pattern of available predictors gets its own fit, on donors that have those predictors and all of the family's columns, so the build never reads a blank as a zero. - **Second-pass predictors.** For child support, the second pass adds the ACS's "all other income" amount. For retirement-account distributions and for work and disability income, it swaps the donors' retirement-income measure for one closer to the ACS's definition. -- **Joint within a family.** In this run, each family holds at most eight columns. The build splits a wider group of columns into batches, and each batch counts as its own family (the `__batch_1`, `__batch_2` names in the table below). The forests draw a family's columns in sequence, each conditioned on the predictors and on the columns already drawn. One family's draws do not enter another family's fit. For example, the forests draw the 54 person-level tax columns jointly only within each of their seven batches. +- **Joint within a family.** In this run, each family holds at most eight columns. The build splits a wider group of columns into batches, and each batch counts as its own family. The forests draw a family's columns in sequence, each conditioned on the predictors and on the columns already drawn. One family's draws do not enter another family's fit. For example, the forests draw the 54 person-level tax columns jointly only within each of their seven batches. - **Random draws.** For each amount, a classifier picks the sign (negative, zero or positive), and the forest returns a value at a random quantile. The draws therefore follow the donors' distribution rather than an average. The run seed, 0, combined with each family's name and pattern of predictors, fixes every draw. Each forest in these passes has 32 trees. - **Blanks only.** The forests fill only blank cells. Where the ACS reports a model input, its value stays as it is. Where the ACS reports only a combined amount, the build uses that amount as a predictor and draws the model's inputs from donors (next paragraph). - **Weights unchanged.** Imputation passes the ACS household weights through unchanged. After imputation, staging pools the ACS and donor records and gives each group half of the donor file's household weight, 61.27 million each, before calibration. @@ -129,25 +146,25 @@ The ACS reports Social Security, retirement income, and interest, dividend and r ### What the run imputed -In the table below, "ASEC" and "PUF" name the two roles a donor person record can hold. An "ASEC" record holds a person as the CPS ASEC recorded them. A "PUF" record holds a tax-detail copy of such a person; the build code names this role `puf_tax_detail`. We did not trace how the donor file made these copies (see "Data sources and years" for the donor build's inputs). +In the table below, "ASEC" and "PUF" name the two roles a donor person record can hold. An "ASEC" record holds a person as the CPS ASEC recorded them. A "PUF" record holds a tax-detail copy of such a person; the build code names this role `puf_tax_detail`. "Donor households", under "Data sources and years", describes how PolicyEngine's national build makes these copies. -The staging summary records 101 imputed columns in 25 families: +Staging imputed 101 columns in 25 families: -| What staging imputes (family) | Columns | Unit | ACS records filled | Donor records trained on | +| What staging imputes | Columns | Unit | ACS records filled | Donor records trained on | |---|---:|---|---:|---:| -| Usual weekly hours (`source_operator_hours_worked`) | 1 | person | 39,800 | 50,490 ASEC | -| Child support received and paid (`acs_local_child_support`) | 2 | person | 3,420,942 | 66,001 ASEC | -| Retirement-account distributions: 401(k), 403(b), simplified employee pension (SEP), Keogh and Roth IRA (`acs_local_retirement_distributions`) | 5 | person | 3,420,942 | 66,001 ASEC | -| Workers' compensation and disability benefits (`acs_local_work_disability_income`) | 2 | person | 3,420,942 | 66,001 ASEC | -| Interest, dividends, capital gains, pensions, Social Security by type, and business and deduction items (`puf_tax_itemization__batch_1` to `_7`) | 54 | person | 3,420,942 | 100,320 PUF | -| Mortgage, health savings account deduction and two other tax items (`puf_tax_itemization`) | 6 | tax unit | 2,095,799 | 48,755 PUF | -| Health coverage, full-time student, pregnancy and WIC (`model_required_boolean__batch_1` to `_4`) | 12 | person | 3,420,942 | 100,320 PUF | -| Assets, medical costs, tax-exempt pensions, unemployment and veterans' benefits, and hours last week (`model_required_numeric__batch_1` to `_2`) | 10 | person | 3,420,942 | 100,320 PUF | -| Own children in household (`model_required_discrete`) | 1 | person | 3,420,942 | 100,320 PUF | -| Care need and adult-care spending (`adult_care`) | 2 | person | 3,420,942 | 100,320 PUF | -| Pre-subsidy rent (`housing`) | 1 | person | 3,239,682 (all but the 181,260 in group quarters) | 100,320 PUF | -| SNAP and TANF receipt, housing assistance take-up and childcare costs (`model_required_boolean`, `benefit_participation`, `model_required_numeric`) | 4 | SPM unit | 1,529,668 | 36,614 PUF | -| Capital gain distributions, a fixed share of imputed long-term gains, with no forest (`capital_gain_details`) | 1 | person | 3,420,942 | none | +| Usual weekly hours | 1 | person | 39,800 | 50,490 ASEC | +| Child support received and paid | 2 | person | 3,420,942 | 66,001 ASEC | +| Retirement-account distributions: 401(k), 403(b), simplified employee pension (SEP), Keogh and Roth IRA | 5 | person | 3,420,942 | 66,001 ASEC | +| Workers' compensation and disability benefits | 2 | person | 3,420,942 | 66,001 ASEC | +| Interest, dividends, capital gains, pensions, Social Security by type, and business and deduction items | 54 | person | 3,420,942 | 100,320 PUF | +| Mortgage, health savings account deduction and two other tax items | 6 | tax unit | 2,095,799 | 48,755 PUF | +| Health coverage, full-time student, pregnancy and WIC | 12 | person | 3,420,942 | 100,320 PUF | +| Assets, medical costs, tax-exempt pensions, unemployment and veterans' benefits, and hours last week | 10 | person | 3,420,942 | 100,320 PUF | +| Own children in household | 1 | person | 3,420,942 | 100,320 PUF | +| Care need and adult-care spending | 2 | person | 3,420,942 | 100,320 PUF | +| Pre-subsidy rent | 1 | person | 3,239,682 (all but the 181,260 in group quarters) | 100,320 PUF | +| SNAP and TANF receipt, housing assistance take-up and childcare costs | 4 | SPM unit | 1,529,668 | 36,614 PUF | +| Capital gain distributions, a fixed share of imputed long-term gains, with no forest | 1 | person | 3,420,942 | none | Three rules limit or replace forest draws: @@ -179,7 +196,7 @@ Rules, seeded draws and other models set these values on ACS records. One of the - **SNAP take-up.** The flag means a unit would take up SNAP if eligible; PolicyEngine's model decides eligibility. Units that report SNAP get the flag. Other units draw it at 79.8%, so that 82% of ACS SPM units, by weight, carry it: USDA's national SNAP participation rate. - **TANF take-up.** Units draw the flag at 21.9%, the rate in HHS's 24th Welfare Indicators report. The draw ignores imputed TANF receipt: 10,559 of the 13,536 ACS units with imputed TANF receipt drew no take-up. -- **SSI and Medicaid take-up.** PolicyEngine's model first runs on the donor and ACS households to find who could get SSI or Medicaid. ACS people who report SSI then take up SSI, and people with ACS Medicaid or other means-tested coverage take up Medicaid. The rest draw toward SSA counts by age band and CMS enrollment counts by state, minus what the donor records already carry. The run's take-up file (`acs_local_ssi_medicaid_take_up.npz`) records the flags: 1,835,876 ACS people take up SSI if eligible, and 3,359,039 take up Medicaid if eligible. The model applies eligibility. +- **SSI and Medicaid take-up.** PolicyEngine's model first runs on the donor and ACS households to find who could get SSI or Medicaid. ACS people who report SSI then take up SSI, and people with ACS Medicaid or other means-tested coverage take up Medicaid. The rest draw toward SSA counts by age band and CMS enrollment counts by state, minus what the donor records already carry. In all, 1,835,876 ACS people take up SSI if eligible, and 3,359,039 take up Medicaid if eligible. The model applies eligibility. - **Other flags.** Medicare take-up follows ACS Medicare coverage. Children aged 3 to 5 draw Head Start take-up at the donor records' weighted take-up share, 4.9%. Housing assistance receipt copies the imputed housing-assistance take-up, a forest draw, and stays false in group quarters. Adults aged 18 to 64 draw an exemption from SNAP's work time limit at 8%, the statutory cap. When the `calibrate` stage writes the calibrated file, it applies these assignments again and stops if they differ from the ones the `materialize` stage recorded. @@ -230,7 +247,7 @@ So each concept's county targets add up to their state target; the largest count The SOI county file has no row for Kalawao County, Hawaii (15005), and neither does the county facts file the run read. The build's code cites the IRS guide to the county file, which says the IRS leaves out items with fewer than 20 returns for a county. For the two SOI concepts, one target covers Kalawao and Maui (15009) together, with Maui's published share. Kalawao keeps its own population and household targets. -The run dropped no target. It passed `--county-drop-empty-soi-rows`, which drops a county SOI target when every household in that county has a zero value for it; no target met that rule. +The run dropped no target. It ran with a setting that drops a county SOI target when every household in that county has a zero value for it, and no target met that rule. ### How we weight the targets @@ -258,17 +275,17 @@ The solve starts from the design weights. Staging builds them when it pools the The solver, Adam (a standard gradient method), works on the logarithm of each weight, so every weight stays positive. It takes 800 steps at a learning rate of 0.02, in two runs of 400 steps, with seed 0. Each step uses every trained target and every household record. The second run starts from the first run's weights, with a fresh optimizer state. No penalty pulls weights toward their design values. The file keeps the weights from the last step. -The loss comes to 0.173 at the design weights, 0.0208 after the first 400 steps and 0.0159 after all 800. The run files record an `initial_loss` of 0.020786: the loss at the start of the second run, not at the design weights. +The loss comes to 0.173 at the design weights, 0.0208 after the first 400 steps and 0.0159 after all 800. ### The weight cap -No household record's final weight may exceed 5 times its design weight (`--county-max-weight-ratio 5`). A donor household's design weight equals exactly half its weight in the donor file, so its limit equals 2.5 times that weight. The cap acts on each record as a hard limit, not a penalty. After every step, the solver lowers any weight over its limit to the limit. It then rescales all weights by one factor to the fixed total and applies the limit again. Both runs measure the limit against the design weights. +No household record's final weight may exceed 5 times its design weight. A donor household's design weight equals exactly half its weight in the donor file, so its limit equals 2.5 times that weight. The cap acts on each record as a hard limit, not a penalty. After every step, the solver lowers any weight over its limit to the limit. It then rescales all weights by one factor to the fixed total and applies the limit again. Both runs measure the limit against the design weights. A rescale factor below 1 leaves the records at the limit under it, at 5 times the factor. The largest final ratio is 4.9297, not 5, and 44,083 records end within 0.01% of it. So the last step's factor came to about 0.986 (4.9297 ÷ 5). The cap has no lower counterpart: 1,246,252 records (78.5% of 1,586,908) end with less than 1% of their design weight. ### The holdout -We hold out county targets in whole holdout groups. A holdout group covers one state's county targets for one concept: SOI returns, SOI AGI or ACS households. The 153 holdout groups cover 9,430 county targets. For each group, the build hashes the group's name with a fixed key, `acs-local-county-v1`, using SHA-256, and turns the result into a number from 0 to 1. It leaves the group out of the solve when that number falls under 0.1 (`--county-holdout-fraction 0.1`). The draw depends only on the group's name and the key, never on the other groups. County population targets belong to no holdout group and always train. +We hold out county targets in whole holdout groups. A holdout group covers one state's county targets for one concept: SOI returns, SOI AGI or ACS households. The 153 holdout groups cover 9,430 county targets. For each group, the build hashes the group's name with a fixed key, `acs-local-county-v1`, using SHA-256, and turns the result into a number from 0 to 1. It leaves the group out of the solve when that number falls under 0.1. The draw depends only on the group's name and the key, never on the other groups. County population targets belong to no holdout group and always train. The code gives its reason for holding out whole groups: "to prevent sibling leakage". A group's county targets add up to its state target, which trains. If the group's other counties trained, the state target minus their sum would give away the held-out county. @@ -312,7 +329,7 @@ The build computes household earnings and income sums from stored inputs, not fr - **Earnings for the checks:** wages, self-employment income and farm income, plus partnership self-employment earnings on donor records. - **Household income for the checks:** wages, self-employment and farm income, plus the stored income inputs. Those inputs cover interest, dividends, rent, estate income, Social Security, SSI, pensions, IRA distributions, unemployment compensation, veterans' benefits, workers' compensation, alimony, child support and miscellaneous income. - On donor records, the build also adds partnership and S-corporation income to the income sum. On ACS records it leaves both out; the code's stated reason is that the ACS self-employment answer "already counts partnership income". The income sum also leaves out donor partnership self-employment earnings, which partnership income mostly holds already. -- In this run, S-corporation income is zero, so it adds nothing. TANF receipt (`receives_tanf`) appears in the file only as a yes/no flag, and the stored inputs have no column for TANF or public assistance dollars (`tanf_reported`, `public_assistance_income`). So the income sum includes neither. +- In this run, S-corporation income is zero, so it adds nothing. TANF receipt (`receives_tanf`) appears in the file only as a yes/no flag, and the stored inputs have no column for TANF or public assistance dollars. So the income sum includes neither. - The build marks the two income tables, B19025 and B19001, `approximate: true`. The code describes the income sum as an approximation of the ACS household income concept. ### The reliability grade @@ -340,21 +357,47 @@ The code returns U when a county lacks that evidence or its source household ide ### Automated gates -The build ran 23 gates and recorded each in the release's `gate_summary.json`; all 23 recorded `passed: true`. Seventeen stop the build when they fail: +The build ran 23 automated checks, which the build calls gates. Seventeen stop the build when they fail, and all 17 passed: - **Geography (1):** each household's PUMA, congressional district and county must be present and must agree with its state. New York City must keep a plausible share of the weight. - **Household inputs (12):** the build assigns some inputs to ACS records: hours worked, program take-up, immigration status, disability, transferred income, SSI disability criteria, SSI and Medicaid take-up, and SNAP receipt. Each must be complete and must vary. Where a gate checks them against native ACS answers or plausibility ranges, they must agree. Every input left at a model default must appear on a reviewed list. ACS self-employment income must count once. Occupation, industry and worked-last-year inputs must be complete. -- **Calibration (1):** the final loss must fall under 10, the same setting that caps each target's scaled error in the loss. It must also fall under the run files' `initial_loss` (0.020786): the loss at the start of the second 400-step run, not the loss at the design weights. The final weights must sum to within 0.1% of the design weights' sum. +- **Calibration (1):** the final loss must fall under 10, the same setting that caps each target's scaled error in the loss. It must also fall under the loss at the start of the second 400-step run (0.0208). The final weights must sum to within 0.1% of the design weights' sum. - **Model readiness (3):** the file stores no input that policyengine-us 2.2.1 lacks, outside a reviewed list. Every SPM unit the model measures has an adult, so the SPM calculation cannot stop on a unit without one. The build wrote its consumer export, and the `qa` stage loaded the calibrated file as stored, with no added fills. -Six gates record evidence. Five of them record `passed: true` whatever they measure: +The other six gates record evidence and do not stop the build. Five of them record what they measure and have no pass condition: -- `cd_holdout`: held-out district targets; none in this run. In the `calibration` gate's breakdown, the build uses the same label, `cd_holdout`, for the 1,052 held-out county targets. -- `weight_origin`: the weight share and ESS of ACS and donor households. -- `input_coverage`: a note that staging checks donor inputs; the gate itself checks nothing. -- `spine_composition`: households and weight of ACS and donor records. -- `spine_ssi_qa`: the `qa` stage's load and its SSI and SNAP figures. +- held-out district targets (none in this run); +- the weight share and ESS of ACS and donor households; +- a note that staging checks the donor inputs; +- the households and weight of ACS and donor records; +- the `qa` stage's load and its SSI and SNAP figures. -The sixth, `district_ess_collapse`, flags congressional districts whose ESS under the final weights fell under a quarter of their ESS under the design weights, or under 15. It stops the build only when the build runs with `--district-ess-gate-blocking`; this run did not use that flag. In this run, 271 of the 436 districts fell under the quarter floor and 155 under 15, so the gate recorded `criteria_met: false` and still recorded `passed: true`. +The sixth flags congressional districts whose ESS under the final weights fell under a quarter of their ESS under the design weights, or under 15. It can be set to stop the build, and this run did not set it. In this run, 271 of the 436 districts fell under the quarter floor and 155 under 15, 275 districts in all, so the gate recorded that its criteria were not met. The `qa` stage loaded the calibrated file with Microcosm's own loader, not policyengine-us's dataset loader. It then ran policyengine-us 2.2.1 for 2024, with no reform, in 80 chunks of 20,000 households, for eight variables: SSI, six SNAP-related variables and the state code. For a separate test on 18 November that loaded the file with policyengine-us's standard loader, see the PoC report. + +## Appendix: build identifiers and settings + +| Item | Value | +|---|---| +| Build | `populace-us-2024-buildo-acs-local-f8b1039f00-20261118T011728Z`, 17–18 November 2026 | +| File | `populace_us_2024_acs_local.h5`, 10,637,811,669 bytes, SHA-256 `82314a3b5a6a95762faf6eb4f5b499ce56608ad6a39a27b75e11c75b4945bd3c` | +| Code | Microcosm, commit `72b7072bf` (staging) and commit `f8b1039f0` (the release build) | +| Model | policyengine-us 2.2.1, policyengine-core 3.32.5 | +| Donor file | Release `populace-us-2024-spm-receipts-20260923` (SHA-256 `00946972…`), in the copy we patched (SHA-256 `438f47f4…`) | +| National build behind the donor file | `populace-us-2024-buildp-sparse-rmloss100-cae8640-20260728T011454Z`, Microcosm commit `cae8640` | +| Target feed | `consumer_facts_us_41b2fb2.jsonl` (SHA-256 `1d45a89c…`) | +| County facts | `consumer_facts_us_county_3e9d3a0.jsonl` (SHA-256 `67b0998a…`) | +| Household location | The legacy rule: county and district draws within each PUMA, as in "How households get their counties" | +| Imputation | Quantile regression forests with 32 trees; seed 0 | +| Minimum support | Three households for each county without one; ranking key `acs-local-county-support-v1` | +| Holdout | Whole holdout groups, held out when their hash falls under 0.1 (`--county-holdout-fraction 0.1`); key `acs-local-county-v1` | +| Empty county SOI targets | Dropped when every household in the county has a zero value (`--county-drop-empty-soi-rows`); none was dropped | +| Loss | Mean of the absolute scaled errors, weighted by loss weight; each error capped at 10 | +| Weight cap | 5 times the design weight (`--county-max-weight-ratio 5`) | +| Solver | Adam on log weights; 800 steps in two runs of 400; learning rate 0.02; seed 0 | +| District effective-sample gate | Records evidence only; the build was not run with `--district-ess-gate-blocking` | + +--- + +Sources: the table in "Data sources and years" lists every source with its vintage and its use in the build. From e95992220fb47b2d4f246a210bb4aab7a6f3c8ea Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mar=C3=ADa=20Juaristi?= <127882282+juaristi22@users.noreply.github.com> Date: Thu, 19 Nov 2026 21:39:21 +0000 Subject: [PATCH 22/31] Say which columns the model ignores in the LWI PoC report The 254 columns policyengine-us 2.2.1 ignores are 213 raw survey fields, 29 build identifiers and 12 derived columns, among them county_fips_2023, as the notes in schema_manifest.md count them. The report said "raw survey fields and build identifiers" (#1647 comment 7022836029). Part of #922. Co-Authored-By: Claude Opus 5.5 --- experiments/us-county-poc-20261117/lwi-poc-report.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/experiments/us-county-poc-20261117/lwi-poc-report.md b/experiments/us-county-poc-20261117/lwi-poc-report.md index 89c42c1b88..9e2df0693e 100644 --- a/experiments/us-county-poc-20261117/lwi-poc-report.md +++ b/experiments/us-county-poc-20261117/lwi-poc-report.md @@ -180,7 +180,7 @@ Most D grades have both causes: 2,905 counties have an effective sample below 30 - Strike benefits are zero for every household. No donor record reports them, and ACS households take the model's default of zero. - S-corporation income is not separated from partnership income. The national data holds both as one combined partnership amount, so the separate S-corporation items are zero. - We left out the 1,946 ACS group-quarters records of children under 15, which carry 0.04% of the ACS household weight. Each would form a poverty-measure unit with no adult, and one such unit stops the model version we use from computing poverty measures for the whole file. -- **Model use.** The file loads with policyengine-us 2.2.1's standard dataset loader. On a computer with 32 GB of memory, the national simulation built in 90 seconds and used at most 18 GB, and it computed 2024 totals of population, employment income and adjusted gross income. For one state, the model also computed income tax, SNAP and household net income, with no missing values. We have not run full-model calculations, such as household net income, for the whole country at once. On a 32 GB computer, run them state by state or in chunks, or use a larger machine. The model ignores 254 extra columns: raw survey fields and build identifiers. +- **Model use.** The file loads with policyengine-us 2.2.1's standard dataset loader. On a computer with 32 GB of memory, the national simulation built in 90 seconds and used at most 18 GB, and it computed 2024 totals of population, employment income and adjusted gross income. For one state, the model also computed income tax, SNAP and household net income, with no missing values. We have not run full-model calculations, such as household net income, for the whole country at once. On a 32 GB computer, run them state by state or in chunks, or use a larger machine. The model ignores 254 extra columns: 213 raw survey fields, 29 build identifiers and 12 derived columns, among them `county_fips_2023`. The schema documentation says which is which. - **One year only.** The file is for 2024. The 2026 and 2027 files are a stretch goal. ## Next steps From 827058d2431a3f2277582d0d150773e8b2bafa8d Mon Sep 17 00:00:00 2001 From: Max Ghenis Date: Thu, 19 Nov 2026 22:09:05 +0000 Subject: [PATCH 23/31] Correct three lines of the schema manifest notes An independent check of the notes found three points to fix: - medicare_part_b_premiums: drop the claim that it held the CPS ASEC field PEMCPREM. On tax-detail copies the donor build may have set it from the PUF instead. policyengine-us 2.2.1 computes the Part B premium itself (medicare_part_b_premium). - A_EXPRRP is the Census value only for income-year 2024 donors. For income years 2022 and 2023 the donor build derived it from line, spouse and parent numbers (base summary relationship_recode_source). - CENSUS_TAX_ID is the Census TAX_ID, which PolicyEngine's CPS extractor copies before it overwrites TAX_ID with the tax unit it builds. The tables and schema_manifest.json are unchanged. Part of #922. Co-Authored-By: Claude Opus 5.5 --- experiments/us-county-poc-20261117/schema_manifest.md | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/experiments/us-county-poc-20261117/schema_manifest.md b/experiments/us-county-poc-20261117/schema_manifest.md index 26ed0cb6bc..2e196afe07 100644 --- a/experiments/us-county-poc-20261117/schema_manifest.md +++ b/experiments/us-county-poc-20261117/schema_manifest.md @@ -30,23 +30,24 @@ policyengine-us 2.2.1 sets a column as an input only if its name is a model vari | Read by the model | 198 | 153 person, 19 household, 14 tax_unit, 10 spm_unit, 1 family, 1 marital_unit | | Raw CPS ASEC fields | 162 | Uppercase, under their Census names: 161 person and household `H_TENURE`. Null on ACS rows, except eight (below). | | Raw ACS 2024 PUMS fields | 51 | Uppercase; null on donor rows. `ST` is the Census `STATE` and `ACS_MIL` the Census `MIL`. Listed below. | -| Build identifiers | 29 | For each of the six tables, `{table}_source_id`, `{table}_support_channel`, `{table}_support_clone_index` and `{table}_spine`; plus `source_year`, `source_household_id`, `source_person_id`, `source_row_id` and the uppercase `CENSUS_TAX_ID`. `household_spine` is `acs_2024_1yr` for ACS households and `asec_puf` for donor households. | +| Build identifiers | 29 | For each of the six tables, `{table}_source_id`, `{table}_support_channel`, `{table}_support_clone_index` and `{table}_spine`; plus `source_year`, `source_household_id`, `source_person_id`, `source_row_id` and `CENSUS_TAX_ID` (see below). `household_spine` is `acs_2024_1yr` for ACS households and `asec_puf` for donor households. | | Derived columns | 12 | `county_fips_2023`, `puma_geoid`, `acs_social_security_income`, `acs_retirement_income`, `acs_interest_dividend_rental_income`, `acs_monthly_contract_rent`, `acs_monthly_gross_rent`, `acs_annual_property_tax`, `tax_unit_role_input`, `filing_status_input`, `parent_1_id`, `parent_2_id` | The 51 ACS fields are, for persons, `SPORDER`, `ADJINC`, `PWGTP`, `AGEP`, `CIT`, `COW`, `DDRS`, `DEAR`, `DEYE`, `DOUT`, `DPHY`, `DREM`, `HINS3`, `HINS4`, `HINS5`, `HINS6`, `HINS7`, `INTP`, `MAR`, `ACS_MIL`, `OIP`, `PAP`, `RELSHIPP`, `RETP`, `SCHG`, `SEMP`, `SEX`, `SSIP`, `SSP`, `WAGP`, `WKHP`, `WKL`, `WKWN`, `YOEP`, `ESR`, `INDP`, `OCCP`, `POBP` and `FWKHP`, and for households `SERIALNO`, `ST`, `PUMA`, `NP`, `ADJHSG`, `TEN`, `RNTP`, `GRNTP`, `TAXAMT`, `TYPEHUGQ`, `FS` and `VEH`. -Three more points: +Four more points: - Eight CPS ASEC names have no nulls: `PH_SEQ`, `A_LINENO`, `A_AGE`, `A_MARITL`, `A_SPOUSE`, `PEPAR1`, `PEPAR2` and `A_EXPRRP`. On ACS rows the build fills them from ACS fields so that it can form tax units. - The model reads raw survey values only under its own names. On ACS rows, for example, `employment_income_before_lsr` is `WAGP` times `ADJINC`. - The model reads `county_fips` (2020 counties). It does not read `county_fips_2023`. +- Two CPS ASEC names do not always hold the Census value. `A_EXPRRP` (relationship to the reference person) is the Census value only for donors from income year 2024; for income years 2022 and 2023, the donor build derived it from line, spouse and parent numbers. `TAX_ID` may hold the tax unit that PolicyEngine's CPS extractor built: the extractor copies the Census `TAX_ID` into `CENSUS_TAX_ID` and then overwrites `TAX_ID`. `CENSUS_TAX_ID` is filled only for income-year 2024 donors. That `TAX_ID` was overwritten in this file is an inference from the extractor's code; we have not compared values. ### Removed columns, the rename and the dtype changes These compare the file with the sample column list sent with the County Files agreement. - `has_marketplace_health_coverage` and `weeks_worked`: policyengine-us 2.2.1 has a formula for each, and the release leaves out any column the model can compute with a formula in some year. It keeps id columns, and inputs that policyengine-us says the data must supply even though it has a fallback formula, such as `is_spm_independent_minor_role`. The formula for `has_marketplace_health_coverage` returns `has_marketplace_health_coverage_at_interview`, which the file keeps. The formula for `weeks_worked` applies from 2025. -- `medicare_part_b_premiums`, the CPS ASEC Part B premium (`PEMCPREM`): policyengine-us 2.2.1 has no variable by this name, so the release no longer stores it. It held values for the 166,321 donor persons only. +- `medicare_part_b_premiums`, a stored Medicare Part B premium: policyengine-us 2.2.1 has no variable by this name and computes the Part B premium itself (`medicare_part_b_premium`), so the release no longer stores it. It held values for the 166,321 donor persons only. - 128 dtype changes are int64 to float64: 127 person columns and household `H_TENURE`. All are CPS ASEC fields with no value on ACS rows. An int64 column cannot hold a missing value, so when the build stacks donor and ACS rows, pandas stores these columns as float64. Only the storage type changes. The sample file had no ACS rows. - The other six are columns that are null on ACS rows, where the release fills the model's default, 0, and stores the model's type, int64 or float64: household `household_vehicles_owned` (int32 to int64) and `household_vehicles_value` (float32 to float64); person `cps_race` (int16 to int64), `fsla_overtime_premium` (float32 to float64) and `treasury_tipped_occupation_code` (int16 to int64); and tax_unit `second_home_mortgage_origination_year` (float64 to int64). From 826838fe07ca14d614d25a22da362313a492cff8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mar=C3=ADa=20Juaristi?= <127882282+juaristi22@users.noreply.github.com> Date: Sun, 22 Nov 2026 14:25:40 +0000 Subject: [PATCH 24/31] Correct the donor households in the LWI methods document (draft v0.2) Max's agents checked v0.1's account of the donor households against the 28 July national build's code, run logs and published files (#1647 comments 7025093817 and 7025096163). This takes their items 1 to 7: the tax-detail records, the donor geography, the forest weights, the role of the ASEC records, the fixed household total, a new paragraph on the targets the donor weights fit, and the settings row. Most of their text goes in word for word; the full tax-detail account now opens "What donor records carry". The document also describes the donor file as it is, the last published release (populace-us-2024-spm-receipts-20260923) with five more person columns, where v0.1 called it a patched copy. The experiments README gives v0.2 and no longer lists the national-build note as open. Part of #922. Co-Authored-By: Claude Opus 5.5 --- experiments/us-county-poc-20261117/README.md | 4 +- .../us-county-poc-20261117/lwi-poc-methods.md | 44 +++++++++++++------ 2 files changed, 32 insertions(+), 16 deletions(-) diff --git a/experiments/us-county-poc-20261117/README.md b/experiments/us-county-poc-20261117/README.md index c46a7c21ec..380b8351cb 100644 --- a/experiments/us-county-poc-20261117/README.md +++ b/experiments/us-county-poc-20261117/README.md @@ -4,11 +4,11 @@ Tracking issue: microcosm#922, the LWI County Files. Plan: microcosm#1647. `lwi-poc-report.md` is draft v0.2 (19 November 2026) of the proof-of-concept report for the Living Wage Institute. It states the fit and the limits of the 2024 county file that the 17–18 November run built: build `populace-us-2024-buildo-acs-local-f8b1039f00-20261118T011728Z`, SHA-256 `82314a3b5a6a95762faf6eb4f5b499ce56608ad6a39a27b75e11c75b4945bd3c`. The draft is under review and has not been sent. v0.2 takes the corrections that part 2 of the methods draft lists (microcosm#1647 comment 7005741386) and describes the 23 release checks as `gate_summary.json` records them. -`lwi-poc-methods.md` is draft v0.1 (19 November 2026) of the methods documentation. It is part 1 of the methods draft that Max's agents posted on microcosm#1647 (comment 7005740491), edited for LWI: an appendix of build identifiers, settings and input digests replaces the links to GitHub comments, and flags, run-file names and imputation family names are out of the text. Its account of how donor households got their geography and their tax-detail records comes from the national build's code at `cae8640`; Max's agents are checking it against that build's run logs. +`lwi-poc-methods.md` is draft v0.2 (20 November 2026) of the methods documentation. It is part 1 of the methods draft that Max's agents posted on microcosm#1647 (comment 7005740491), edited for LWI: an appendix of build identifiers, settings and input digests replaces the links to GitHub comments, and flags, run-file names and imputation family names are out of the text. v0.2 takes the corrections from Max's agents' check of v0.1's account of the donor households (their geography, their tax-detail records and the targets their weights fit) against the 28 July national build's code, run logs and published files (microcosm#1647 comments 7025093817 and 7025096163). It also describes the donor file as it is, the last published release with five more person columns, where v0.1 called it a patched copy. `schema_manifest.md` and `schema_manifest.json` are the schema documentation: `tools/us_release_schema_manifest.py`'s output for the file, with a notes section at the top of the Markdown (microcosm#1647 comment 7022836029). - **Format.** The report and the methods documentation are `pe-doc` Markdown (PolicyEngine/document-templates). Each has the front matter, the three-line title block and source notes after the last rule. `pe-doc` has no report kind, so both use `kind: proposal` with `psl_foundation: false`. - **Sources.** The numbers come from the run report on microcosm#1647 (comments 6982547034 and 6982549060) and from the release's own reports: `county_reliability.json` and `.csv`, `calibration_diagnostics.json` and `gate_summary.json`. The loader result comes from a test on 18 November with policyengine-us 2.2.1. - **Delivery.** The file, this report, the methods documentation and the schema documentation are shared through the private Hugging Face dataset `policyengine/lwi-county-files`. The report refers to the other two documents by name, because a link into a private repository does not open for a reader who has only a download token. -- **Still open.** Max's agents' note on the 28 July national build (the donor geography, the tax-detail records and the targets the donor weights fit), the review, the PDF builds, and Max's go for the upload. +- **Still open.** The review, the PDF builds, and Max's go for the upload. diff --git a/experiments/us-county-poc-20261117/lwi-poc-methods.md b/experiments/us-county-poc-20261117/lwi-poc-methods.md index d0d46a432e..be57ce05bb 100644 --- a/experiments/us-county-poc-20261117/lwi-poc-methods.md +++ b/experiments/us-county-poc-20261117/lwi-poc-methods.md @@ -1,7 +1,7 @@ --- kind: proposal client: "Living Wage Institute" -status: "draft v0.1 (2026-11-19): for María and Max to review, not for sending" +status: "draft v0.2 (2026-11-20): for María and Max to review, not for sending" pe-doc: psl_foundation: false split_tables: true @@ -28,8 +28,8 @@ We built the 2024 county file from two sets of household records and from publis | Source | Vintage | What the build uses it for | |---|---|---| | ACS public-use microdata, household and person files | 2024 1-year | 1,529,668 ACS household records with 3,420,942 people. Of these, 181,260 are group-quarters records: one person each, living in a place such as a nursing home or college dormitory rather than a housing unit, and counting as a household of one. These counts come after staging drops group-quarters records of children under 15 (see "What we impute onto ACS households, and from which donors") | -| PolicyEngine's national donor file, release `populace-us-2024-spm-receipts-20260923`, in a copy we patched | See "Donor households" below the table | 57,240 donor household records with 166,321 person records; we train the imputation on their person records, tax units (the people on one tax return) and SPM units (the family unit of the Supplemental Poverty Measure) | -| Current Population Survey Annual Social and Economic Supplement (CPS ASEC), person files `pppub23`–`pppub25` | Survey years 2023–2025 (income years 2022–2024) | The donor households' survey records; three work columns our patch adds | +| PolicyEngine's national donor file: release `populace-us-2024-spm-receipts-20260923`, with five more person columns | See "Donor households" below the table | 57,240 donor household records with 166,321 person records; we train the imputation on their person records, tax units (the people on one tax return) and SPM units (the family unit of the Supplemental Poverty Measure) | +| Current Population Survey Annual Social and Economic Supplement (CPS ASEC), person files `pppub23`–`pppub25` | Survey years 2023–2025 (income years 2022–2024) | The donor households' survey records, and three work columns on their person records | | Internal Revenue Service (IRS) Statistics of Income (SOI) public-use file (PUF), in PolicyEngine's processed version 1.8.0 | Tax year 2015, scaled forward to 2024 | The tax items on the donor file's tax-detail records, through PolicyEngine's national build (see "Donor households" below the table) | | Census 2020 tract-to-PUMA (Public Use Microdata Area) relationship file; 2020 Census redistricting (P.L. 94-171) block populations; the Census file of each block's 119th Congress district | 2020 Census; 119th Congress districts | The PUMA ladder (see "Population" below): the county and district draws within each PUMA, and every population target | | SOI Historic Table 2, state data | Tax year 2022; tax year 2023 for 408 rows | 4,227 state tax targets, and the state totals we split into county tax targets | @@ -49,10 +49,10 @@ We built the 2024 county file from two sets of household records and from publis **Donor households.** Donor households are survey households from PolicyEngine's national donor file. We add them to the ACS households and train the imputation on their person records, tax units and SPM units. The file comes from three releases in the public Hugging Face dataset `policyengine/populace-us`: a national build and two later releases that add columns to it. - The national build, `populace-us-2024-buildp-sparse-rmloss100-cae8640-20260728T011454Z` of 28 July 2026, chose 57,240 household records from 337,704 candidates. Its records name its inputs as the CPS ASEC for income years 2022–2024 and PolicyEngine's processed PUF, version 1.8.0. In that build's code, version 1.8.0 is the 2015 public-use file, scaled forward to 2024. -- In PolicyEngine's national build code at that build's commit (`cae8640`), each CPS ASEC household appears as two records that share its weight equally. One keeps the household as the CPS ASEC recorded it. The other, a tax-detail record, takes its tax items from the PUF: quantile regression forests trained on the PUF's tax units draw them, given the tax unit's filing status, its number of people and its incomes (wages, self-employment income, taxable interest, dividends and capital gains). The code then spreads each tax unit's amounts over its members in their CPS shares. Because the national build then chose among these records, a donor household can appear in the donor file as one of its two records or as both (see "What donor records carry"). +- In PolicyEngine's national build code at that build's commit (`cae8640`), each CPS ASEC household appears as two records, which start with equal halves of its weight. One, the ASEC record, keeps the household's survey answers, except that two of the build's steps changed its taxable interest and its Social Security. The other, a tax-detail record, starts as a copy of the ASEC record; quantile regression forests trained on PUF tax units then redraw its tax items. Because the national build then chose among these records and set each one's weight on its own, a donor household can appear in the donor file as one of its two records or as both, and where it appears as both, its two weights usually differ (see "What donor records carry"). - Release `populace-us-2024-spm-20260915` added an SPM role flag. Release `populace-us-2024-spm-receipts-20260923` added reported receipt of SNAP, TANF and WIC (the Special Supplemental Nutrition Program for Women, Infants, and Children). Both drew on the same ASEC person files, and neither changed an existing column. -For this PoC we patched a copy of the last release. We added two industry columns and a worked-last-year column from the ASEC person files. We also added two columns that hold only zeros: strike benefits, and passive partnership and S-corporation income. We kept every household and person record. +The donor file holds every household and person record of the last release, with five more person columns. Two industry columns and a worked-last-year column come from the ASEC person files. The other two hold only zeros: strike benefits, and passive partnership and S-corporation income. **Population.** A PUMA is the smallest area the ACS microdata identifies. The PUMA ladder is a table of each 2020 PUMA's population, summed from 2020 Census block populations and split across census tracts, counties and congressional districts. For the county targets, we group the tracts by their 2023 county code; under those codes, Connecticut's tracts fall into its nine planning regions. We then scale each state's counties to the state's PUMA total. Every population target comes from this ladder, so states, districts and counties each sum to 331,449,281, the ladder's total of 2020 Census block populations. The county facts file also holds the Census Bureau's 2024 county population estimates and ACS table B01003 (total population); no target or check uses either. @@ -96,9 +96,13 @@ The file carries two county codes. `county_fips` holds 2020 counties, which divi Donor households keep the district, county, tract and block stored in the donor file. Staging checks that each stored district and county lies in the household's state and that the county matches the tract's county. It sets the household's PUMA from the tract and takes `county_fips_2023` from the tract. -The donor file's household table comes unchanged from PolicyEngine's 28 July 2026 national build. Our patch added only person columns. By their published records, the two later releases added no household column and changed no existing column. The stored geography is therefore the national build's. +The donor file's household table comes unchanged from PolicyEngine's 28 July 2026 national build. The five columns that the donor file holds beyond the last release are all person columns. By their published records, the two later releases added no household column and changed no existing column. The stored geography is therefore the national build's. -In PolicyEngine's national build code at that build's commit (`cae8640`), each household gets its geography from two draws. The first draws a congressional district within the household's state, with odds in proportion to each district's number of tax returns in the IRS congressional district data. The second draws one 2020 census block within that district, in proportion to block population. The tract and the county follow from the block. A donor household's county therefore comes from these draws, not from the county its CPS ASEC record names. +PolicyEngine's national build code drew these locations when it built its 337,704 candidate records, on 27 July 2026 at commit `2ae4339`; the location code is the same at `cae8640`, and the 28 July build kept the locations of the 57,240 records it chose. The code gives each record, not each household, its own two draws, so a household's ASEC record and its tax-detail copy can land in different districts, counties and tracts of their state. In the county file, 9,963 donor households appear as both records, and 8,731 of them have their two records in different counties. + +The first of the two draws picks a 119th Congress district within the record's state. Its odds come from the IRS congressional district file (`22incd.csv`), which, by the build's records, counts tax returns by the districts of the 117th Congress: the code moves each old district's count onto the new districts in proportion to the 2020 Census population they share. Montana had one district in the 117th Congress and has two in the 119th, so its two districts' odds rest on population alone. The second draws one 2020 census block within that district, in proportion to block population. The tract and the county follow from the block, and so do the place, the state legislative districts and the core-based statistical area (CBSA). A donor household's county therefore comes from these draws, not from the county its CPS ASEC record names. + +The code looks up the place and the legislative districts in the Census Bureau's 2020 block assignment files, whose legislative districts are the plans as of the Bureau's 2020 redistricting data release, and the CBSA in the Office of Management and Budget's 2023 list of metropolitan and micropolitan areas. The county file keeps these columns only on donor records; on ACS records the block, tract, place, legislative district and CBSA columns all hold empty values. The CBSA is also empty on donor records outside every metropolitan and micropolitan area, and on all 908 Connecticut donor records: the 2023 list names Connecticut's planning regions, while the block codes carry its 2020 counties, so the lookup found no match. PolicyEngine fixed that lookup on 30 September 2026, after the national build. ### Counties without households @@ -134,7 +138,7 @@ We fill most of the missing inputs from PolicyEngine's national donor file: 57,2 We use quantile regression forests in Microcosm's own form, with sign classifiers, chained draws and donor weights. A quantile regression forest predicts the whole distribution of a value, not only its average. Staging runs three imputation passes in order. The first imputes usual weekly hours. The second imputes child support, retirement-account distributions, and work and disability income. The third imputes everything else. In each pass: -- **Training records.** Donor person records, tax units or SPM units. The first two passes train on the donors' ASEC person records and the third on their tax-detail copies (both defined below). Each forest resamples the donors in proportion to their weights in the donor file. The sign classifier below uses the same weights directly. +- **Training records.** Donor person records, tax units or SPM units. The first two passes train on the donors' ASEC person records and the third on their tax-detail copies (both defined below). Each forest resamples the donors in proportion to their weights in the donor file. Those weights are concentrated (see "The donor file's weights" under "Design weights and the solver"): 41,430 of the 57,240 donor households have a weight below 2 there, and together they hold 0.003% of the donor weight. The other 15,810 households hold 18,867 of the 66,001 ASEC person records and 27,402 of the 100,320 tax-detail records, so almost every record a forest resamples comes from them. The sign classifier below uses the same weights directly. - **Predictors.** Age, sex and state, plus, where the ACS record has them, wages, self-employment income, Social Security, retirement income, interest, dividend and rental income, household-head status and housing tenure. Tax-unit and SPM-unit fits use the unit's number of people, of women and of household heads, its summed ages, state, housing tenure and summed incomes. Each pattern of available predictors gets its own fit, on donors that have those predictors and all of the family's columns, so the build never reads a blank as a zero. - **Second-pass predictors.** For child support, the second pass adds the ACS's "all other income" amount. For retirement-account distributions and for work and disability income, it swaps the donors' retirement-income measure for one closer to the ACS's definition. - **Joint within a family.** In this run, each family holds at most eight columns. The build splits a wider group of columns into batches, and each batch counts as its own family. The forests draw a family's columns in sequence, each conditioned on the predictors and on the columns already drawn. One family's draws do not enter another family's fit. For example, the forests draw the 54 person-level tax columns jointly only within each of their seven batches. @@ -146,7 +150,7 @@ The ACS reports Social Security, retirement income, and interest, dividend and r ### What the run imputed -In the table below, "ASEC" and "PUF" name the two roles a donor person record can hold. An "ASEC" record holds a person as the CPS ASEC recorded them. A "PUF" record holds a tax-detail copy of such a person; the build code names this role `puf_tax_detail`. "Donor households", under "Data sources and years", describes how PolicyEngine's national build makes these copies. +In the table below, "ASEC" and "PUF" name the two roles a donor person record can hold. An "ASEC" record holds a person's CPS ASEC record as the national build kept it. A "PUF" record holds a tax-detail copy of such a person; the build code names this role `puf_tax_detail`. "What donor records carry", at the end of this section, describes how PolicyEngine's national build makes both records and what it changed on each. Staging imputed 101 columns in 25 families: @@ -178,7 +182,7 @@ The ACS reports one self-employment amount per person (SEMP). The 2024 ACS subje - We keep each person's ACS self-employment amount. The forests still draw its three parts (farm operations, partnership self-employment earnings and specified-service business income). The build then sets all three to zero for all 3,420,942 ACS people. Of those draws, 44,478, 73,164 and 114,327 had a nonzero value. A gate, one of the build's automated checks (see "Automated gates"), found no ACS person whose self-employment differs by more than $1 from SEMP in 2024 dollars. - The build sets partnership-income draws to zero for three groups. The first is people who report nonzero SEMP (171,732). The second is a head or spouse whose tax-unit partner reports nonzero SEMP (84,177). The 2024 ACS form asks people to report jointly received income under one person (item 43, as the code cites it). The third is people with blank SEMP, all aged under 15 (508,152). That removed 16,571 nonzero draws. At the ACS's own household weights, before pooling rescales them, they came to $159.4 billion of income and $13.9 billion of losses. Partnership income stays nonzero on 139,930 ACS records. -- S-corporation income and passive partnership and S-corporation income stay zero on every ACS and donor record. Both columns hold only zeros in the donor file, so the forests have nothing to learn from and draw zero. S-corporation income comes unchanged from the published donor file; our patch added the passive column (see "What donor records carry"). The recorded reason for both: the donor file holds partnership and S-corporation income as one combined partnership amount, with no record of the split. +- S-corporation income and passive partnership and S-corporation income stay zero on every ACS and donor record. Both columns hold only zeros in the donor file, so the forests have nothing to learn from and draw zero. S-corporation income comes unchanged from the last release; the passive column is one of the five person columns that the donor file holds beyond that release (see "What donor records carry"). The recorded reason for both: the donor file holds partnership and S-corporation income as one combined partnership amount, with no record of the split. - A staging check refuses any donor column that the third pass reads and that holds only default values, unless the staging command lists it. The command listed these two columns. Strike benefits, which also hold only zeros in the donor file, needed no listing, because the third pass does not read them. ### Take-up and other assigned values @@ -207,9 +211,19 @@ After these steps, 58 model inputs still have blank cells: 143,641,752 on ACS re ### What donor records carry +In the national build's code (`cae8640`), each CPS ASEC household appears as two records, which start with equal halves of its weight. One, the ASEC record, keeps the household's survey answers, along with values the build derives or draws for every record, such as its location, its rent before subsidies and its adult-care spending. Two of the build's steps changed amounts on it. The step that drew the tax items also pruned taxable interest: by PolicyEngine's own later count, it set taxable interest to zero for every ASEC tax unit with less than $444 and raised the rest by 0.7%, which kept the total. The national build later rescaled Social Security by type on every record to Social Security Administration totals. + +The other, a tax-detail record, starts as a copy of the ASEC record. Quantile regression forests, trained with the PUF's weights on 208,611 PUF tax units, then redraw 65 tax items for each of the copy's tax units, one at a time, given the unit's filing status, its number of people, its CPS ASEC incomes (wages, self-employment income, taxable interest, dividends, and short- and long-term capital gains) and the items already drawn. Those incomes are among the 65 items. Summed without weights over the 168,852 tax-detail records among the national build's 337,704 candidates, the redrawn wages, taxable interest and capital gains come within 0.1% of the CPS ASEC amounts and dividends within 0.4%. Self-employment income totals 11% less in the column the ASEC records use and 49.7% more across both columns: on the copies, a later step puts each person's whole self-employment income in one of two columns, by a drawn flag for specified service businesses, and the second column is zero on every ASEC record. The national build later cut one tax item, capital gain distributions reported without Schedule D, to 15% of its drawn total to match an IRS Statistics of Income total. + +Where the tax unit's members hold an amount for an item in their CPS ASEC records, the code spreads the unit's draw over them in those shares. Otherwise it spreads the draw by a related amount, such as earnings, where the code names one, and gives the whole draw to the unit's first person where it names none, as for mortgage interest, charitable gifts, real estate taxes and partnership income. For Social Security, the code splits the drawn total by type in the shares of the unit's CPS ASEC Social Security, or in four equal parts (retirement, disability, survivors and dependents) where the unit has none in the CPS ASEC. + +Forests trained on the ASEC records then redraw several survey items on each tax-detail record: child support, disability benefits, workers' compensation, weeks unemployed, childcare costs, energy subsidies, retirement contributions, four kinds of retirement-account distributions, last year's earnings, housing assistance receipt and take-up and, at the end of the national build, health insurance premiums. Except for weeks unemployed, these forests read the record's age, sex, employer coverage, filing status and dependents, and the wages, self-employment income and Social Security the PUF forests drew for it. The tax-detail record keeps its other survey items as copied. + +Because the national build then chose among these records, a donor household can appear in the donor file as one of its two records or as both. The national build's calibration then set each record's weight on its own: of the 9,963 households that the donor file holds as both records, 496 have equal weights there (see "The donor file's weights" under "Design weights and the solver"). + The donor file's 166,321 person records come from the CPS ASEC for income years 2022, 2023 and 2024 (54,464, 54,654 and 57,203 records). Of these, 66,001 are ASEC person records and 100,320 are tax-detail copies. They hold 135,833 distinct people, each counted once per income year: 30,488 people appear twice, once in each role. In the county file, the 57,240 donor household records hold 47,277 distinct source households (see "Copies" under "The reliability grade"). -For this PoC we used a patched copy of PolicyEngine's published donor file. The patch added three ASEC work columns (detailed industry, major industry and whether the person worked last year). It matched each of the 166,321 donor person records to its ASEC record exactly once, with no identity mismatches. It re-derived eight existing columns and found them equal on every record. It also added strike benefits and passive partnership and S-corporation income as zeros, and changed no column the published file already held. The patch tool's code gives a fixed reason for strike benefits: no donor record, and no record in the ASEC person files for survey years 2023 to 2026, reports them. The patch run itself read only the files for survey years 2023 to 2025, for the work columns. +The donor file holds five person columns that its last release, `populace-us-2024-spm-receipts-20260923`, does not. Three are ASEC work columns: detailed industry, major industry and whether the person worked last year. Each of the 166,321 donor person records takes them from its own ASEC record, which it matches exactly once, with no identity mismatches. On every record, eight columns that the release already holds equal the values re-derived from that ASEC record. The other two columns, strike benefits and passive partnership and S-corporation income, hold only zeros, and every column of the release is unchanged. For strike benefits, the code that adds these columns states a fixed reason: no donor record, and no record in the ASEC person files for survey years 2023 to 2026, reports them. Its run read only the files for survey years 2023 to 2025, for the work columns. ## Calibration: the targets, how we weight them, and the weight cap @@ -271,7 +285,9 @@ Two shares describe each group of targets. Its loss weight share is its share of ### Design weights and the solver -The solve starts from the design weights. Staging builds them when it pools the ACS and donor records. It takes each ACS household's housing-unit weight (WGTP; a group-quarters record takes its person weight) and each donor household's weight in the donor file. It then scales each group to half of the donor file's household weight total: 61.27 million each, 122.5 million in all. These scaled weights are the design weights. The solve keeps their total fixed. The weight cap, every weight ratio below and the loss at the design weights all use them. +The solve starts from the design weights. Staging builds them when it pools the ACS and donor records. It takes each ACS household's housing-unit weight (WGTP; a group-quarters record takes its person weight) and each donor household's weight in the donor file. It then scales each group to half of the donor file's household weight total: 61.27 million each, 122.5 million in all. These scaled weights are the design weights. The weight cap, every weight ratio below and the loss at the design weights all use them. The solve keeps their total fixed at 122,537,092, the donor file's household weight total, which PolicyEngine's national build set (see "The donor file's weights" below). That total is smaller than the sum of the 51 state household targets, 129,227,496. At the final weights, the records those targets count add up to 122,512,091. The 181,260 group-quarters records add up to 25,001, against 3,620,662 at the design weights. + +**The donor file's weights.** PolicyEngine's 28 July 2026 national build set the donor households' weights by calibrating them to 5,659 targets for 2024: 448 national and 5,211 for the 50 states and DC, with none below state level. IRS SOI tables supply 4,182 of them and Census population estimates by age 936; the rest come from CMS, SSA, USDA SNAP, the Census Bureau's state tax collections, HHS, the Joint Committee on Taxation, CBO, the Bureau of Economic Analysis and the Federal Reserve, plus one national total of Keogh distributions that the build computed from the selected records themselves. The build rebased 662 count targets and 662 dollar targets to later IRS totals for tax years 2023 and 2024, and it aged 1,988 dollar targets to 2024: 1,401 by SOI's national growth to 2023 and then CBO's projected growth to 2024, and 587 by CBO's projected growth from 2023 alone. Its loss caps each target's scaled error at 1 (100%), and it held out no target. Each weight could rise to at most 5 times its starting weight, with no lower limit, and the total stayed at 122,537,092: the build had scaled up the selected households' base weights so that they counted 334.2 million people. At the final weights, 41,302 of the 57,240 households keep less than 0.1% of their starting weight, and the effective sample size (defined under "The reliability grade") falls from 42,355 to 9,174. The donor file carries these final weights unchanged, and since each donor household's design weight is half its weight there, 41,430 of the 57,240 donor households start the county solve with a design weight below 1. The solver, Adam (a standard gradient method), works on the logarithm of each weight, so every weight stays positive. It takes 800 steps at a learning rate of 0.02, in two runs of 400 steps, with seed 0. Each step uses every trained target and every household record. The second run starts from the first run's weights, with a fresh optimizer state. No penalty pulls weights toward their design values. The file keeps the weights from the last step. @@ -384,11 +400,11 @@ The `qa` stage loaded the calibrated file with Microcosm's own loader, not polic | File | `populace_us_2024_acs_local.h5`, 10,637,811,669 bytes, SHA-256 `82314a3b5a6a95762faf6eb4f5b499ce56608ad6a39a27b75e11c75b4945bd3c` | | Code | Microcosm, commit `72b7072bf` (staging) and commit `f8b1039f0` (the release build) | | Model | policyengine-us 2.2.1, policyengine-core 3.32.5 | -| Donor file | Release `populace-us-2024-spm-receipts-20260923` (SHA-256 `00946972…`), in the copy we patched (SHA-256 `438f47f4…`) | +| Donor file | Release `populace-us-2024-spm-receipts-20260923` (SHA-256 `00946972…`) with five more person columns; the file the build read has SHA-256 `438f47f4…` | | National build behind the donor file | `populace-us-2024-buildp-sparse-rmloss100-cae8640-20260728T011454Z`, Microcosm commit `cae8640` | | Target feed | `consumer_facts_us_41b2fb2.jsonl` (SHA-256 `1d45a89c…`) | | County facts | `consumer_facts_us_county_3e9d3a0.jsonl` (SHA-256 `67b0998a…`) | -| Household location | The legacy rule: county and district draws within each PUMA, as in "How households get their counties" | +| Household location | The legacy rule: ACS households draw a county and a district within their PUMA; donor households keep the locations stored in the donor file. See "How households get their counties" | | Imputation | Quantile regression forests with 32 trees; seed 0 | | Minimum support | Three households for each county without one; ranking key `acs-local-county-support-v1` | | Holdout | Whole holdout groups, held out when their hash falls under 0.1 (`--county-holdout-fraction 0.1`); key `acs-local-county-v1` | From d28b206e149f9adb01400a2a800adff1479a4a18 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mar=C3=ADa=20Juaristi?= <127882282+juaristi22@users.noreply.github.com> Date: Sun, 22 Nov 2026 14:25:44 +0000 Subject: [PATCH 25/31] Edit the LWI PoC report for its readers (draft v0.3) This takes the review of v0.2. The delivery table gives each item and its status in this delivery, without the agreement column or the delivery-notice row. The method summary gives the national file's build date and leaves out the columns added to it, and the last next step no longer mentions a rebuild from certified national data. The comparison with the earlier state-and-district file is out, so next step 3 no longer refers to the district fit it had. The title is shorter, so it fits on one line. For the pe-doc build, the front matter sets the PDF's title (the proposal kind would otherwise call it "a PolicyEngine proposal"), keeps each table on one page and turns off the budget-table widths, and the separator rows set each table's column widths and right-align its numbers. The built PDF is not in the repository. The experiments README gives v0.3. Part of #922. Co-Authored-By: Claude Opus 5.5 --- experiments/us-county-poc-20261117/README.md | 2 +- .../us-county-poc-20261117/lwi-poc-report.md | 51 +++++++++---------- 2 files changed, 25 insertions(+), 28 deletions(-) diff --git a/experiments/us-county-poc-20261117/README.md b/experiments/us-county-poc-20261117/README.md index 380b8351cb..1bcc959f9d 100644 --- a/experiments/us-county-poc-20261117/README.md +++ b/experiments/us-county-poc-20261117/README.md @@ -2,7 +2,7 @@ Tracking issue: microcosm#922, the LWI County Files. Plan: microcosm#1647. -`lwi-poc-report.md` is draft v0.2 (19 November 2026) of the proof-of-concept report for the Living Wage Institute. It states the fit and the limits of the 2024 county file that the 17–18 November run built: build `populace-us-2024-buildo-acs-local-f8b1039f00-20261118T011728Z`, SHA-256 `82314a3b5a6a95762faf6eb4f5b499ce56608ad6a39a27b75e11c75b4945bd3c`. The draft is under review and has not been sent. v0.2 takes the corrections that part 2 of the methods draft lists (microcosm#1647 comment 7005741386) and describes the 23 release checks as `gate_summary.json` records them. +`lwi-poc-report.md` is draft v0.3 (20 November 2026) of the proof-of-concept report for the Living Wage Institute. It states the fit and the limits of the 2024 county file that the 17–18 November run built: build `populace-us-2024-buildo-acs-local-f8b1039f00-20261118T011728Z`, SHA-256 `82314a3b5a6a95762faf6eb4f5b499ce56608ad6a39a27b75e11c75b4945bd3c`. The draft is under review and has not been sent. v0.2 took the corrections that part 2 of the methods draft lists (microcosm#1647 comment 7005741386) and described the 23 release checks as `gate_summary.json` records them. v0.3 edits it for its readers: the delivery table gives each item's status in this delivery, the method summary describes PolicyEngine's national file as it is, and the comparison with PolicyEngine's earlier state-and-district file is out. `lwi-poc-methods.md` is draft v0.2 (20 November 2026) of the methods documentation. It is part 1 of the methods draft that Max's agents posted on microcosm#1647 (comment 7005740491), edited for LWI: an appendix of build identifiers, settings and input digests replaces the links to GitHub comments, and flags, run-file names and imputation family names are out of the text. v0.2 takes the corrections from Max's agents' check of v0.1's account of the donor households (their geography, their tax-detail records and the targets their weights fit) against the 28 July national build's code, run logs and published files (microcosm#1647 comments 7025093817 and 7025096163). It also describes the donor file as it is, the last published release with five more person columns, where v0.1 called it a patched copy. diff --git a/experiments/us-county-poc-20261117/lwi-poc-report.md b/experiments/us-county-poc-20261117/lwi-poc-report.md index 9e2df0693e..4e355a1d9a 100644 --- a/experiments/us-county-poc-20261117/lwi-poc-report.md +++ b/experiments/us-county-poc-20261117/lwi-poc-report.md @@ -1,14 +1,16 @@ --- kind: proposal client: "Living Wage Institute" -status: "draft v0.2 (2026-11-19): for María and Max to review, not for sending" +title: "County Files proof of concept: 2024 county file — a PolicyEngine report" +status: "draft v0.3 (2026-11-20): for María and Max to review, not for sending" pe-doc: psl_foundation: false - split_tables: true + split_tables: false + budget_widths: false pdf_name: "PolicyEngine - County Files proof of concept report" --- -# County Files proof of concept: the 2024 county file +# County Files proof of concept: 2024 county file **What we built, how well it matches official county statistics, and what comes next** @@ -25,20 +27,19 @@ A PolicyEngine report · for the Living Wage Institute · November 2026 ## What we are delivering -| Item | In the agreement | Status for Monday | -|---|---|---| -| The 2024 county file | Yes | Built on 18 November 2026. Every check that can stop the build passed (see the appendix). Shared in a private Hugging Face repository, `policyengine/lwi-county-files`, with a read-only access token. | -| A written delivery notice | Yes | Max Ghenis sends it. | -| This report: the fit and the limits | For the proof of concept | This document. | -| Methods documentation | Yes | Delivered with this report, in the same repository. | -| Schema documentation | Yes | Delivered with this report, in the same repository: every table and column of the file, with its type and its missing values, and the changes from the sample column list sent with the agreement. | -| The 2026 and 2027 county files | Stretch goal | Not yet produced. | -| Household measures (earnings, gross income and net income for each household) | Stretch goal | Not yet produced. | +| Item | Status in this delivery | +|--------------------------------|------------------------------------------------| +| The 2024 county file | Delivered as `populace_us_2024_acs_local.h5`, in the private Hugging Face repository `policyengine/lwi-county-files`, shared with a read-only access token. | +| This report: the fit and the limits | Delivered as this document, in the same repository. | +| Methods documentation | Delivered as a document in the same repository. | +| Schema documentation | Delivered as a document in the same repository. It lists every table and column of the file, with its type and its missing values, and the changes from the sample column list sent with the agreement. | +| The 2026 and 2027 county files | A stretch goal, not yet produced. | +| Household measures (earnings, gross income and net income for each household) | A stretch goal, not yet produced. | ## The 2024 county file | Feature | Value | -|---|---| +|------------------|----------------------------------------------------------------| | Year | 2024 | | Geography | 3,144 counties and county-equivalents on the 2023 county codes, including Connecticut's nine planning regions; 436 congressional districts. Puerto Rico is not included. | | Household records | 1,586,908: 1,529,668 from the 2024 American Community Survey (ACS), of which 181,260 are one-person group-quarters records (for example, in nursing homes or college dormitories), and 57,240 national donor households | @@ -54,7 +55,7 @@ Every county has at least one household. Counting households in housing units (A The method has four steps. The methods documentation, delivered with this report, gives the detail, and our working papers explain the main choices. 1. **Households and their counties.** We start from the 2024 ACS 1-year public-use microdata. The ACS gives each household's PUMA, not its county. So we draw a county for each ACS household within its PUMA, with odds in proportion to the population each county shares with that PUMA. Each household keeps its whole weight in the county it draws. -2. **National donor households.** The ACS does not collect detailed tax items. We add 57,240 donor households from PolicyEngine's published national file, which combines the Current Population Survey (CPS ASEC) with tax detail imputed from the IRS public-use file. For this proof of concept, we patched a copy of that file: we added three work columns from the CPS ASEC and two columns of zeros, and kept every record. These households keep the county that the national file gives them. +2. **National donor households.** The ACS does not collect detailed tax items. We add 57,240 donor households from PolicyEngine's published 2024 national file, built on 28 July 2026 from the Current Population Survey (CPS ASEC), with tax detail imputed from the IRS public-use file. These households keep the county that the national file gives them. 3. **Imputation.** We give ACS households most of the characteristics the ACS lacks, such as detailed tax items, from the donor households, with quantile regression forests (working paper: [microcosm.institute/support/paper](https://microcosm.institute/support/paper)). A few come from elsewhere: the household's own ACS answer sets SNAP receipt, a model trained on the Survey of Income and Program Participation sets SSI disability status, and rules and seeded random draws set immigration status and program take-up. Inputs still blank after that take the model's default values, such as zero tips and zero net worth. Imputation gives records their characteristics. It does not change how many households each record represents. 4. **Calibration.** We then adjust the household weights so that the file comes close to 16,440 targets at once: 4,482 for states, 436 for congressional districts and 11,522 for counties. The targets come from official statistics, but not all of them equal a published figure: we age IRS dollar amounts to 2024, split each state's IRS totals of returns and adjusted gross income across its counties by the counties' shares in the IRS county data, and take every population target from 2020 Census block populations. A cap keeps each household's final weight at most five times its starting weight. A paper on this calibration method is in preparation. @@ -69,7 +70,7 @@ We measure each target's error as the difference between the file's estimate and ### States and the nation | Targets | Number | Within 10% | Median error | -|---|---|---|---| +|-----------------------------------|-----------:|---------------:|---------------:| | IRS tax statistics, by state | 4,227 | 96.0% | 0.12% | | SNAP households and benefits, by state | 102 | 100% | 0.11% | | Medicaid enrollment, by state | 51 | 100% | 0.08% | @@ -88,7 +89,7 @@ National totals are the sum of the state estimates, compared with the sum of the ### Counties: targets used in calibration | County targets | Number | Within 10% | Median error | -|---|---|---|---| +|-----------------------------------|-----------:|---------------:|---------------:| | Population | 3,144 | 67.5% | 3.7% | | IRS tax returns | 2,702 | 70.8% | 3.6% | | IRS adjusted gross income | 2,846 | 82.3% | 0.4% | @@ -102,7 +103,7 @@ In 856 counties (27%), every county target used in calibration is within 10%. Be For the 1,052 held-out county targets, we compare the file with a simple baseline: each state's total split across its counties by population. | Held-out county targets | Number | Median error: file | Median error: baseline | Within 10%: file | Within 10%: baseline | -|---|---|---|---|---|---| +|----------------------|------:|------------:|------------:|------------:|------------:| | IRS tax returns | 441 | 14.8% | 5.7% | 36.7% | 73.0% | | IRS adjusted gross income | 297 | 32.8% | 39.2% | 13.5% | 11.8% | | ACS households | 314 | 19.6% | 5.4% | 26.1% | 76.4% | @@ -115,7 +116,7 @@ The file beats the baseline for county adjusted gross income, but not for counts For these checks, a county's comparison value is the file's own state total, split across the state's counties in the published ACS county proportions. The checks therefore test how the file divides each state among its counties, not its state totals. The baseline splits the same state total by population. | ACS county statistic | Median error: file | Median error: baseline | Counties where the file is closer | -|---|---|---|---| +|-------------------------------------|------------:|------------:|----------------:| | Total earnings | 19.3% | 28.8% | 61% | | Total household income (approximate) | 13.8% | 21.3% | 63% | | Households with earnings | 15.8% | 7.2% | 30% | @@ -125,16 +126,12 @@ The file also ranks counties better than the baseline by earnings per person and The file's median household income is too high in most counties: in the median county it is 17% above the published ACS value. Its rank correlation with the published county medians is 0.30. -### Compared with the earlier state-and-district file - -PolicyEngine's published 2024 state-and-district file did not have county targets. On the 4,459 targets that both files used, the share within 10% is almost the same: 97.0% before and 96.9% now. Two things are lower in the county file: congressional district population fell from 97.0% to 92.2% within 10%, and the national effective sample fell from about 12,100 to about 7,900. The two files also differ in some of their other targets, so we cannot yet say how much of either change comes from the county targets. - ## How reliable each county is Each county gets a provisional reliability grade from two measures: its effective sample and its largest error. The largest error is taken over the county's calibration targets, its held-out targets and its ACS checks. | Grade | Rule | Counties | -|---|---|---| +|-------|---------------------------------------------------------------|---------:| | A | Effective sample at least 400, and largest error at most 10% | 0 | | B | Effective sample at least 100, and largest error at most 20% | 3 | | C | Effective sample at least 30, and largest error at most 50% | 103 | @@ -187,14 +184,14 @@ Most D grades have both causes: 2,905 counties have an effective sample below 30 1. **Raise the effective sample in each county.** Spread each county's weight over more households, mainly by lowering the share of the weight that donor households carry. We will measure progress with the effective sample per county and the share of the population in counties at grade C or better. 2. **Balance the contribution of cloned records to the calibration.** Keep any single source household, together with its copies, from dominating the weights that the calibration chooses. -3. **Improve the calibration fit.** Give the county targets more weight, so that held-out county targets beat the population-share baseline, and fix the national tax outliers listed above. We will also bring district population back to its earlier fit. +3. **Improve the calibration fit.** Give the county targets more weight, so that held-out county targets beat the population-share baseline, and fix the national tax outliers listed above. We will also improve the fit to congressional district population. 4. **Complete the stretch goals.** Produce the 2026 and 2027 county files and the household measures. -5. **Build the final County Files.** Rebuild from PolicyEngine's certified national data and remove the shortcuts this proof of concept uses. +5. **Build the final County Files.** Remove the shortcuts this proof of concept uses. ## Appendix: file provenance | Item | Value | -|---|---| +|----------------|----------------------------------------------------------------| | Build | `populace-us-2024-buildo-acs-local-f8b1039f00-20261118T011728Z` | | File | `populace_us_2024_acs_local.h5`, 10,637,811,669 bytes | | SHA-256 | `82314a3b5a6a95762faf6eb4f5b499ce56608ad6a39a27b75e11c75b4945bd3c` | @@ -209,4 +206,4 @@ Most D grades have both causes: 2,905 counties have an effective sample below 30 ¹ The income distribution error is the sum, over the 16 ACS income brackets, of the absolute differences between the file's number of households and the comparison value, divided by the sum of the county's comparison values. Each bracket's comparison value is the file's state total for that bracket, split across counties in the published ACS proportions. When the two totals agree, an error of 100% means that half of the households fall in the wrong bracket. -Sources: US Census Bureau, American Community Survey 2024 1-year public-use microdata and 2020–2024 5-year county tables B11001, B19001, B19013, B19025, B19051 and B19061; US Census Bureau, 2020 Census block populations and the 2020 tract-to-PUMA and block-to-congressional-district files; IRS Statistics of Income, state, county and congressional district data and national totals (Publication 1304); Congressional Budget Office, revenue projections, February 2026; USDA Food and Nutrition Service, SNAP state participation and benefits, fiscal year 2024, and the SNAP participation rate; CMS, Medicaid and CHIP enrollment data, December 2024; Social Security Administration, SSI Monthly Statistics, December 2024; HHS Office of the Assistant Secretary for Planning and Evaluation, Welfare Indicators report; US Census Bureau, Survey of Income and Program Participation 2023 public-use file; Pew Research Center and the Higher Ed Immigration Portal; US Census Bureau and Bureau of Labor Statistics, Current Population Survey Annual Social and Economic Supplement 2023–2025, through PolicyEngine's national data and directly for three work columns; the IRS Statistics of Income public-use file (tax year 2015), through PolicyEngine's national data. The methods documentation gives each source's vintage and use. +Sources: US Census Bureau, American Community Survey 2024 1-year public-use microdata and 2020–2024 5-year county tables B11001, B19001, B19013, B19025, B19051 and B19061; US Census Bureau, 2020 Census block populations and the 2020 tract-to-PUMA and block-to-congressional-district files; IRS Statistics of Income, state, county and congressional district data and national totals (Publication 1304); Congressional Budget Office, revenue projections, February 2026; USDA Food and Nutrition Service, SNAP state participation and benefits, fiscal year 2024, and the SNAP participation rate; CMS, Medicaid and CHIP enrollment data, December 2024; Social Security Administration, SSI Monthly Statistics, December 2024; HHS Office of the Assistant Secretary for Planning and Evaluation, Welfare Indicators report; US Census Bureau, Survey of Income and Program Participation 2023 public-use file; Pew Research Center and the Higher Ed Immigration Portal; US Census Bureau and Bureau of Labor Statistics, Current Population Survey Annual Social and Economic Supplement 2023–2025, the survey behind PolicyEngine's national data; the IRS Statistics of Income public-use file (tax year 2015), through PolicyEngine's national data. The methods documentation gives each source's vintage and use. From bfcb573319a09230aaa2fd7fdaf716eb8ca8b96e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mar=C3=ADa=20Juaristi?= <127882282+juaristi22@users.noreply.github.com> Date: Tue, 24 Nov 2026 11:08:25 +0000 Subject: [PATCH 26/31] Set the pe-doc layout of the LWI methods document Layout only; the text is unchanged. The front matter sets the PDF's title (the proposal kind would otherwise call it "a PolicyEngine proposal") and turns off the budget-table widths, since the last table is the appendix, not a budget. The separator rows of the sources, imputation, targets and appendix tables set their column widths, so long labels no longer wrap into tall rows. The PDF built this way has 21 pages, where it had 24. Part of #922. Co-Authored-By: Claude Opus 5.5 --- experiments/us-county-poc-20261117/lwi-poc-methods.md | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/experiments/us-county-poc-20261117/lwi-poc-methods.md b/experiments/us-county-poc-20261117/lwi-poc-methods.md index be57ce05bb..8d88fa448a 100644 --- a/experiments/us-county-poc-20261117/lwi-poc-methods.md +++ b/experiments/us-county-poc-20261117/lwi-poc-methods.md @@ -1,10 +1,12 @@ --- kind: proposal client: "Living Wage Institute" +title: "County Files proof of concept: methods — a PolicyEngine methods note" status: "draft v0.2 (2026-11-20): for María and Max to review, not for sending" pe-doc: psl_foundation: false split_tables: true + budget_widths: false pdf_name: "PolicyEngine - County Files proof of concept methods" --- @@ -26,7 +28,7 @@ The PoC report gives the results, and the schema documentation lists the file's We built the 2024 county file from two sets of household records and from published statistics, with PolicyEngine's US tax-benefit model. We list each source at the vintage the build read on 17–18 November 2026. The build records the SHA-256 digest of every input file; the appendix lists the main ones. | Source | Vintage | What the build uses it for | -|---|---|---| +|---------------------------|----------------|-------------------------------------| | ACS public-use microdata, household and person files | 2024 1-year | 1,529,668 ACS household records with 3,420,942 people. Of these, 181,260 are group-quarters records: one person each, living in a place such as a nursing home or college dormitory rather than a housing unit, and counting as a household of one. These counts come after staging drops group-quarters records of children under 15 (see "What we impute onto ACS households, and from which donors") | | PolicyEngine's national donor file: release `populace-us-2024-spm-receipts-20260923`, with five more person columns | See "Donor households" below the table | 57,240 donor household records with 166,321 person records; we train the imputation on their person records, tax units (the people on one tax return) and SPM units (the family unit of the Supplemental Poverty Measure) | | Current Population Survey Annual Social and Economic Supplement (CPS ASEC), person files `pppub23`–`pppub25` | Survey years 2023–2025 (income years 2022–2024) | The donor households' survey records, and three work columns on their person records | @@ -155,7 +157,7 @@ In the table below, "ASEC" and "PUF" name the two roles a donor person record ca Staging imputed 101 columns in 25 families: | What staging imputes | Columns | Unit | ACS records filled | Donor records trained on | -|---|---:|---|---:|---:| +|--------------------------------|-------:|---------|---------------:|--------------:| | Usual weekly hours | 1 | person | 39,800 | 50,490 ASEC | | Child support received and paid | 2 | person | 3,420,942 | 66,001 ASEC | | Retirement-account distributions: 401(k), 403(b), simplified employee pension (SEP), Keogh and Roth IRA | 5 | person | 3,420,942 | 66,001 ASEC | @@ -234,7 +236,7 @@ Only some targets equal published figures. The state SNAP and Medicaid targets e ### The targets | Targets | Level | Trained | Held out | Source | -|---|---|---:|---:|---| +|--------------------------|-----------|---------:|--------:|------------------------| | SOI, all returns: the return count, AGI, and 45 return counts and dollar amounts for 23 income, deduction, credit and tax items | State | 2,397 | 0 | SOI Historic Table 2, tax year 2022 | | SOI taxable interest: returns and dollars in 9 AGI bands | State | 912 | 0 | SOI Historic Table 2, tax year 2022 (the band under $1 has no row for 3 states) | | SOI EITC: claims and dollars, in total and by number of children | State | 510 | 0 | SOI Historic Table 2, tax year 2022 | @@ -395,7 +397,7 @@ The `qa` stage loaded the calibrated file with Microcosm's own loader, not polic ## Appendix: build identifiers and settings | Item | Value | -|---|---| +|------------------|--------------------------------------------------------------| | Build | `populace-us-2024-buildo-acs-local-f8b1039f00-20261118T011728Z`, 17–18 November 2026 | | File | `populace_us_2024_acs_local.h5`, 10,637,811,669 bytes, SHA-256 `82314a3b5a6a95762faf6eb4f5b499ce56608ad6a39a27b75e11c75b4945bd3c` | | Code | Microcosm, commit `72b7072bf` (staging) and commit `f8b1039f0` (the release build) | From 0e00ab5fde91f7838fa73e5ff3f021786ba93fdf Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mar=C3=ADa=20Juaristi?= <127882282+juaristi22@users.noreply.github.com> Date: Tue, 24 Nov 2026 11:09:43 +0000 Subject: [PATCH 27/31] Correct five donor passages in the LWI methods document (draft v0.3) Max's agents checked v0.2's donor passages against the build's records again (#1647 comment 7128462564). This takes their five corrections word for word: - the donor file builds on the three releases but is not one of them; - a tax unit's draw goes to its first person whenever its members hold none of the related amount, not only where the code names none; - the survey-item forests read whether the tax unit files jointly, the self-employment income in the column the ASEC records use, and the rescaled Social Security where they ran after the rescale; - each donor person record takes the work columns from its own row in the ASEC person files, the same row for a person in both roles; - the 57,240 donor records are counted as household records. Their sixth item, on the report, is not in this commit. The experiments README gives v0.3 and what is still open. Part of #922. Co-Authored-By: Claude Opus 5.5 --- experiments/us-county-poc-20261117/README.md | 4 ++-- .../us-county-poc-20261117/lwi-poc-methods.md | 14 +++++++------- 2 files changed, 9 insertions(+), 9 deletions(-) diff --git a/experiments/us-county-poc-20261117/README.md b/experiments/us-county-poc-20261117/README.md index 1bcc959f9d..cb64e29182 100644 --- a/experiments/us-county-poc-20261117/README.md +++ b/experiments/us-county-poc-20261117/README.md @@ -4,11 +4,11 @@ Tracking issue: microcosm#922, the LWI County Files. Plan: microcosm#1647. `lwi-poc-report.md` is draft v0.3 (20 November 2026) of the proof-of-concept report for the Living Wage Institute. It states the fit and the limits of the 2024 county file that the 17–18 November run built: build `populace-us-2024-buildo-acs-local-f8b1039f00-20261118T011728Z`, SHA-256 `82314a3b5a6a95762faf6eb4f5b499ce56608ad6a39a27b75e11c75b4945bd3c`. The draft is under review and has not been sent. v0.2 took the corrections that part 2 of the methods draft lists (microcosm#1647 comment 7005741386) and described the 23 release checks as `gate_summary.json` records them. v0.3 edits it for its readers: the delivery table gives each item's status in this delivery, the method summary describes PolicyEngine's national file as it is, and the comparison with PolicyEngine's earlier state-and-district file is out. -`lwi-poc-methods.md` is draft v0.2 (20 November 2026) of the methods documentation. It is part 1 of the methods draft that Max's agents posted on microcosm#1647 (comment 7005740491), edited for LWI: an appendix of build identifiers, settings and input digests replaces the links to GitHub comments, and flags, run-file names and imputation family names are out of the text. v0.2 takes the corrections from Max's agents' check of v0.1's account of the donor households (their geography, their tax-detail records and the targets their weights fit) against the 28 July national build's code, run logs and published files (microcosm#1647 comments 7025093817 and 7025096163). It also describes the donor file as it is, the last published release with five more person columns, where v0.1 called it a patched copy. +`lwi-poc-methods.md` is draft v0.3 (24 November 2026) of the methods documentation. It is part 1 of the methods draft that Max's agents posted on microcosm#1647 (comment 7005740491), edited for LWI: an appendix of build identifiers, settings and input digests replaces the links to GitHub comments, and flags, run-file names and imputation family names are out of the text. v0.2 took the corrections from Max's agents' check of v0.1's account of the donor households (their geography, their tax-detail records and the targets their weights fit) against the 28 July national build's code, run logs and published files (microcosm#1647 comments 7025093817 and 7025096163), and described the donor file as it is, the last published release with five more person columns, where v0.1 called it a patched copy. v0.3 takes the five corrections from their second check of the donor passages (microcosm#1647 comment 7128462564). `schema_manifest.md` and `schema_manifest.json` are the schema documentation: `tools/us_release_schema_manifest.py`'s output for the file, with a notes section at the top of the Markdown (microcosm#1647 comment 7022836029). - **Format.** The report and the methods documentation are `pe-doc` Markdown (PolicyEngine/document-templates). Each has the front matter, the three-line title block and source notes after the last rule. `pe-doc` has no report kind, so both use `kind: proposal` with `psl_foundation: false`. - **Sources.** The numbers come from the run report on microcosm#1647 (comments 6982547034 and 6982549060) and from the release's own reports: `county_reliability.json` and `.csv`, `calibration_diagnostics.json` and `gate_summary.json`. The loader result comes from a test on 18 November with policyengine-us 2.2.1. - **Delivery.** The file, this report, the methods documentation and the schema documentation are shared through the private Hugging Face dataset `policyengine/lwi-county-files`. The report refers to the other two documents by name, because a link into a private repository does not open for a reader who has only a download token. -- **Still open.** The review, the PDF builds, and Max's go for the upload. +- **Still open.** Max's review, and his go to share the Hugging Face repository with LWI. diff --git a/experiments/us-county-poc-20261117/lwi-poc-methods.md b/experiments/us-county-poc-20261117/lwi-poc-methods.md index 8d88fa448a..d3ed13b04c 100644 --- a/experiments/us-county-poc-20261117/lwi-poc-methods.md +++ b/experiments/us-county-poc-20261117/lwi-poc-methods.md @@ -2,7 +2,7 @@ kind: proposal client: "Living Wage Institute" title: "County Files proof of concept: methods — a PolicyEngine methods note" -status: "draft v0.2 (2026-11-20): for María and Max to review, not for sending" +status: "draft v0.3 (2026-11-24): for María and Max to review, not for sending" pe-doc: psl_foundation: false split_tables: true @@ -48,7 +48,7 @@ We built the 2024 county file from two sets of household records and from publis | USDA SNAP participation rate; the Department of Health and Human Services (HHS) Office of the Assistant Secretary for Planning and Evaluation (ASPE) take-up rate for Temporary Assistance for Needy Families (TANF), from its 24th Welfare Indicators report | The run records no year | SNAP and TANF take-up on ACS households | | policyengine-us; policyengine-core | 2.2.1; 3.32.5 | The model the build ran; the release manifest records both versions | -**Donor households.** Donor households are survey households from PolicyEngine's national donor file. We add them to the ACS households and train the imputation on their person records, tax units and SPM units. The file comes from three releases in the public Hugging Face dataset `policyengine/populace-us`: a national build and two later releases that add columns to it. +**Donor households.** Donor households are survey households from PolicyEngine's national donor file. We add them to the ACS households and train the imputation on their person records, tax units and SPM units. The file builds on three releases in the public Hugging Face dataset `policyengine/populace-us`: a national build and two later releases that add columns to it. It is not itself one of them: none of the three holds its five more person columns. - The national build, `populace-us-2024-buildp-sparse-rmloss100-cae8640-20260728T011454Z` of 28 July 2026, chose 57,240 household records from 337,704 candidates. Its records name its inputs as the CPS ASEC for income years 2022–2024 and PolicyEngine's processed PUF, version 1.8.0. In that build's code, version 1.8.0 is the 2015 public-use file, scaled forward to 2024. - In PolicyEngine's national build code at that build's commit (`cae8640`), each CPS ASEC household appears as two records, which start with equal halves of its weight. One, the ASEC record, keeps the household's survey answers, except that two of the build's steps changed its taxable interest and its Social Security. The other, a tax-detail record, starts as a copy of the ASEC record; quantile regression forests trained on PUF tax units then redraw its tax items. Because the national build then chose among these records and set each one's weight on its own, a donor household can appear in the donor file as one of its two records or as both, and where it appears as both, its two weights usually differ (see "What donor records carry"). @@ -140,7 +140,7 @@ We fill most of the missing inputs from PolicyEngine's national donor file: 57,2 We use quantile regression forests in Microcosm's own form, with sign classifiers, chained draws and donor weights. A quantile regression forest predicts the whole distribution of a value, not only its average. Staging runs three imputation passes in order. The first imputes usual weekly hours. The second imputes child support, retirement-account distributions, and work and disability income. The third imputes everything else. In each pass: -- **Training records.** Donor person records, tax units or SPM units. The first two passes train on the donors' ASEC person records and the third on their tax-detail copies (both defined below). Each forest resamples the donors in proportion to their weights in the donor file. Those weights are concentrated (see "The donor file's weights" under "Design weights and the solver"): 41,430 of the 57,240 donor households have a weight below 2 there, and together they hold 0.003% of the donor weight. The other 15,810 households hold 18,867 of the 66,001 ASEC person records and 27,402 of the 100,320 tax-detail records, so almost every record a forest resamples comes from them. The sign classifier below uses the same weights directly. +- **Training records.** Donor person records, tax units or SPM units. The first two passes train on the donors' ASEC person records and the third on their tax-detail copies (both defined below). Each forest resamples the donors in proportion to their weights in the donor file. Those weights are concentrated (see "The donor file's weights" under "Design weights and the solver"): 41,430 of the 57,240 donor household records have a weight below 2 there, and together they hold 0.003% of the donor weight. The other 15,810 records hold 18,867 of the 66,001 ASEC person records and 27,402 of the 100,320 tax-detail records, so almost every record a forest resamples comes from them. The sign classifier below uses the same weights directly. - **Predictors.** Age, sex and state, plus, where the ACS record has them, wages, self-employment income, Social Security, retirement income, interest, dividend and rental income, household-head status and housing tenure. Tax-unit and SPM-unit fits use the unit's number of people, of women and of household heads, its summed ages, state, housing tenure and summed incomes. Each pattern of available predictors gets its own fit, on donors that have those predictors and all of the family's columns, so the build never reads a blank as a zero. - **Second-pass predictors.** For child support, the second pass adds the ACS's "all other income" amount. For retirement-account distributions and for work and disability income, it swaps the donors' retirement-income measure for one closer to the ACS's definition. - **Joint within a family.** In this run, each family holds at most eight columns. The build splits a wider group of columns into batches, and each batch counts as its own family. The forests draw a family's columns in sequence, each conditioned on the predictors and on the columns already drawn. One family's draws do not enter another family's fit. For example, the forests draw the 54 person-level tax columns jointly only within each of their seven batches. @@ -217,15 +217,15 @@ In the national build's code (`cae8640`), each CPS ASEC household appears as two The other, a tax-detail record, starts as a copy of the ASEC record. Quantile regression forests, trained with the PUF's weights on 208,611 PUF tax units, then redraw 65 tax items for each of the copy's tax units, one at a time, given the unit's filing status, its number of people, its CPS ASEC incomes (wages, self-employment income, taxable interest, dividends, and short- and long-term capital gains) and the items already drawn. Those incomes are among the 65 items. Summed without weights over the 168,852 tax-detail records among the national build's 337,704 candidates, the redrawn wages, taxable interest and capital gains come within 0.1% of the CPS ASEC amounts and dividends within 0.4%. Self-employment income totals 11% less in the column the ASEC records use and 49.7% more across both columns: on the copies, a later step puts each person's whole self-employment income in one of two columns, by a drawn flag for specified service businesses, and the second column is zero on every ASEC record. The national build later cut one tax item, capital gain distributions reported without Schedule D, to 15% of its drawn total to match an IRS Statistics of Income total. -Where the tax unit's members hold an amount for an item in their CPS ASEC records, the code spreads the unit's draw over them in those shares. Otherwise it spreads the draw by a related amount, such as earnings, where the code names one, and gives the whole draw to the unit's first person where it names none, as for mortgage interest, charitable gifts, real estate taxes and partnership income. For Social Security, the code splits the drawn total by type in the shares of the unit's CPS ASEC Social Security, or in four equal parts (retirement, disability, survivors and dependents) where the unit has none in the CPS ASEC. +Where the tax unit's members hold an amount for an item in their CPS ASEC records, the code spreads the unit's draw over them in those shares. Otherwise it spreads the draw by a related amount, such as earnings, where the code names one and the unit's members hold some of it, and gives the whole draw to the unit's first person in every other case, as for mortgage interest, charitable gifts, real estate taxes and partnership income, for which the code names no related amount. For Social Security, the code splits the drawn total by type in the shares of the unit's CPS ASEC Social Security, or in four equal parts (retirement, disability, survivors and dependents) where the unit has none in the CPS ASEC. -Forests trained on the ASEC records then redraw several survey items on each tax-detail record: child support, disability benefits, workers' compensation, weeks unemployed, childcare costs, energy subsidies, retirement contributions, four kinds of retirement-account distributions, last year's earnings, housing assistance receipt and take-up and, at the end of the national build, health insurance premiums. Except for weeks unemployed, these forests read the record's age, sex, employer coverage, filing status and dependents, and the wages, self-employment income and Social Security the PUF forests drew for it. The tax-detail record keeps its other survey items as copied. +Forests trained on the ASEC records then redraw several survey items on each tax-detail record: child support, disability benefits, workers' compensation, weeks unemployed, childcare costs, energy subsidies, retirement contributions, four kinds of retirement-account distributions, last year's earnings, housing assistance receipt and take-up and, at the end of the national build, health insurance premiums. Except for weeks unemployed, these forests read the record's age, sex, employer coverage, whether its tax unit files jointly and its number of dependents, the wages and Social Security the PUF forests drew for it, and its self-employment income in the column the ASEC records use, which is zero on a copy whose drawn flag put that income in the second column. By the code's order, the forests that ran after the national build rescaled Social Security, the health insurance premium forest among them, read the rescaled amounts. The tax-detail record keeps its other survey items as copied. Because the national build then chose among these records, a donor household can appear in the donor file as one of its two records or as both. The national build's calibration then set each record's weight on its own: of the 9,963 households that the donor file holds as both records, 496 have equal weights there (see "The donor file's weights" under "Design weights and the solver"). The donor file's 166,321 person records come from the CPS ASEC for income years 2022, 2023 and 2024 (54,464, 54,654 and 57,203 records). Of these, 66,001 are ASEC person records and 100,320 are tax-detail copies. They hold 135,833 distinct people, each counted once per income year: 30,488 people appear twice, once in each role. In the county file, the 57,240 donor household records hold 47,277 distinct source households (see "Copies" under "The reliability grade"). -The donor file holds five person columns that its last release, `populace-us-2024-spm-receipts-20260923`, does not. Three are ASEC work columns: detailed industry, major industry and whether the person worked last year. Each of the 166,321 donor person records takes them from its own ASEC record, which it matches exactly once, with no identity mismatches. On every record, eight columns that the release already holds equal the values re-derived from that ASEC record. The other two columns, strike benefits and passive partnership and S-corporation income, hold only zeros, and every column of the release is unchanged. For strike benefits, the code that adds these columns states a fixed reason: no donor record, and no record in the ASEC person files for survey years 2023 to 2026, reports them. Its run read only the files for survey years 2023 to 2025, for the work columns. +The donor file holds five person columns that its last release, `populace-us-2024-spm-receipts-20260923`, does not. Three are ASEC work columns: detailed industry, major industry and whether the person worked last year. Each of the 166,321 donor person records takes them from its own row in the ASEC person files, which it matches exactly once, with no identity mismatches; a person who appears in both roles takes them from the same row for both records. On every record, eight columns that the release already holds equal the values re-derived from that row. The other two columns, strike benefits and passive partnership and S-corporation income, hold only zeros, and every column of the release is unchanged. For strike benefits, the code that adds these columns states a fixed reason: no donor record, and no record in the ASEC person files for survey years 2023 to 2026, reports them. Its run read only the files for survey years 2023 to 2025, for the work columns. ## Calibration: the targets, how we weight them, and the weight cap @@ -289,7 +289,7 @@ Two shares describe each group of targets. Its loss weight share is its share of The solve starts from the design weights. Staging builds them when it pools the ACS and donor records. It takes each ACS household's housing-unit weight (WGTP; a group-quarters record takes its person weight) and each donor household's weight in the donor file. It then scales each group to half of the donor file's household weight total: 61.27 million each, 122.5 million in all. These scaled weights are the design weights. The weight cap, every weight ratio below and the loss at the design weights all use them. The solve keeps their total fixed at 122,537,092, the donor file's household weight total, which PolicyEngine's national build set (see "The donor file's weights" below). That total is smaller than the sum of the 51 state household targets, 129,227,496. At the final weights, the records those targets count add up to 122,512,091. The 181,260 group-quarters records add up to 25,001, against 3,620,662 at the design weights. -**The donor file's weights.** PolicyEngine's 28 July 2026 national build set the donor households' weights by calibrating them to 5,659 targets for 2024: 448 national and 5,211 for the 50 states and DC, with none below state level. IRS SOI tables supply 4,182 of them and Census population estimates by age 936; the rest come from CMS, SSA, USDA SNAP, the Census Bureau's state tax collections, HHS, the Joint Committee on Taxation, CBO, the Bureau of Economic Analysis and the Federal Reserve, plus one national total of Keogh distributions that the build computed from the selected records themselves. The build rebased 662 count targets and 662 dollar targets to later IRS totals for tax years 2023 and 2024, and it aged 1,988 dollar targets to 2024: 1,401 by SOI's national growth to 2023 and then CBO's projected growth to 2024, and 587 by CBO's projected growth from 2023 alone. Its loss caps each target's scaled error at 1 (100%), and it held out no target. Each weight could rise to at most 5 times its starting weight, with no lower limit, and the total stayed at 122,537,092: the build had scaled up the selected households' base weights so that they counted 334.2 million people. At the final weights, 41,302 of the 57,240 households keep less than 0.1% of their starting weight, and the effective sample size (defined under "The reliability grade") falls from 42,355 to 9,174. The donor file carries these final weights unchanged, and since each donor household's design weight is half its weight there, 41,430 of the 57,240 donor households start the county solve with a design weight below 1. +**The donor file's weights.** PolicyEngine's 28 July 2026 national build set the donor households' weights by calibrating them to 5,659 targets for 2024: 448 national and 5,211 for the 50 states and DC, with none below state level. IRS SOI tables supply 4,182 of them and Census population estimates by age 936; the rest come from CMS, SSA, USDA SNAP, the Census Bureau's state tax collections, HHS, the Joint Committee on Taxation, CBO, the Bureau of Economic Analysis and the Federal Reserve, plus one national total of Keogh distributions that the build computed from the selected records themselves. The build rebased 662 count targets and 662 dollar targets to later IRS totals for tax years 2023 and 2024, and it aged 1,988 dollar targets to 2024: 1,401 by SOI's national growth to 2023 and then CBO's projected growth to 2024, and 587 by CBO's projected growth from 2023 alone. Its loss caps each target's scaled error at 1 (100%), and it held out no target. Each weight could rise to at most 5 times its starting weight, with no lower limit, and the total stayed at 122,537,092: the build had scaled up the selected households' base weights so that they counted 334.2 million people. At the final weights, 41,302 of the 57,240 household records keep less than 0.1% of their starting weight, and the effective sample size (defined under "The reliability grade") falls from 42,355 to 9,174. The donor file carries these final weights unchanged, and since each donor household record's design weight is half its weight there, 41,430 of the 57,240 donor household records start the county solve with a design weight below 1. The solver, Adam (a standard gradient method), works on the logarithm of each weight, so every weight stays positive. It takes 800 steps at a learning rate of 0.02, in two runs of 400 steps, with seed 0. Each step uses every trained target and every household record. The second run starts from the first run's weights, with a fresh optimizer state. No penalty pulls weights toward their design values. The file keeps the weights from the last step. From 7306a4365cd94dc30207cf8533c7b876e11dfab2 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mar=C3=ADa=20Juaristi?= <127882282+juaristi22@users.noreply.github.com> Date: Tue, 24 Nov 2026 11:14:39 +0000 Subject: [PATCH 28/31] Count the donor households as 47,277 in the LWI PoC report (draft v0.4) Max's agents' second check (#1647 comment 7128462564, item 6) found that the report counts the 57,240 donor household records as households. They hold 47,277 distinct source households, 9,963 of them twice. Step 2 of the method now adds 47,277 donor households. The file table's household-record row keeps its 57,240 donor records, so that it still sums to 1,586,908, and says they come from 47,277 households. The first reason the effective samples are small now says the 47,277 households account for 3.6% of the records, their records' share. The experiments README gives v0.4. Part of #922. Co-Authored-By: Claude Opus 5.5 --- experiments/us-county-poc-20261117/README.md | 2 +- experiments/us-county-poc-20261117/lwi-poc-report.md | 8 ++++---- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/experiments/us-county-poc-20261117/README.md b/experiments/us-county-poc-20261117/README.md index cb64e29182..2e930c8e05 100644 --- a/experiments/us-county-poc-20261117/README.md +++ b/experiments/us-county-poc-20261117/README.md @@ -2,7 +2,7 @@ Tracking issue: microcosm#922, the LWI County Files. Plan: microcosm#1647. -`lwi-poc-report.md` is draft v0.3 (20 November 2026) of the proof-of-concept report for the Living Wage Institute. It states the fit and the limits of the 2024 county file that the 17–18 November run built: build `populace-us-2024-buildo-acs-local-f8b1039f00-20261118T011728Z`, SHA-256 `82314a3b5a6a95762faf6eb4f5b499ce56608ad6a39a27b75e11c75b4945bd3c`. The draft is under review and has not been sent. v0.2 took the corrections that part 2 of the methods draft lists (microcosm#1647 comment 7005741386) and described the 23 release checks as `gate_summary.json` records them. v0.3 edits it for its readers: the delivery table gives each item's status in this delivery, the method summary describes PolicyEngine's national file as it is, and the comparison with PolicyEngine's earlier state-and-district file is out. +`lwi-poc-report.md` is draft v0.4 (24 November 2026) of the proof-of-concept report for the Living Wage Institute. It states the fit and the limits of the 2024 county file that the 17–18 November run built: build `populace-us-2024-buildo-acs-local-f8b1039f00-20261118T011728Z`, SHA-256 `82314a3b5a6a95762faf6eb4f5b499ce56608ad6a39a27b75e11c75b4945bd3c`. The draft is under review and has not been sent. v0.2 took the corrections that part 2 of the methods draft lists (microcosm#1647 comment 7005741386) and described the 23 release checks as `gate_summary.json` records them. v0.3 edits it for its readers: the delivery table gives each item's status in this delivery, the method summary describes PolicyEngine's national file as it is, and the comparison with PolicyEngine's earlier state-and-district file is out. v0.4 gives the number of donor households as 47,277, the distinct households behind the 57,240 donor household records (microcosm#1647 comment 7128462564, item 6). `lwi-poc-methods.md` is draft v0.3 (24 November 2026) of the methods documentation. It is part 1 of the methods draft that Max's agents posted on microcosm#1647 (comment 7005740491), edited for LWI: an appendix of build identifiers, settings and input digests replaces the links to GitHub comments, and flags, run-file names and imputation family names are out of the text. v0.2 took the corrections from Max's agents' check of v0.1's account of the donor households (their geography, their tax-detail records and the targets their weights fit) against the 28 July national build's code, run logs and published files (microcosm#1647 comments 7025093817 and 7025096163), and described the donor file as it is, the last published release with five more person columns, where v0.1 called it a patched copy. v0.3 takes the five corrections from their second check of the donor passages (microcosm#1647 comment 7128462564). diff --git a/experiments/us-county-poc-20261117/lwi-poc-report.md b/experiments/us-county-poc-20261117/lwi-poc-report.md index 4e355a1d9a..89df137fe1 100644 --- a/experiments/us-county-poc-20261117/lwi-poc-report.md +++ b/experiments/us-county-poc-20261117/lwi-poc-report.md @@ -2,7 +2,7 @@ kind: proposal client: "Living Wage Institute" title: "County Files proof of concept: 2024 county file — a PolicyEngine report" -status: "draft v0.3 (2026-11-20): for María and Max to review, not for sending" +status: "draft v0.4 (2026-11-24): for María and Max to review, not for sending" pe-doc: psl_foundation: false split_tables: false @@ -42,7 +42,7 @@ A PolicyEngine report · for the Living Wage Institute · November 2026 |------------------|----------------------------------------------------------------| | Year | 2024 | | Geography | 3,144 counties and county-equivalents on the 2023 county codes, including Connecticut's nine planning regions; 436 congressional districts. Puerto Rico is not included. | -| Household records | 1,586,908: 1,529,668 from the 2024 American Community Survey (ACS), of which 181,260 are one-person group-quarters records (for example, in nursing homes or college dormitories), and 57,240 national donor households | +| Household records | 1,586,908: 1,529,668 from the 2024 American Community Survey (ACS), of which 181,260 are one-person group-quarters records (for example, in nursing homes or college dormitories), and 57,240 from 47,277 national donor households | | Person records | 3,587,263: 3,420,942 ACS and 166,321 donor | | Weighted totals | About 122.5 million households and 331 million people | | Model | policyengine-us 2.2.1 | @@ -55,7 +55,7 @@ Every county has at least one household. Counting households in housing units (A The method has four steps. The methods documentation, delivered with this report, gives the detail, and our working papers explain the main choices. 1. **Households and their counties.** We start from the 2024 ACS 1-year public-use microdata. The ACS gives each household's PUMA, not its county. So we draw a county for each ACS household within its PUMA, with odds in proportion to the population each county shares with that PUMA. Each household keeps its whole weight in the county it draws. -2. **National donor households.** The ACS does not collect detailed tax items. We add 57,240 donor households from PolicyEngine's published 2024 national file, built on 28 July 2026 from the Current Population Survey (CPS ASEC), with tax detail imputed from the IRS public-use file. These households keep the county that the national file gives them. +2. **National donor households.** The ACS does not collect detailed tax items. We add 47,277 donor households from PolicyEngine's published 2024 national file, built on 28 July 2026 from the Current Population Survey (CPS ASEC), with tax detail imputed from the IRS public-use file. These households keep the county that the national file gives them. 3. **Imputation.** We give ACS households most of the characteristics the ACS lacks, such as detailed tax items, from the donor households, with quantile regression forests (working paper: [microcosm.institute/support/paper](https://microcosm.institute/support/paper)). A few come from elsewhere: the household's own ACS answer sets SNAP receipt, a model trained on the Survey of Income and Program Participation sets SSI disability status, and rules and seeded random draws set immigration status and program take-up. Inputs still blank after that take the model's default values, such as zero tips and zero net worth. Imputation gives records their characteristics. It does not change how many households each record represents. 4. **Calibration.** We then adjust the household weights so that the file comes close to 16,440 targets at once: 4,482 for states, 436 for congressional districts and 11,522 for counties. The targets come from official statistics, but not all of them equal a published figure: we age IRS dollar amounts to 2024, split each state's IRS totals of returns and adjusted gross income across its counties by the counties' shares in the IRS county data, and take every population target from 2020 Census block populations. A cap keeps each household's final weight at most five times its starting weight. A paper on this calibration method is in preparation. @@ -148,7 +148,7 @@ Most D grades have both causes: 2,905 counties have an effective sample below 30 **Why the effective samples are small.** There are three reasons: -1. **Donor households carry most of the weight.** The 57,240 national donor households are 3.6% of the records, but they carry 77% of the household weight. Before calibration they carried half. In each county, a few of them hold most of the weight. +1. **Donor households carry most of the weight.** The 47,277 national donor households account for 3.6% of the records, but they carry 77% of the household weight. Before calibration they carried half. In each county, a few of them hold most of the weight. 2. **Calibration concentrates the weight further.** After calibration, 1% of the household records hold 81% of the weight. Before calibration, they held 51%. 3. **The calibration gives most of its weight to state targets.** Before the solve, state and district targets make up 94% of the calibration's weighting and county targets 6%. At the final weights, county targets carry 27% of the remaining error. The fit is close for state totals and looser for counties. We have not yet tested other weightings. From 5f3020b61fb1ab72ae72e44d59bdce181489cd53 Mon Sep 17 00:00:00 2001 From: Max Ghenis Date: Tue, 24 Nov 2026 18:02:14 +0100 Subject: [PATCH 29/31] Follow the agreement's MVP wording in the LWI PoC report (draft v0.5) Max chose to fix the report's wording before his handover email goes (d3352: "d3352 fix first", "Drop synthetic"). The report now says the agreement lists the 2026 and 2027 files and the household measures in the MVP, where v0.4 called them a stretch goal, and says where the records come from instead of calling them synthetic. Wording as proposed in microcosm#1647 comment 7137552522; the rendered PDF differs from v0.4's only in those five lines. Co-Authored-By: Claude Opus 5.5 --- experiments/us-county-poc-20261117/README.md | 2 +- experiments/us-county-poc-20261117/lwi-poc-report.md | 12 ++++++------ 2 files changed, 7 insertions(+), 7 deletions(-) diff --git a/experiments/us-county-poc-20261117/README.md b/experiments/us-county-poc-20261117/README.md index 2e930c8e05..d99db2fe32 100644 --- a/experiments/us-county-poc-20261117/README.md +++ b/experiments/us-county-poc-20261117/README.md @@ -2,7 +2,7 @@ Tracking issue: microcosm#922, the LWI County Files. Plan: microcosm#1647. -`lwi-poc-report.md` is draft v0.4 (24 November 2026) of the proof-of-concept report for the Living Wage Institute. It states the fit and the limits of the 2024 county file that the 17–18 November run built: build `populace-us-2024-buildo-acs-local-f8b1039f00-20261118T011728Z`, SHA-256 `82314a3b5a6a95762faf6eb4f5b499ce56608ad6a39a27b75e11c75b4945bd3c`. The draft is under review and has not been sent. v0.2 took the corrections that part 2 of the methods draft lists (microcosm#1647 comment 7005741386) and described the 23 release checks as `gate_summary.json` records them. v0.3 edits it for its readers: the delivery table gives each item's status in this delivery, the method summary describes PolicyEngine's national file as it is, and the comparison with PolicyEngine's earlier state-and-district file is out. v0.4 gives the number of donor households as 47,277, the distinct households behind the 57,240 donor household records (microcosm#1647 comment 7128462564, item 6). +`lwi-poc-report.md` is draft v0.5 (24 November 2026) of the proof-of-concept report for the Living Wage Institute. It states the fit and the limits of the 2024 county file that the 17–18 November run built: build `populace-us-2024-buildo-acs-local-f8b1039f00-20261118T011728Z`, SHA-256 `82314a3b5a6a95762faf6eb4f5b499ce56608ad6a39a27b75e11c75b4945bd3c`. The draft is under review and has not been sent. v0.2 took the corrections that part 2 of the methods draft lists (microcosm#1647 comment 7005741386) and described the 23 release checks as `gate_summary.json` records them. v0.3 edits it for its readers: the delivery table gives each item's status in this delivery, the method summary describes PolicyEngine's national file as it is, and the comparison with PolicyEngine's earlier state-and-district file is out. v0.4 gives the number of donor households as 47,277, the distinct households behind the 57,240 donor household records (microcosm#1647 comment 7128462564, item 6). v0.5 says that the agreement lists the 2026 and 2027 files and the household measures in the MVP, where v0.4 called them a stretch goal, and says where the records come from instead of calling them synthetic (microcosm#1647 comment 7137552522). `lwi-poc-methods.md` is draft v0.3 (24 November 2026) of the methods documentation. It is part 1 of the methods draft that Max's agents posted on microcosm#1647 (comment 7005740491), edited for LWI: an appendix of build identifiers, settings and input digests replaces the links to GitHub comments, and flags, run-file names and imputation family names are out of the text. v0.2 took the corrections from Max's agents' check of v0.1's account of the donor households (their geography, their tax-detail records and the targets their weights fit) against the 28 July national build's code, run logs and published files (microcosm#1647 comments 7025093817 and 7025096163), and described the donor file as it is, the last published release with five more person columns, where v0.1 called it a patched copy. v0.3 takes the five corrections from their second check of the donor passages (microcosm#1647 comment 7128462564). diff --git a/experiments/us-county-poc-20261117/lwi-poc-report.md b/experiments/us-county-poc-20261117/lwi-poc-report.md index 89df137fe1..90fb70a019 100644 --- a/experiments/us-county-poc-20261117/lwi-poc-report.md +++ b/experiments/us-county-poc-20261117/lwi-poc-report.md @@ -2,7 +2,7 @@ kind: proposal client: "Living Wage Institute" title: "County Files proof of concept: 2024 county file — a PolicyEngine report" -status: "draft v0.4 (2026-11-24): for María and Max to review, not for sending" +status: "draft v0.5 (2026-11-24): for María and Max to review, not for sending" pe-doc: psl_foundation: false split_tables: false @@ -18,7 +18,7 @@ A PolicyEngine report · for the Living Wage Institute · November 2026 ## Summary -- **We are delivering a 2024 county file.** It is one microdata file of synthetic households that covers all 3,144 US counties and county-equivalents. It is weighted to represent about 122.5 million households and 331 million people, and it runs in PolicyEngine's US tax-benefit model (policyengine-us 2.2.1). +- **We are delivering a 2024 county file.** It is one household microdata file that covers all 3,144 US counties and county-equivalents. Its records come from the 2024 American Community Survey (ACS) public-use microdata and from PolicyEngine's national file. We draw a county for each ACS household, impute most of what the ACS lacks and calibrate the weights (see "How we built it"). The file's weights represent about 122.5 million households and 331 million people. The file runs in PolicyEngine's US tax-benefit model (policyengine-us 2.2.1). - **State results are strong.** After calibration, 96% of the 4,227 IRS state tax targets are within 10% of their target value, and every SNAP, Medicaid and state population target is within 10%. - **County totals are useful, but county distributions are not yet reliable.** Two-thirds of the county targets used in calibration are within 10%. Against county statistics the calibration never saw, the file estimates total earnings and total household income better than a simple population-share split. It is worse than that split for the number of households with earnings and for the income distribution. - **The main limit is the effective sample in each county.** In the median county, the weights behave like a sample of about 6 households. National donor households make up 3.6% of the records but carry 77% of the weight, so a few of them dominate each county. @@ -33,8 +33,8 @@ A PolicyEngine report · for the Living Wage Institute · November 2026 | This report: the fit and the limits | Delivered as this document, in the same repository. | | Methods documentation | Delivered as a document in the same repository. | | Schema documentation | Delivered as a document in the same repository. It lists every table and column of the file, with its type and its missing values, and the changes from the sample column list sent with the agreement. | -| The 2026 and 2027 county files | A stretch goal, not yet produced. | -| Household measures (earnings, gross income and net income for each household) | A stretch goal, not yet produced. | +| The 2026 and 2027 county files | Not yet produced; the agreement lists them in the MVP. | +| Household measures (earnings, gross income and net income for each household) | Not yet produced; the agreement lists them in the MVP. | ## The 2024 county file @@ -178,14 +178,14 @@ Most D grades have both causes: 2,905 counties have an effective sample below 30 - S-corporation income is not separated from partnership income. The national data holds both as one combined partnership amount, so the separate S-corporation items are zero. - We left out the 1,946 ACS group-quarters records of children under 15, which carry 0.04% of the ACS household weight. Each would form a poverty-measure unit with no adult, and one such unit stops the model version we use from computing poverty measures for the whole file. - **Model use.** The file loads with policyengine-us 2.2.1's standard dataset loader. On a computer with 32 GB of memory, the national simulation built in 90 seconds and used at most 18 GB, and it computed 2024 totals of population, employment income and adjusted gross income. For one state, the model also computed income tax, SNAP and household net income, with no missing values. We have not run full-model calculations, such as household net income, for the whole country at once. On a 32 GB computer, run them state by state or in chunks, or use a larger machine. The model ignores 254 extra columns: 213 raw survey fields, 29 build identifiers and 12 derived columns, among them `county_fips_2023`. The schema documentation says which is which. -- **One year only.** The file is for 2024. The 2026 and 2027 files are a stretch goal. +- **One year only.** The file is for 2024. We have not yet produced the 2026 and 2027 files, which the agreement lists in the MVP. ## Next steps 1. **Raise the effective sample in each county.** Spread each county's weight over more households, mainly by lowering the share of the weight that donor households carry. We will measure progress with the effective sample per county and the share of the population in counties at grade C or better. 2. **Balance the contribution of cloned records to the calibration.** Keep any single source household, together with its copies, from dominating the weights that the calibration chooses. 3. **Improve the calibration fit.** Give the county targets more weight, so that held-out county targets beat the population-share baseline, and fix the national tax outliers listed above. We will also improve the fit to congressional district population. -4. **Complete the stretch goals.** Produce the 2026 and 2027 county files and the household measures. +4. **Add the files and measures the agreement lists in the MVP.** Produce the 2026 and 2027 county files and the household measures. 5. **Build the final County Files.** Remove the shortcuts this proof of concept uses. ## Appendix: file provenance From ef1f8babfe873f2e121bdb70de1ac2fbff40cb23 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mar=C3=ADa=20Juaristi?= <127882282+juaristi22@users.noreply.github.com> Date: Wed, 25 Nov 2026 11:50:18 +0000 Subject: [PATCH 30/31] Record that the LWI PoC documents were sent The report (v0.5) and the methods documentation (v0.3) went to LWI with the file and the schema documentation, through the private Hugging Face dataset policyengine/lwi-county-files as it stood at commit b92e7096. Their status lines and the experiments README now say so, in place of "not for sending" and the open review. Text only: the built PDFs do not change, because pe-doc keeps the status out of them. Part of #922. Co-Authored-By: Claude Opus 5.5 --- experiments/us-county-poc-20261117/README.md | 6 +++--- experiments/us-county-poc-20261117/lwi-poc-methods.md | 2 +- experiments/us-county-poc-20261117/lwi-poc-report.md | 2 +- 3 files changed, 5 insertions(+), 5 deletions(-) diff --git a/experiments/us-county-poc-20261117/README.md b/experiments/us-county-poc-20261117/README.md index d99db2fe32..6a2e134987 100644 --- a/experiments/us-county-poc-20261117/README.md +++ b/experiments/us-county-poc-20261117/README.md @@ -2,13 +2,13 @@ Tracking issue: microcosm#922, the LWI County Files. Plan: microcosm#1647. -`lwi-poc-report.md` is draft v0.5 (24 November 2026) of the proof-of-concept report for the Living Wage Institute. It states the fit and the limits of the 2024 county file that the 17–18 November run built: build `populace-us-2024-buildo-acs-local-f8b1039f00-20261118T011728Z`, SHA-256 `82314a3b5a6a95762faf6eb4f5b499ce56608ad6a39a27b75e11c75b4945bd3c`. The draft is under review and has not been sent. v0.2 took the corrections that part 2 of the methods draft lists (microcosm#1647 comment 7005741386) and described the 23 release checks as `gate_summary.json` records them. v0.3 edits it for its readers: the delivery table gives each item's status in this delivery, the method summary describes PolicyEngine's national file as it is, and the comparison with PolicyEngine's earlier state-and-district file is out. v0.4 gives the number of donor households as 47,277, the distinct households behind the 57,240 donor household records (microcosm#1647 comment 7128462564, item 6). v0.5 says that the agreement lists the 2026 and 2027 files and the household measures in the MVP, where v0.4 called them a stretch goal, and says where the records come from instead of calling them synthetic (microcosm#1647 comment 7137552522). +`lwi-poc-report.md` is v0.5 (24 November 2026) of the proof-of-concept report for the Living Wage Institute, the version sent to LWI. It states the fit and the limits of the 2024 county file that the 17–18 November run built: build `populace-us-2024-buildo-acs-local-f8b1039f00-20261118T011728Z`, SHA-256 `82314a3b5a6a95762faf6eb4f5b499ce56608ad6a39a27b75e11c75b4945bd3c`. v0.2 took the corrections that part 2 of the methods draft lists (microcosm#1647 comment 7005741386) and described the 23 release checks as `gate_summary.json` records them. v0.3 edits it for its readers: the delivery table gives each item's status in this delivery, the method summary describes PolicyEngine's national file as it is, and the comparison with PolicyEngine's earlier state-and-district file is out. v0.4 gives the number of donor households as 47,277, the distinct households behind the 57,240 donor household records (microcosm#1647 comment 7128462564, item 6). v0.5 says that the agreement lists the 2026 and 2027 files and the household measures in the MVP, where v0.4 called them a stretch goal, and says where the records come from instead of calling them synthetic (microcosm#1647 comment 7137552522). -`lwi-poc-methods.md` is draft v0.3 (24 November 2026) of the methods documentation. It is part 1 of the methods draft that Max's agents posted on microcosm#1647 (comment 7005740491), edited for LWI: an appendix of build identifiers, settings and input digests replaces the links to GitHub comments, and flags, run-file names and imputation family names are out of the text. v0.2 took the corrections from Max's agents' check of v0.1's account of the donor households (their geography, their tax-detail records and the targets their weights fit) against the 28 July national build's code, run logs and published files (microcosm#1647 comments 7025093817 and 7025096163), and described the donor file as it is, the last published release with five more person columns, where v0.1 called it a patched copy. v0.3 takes the five corrections from their second check of the donor passages (microcosm#1647 comment 7128462564). +`lwi-poc-methods.md` is v0.3 (24 November 2026) of the methods documentation, the version sent to LWI. It is part 1 of the methods draft that Max's agents posted on microcosm#1647 (comment 7005740491), edited for LWI: an appendix of build identifiers, settings and input digests replaces the links to GitHub comments, and flags, run-file names and imputation family names are out of the text. v0.2 took the corrections from Max's agents' check of v0.1's account of the donor households (their geography, their tax-detail records and the targets their weights fit) against the 28 July national build's code, run logs and published files (microcosm#1647 comments 7025093817 and 7025096163), and described the donor file as it is, the last published release with five more person columns, where v0.1 called it a patched copy. v0.3 takes the five corrections from their second check of the donor passages (microcosm#1647 comment 7128462564). `schema_manifest.md` and `schema_manifest.json` are the schema documentation: `tools/us_release_schema_manifest.py`'s output for the file, with a notes section at the top of the Markdown (microcosm#1647 comment 7022836029). - **Format.** The report and the methods documentation are `pe-doc` Markdown (PolicyEngine/document-templates). Each has the front matter, the three-line title block and source notes after the last rule. `pe-doc` has no report kind, so both use `kind: proposal` with `psl_foundation: false`. - **Sources.** The numbers come from the run report on microcosm#1647 (comments 6982547034 and 6982549060) and from the release's own reports: `county_reliability.json` and `.csv`, `calibration_diagnostics.json` and `gate_summary.json`. The loader result comes from a test on 18 November with policyengine-us 2.2.1. - **Delivery.** The file, this report, the methods documentation and the schema documentation are shared through the private Hugging Face dataset `policyengine/lwi-county-files`. The report refers to the other two documents by name, because a link into a private repository does not open for a reader who has only a download token. -- **Still open.** Max's review, and his go to share the Hugging Face repository with LWI. +- **Sent.** PolicyEngine sent LWI the file and the three documents through the private Hugging Face dataset, as it stood at commit `b92e7096`: the report (v0.5) and the methods documentation (v0.3) as PDFs, and the schema documentation as Markdown and JSON. diff --git a/experiments/us-county-poc-20261117/lwi-poc-methods.md b/experiments/us-county-poc-20261117/lwi-poc-methods.md index d3ed13b04c..5bf5a8c3fc 100644 --- a/experiments/us-county-poc-20261117/lwi-poc-methods.md +++ b/experiments/us-county-poc-20261117/lwi-poc-methods.md @@ -2,7 +2,7 @@ kind: proposal client: "Living Wage Institute" title: "County Files proof of concept: methods — a PolicyEngine methods note" -status: "draft v0.3 (2026-11-24): for María and Max to review, not for sending" +status: "v0.3 (2026-11-24): sent to LWI" pe-doc: psl_foundation: false split_tables: true diff --git a/experiments/us-county-poc-20261117/lwi-poc-report.md b/experiments/us-county-poc-20261117/lwi-poc-report.md index 90fb70a019..68fc54b6e1 100644 --- a/experiments/us-county-poc-20261117/lwi-poc-report.md +++ b/experiments/us-county-poc-20261117/lwi-poc-report.md @@ -2,7 +2,7 @@ kind: proposal client: "Living Wage Institute" title: "County Files proof of concept: 2024 county file — a PolicyEngine report" -status: "draft v0.5 (2026-11-24): for María and Max to review, not for sending" +status: "v0.5 (2026-11-24): sent to LWI" pe-doc: psl_foundation: false split_tables: false From 2488f3aa179969e23e6ee7a9007f17c91fbbb7a9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mar=C3=ADa=20Juaristi?= <127882282+juaristi22@users.noreply.github.com> Date: Wed, 25 Nov 2026 12:55:56 +0000 Subject: [PATCH 31/31] Say that only the LWI PoC report reached LWI, by email On 24 November Max emailed LWI the report v0.5 as a PDF and asked who should get access to the private Hugging Face dataset. Nobody at LWI has access yet, so the file, the methods documentation v0.3 and the schema documentation have not reached them. The README and the methods document's status line said otherwise (review comment 7163022695). Co-Authored-By: Claude Opus 5.5 --- experiments/us-county-poc-20261117/README.md | 6 +++--- experiments/us-county-poc-20261117/lwi-poc-methods.md | 2 +- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/experiments/us-county-poc-20261117/README.md b/experiments/us-county-poc-20261117/README.md index 6a2e134987..407aecc7f5 100644 --- a/experiments/us-county-poc-20261117/README.md +++ b/experiments/us-county-poc-20261117/README.md @@ -4,11 +4,11 @@ Tracking issue: microcosm#922, the LWI County Files. Plan: microcosm#1647. `lwi-poc-report.md` is v0.5 (24 November 2026) of the proof-of-concept report for the Living Wage Institute, the version sent to LWI. It states the fit and the limits of the 2024 county file that the 17–18 November run built: build `populace-us-2024-buildo-acs-local-f8b1039f00-20261118T011728Z`, SHA-256 `82314a3b5a6a95762faf6eb4f5b499ce56608ad6a39a27b75e11c75b4945bd3c`. v0.2 took the corrections that part 2 of the methods draft lists (microcosm#1647 comment 7005741386) and described the 23 release checks as `gate_summary.json` records them. v0.3 edits it for its readers: the delivery table gives each item's status in this delivery, the method summary describes PolicyEngine's national file as it is, and the comparison with PolicyEngine's earlier state-and-district file is out. v0.4 gives the number of donor households as 47,277, the distinct households behind the 57,240 donor household records (microcosm#1647 comment 7128462564, item 6). v0.5 says that the agreement lists the 2026 and 2027 files and the household measures in the MVP, where v0.4 called them a stretch goal, and says where the records come from instead of calling them synthetic (microcosm#1647 comment 7137552522). -`lwi-poc-methods.md` is v0.3 (24 November 2026) of the methods documentation, the version sent to LWI. It is part 1 of the methods draft that Max's agents posted on microcosm#1647 (comment 7005740491), edited for LWI: an appendix of build identifiers, settings and input digests replaces the links to GitHub comments, and flags, run-file names and imputation family names are out of the text. v0.2 took the corrections from Max's agents' check of v0.1's account of the donor households (their geography, their tax-detail records and the targets their weights fit) against the 28 July national build's code, run logs and published files (microcosm#1647 comments 7025093817 and 7025096163), and described the donor file as it is, the last published release with five more person columns, where v0.1 called it a patched copy. v0.3 takes the five corrections from their second check of the donor passages (microcosm#1647 comment 7128462564). +`lwi-poc-methods.md` is v0.3 (24 November 2026) of the methods documentation, the final version, in the private dataset for LWI. It is part 1 of the methods draft that Max's agents posted on microcosm#1647 (comment 7005740491), edited for LWI: an appendix of build identifiers, settings and input digests replaces the links to GitHub comments, and flags, run-file names and imputation family names are out of the text. v0.2 took the corrections from Max's agents' check of v0.1's account of the donor households (their geography, their tax-detail records and the targets their weights fit) against the 28 July national build's code, run logs and published files (microcosm#1647 comments 7025093817 and 7025096163), and described the donor file as it is, the last published release with five more person columns, where v0.1 called it a patched copy. v0.3 takes the five corrections from their second check of the donor passages (microcosm#1647 comment 7128462564). `schema_manifest.md` and `schema_manifest.json` are the schema documentation: `tools/us_release_schema_manifest.py`'s output for the file, with a notes section at the top of the Markdown (microcosm#1647 comment 7022836029). - **Format.** The report and the methods documentation are `pe-doc` Markdown (PolicyEngine/document-templates). Each has the front matter, the three-line title block and source notes after the last rule. `pe-doc` has no report kind, so both use `kind: proposal` with `psl_foundation: false`. - **Sources.** The numbers come from the run report on microcosm#1647 (comments 6982547034 and 6982549060) and from the release's own reports: `county_reliability.json` and `.csv`, `calibration_diagnostics.json` and `gate_summary.json`. The loader result comes from a test on 18 November with policyengine-us 2.2.1. -- **Delivery.** The file, this report, the methods documentation and the schema documentation are shared through the private Hugging Face dataset `policyengine/lwi-county-files`. The report refers to the other two documents by name, because a link into a private repository does not open for a reader who has only a download token. -- **Sent.** PolicyEngine sent LWI the file and the three documents through the private Hugging Face dataset, as it stood at commit `b92e7096`: the report (v0.5) and the methods documentation (v0.3) as PDFs, and the schema documentation as Markdown and JSON. +- **Delivery.** The file, this report, the methods documentation and the schema documentation are in the private Hugging Face dataset `policyengine/lwi-county-files`. The report refers to the other two documents by name, because a link into a private repository does not open for a reader who has only a download token. +- **Sent.** On 24 November Max emailed LWI the report (v0.5) as a PDF. The file, the methods documentation (v0.3) and the schema documentation (Markdown and JSON) are in the private Hugging Face dataset at commit `b92e7096`. LWI gets access once it names who should have it. diff --git a/experiments/us-county-poc-20261117/lwi-poc-methods.md b/experiments/us-county-poc-20261117/lwi-poc-methods.md index 5bf5a8c3fc..1e66c60a50 100644 --- a/experiments/us-county-poc-20261117/lwi-poc-methods.md +++ b/experiments/us-county-poc-20261117/lwi-poc-methods.md @@ -2,7 +2,7 @@ kind: proposal client: "Living Wage Institute" title: "County Files proof of concept: methods — a PolicyEngine methods note" -status: "v0.3 (2026-11-24): sent to LWI" +status: "v0.3 (2026-11-24): final, in the private dataset for LWI" pe-doc: psl_foundation: false split_tables: true