Skip to content

Test that materialize gives one target matrix at any chunk and batch size - #1805

Draft
anth-volk wants to merge 3 commits into
mainfrom
claude/us-local-materialize-chunk-independence
Draft

anth-volk wants to merge 3 commits into
mainfrom
claude/us-local-materialize-chunk-independence

Conversation

@anth-volk

Copy link
Copy Markdown
Contributor

Tracker task 1.7 · 1 (project 15, US build memory, CPU and run time).

What this adds

Tests that materialize_chunked (tools/build_us_acs_local_release.py) gives the same target matrix whatever --hh-chunk and --batch are. Each layout's result is compared with a one-chunk, one-batch run, bit for bit:

  • the compiled target specs' names, in order;
  • the CSR matrix's type and shape, and the dtype and raw bytes of data, indices and indptr;
  • the bytes save_target_matrix writes for that matrix (compared by sha256).

There is no numeric tolerance. On a difference, the helper names each differing target, how many households differ, the largest absolute difference and the first household positions.

The matrix compared is the one materialize_chunked returns. do_materialize then adds the county and population rows (attach_surface, population_targets) before writing target_matrix.npz; those steps are not chunked and are not covered here.

Files:

  • docs/us-modal-stage-runbook.md: the sentence saying nobody had checked chunk independence now names these tests.

  • test_support/microcosm_build/us_local_materialize_chunks.py: the comparison helper, assert_same_surface. It encodes the matrix through canonical_result_bytes from the worker-pool identity helper (Shared worker pool for household-batched policyengine-us work (1.4 · 1) #1726).

  • packages/microcosm-build/tests/engine_free/us/test_us_acs_local_sparse_cd.py: a fake-engine test on fifteen households, at eight layouts. The households are three copies of the nested fixture, with interleaved ids, person rows in shuffled order, and one copied household moved to district 3601. The layouts:

    • one chunk in several batches;
    • a chunk larger than the frame;
    • three and five equal chunks;
    • an uneven last chunk;
    • a last chunk of one household;
    • uneven batches in uneven chunks;
    • one household per chunk.

    Fake-engine amounts are divided by 7, so float32 rounding is exercised. The surface is the district SOI surface with state parents: district rows split from geography-free carriers, plus one district row with no state, and one target that does not compile (so sparse_rows runs). The test also checks that:

    • each layout ran exactly its chunks and engines (each engine's pass and household ids);
    • every declared row but two (named in the test, with the reason) holds values;
    • chunk 0's direct check of one district row per carrier picks 3601 rows in the reference (0601 for the one carrier that has only a 0601 row) and 0601 rows in every layout of several chunks.

    A control test shows that a column which adds how many households its engine holds makes the comparison fail and name that column.

  • packages/microcosm-build/tests/engine_workflow/us/test_us_acs_local_materialize_chunks.py: the same comparison with the real policyengine-us on six households in three states and five districts. Nothing is patched: input projection, the reviewed-null fill (with one registered null), the population-aggregate refusal that several chunks turn on, and chunk 0's direct district-row check all run. The only addition is a wrapper that records each engine batch's household count.

    • Targets are the local build's default families: SNAP amount and household count, Medicaid enrollment, SOI state AGI and return counts, and district rows split from carriers (AGI, returns, an AGI band count, EITC, joint-filer wages).
    • Layouts: one chunk; two equal chunks in batches of 2 and 1; an uneven last chunk; one household per chunk.
    • The test checks each layout's chunks, engine batches and the district chunk 0 checks directly (602 in the reference, 601 or 602 in the others), and that some stored values are fractional.

The tests pass on main unchanged

No production code changes. The tests passed on origin/main (8784a1f) as written, so there is no failing-test commit; the tests are the deliverable. Two rounds of adversarial review followed; their fixes changed only the tests and the wording. To check that the comparison can fail, I made a temporary edit that scales chunk values after chunk 0 by 1 + 1e-6. The fake-engine test then failed and listed the targets and households. The edit was reverted and not committed.

What differs between one chunk and several, and why it does not change the matrix

  • Compiled target set. compiled_names comes from chunk 0, and a later chunk with a different set is refused. Whether a spec compiles depends only on its metadata, the engine's variable list and the frame's columns (_target_spec_is_materialized, _base_simulation_household_columns), and every chunk has the same columns, so every chunk compiles the same set.
  • Chunk 0's extra specs. carrier_check_specs adds one district row per carrier to chunk 0's engine pass. It picks the district with the most households in chunk 0, so the rows differ with the chunk size. The extra specs add columns to chunk 0's target frame. Every stored row is read by its own measure name, and the SOI slice builds each column from tax-unit arrays computed once per engine, so the extra columns change no other column. With them, chunk 0 also parses the district codes, which other chunks may skip; that changes no value. Both tests cover a reference and layouts that check different rows directly.
  • parents. district_row_parents reads only the plan and the compiled names, so computing it once is the same as computing it per chunk.
  • Refusals that several chunks turn on. With more than one chunk, refuse_population_aggregates=True, assert_group_entities_nest_in_households and assert_medicaid_claiming_tax_units_local run. They only refuse; they never change a value.
    • So a target that reaches a watched population aggregate materializes in one chunk of one batch but is refused in several. That is a refusal, not a different matrix.
    • The real-engine test's several-chunk layouts pass, so its targets reach none of the watched aggregates.
  • Random draws. No formula a target reaches draws random numbers, by entity id or by call count:
    • policyengine-us 2.2.1 has no use of numpy.random, default_rng or the standard-library random outside its tests (searched in the installed package).
    • policyengine-core 3.32.5 refuses formula-time randomness: commons.formulas.random raises, and Variable.__init__ runs check_formula_determinism. That check looks at a formula's own global and closure references, not at the helpers it calls.
    • The seeding this path reaches is the np.random.seed(0) in Simulation.__init__, which feeds no formula. Core's other seeding sites (from a situation's hash, sample_person, and the subsample method) do not run for a Microsimulation built from a dataset.
  • Ranking within groups. Population.get_rank (used for tax-unit heads and spouses) pads each group to the size of the largest group in the engine, and that size differs between chunks. It sorts with kind="stable", so a finite value's rank, ties included, does not depend on the padding. A NaN criterion would sort after the padding and its rank would depend on it. fill_reviewed_nulls refuses unregistered NaN inputs, so only a formula that returns NaN could reach that case.
  • Assembly. SparseTargetAssembler drops zeros after float32 rounding and refuses a cell written twice. to_csr sums duplicates (which sorts the entries) and sorts indices, so the CSR does not depend on the order in which chunks were added.

Not covered

  • --hh-chunk is also the engine batch size of the SSI and Medicaid take-up pre-pass (_with_local_ssi_medicaid_take_up through _acs_engine_values) in do_materialize, which runs before materialize_chunked. These tests do not run it; pooling it is task 2.5 · 2.
  • The real-engine fixture is small. It shows that, 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, and test_population_aggregate_list_matches_installed_engine_sources keeps that list in step with the engine's sources. Neither proves that every formula stays within a household.
  • Only the matrix is the same across layouts. materialize_rss.json records chunk_stats and carrier_check, which depend on --hh-chunk by design: which district rows chunk 0 checks directly, and per-chunk tallies.
  • do_qa also reads the frame in --hh-chunk household chunks; that is task 1.7 · 2's area and not tested here.

Observation for 2.5 · 1

Each chunk calls release_tool._materialize_target_frame, which builds a new CountryTaxBenefitSystem() (it is not cached), and materialize_chunked builds two more for the projection and the null fill. The engine computation itself uses Microsimulation's shared system, so this only costs time per chunk.

Tests run

Only the tests this PR adds, by node ID:

  • packages/microcosm-build/tests/engine_free/us/test_us_acs_local_sparse_cd.py::test_every_chunk_and_batch_size_gives_the_one_chunk_target_matrix (8 layouts)
  • packages/microcosm-build/tests/engine_free/us/test_us_acs_local_sparse_cd.py::test_the_chunk_comparison_reports_a_value_read_from_other_households
  • packages/microcosm-build/tests/engine_workflow/us/test_us_acs_local_materialize_chunks.py::test_every_chunk_and_batch_size_gives_the_one_chunk_target_matrix (477 s locally)
  • the eight existing tests in test_us_acs_local_sparse_cd.py that call _materialize, which now shares the fake-engine setup with the new tests

🤖 Generated with Claude Code

anth-volk and others added 3 commits November 28, 2026 03:34
…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 <noreply@anthropic.com>
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 <noreply@anthropic.com>
…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 <noreply@anthropic.com>

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant