From 4c78c72fde4a4ee1674910a120dfdb438b2e40b6 Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Sat, 28 Nov 2026 03:34:31 +0400 Subject: [PATCH 1/3] Test that materialize gives one target matrix at any chunk and batch size materialize_chunked in tools/build_us_acs_local_release.py runs policyengine-us over household chunks (--hh-chunk), each in engine batches (--batch), and assembles a CSR float32 targets-by-households matrix. These tests compare each layout's result with a one-chunk, one-batch run, bit for bit: the compiled target names in order, and the matrix's type, shape and the dtype and bytes of data, indices and indptr, so also the bytes save_target_matrix writes. - test_support/microcosm_build/us_local_materialize_chunks.py: the comparison, through canonical_result_bytes; on a difference it names the targets, household positions and largest absolute difference. - engine_free/us/test_us_acs_local_sparse_cd.py: fake-engine test on fifteen households at eight layouts (one chunk in several batches, a chunk larger than the frame, equal chunks, uneven last chunks, one household per chunk), on the district SOI surface with state parents, fractional amounts, and a target that does not compile. It checks the chunks and engine batches each layout ran, and that chunk 0's direct district-row check picks other rows than the reference's. A control test shows the comparison names a column that reads how many households its engine holds. - engine_workflow/us/test_us_acs_local_materialize_chunks.py: the same comparison with the real policyengine-us on six households, unpatched, over SNAP, Medicaid enrollment and SOI state and district rows. The tests pass on main unchanged: no code change is needed. Co-Authored-By: Claude Opus 5.5 --- .../us/test_us_acs_local_sparse_cd.py | 334 +++++++++++++++++- .../test_us_acs_local_materialize_chunks.py | 303 ++++++++++++++++ .../us_local_materialize_chunks.py | 119 +++++++ 3 files changed, 752 insertions(+), 4 deletions(-) create mode 100644 packages/microcosm-build/tests/engine_workflow/us/test_us_acs_local_materialize_chunks.py create mode 100644 test_support/microcosm_build/us_local_materialize_chunks.py diff --git a/packages/microcosm-build/tests/engine_free/us/test_us_acs_local_sparse_cd.py b/packages/microcosm-build/tests/engine_free/us/test_us_acs_local_sparse_cd.py index a299e07f0a..08e89e7279 100644 --- a/packages/microcosm-build/tests/engine_free/us/test_us_acs_local_sparse_cd.py +++ b/packages/microcosm-build/tests/engine_free/us/test_us_acs_local_sparse_cd.py @@ -24,7 +24,13 @@ from microcosm.calibrate import TargetSpec from microcosm.calibrate.matrix import build_constraint_matrix from microcosm.calibrate.target import TargetSet -from microcosm.frame import US_SCHEMA, Frame, SharedColumnChangedError +from microcosm.frame import ( + US_SCHEMA, + Frame, + SharedColumnChangedError, + WeightKind, + Weights, +) from test_support.paths import paths_for _TEST_PATHS = paths_for("microcosm-build") @@ -177,10 +183,24 @@ def _identity(digests: dict, *, households: int) -> dict: } +def _install_fake_materialization(module, fixtures, release, monkeypatch): + """The fake engine, with the projection and null fill as no-ops. + + Returns the fake engine's ledger of the engines it builds. + """ + + ledger = fixtures._install_fake_engine( + release, monkeypatch, reform_specs=fixtures._REFORMS + ) + monkeypatch.setattr( + module, "project_input_only", lambda frame, **options: (frame, {}) + ) + monkeypatch.setattr(module, "fill_reviewed_nulls", lambda *args, **options: None) + return ledger + + def _materialize(module, fixtures, release, monkeypatch, tmp_path, specs, hh_chunk): - fixtures._install_fake_engine(release, monkeypatch, reform_specs=fixtures._REFORMS) - monkeypatch.setattr(module, "project_input_only", lambda frame, **kw: (frame, {})) - monkeypatch.setattr(module, "fill_reviewed_nulls", lambda *args, **kw: None) + _install_fake_materialization(module, fixtures, release, monkeypatch) return module.materialize_chunked( fixtures._nested_frame(), specs, @@ -546,6 +566,312 @@ def corrupting_later_chunks(self, row, low, carrier, positions, *, name): ) +# --------------------------------------------------------------------------- +# Chunk independence: every chunk and batch size gives the one-chunk matrix +# --------------------------------------------------------------------------- + +#: Copies of the nested fixture's five households in :func:`_copied_frame`. +_COPIES = 3 +#: An id ``k`` of the fixture becomes ``_ID_STRIDE * k + copy``. +_ID_STRIDE = 4 +_COPIED_HOUSEHOLDS = 5 * _COPIES +#: Copy 1 of the fixture's Maryland household 4 moves to New York district +#: 3601, which then has the most households of any district. +_MOVED_HOUSEHOLD_ID = _ID_STRIDE * 4 + 1 +#: Declared rows that hold no value in the reference: no household lives in +#: Texas, and no Maryland tax unit of the fixture files jointly with wages. +_EMPTY_ROWS = {"cd_4801_agi", "cd_2401_joint_wages"} +#: A target whose engine variable the fake engine does not define, so it does +#: not compile and ``materialize_chunked`` drops its row (``sparse_rows``). +_UNCOMPILED_TARGET = "unmodelled_benefit_total" + + +def _copied_frame(fixtures) -> Frame: + """Fifteen households: three copies of the nested fixture, ids interleaved. + + - Every id ``k`` of the fixture becomes ``4k + copy``. The fake engine + computes each value from its record's own id, so the copies' values + differ. + - Group tables stay sorted by id, as ``Frame`` requires, so household rows + cycle through the copies, and a chunk boundary can fall inside a state + or a district. + - The person rows are in a fixed shuffled order, so a household's people + are not adjacent rows. + - One copied Maryland household moves to New York district 3601. 3601 then + has the most households, so chunk 0's direct check of one district row + per carrier picks 3601 rows in a one-chunk run, but 0601 rows in a chunk + 0 that starts with the 0601 households and is not the whole frame. + """ + + base = fixtures._nested_frame() + tables = {} + for entity in base.entities: + copies = [] + for copy_number in range(_COPIES): + table = base.table(entity).copy() + id_columns = [ + column + for column in table.columns + if column == f"{entity}_id" + or (entity == "person" and column.startswith("person_")) + ] + table[id_columns] = _ID_STRIDE * table[id_columns] + copy_number + copies.append(table) + combined = pd.concat(copies, ignore_index=True) + if entity == "person": + order = np.random.default_rng(0).permutation(len(combined)) + combined = combined.iloc[order] + else: + combined = combined.sort_values(f"{entity}_id") + tables[entity] = combined.reset_index(drop=True) + household = tables["household"] + moved = household["household_id"] == _MOVED_HOUSEHOLD_ID + assert int(moved.sum()) == 1 + household.loc[moved, "state_fips"] = 36 + household.loc[moved, "congressional_district_geoid"] = "3601" + weights = household["household_id"].to_numpy(dtype=np.float64) + assert len(weights) == _COPIED_HOUSEHOLDS + return Frame(tables, US_SCHEMA, {"household": Weights(weights, WeightKind.DESIGN)}) + + +#: Fake-engine variables whose values stay whole: statuses, flags, counts, ages. +_WHOLE_VALUED_VARIABLES = frozenset( + {"filing_status", "tax_unit_itemizes", "eitc_child_count", "age"} +) + + +def _with_fractional_fake_values(monkeypatch) -> None: + """Divide the fake engine's amounts by 7, so most are not whole numbers. + + The fake engine's own values are whole, and float32 holds those exactly; + sevenths make the float64-to-float32 conversion round. Call it once per + test: a second call would divide by 7 again. + """ + + from test_support.microcosm_build import ( + us_batched_target_materialization as fake_engine, + ) + + whole_value = fake_engine._record_value + + def fractional_value(variable: str, record_id: int): + value = whole_value(variable, record_id) + if variable in _WHOLE_VALUED_VARIABLES: + return value + return value / 7.0 + + monkeypatch.setattr(fake_engine, "_record_value", fractional_value) + + +def _materialize_layout( + module, + fixtures, + release, + monkeypatch, + tmp_path, + *, + hh_chunk, + batch, +): + """``materialize_chunked`` on :func:`_copied_frame`, with its engine ledger.""" + + ledger = _install_fake_materialization(module, fixtures, release, monkeypatch) + specs = ( + *_parented_surface_specs(fixtures), + fixtures._variable(_UNCOMPILED_TARGET, base_variable="unmodelled_benefit"), + ) + materialized = module.materialize_chunked( + _copied_frame(fixtures), + specs, + hh_chunk=hh_chunk, + batch=batch, + summary_path=tmp_path / "summary.json", + ) + return materialized, ledger + + +def _engine_batches(chunk_sizes, batch) -> list[int]: + """The households of each engine the fake engine builds, in order. + + Each chunk runs the base pass, then the one JCT reform family, each in + batches of at most ``batch`` households. + """ + + sizes = [] + for chunk in chunk_sizes: + batches = [batch] * (chunk // batch) + ( + [chunk % batch] if chunk % batch else [] + ) + sizes += batches * 2 + return sizes + + +def _directly_checked_districts(materialized) -> set[str]: + """Districts of the rows chunk 0 materialized directly, one per carrier.""" + + return { + entry["target"].split("_")[1] for entry in materialized.carrier_check["checked"] + } + + +#: (hh_chunk, batch, chunk sizes) over the fifteen households. +_CHUNK_LAYOUTS = { + "one-chunk-several-batches": (15, 4, (15,)), + "chunk-larger-than-the-frame": (24, 6, (15,)), + "three-equal-chunks": (5, 5, (5, 5, 5)), + "five-equal-chunks-one-household-batches": (3, 1, (3,) * 5), + "uneven-last-chunk": (4, 3, (4, 4, 4, 3)), + "last-chunk-of-one-household": (7, 2, (7, 7, 1)), + "uneven-batches-in-uneven-chunks": (6, 4, (6, 6, 3)), + "one-household-per-chunk": (1, 1, (1,) * 15), +} + + +@pytest.mark.parametrize( + ("hh_chunk", "batch", "chunk_sizes"), + list(_CHUNK_LAYOUTS.values()), + ids=list(_CHUNK_LAYOUTS), +) +def test_every_chunk_and_batch_size_gives_the_one_chunk_target_matrix( + monkeypatch, tmp_path, hh_chunk, batch, chunk_sizes +) -> None: + """The matrix ``materialize_chunked`` returns does not depend on + ``--hh-chunk`` or ``--batch``. + + The reference is one chunk in one engine batch. Each layout must give the + same compiled target names in order and the same CSR matrix bit for bit: + type, shape, and the dtype and bytes of ``data``, ``indices`` and + ``indptr``, so also the same bytes from ``save_target_matrix``. + + The surface holds district SOI rows split from geography-free carriers + under state parents, one district row with no state (the split that does + not mask by state), and a target that does not compile. Chunk 0 also + materializes one district row per carrier directly, and in a layout of + several chunks it picks other rows than the reference does. + + This shows that the assembly does not depend on the chunk or batch size. + The fake engine computes each value from its own record, so it cannot + show whether policyengine-us formulas read other households; + ``engine_workflow/us/test_us_acs_local_materialize_chunks.py`` runs the + real engine on a small frame. + """ + + from test_support.microcosm_build.us_local_materialize_chunks import ( + assert_same_surface, + ) + + module = _load_tool_module() + import build_us_fiscal_refresh_release as release + + fixtures = _load_fixtures() + _with_fractional_fake_values(monkeypatch) + reference, reference_ledger = _materialize_layout( + module, + fixtures, + release, + monkeypatch, + tmp_path, + hh_chunk=_COPIED_HOUSEHOLDS, + batch=_COPIED_HOUSEHOLDS, + ) + materialized, ledger = _materialize_layout( + module, fixtures, release, monkeypatch, tmp_path, hh_chunk=hh_chunk, batch=batch + ) + + # The reference ran one chunk, each engine over every household. + assert [stat["households"] for stat in reference.chunk_stats] == [15] + assert [len(run["households"]) for run in reference_ledger.constructions] == [ + 15, + 15, + ] + # The layout ran its chunks, and each engine over one batch of a chunk. + assert [stat["households"] for stat in materialized.chunk_stats] == list( + chunk_sizes + ) + assert [len(run["households"]) for run in ledger.constructions] == ( + _engine_batches(chunk_sizes, batch) + ) + # Chunk 0's direct check covered other rows than the reference's when the + # layout has several chunks (0601 against 3601). + assert "3601" in _directly_checked_districts(reference) + if len(chunk_sizes) > 1: + assert _directly_checked_districts(materialized) == {"0601"} + assert materialized.carrier_check["all_equal"] is True + assert materialized.carrier_check["parent_blocks_checked"] == 3 * len(chunk_sizes) + + # No part of the comparison is empty: every household holds a value, every + # declared row but the two of _EMPTY_ROWS holds one, the uncompiled target + # is dropped, and float32 rounding changed some values. + assert np.all(np.diff(reference.matrix.tocsc().indptr) > 0) + assert _UNCOMPILED_TARGET not in reference.names + empty = { + name + for row, name in enumerate(reference.names) + if reference.matrix[[row]].nnz == 0 + } + assert empty == _EMPTY_ROWS + assert np.any(reference.matrix.data % 1 != 0) + + assert_same_surface( + reference, materialized, label=f"hh_chunk={hh_chunk}, batch={batch}" + ) + save = module.cd_surface.save_target_matrix + assert save(tmp_path / "layout.npz", materialized.matrix) == save( + tmp_path / "reference.npz", reference.matrix + ) + + +def test_the_chunk_comparison_reports_a_value_read_from_other_households( + monkeypatch, tmp_path +) -> None: + """A control: a column that adds how many households its engine holds + differs between chunk sizes, and the comparison names the column, how + many households differ, by how much, and the first of them.""" + + from test_support.microcosm_build.us_local_materialize_chunks import ( + assert_same_surface, + ) + + module = _load_tool_module() + import build_us_fiscal_refresh_release as release + + fixtures = _load_fixtures() + own_columns = release._base_simulation_household_columns + + def columns_reading_the_whole_batch(frame, target_specs, *, simulation, system): + columns = own_columns(frame, target_specs, simulation=simulation, system=system) + columns["tanf"] = columns["tanf"] + frame.n("household") + return columns + + monkeypatch.setattr( + release, "_base_simulation_household_columns", columns_reading_the_whole_batch + ) + + def run(hh_chunk): + materialized, _ = _materialize_layout( + module, + fixtures, + release, + monkeypatch, + tmp_path, + hh_chunk=hh_chunk, + batch=hh_chunk, + ) + return materialized + + reference, chunked = run(_COPIED_HOUSEHOLDS), run(5) + + with pytest.raises( + AssertionError, + match=( + r"three chunks: the target matrix differs from the reference run\.\n" + r"1 target\(s\) hold different values:\n tanf: 15 household\(s\), " + r"largest absolute difference 10\.0 \(household 0: " + ), + ): + assert_same_surface(reference, chunked, label="three chunks") + + def test_a_state_cd_row_without_a_compiled_parent_is_refused() -> None: """Otherwise its per-chunk check would silently check nothing.""" diff --git a/packages/microcosm-build/tests/engine_workflow/us/test_us_acs_local_materialize_chunks.py b/packages/microcosm-build/tests/engine_workflow/us/test_us_acs_local_materialize_chunks.py new file mode 100644 index 0000000000..99f9cdcdbd --- /dev/null +++ b/packages/microcosm-build/tests/engine_workflow/us/test_us_acs_local_materialize_chunks.py @@ -0,0 +1,303 @@ +"""The ACS local release's materialize step gives one target matrix at any chunk size. + +``materialize_chunked`` (``tools/build_us_acs_local_release.py``) runs +policyengine-us over contiguous household chunks (``--hh-chunk``), each in +engine batches (``--batch``), and assembles the targets-by-households CSR +float32 matrix of the targets it compiles. This test runs it with the real +engine on six households, unpatched: the input projection, the reviewed-null +fill, the population-aggregate refusal that several chunks turn on, and chunk +0's direct check of one district row per carrier. Every layout must give the +one-chunk, one-batch run's compiled target names and matrix bit for bit. So, +on these six households and layouts, no formula these targets reach changed a +stored value by reading another household; the scan of the installed engine's +sources in ``test_us_batched_target_materialization.py`` is the check over the +whole engine. + +The targets are the local build's default families: SNAP amounts and +household counts, Medicaid enrollment, and IRS SOI state rows with district +rows split from geography-free carriers under state parents. +``engine_free/us/test_us_acs_local_sparse_cd.py`` checks the same comparison +over more layouts with a fake engine. +""" + +from __future__ import annotations + +import json + +import numpy as np +import pandas as pd + +from microcosm.frame import US_SCHEMA, Frame, WeightKind, Weights +from test_support.microcosm_build.us_acs_local_reviewed_nulls import load_tool_module +from test_support.microcosm_build.us_batched_target_materialization import ( + _soi, + _spec, +) +from test_support.microcosm_build.us_local_materialize_chunks import ( + assert_same_surface, +) + +#: (household_id, state_fips, congressional_district_geoid). District 602 +#: has two households, every other district one. +_HOUSEHOLDS = ( + (1, 6, 601), + (2, 6, 602), + (3, 36, 3601), + (4, 6, 602), + (5, 24, 2401), + (6, 36, 3602), +) +#: (household_id, tax_unit_id, marital_unit_id, age, +#: employment_income_before_lsr, taxable_interest_income). Married couples +#: share a marital unit; NaN is a registered null the fill sets to 0. +_PERSONS = ( + (1, 10, 101, 34.0, 18_000.0, 0.0), + (1, 10, 102, 6.0, 0.0, 0.0), + (1, 10, 103, 3.0, 0.0, 0.0), + (2, 20, 201, 45.0, 210_000.0, 4_000.0), + (2, 20, 201, 43.0, 95_000.0, np.nan), + (3, 30, 301, 71.0, 0.0, 12_000.0), + (3, 31, 302, 24.0, 9_000.0, 0.0), + (4, 40, 401, 29.0, 0.0, 0.0), + (4, 40, 402, 1.0, 0.0, 0.0), + (5, 50, 501, 52.0, 64_000.0, 300.0), + (5, 50, 501, 50.0, 31_000.0, 0.0), + (5, 50, 502, 15.0, 2_000.0, 0.0), + (6, 60, 601, 27.0, 26_000.0, 0.0), + (6, 60, 601, 26.0, 12_000.0, 0.0), + (6, 60, 602, 2.0, 0.0, 0.0), +) +_DISTRICTS = ( + ("06", "601"), + ("06", "602"), + ("36", "3601"), + ("36", "3602"), + ("24", "2401"), +) + +#: (hh_chunk, batch, chunk sizes, households of each engine batch, the +#: district of the rows chunk 0 materializes directly). Chunk 0 checks the +#: district with the most households in it, the first declared on a tie. +_REFERENCE_LAYOUT = (6, 6, (6,), (6,), "602") +_LAYOUTS = ( + # Two equal chunks, each in batches of 2 and 1. + (3, 2, (3, 3), (2, 1, 2, 1), "601"), + # An uneven last chunk. + (4, 4, (4, 2), (4, 2), "602"), + # One household per chunk. + (1, 1, (1,) * 6, (1,) * 6, "601"), +) + + +def _frame() -> Frame: + """Six households in three states and five districts; every group nests + in its household, and one household holds two tax units.""" + + persons = pd.DataFrame( + { + "person_id": np.arange(1, len(_PERSONS) + 1, dtype="int64"), + "person_household_id": np.asarray([row[0] for row in _PERSONS], "int64"), + "person_tax_unit_id": np.asarray([row[1] for row in _PERSONS], "int64"), + "person_spm_unit_id": np.asarray( + [row[0] * 100 for row in _PERSONS], "int64" + ), + "person_family_id": np.asarray( + [row[0] * 1000 for row in _PERSONS], "int64" + ), + "person_marital_unit_id": np.asarray([row[2] for row in _PERSONS], "int64"), + "age": np.asarray([row[3] for row in _PERSONS]), + "employment_income_before_lsr": np.asarray([row[4] for row in _PERSONS]), + "taxable_interest_income": np.asarray([row[5] for row in _PERSONS]), + } + ) + 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}) + tables["household"] = pd.DataFrame( + { + "household_id": np.asarray([row[0] for row in _HOUSEHOLDS], "int64"), + "state_fips": np.asarray([row[1] for row in _HOUSEHOLDS], "int64"), + "congressional_district_geoid": np.asarray( + [row[2] for row in _HOUSEHOLDS], "int64" + ), + } + ) + return Frame( + tables, + US_SCHEMA, + {"household": Weights(np.arange(1.0, len(_HOUSEHOLDS) + 1), WeightKind.DESIGN)}, + ) + + +def _admin_variable(name, family, base_variable, **metadata): + return _spec( + name, + family, + { + "materializer": "policyengine_variable", + "base_variable": base_variable, + **metadata, + }, + ) + + +def _specs() -> tuple: + specs = [ + _admin_variable( + "snap_ca", "usda_snap", "snap", measure_mode="sum", state_fips="06" + ), + _admin_variable( + "snap_households_ny", + "usda_snap", + "snap", + measure_mode="indicator_sum", + indicator_map_to="household", + state_fips="36", + ), + _admin_variable( + "medicaid_enrollment_ca", + "cms_medicaid", + "medicaid_enrolled", + measure_mode="indicator_sum", + state_fips="06", + target_role="medicaid_enrollment", + ), + ] + for state in ("06", "36", "24"): + specs += [ + _soi(f"state_{state}_agi", "adjusted_gross_income", state_fips=state), + _soi(f"state_{state}_returns", "count", state_fips=state), + ] + for state, district in _DISTRICTS: + located = {"state_fips": state, "congressional_district_geoid": district} + specs += [ + _soi( + f"cd_{district}_agi", + "adjusted_gross_income", + state_cd_parent_target_name=f"state_{state}_agi", + state_cd_vintage_rule="fixture", + **located, + ), + _soi( + f"cd_{district}_returns", + "count", + state_cd_parent_target_name=f"state_{state}_returns", + state_cd_vintage_rule="fixture", + **located, + ), + _soi( + f"cd_{district}_agi_under_50k_returns", + "count", + agi_lower_bound="1", + agi_upper_bound="50000", + **located, + ), + _soi(f"cd_{district}_eitc", "eitc", **located), + _soi( + f"cd_{district}_joint_wages", + "employment_income", + filing_status="Married Filing Jointly/Surviving Spouse", + **located, + ), + ] + return tuple(specs) + + +def _summary(tmp_path): + path = tmp_path / "staging.summary.json" + path.write_text( + json.dumps( + { + "reviewed_engine_input_nulls": [ + { + "entity": "person", + "column": "taxable_interest_income", + "missing_rows": 1, + "rows": len(_PERSONS), + } + ] + } + ) + ) + return path + + +def _directly_checked_districts(materialized) -> set[str]: + """Districts of the rows chunk 0 materialized directly, one per carrier.""" + + return { + entry["target"].split("_")[1] for entry in materialized.carrier_check["checked"] + } + + +def test_every_chunk_and_batch_size_gives_the_one_chunk_target_matrix( + monkeypatch, tmp_path +) -> None: + module = load_tool_module() + import build_us_fiscal_refresh_release as release + + summary = _summary(tmp_path) + # Each engine batch builds one dataset; record its households, nothing else. + batch_households: list[int] = [] + own_dataset_from_frame = release._dataset_from_frame + + def recording_dataset_from_frame(frame, **options): + batch_households.append(frame.n("household")) + return own_dataset_from_frame(frame, **options) + + monkeypatch.setattr(release, "_dataset_from_frame", recording_dataset_from_frame) + + def materialize(hh_chunk, batch, chunk_sizes, batches, checked_district, label): + batch_households.clear() + materialized = module.materialize_chunked( + _frame(), _specs(), hh_chunk=hh_chunk, batch=batch, summary_path=summary + ) + assert [stat["households"] for stat in materialized.chunk_stats] == list( + chunk_sizes + ), label + assert batch_households == list(batches), label + assert _directly_checked_districts(materialized) == {checked_district}, label + assert materialized.carrier_check["all_equal"] is True, label + # Three state AGI and three state return-count parents, every chunk. + assert materialized.carrier_check["parent_blocks_checked"] == 6 * len( + chunk_sizes + ), label + return materialized + + reference = materialize(*_REFERENCE_LAYOUT, label="reference") + # Every declared target compiled, in declared order. + assert [spec.name for spec in reference.compiled_specs] == [ + spec.name for spec in _specs() + ] + # The fixture reaches real engine output in each family. + dense = dict(zip(reference.names, reference.matrix.toarray(), strict=True)) + for name in ( + "snap_ca", + "snap_households_ny", + "medicaid_enrollment_ca", + "state_06_agi", + "state_36_returns", + "cd_601_eitc", + "cd_602_joint_wages", + "cd_3601_agi_under_50k_returns", + "cd_3602_eitc", + ): + assert dense[name].any(), name + for _state, district in _DISTRICTS: + assert dense[f"cd_{district}_agi"].any(), district + # Some stored values are not whole numbers (the EITC of household 6, in + # the credit's phase-out range), so float32 rounding is compared too. + assert np.any(reference.matrix.data % 1 != 0) + assert reference.carrier_check["rows_without_parent_check"] == 3 * len(_DISTRICTS) + + save = module.cd_surface.save_target_matrix + reference_sha256 = save(tmp_path / "reference.npz", reference.matrix) + for layout in _LAYOUTS: + hh_chunk, batch = layout[:2] + label = f"hh_chunk={hh_chunk}, batch={batch}" + materialized = materialize(*layout, label=label) + assert_same_surface(reference, materialized, label=label) + assert save(tmp_path / f"{hh_chunk}-{batch}.npz", materialized.matrix) == ( + reference_sha256 + ), label diff --git a/test_support/microcosm_build/us_local_materialize_chunks.py b/test_support/microcosm_build/us_local_materialize_chunks.py new file mode 100644 index 0000000000..f996d8c107 --- /dev/null +++ b/test_support/microcosm_build/us_local_materialize_chunks.py @@ -0,0 +1,119 @@ +"""Compare the ACS local release's target matrices across household chunk sizes. + +``materialize_chunked`` (``tools/build_us_acs_local_release.py``) returns a +CSR float32 matrix of targets by households, built one household chunk at a +time. Two runs give the same matrix when these are bit-for-bit equal, compared +through :func:`canonical_result_bytes`: + +* the compiled target specs' names, in order; +* the matrix's type, shape and the dtype and raw bytes of its ``data``, + ``indices`` and ``indptr`` arrays. + +Those arrays and the shape are what ``save_target_matrix`` writes for these +rows. ``do_materialize`` writes ``target_matrix.npz`` from them after adding +the county and population rows, which this comparison does not cover. On a +difference, :func:`assert_same_surface` names the targets and household +positions that differ and by how much. +""" + +from __future__ import annotations + +import numpy as np + +from test_support.microcosm_build.worker_pool_identity import canonical_result_bytes + +__all__ = ["assert_same_surface", "surface_bytes"] + +#: How many differing targets, and households per target, a report lists. +_REPORTED_TARGETS = 10 +_REPORTED_HOUSEHOLDS = 5 + + +def _target_names(materialized) -> list[str]: + """The compiled target specs' names, in matrix row order. + + ``MaterializedSurface.names`` gives their measures, which can differ. + """ + + return [spec.name for spec in materialized.compiled_specs] + + +def surface_bytes(materialized) -> bytes: + """The canonical bytes of a ``MaterializedSurface``'s target names and matrix.""" + + matrix = materialized.matrix + return canonical_result_bytes( + { + "names": _target_names(materialized), + "matrix_type": type(matrix), + "shape": tuple(int(size) for size in matrix.shape), + "data": matrix.data, + "indices": matrix.indices, + "indptr": matrix.indptr, + } + ) + + +def _value_differences(reference, materialized) -> list[str]: + """Report lines for the targets whose values differ; empty if none.""" + + expected = reference.matrix.toarray() + actual = materialized.matrix.toarray() + # Bitwise, so -0.0 against 0.0 and NaN payloads count as differences. + bits = np.dtype(f"u{expected.dtype.itemsize}") + differs = expected.view(bits) != actual.view(bits) + rows = np.flatnonzero(differs.any(axis=1)) + if not len(rows): + return [] + lines = [f"{len(rows)} target(s) hold different values:"] + for row in rows[:_REPORTED_TARGETS]: + households = np.flatnonzero(differs[row]) + shown = ", ".join( + f"household {int(position)}: {float(expected[row, position])!r} -> " + f"{float(actual[row, position])!r}" + for position in households[:_REPORTED_HOUSEHOLDS] + ) + largest = float( + np.max( + np.abs( + expected[row, households].astype(np.float64) + - actual[row, households].astype(np.float64) + ) + ) + ) + lines.append( + f" {_target_names(reference)[row]}: {len(households)} household(s), " + f"largest absolute difference {largest!r} ({shown})" + ) + return lines + + +def assert_same_surface(reference, materialized, *, label: str) -> None: + """Refuse ``materialized`` unless it is bit-for-bit ``reference``.""" + + if surface_bytes(materialized) == surface_bytes(reference): + return + lines = [f"{label}: the target matrix differs from the reference run."] + if _target_names(materialized) != _target_names(reference): + lines.append( + f"Compiled target names differ: {_target_names(reference)} -> " + f"{_target_names(materialized)}." + ) + else: + expected, actual = reference.matrix, materialized.matrix + layout = { + "type": (type(expected), type(actual)), + "shape": (expected.shape, actual.shape), + "data dtype": (expected.data.dtype, actual.data.dtype), + "indices dtype": (expected.indices.dtype, actual.indices.dtype), + "indptr dtype": (expected.indptr.dtype, actual.indptr.dtype), + } + changed = {key: pair for key, pair in layout.items() if pair[0] != pair[1]} + if changed: + lines.append(f"Matrix layout differs: {changed}.") + else: + lines += _value_differences(reference, materialized) or [ + "Every value is equal, but the stored entries differ " + "(an explicit zero, or indices in another order)." + ] + raise AssertionError("\n".join(lines)) From 68debd4df99b330fdfdf1a6b7ab880166a4b7bf2 Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Sat, 28 Nov 2026 03:35:30 +0400 Subject: [PATCH 2/3] Point the Modal runbook at the materialize chunk-independence tests The runbook said nobody had checked that materialize_chunked's household chunks are independent. Name the two tests that compare its target matrix across chunk and batch sizes. Co-Authored-By: Claude Opus 5.5 --- docs/us-modal-stage-runbook.md | 11 ++++++++--- 1 file changed, 8 insertions(+), 3 deletions(-) diff --git a/docs/us-modal-stage-runbook.md b/docs/us-modal-stage-runbook.md index 8a2b313145..dee9832008 100644 --- a/docs/us-modal-stage-runbook.md +++ b/docs/us-modal-stage-runbook.md @@ -923,9 +923,14 @@ against 1.6 hours locally. At the preemption rate this run saw, a 5- to 7-hour preemptible run finishes uninterrupted 1 to 3% of the time, so non-preemptible is the practical placement for it. The Modal path works, but it does not yet make this stage cheaper or faster. The run did show that the stage runs as one long single-core -loop over 80 chunks of households. If the chunks are independent, which -this runbook has not checked in `materialize_chunked`, fanning them out -across containers would let preemption lose one chunk instead of the run. +loop over 80 chunks of households. Two tests compare the target matrix +`materialize_chunked` returns at several `--hh-chunk` and `--batch` values +with one chunk in one batch, bit for bit: a fake-engine test in +`packages/microcosm-build/tests/engine_free/us/test_us_acs_local_sparse_cd.py` +and a real-engine test on six households in +`packages/microcosm-build/tests/engine_workflow/us/test_us_acs_local_materialize_chunks.py`. +The chunks are independent in those tests, so fanning them out across +containers would let preemption lose one chunk instead of the run. ## Route A's base stage From 5439aa20fbb21dad45b940d86db1b33165ac2242 Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Sat, 28 Nov 2026 03:44:33 +0400 Subject: [PATCH 3/3] Fix review round 2: check each engine's pass and households, correct wording - The fake-engine test compares each engine the fake engine builds by its pass (base or JCT reform) and household ids, not only its size, and reads compiled spec names rather than measures. - _copied_frame's docstring states the chunk 0 sizes that check 0601 rows, and the cd_0601_wages carrier that has only a 0601 row. - The real-engine test's docstring names the dataset-builder wrapper it adds, and no longer calls the population-aggregate source scan a check over the whole engine. Co-Authored-By: Claude Opus 5.5 --- .../us/test_us_acs_local_sparse_cd.py | 61 ++++++++++++------- .../test_us_acs_local_materialize_chunks.py | 24 +++++--- 2 files changed, 53 insertions(+), 32 deletions(-) diff --git a/packages/microcosm-build/tests/engine_free/us/test_us_acs_local_sparse_cd.py b/packages/microcosm-build/tests/engine_free/us/test_us_acs_local_sparse_cd.py index 08e89e7279..240dd6f81e 100644 --- a/packages/microcosm-build/tests/engine_free/us/test_us_acs_local_sparse_cd.py +++ b/packages/microcosm-build/tests/engine_free/us/test_us_acs_local_sparse_cd.py @@ -599,8 +599,9 @@ def _copied_frame(fixtures) -> Frame: are not adjacent rows. - One copied Maryland household moves to New York district 3601. 3601 then has the most households, so chunk 0's direct check of one district row - per carrier picks 3601 rows in a one-chunk run, but 0601 rows in a chunk - 0 that starts with the 0601 households and is not the whole frame. + per carrier picks 3601 rows in a one-chunk run (except for the + ``cd_0601_wages`` carrier, which has only a 0601 row), but 0601 rows + for every carrier in a chunk 0 of at most ten households. """ base = fixtures._nested_frame() @@ -690,20 +691,36 @@ def _materialize_layout( return materialized, ledger -def _engine_batches(chunk_sizes, batch) -> list[int]: - """The households of each engine the fake engine builds, in order. +def _engine_runs(household_ids, chunk_sizes, batch) -> list[tuple]: + """Each engine the fake engine should build, in order: its pass and its + household ids. - Each chunk runs the base pass, then the one JCT reform family, each in - batches of at most ``batch`` households. + Each chunk runs the base pass, then the one JCT reform family, each over + consecutive batches of at most ``batch`` of the chunk's households. """ - sizes = [] + runs = [] + low = 0 for chunk in chunk_sizes: - batches = [batch] * (chunk // batch) + ( - [chunk % batch] if chunk % batch else [] - ) - sizes += batches * 2 - return sizes + chunk_ids = tuple(int(value) for value in household_ids[low : low + chunk]) + batches = [chunk_ids[start : start + batch] for start in range(0, chunk, batch)] + runs += [("base", ids) for ids in batches] + runs += [("reform", ids) for ids in batches] + low += chunk + return runs + + +def _ledger_runs(ledger) -> list[tuple]: + """The engines the fake engine built: their pass and household ids.""" + + return [ + ("base" if run["reform"] is None else "reform", run["households"]) + for run in ledger.constructions + ] + + +def _compiled_names(materialized) -> list[str]: + return [spec.name for spec in materialized.compiled_specs] def _directly_checked_districts(materialized) -> set[str]: @@ -778,19 +795,17 @@ def test_every_chunk_and_batch_size_gives_the_one_chunk_target_matrix( module, fixtures, release, monkeypatch, tmp_path, hh_chunk=hh_chunk, batch=batch ) - # The reference ran one chunk, each engine over every household. + # The reference ran one chunk, each engine over every household; the + # layout ran its chunks, each engine over one batch of a chunk. + household_ids = _copied_frame(fixtures).table("household")["household_id"] assert [stat["households"] for stat in reference.chunk_stats] == [15] - assert [len(run["households"]) for run in reference_ledger.constructions] == [ - 15, - 15, - ] - # The layout ran its chunks, and each engine over one batch of a chunk. + assert _ledger_runs(reference_ledger) == _engine_runs( + household_ids, (15,), _COPIED_HOUSEHOLDS + ) assert [stat["households"] for stat in materialized.chunk_stats] == list( chunk_sizes ) - assert [len(run["households"]) for run in ledger.constructions] == ( - _engine_batches(chunk_sizes, batch) - ) + assert _ledger_runs(ledger) == _engine_runs(household_ids, chunk_sizes, batch) # Chunk 0's direct check covered other rows than the reference's when the # layout has several chunks (0601 against 3601). assert "3601" in _directly_checked_districts(reference) @@ -803,10 +818,10 @@ def test_every_chunk_and_batch_size_gives_the_one_chunk_target_matrix( # declared row but the two of _EMPTY_ROWS holds one, the uncompiled target # is dropped, and float32 rounding changed some values. assert np.all(np.diff(reference.matrix.tocsc().indptr) > 0) - assert _UNCOMPILED_TARGET not in reference.names + assert _UNCOMPILED_TARGET not in _compiled_names(reference) empty = { name - for row, name in enumerate(reference.names) + for row, name in enumerate(_compiled_names(reference)) if reference.matrix[[row]].nnz == 0 } assert empty == _EMPTY_ROWS diff --git a/packages/microcosm-build/tests/engine_workflow/us/test_us_acs_local_materialize_chunks.py b/packages/microcosm-build/tests/engine_workflow/us/test_us_acs_local_materialize_chunks.py index 99f9cdcdbd..be27384eb4 100644 --- a/packages/microcosm-build/tests/engine_workflow/us/test_us_acs_local_materialize_chunks.py +++ b/packages/microcosm-build/tests/engine_workflow/us/test_us_acs_local_materialize_chunks.py @@ -1,17 +1,23 @@ -"""The ACS local release's materialize step gives one target matrix at any chunk size. +"""The ACS local release's materialize step gives one target matrix at several chunk sizes. ``materialize_chunked`` (``tools/build_us_acs_local_release.py``) runs policyengine-us over contiguous household chunks (``--hh-chunk``), each in engine batches (``--batch``), and assembles the targets-by-households CSR float32 matrix of the targets it compiles. This test runs it with the real -engine on six households, unpatched: the input projection, the reviewed-null -fill, the population-aggregate refusal that several chunks turn on, and chunk -0's direct check of one district row per carrier. Every layout must give the -one-chunk, one-batch run's compiled target names and matrix bit for bit. So, -on these six households and layouts, no formula these targets reach changed a -stored value by reading another household; the scan of the installed engine's -sources in ``test_us_batched_target_materialization.py`` is the check over the -whole engine. +engine on six households. Nothing in it is replaced: the input projection, the +reviewed-null fill, the population-aggregate refusal that several chunks turn +on, and chunk 0's direct check of one district row per carrier all run. The +test only wraps the release tool's ``_dataset_from_frame`` to record how many +households each engine batch holds. + +Every layout must give the one-chunk, one-batch run's compiled target names +and matrix bit for bit. So, on these six households and layouts, no formula +these targets reach changed a stored value by reading another household. That +is not a proof for other households: the run-time refusal covers the listed +population-aggregate variables, the source scan in +``test_us_batched_target_materialization.py`` keeps that list in step with +the engine's sources, and neither proves that every formula stays within a +household. The targets are the local build's default families: SNAP amounts and household counts, Medicaid enrollment, and IRS SOI state rows with district