From 65aec3dd1056e1c5c4831de2c2b72a986c27675e Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Fri, 27 Nov 2026 01:06:43 +0400 Subject: [PATCH 1/6] Test that the input-stage batch loops refuse population aggregates and release engines MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Add failing tests for tracker task 1.6 · 2. The release's five input-stage loops (ACA source inputs, Medicaid eligibility, December SSI amounts, SNAP eligibility and the other-health-insurance premiums) should: - write exactly what main's loops write: a frozen copy of each loop from origin/main c58596526 is the reference, compared byte for byte; - refuse a batch engine, or a branch it dropped, that computed a population-aggregate variable, as target compilation does, with a refuse_population_aggregates override; - refuse a frame whose groups or Medicaid claims cross households; - release every batch engine before the next, also when a batch fails. Also test the new household_batches module with stand-in engines, the US adapter's caller-owned engine, and that the local-area build switches the refusal on for its donor and ACS views. Co-Authored-By: Claude Opus 5.5 --- .../us/test_us_acs_local_release_tool.py | 27 +- .../us/test_us_household_batches.py | 333 +++++++++++ .../us/test_us_input_batch_loops.py | 249 ++++++++ .../us/test_policyengine_us_adapter.py | 19 + .../microcosm_build/us_input_batch_loops.py | 322 +++++++++++ .../us_input_batch_loops_main_baseline.py | 539 ++++++++++++++++++ 6 files changed, 1480 insertions(+), 9 deletions(-) create mode 100644 packages/microcosm-build/tests/engine_free/us/test_us_household_batches.py create mode 100644 packages/microcosm-build/tests/engine_workflow/us/test_us_input_batch_loops.py create mode 100644 test_support/microcosm_build/us_input_batch_loops.py create mode 100644 test_support/microcosm_build/us_input_batch_loops_main_baseline.py 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 deba5f9713..b00900c3ad 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 @@ -2699,10 +2699,19 @@ def classify(view): ) def helper(column, name): - def evaluate(view, *, maximum_microsim_batch_size): + def evaluate( + view, *, maximum_microsim_batch_size, refuse_population_aggregates=None + ): # The engine sees the projected view, never a formula output. assert "invented_formula_output" not in view.table("person") - calls.append((name, view.n("household"), maximum_microsim_batch_size)) + calls.append( + ( + name, + view.n("household"), + maximum_microsim_batch_size, + refuse_population_aggregates, + ) + ) values = view.table("person")[column].to_numpy() return ( values if eligible is None or name != "eligible" else eligible(values) @@ -2751,16 +2760,18 @@ def test_ssi_medicaid_stage_runs_both_engine_passes_in_household_chunks( assert calls == [ ("project",), ("fill", summary), - ("uncapped", 40, 100), + # The donor and ACS views are each part of the population, so the + # population-aggregate refusal is on even for a view in one chunk. + ("uncapped", 40, 100, True), ("project",), ("fill", summary), - ("eligible", 40, 100), + ("eligible", 40, 100, True), ("project",), ("fill", summary), - ("uncapped", 600, 100), + ("uncapped", 600, 100, True), ("project",), ("fill", summary), - ("eligible", 600, 100), + ("eligible", 600, 100, True), ] assert receipt["gate"] == { "name": "acs_local_ssi_medicaid_take_up_signal", @@ -3742,9 +3753,7 @@ def test_pinned_feed_soi_surfaces_match_their_contracts() -> None: # at-large districts (each copy repeated its state row). totals_soi = [spec for spec in totals_registry.specs if spec.family == "irs_soi"] assert len(totals_soi) == 102 - assert {spec.metadata["ledger_geography_level"] for spec in totals_soi} == { - "state" - } + assert {spec.metadata["ledger_geography_level"] for spec in totals_soi} == {"state"} assert {spec.metadata["source_measure_id"] for spec in totals_soi} == { "premium_tax_credit_returns", "premium_tax_credit_amount", diff --git a/packages/microcosm-build/tests/engine_free/us/test_us_household_batches.py b/packages/microcosm-build/tests/engine_free/us/test_us_household_batches.py new file mode 100644 index 0000000000..f3f30cedab --- /dev/null +++ b/packages/microcosm-build/tests/engine_free/us/test_us_household_batches.py @@ -0,0 +1,333 @@ +"""Household batches shared by the US release's policyengine-us passes. + +``microcosm.build.us_runtime.household_batches`` splits a frame's households +into contiguous batches, runs the frame checks that batching needs, and runs +each batch engine inside :func:`checked_batch_engine`, which refuses a +population-aggregate variable before the engine is released. These tests use +stand-in engines; ``test_us_input_batch_loops.py`` runs the real engine. +""" + +from __future__ import annotations + +import gc +from types import SimpleNamespace + +import numpy as np +import pandas as pd +import pytest + +import microcosm.build.us_runtime.household_batches as household_batches +from microcosm.build.us_runtime.household_batches import ( + INPUT_PASS_POPULATION_AGGREGATE_REMEDY, + assert_group_entities_nest_in_households, + assert_medicaid_claiming_tax_units_local, + automatic_gc_suspended, + checked_batch_engine, + household_batch_plan, + household_position_batches, + refuse_batch_population_aggregates, + select_households_by_position, +) +from microcosm.frame import US_SCHEMA, Frame, WeightKind, Weights + +AGGREGATE = "medicaid_slcsp_state_denominator" +WORK = "The probe pass" + + +def _frame( + *, + person_household_ids=(1, 1, 2, 3, 3), + person_spm_unit_ids=(10, 10, 20, 30, 31), + medicaid_claiming_tax_unit_ids=None, +) -> Frame: + person_household_ids = np.asarray(person_household_ids, dtype="int64") + person = pd.DataFrame( + { + "person_id": np.arange(1, len(person_household_ids) + 1, dtype="int64"), + "person_household_id": person_household_ids, + "person_tax_unit_id": person_household_ids * 100, + "person_spm_unit_id": np.asarray(person_spm_unit_ids, dtype="int64"), + "person_family_id": person_household_ids * 1_000, + "person_marital_unit_id": person_household_ids * 10_000, + } + ) + if medicaid_claiming_tax_unit_ids is not None: + person["medicaid_claiming_tax_unit_id"] = np.asarray( + medicaid_claiming_tax_unit_ids, dtype="int64" + ) + tables = {"person": person} + for entity in ("tax_unit", "spm_unit", "family", "marital_unit"): + ids = np.unique(person[f"person_{entity}_id"].to_numpy()) + tables[entity] = pd.DataFrame({f"{entity}_id": ids}) + household_ids = np.unique(person_household_ids) + tables["household"] = pd.DataFrame({"household_id": household_ids}) + return Frame( + tables, + US_SCHEMA, + { + "household": Weights( + np.ones(len(household_ids), dtype=np.float64), WeightKind.DESIGN + ) + }, + ) + + +class _StandInEngine: + """Holds known periods per variable and creates stand-in branches.""" + + def __init__(self, known_periods=None) -> None: + self.known_periods = dict(known_periods or {}) + self.branches: dict[str, _StandInEngine] = {} + + def get_holder(self, variable): + return SimpleNamespace( + get_known_periods=lambda: list(self.known_periods.get(variable, [])) + ) + + def get_branch(self, name): + branch = _StandInEngine() + self.branches[name] = branch + return branch + + +@pytest.fixture +def released(monkeypatch): + """Record each engine ``checked_batch_engine`` releases, in order.""" + + engines: list[object] = [] + monkeypatch.setattr(household_batches, "release_engine_simulation", engines.append) + return engines + + +@pytest.mark.parametrize( + ("n_households", "batch_size", "expected"), + [ + (5, 2, [[0, 1], [2, 3], [4]]), + (5, None, [[0, 1, 2, 3, 4]]), + (5, 0, [[0, 1, 2, 3, 4]]), + (5, -3, [[0, 1, 2, 3, 4]]), + (5, 5, [[0, 1, 2, 3, 4]]), + (5, 9, [[0, 1, 2, 3, 4]]), + (0, 2, []), + ], +) +def test_household_position_batches_are_contiguous_ranges( + n_households, batch_size, expected +) -> None: + batches = list(household_position_batches(n_households, batch_size)) + + assert [batch.tolist() for batch in batches] == expected + assert all(batch.dtype == np.int64 for batch in batches) + + +def test_selected_households_keep_their_people_and_groups() -> None: + selected = select_households_by_position(_frame(), np.asarray([0, 2])) + + assert selected.table("household")["household_id"].tolist() == [1, 3] + assert selected.table("person")["person_id"].tolist() == [1, 2, 4, 5] + assert selected.table("spm_unit")["spm_unit_id"].tolist() == [10, 30, 31] + + +@pytest.mark.parametrize( + ("batch_size", "refuse_population_aggregates", "batches", "refusing"), + [ + pytest.param(2, None, 2, True, id="more-than-one-batch"), + pytest.param(None, None, 1, False, id="one-batch"), + pytest.param(None, True, 1, True, id="one-batch-switched-on"), + pytest.param(2, False, 2, False, id="more-than-one-batch-switched-off"), + ], +) +def test_batch_plan_switches_the_refusal_on_for_more_than_one_batch( + batch_size, refuse_population_aggregates, batches, refusing +) -> None: + plan = household_batch_plan( + _frame(), + batch_size, + refuse_population_aggregates=refuse_population_aggregates, + work=WORK, + ) + + assert len(plan.batches) == batches + assert plan.refuse_population_aggregates is refusing + + +@pytest.mark.parametrize( + ("batch_size", "refuse_population_aggregates", "refused"), + [ + pytest.param(2, None, True, id="more-than-one-batch"), + pytest.param(2, False, True, id="split-even-with-refusal-off"), + pytest.param(None, True, True, id="one-batch-refusal-on"), + pytest.param(None, None, False, id="one-batch-holds-the-pool"), + ], +) +def test_batch_plan_refuses_a_group_that_spans_households( + batch_size, refuse_population_aggregates, refused +) -> None: + # SPM unit 20 holds a person from household 2 and one from household 3. + frame = _frame(person_spm_unit_ids=(10, 10, 20, 20, 31)) + + def plan(): + return household_batch_plan( + frame, + batch_size, + refuse_population_aggregates=refuse_population_aggregates, + work=WORK, + ) + + if refused: + with pytest.raises(ValueError, match="spm_unit units must be nested"): + plan() + else: + plan() + + +@pytest.mark.parametrize( + ("batch_size", "refuse_population_aggregates", "refused"), + [ + pytest.param(2, None, True, id="more-than-one-batch"), + pytest.param(None, True, True, id="one-batch-refusal-on"), + pytest.param(2, False, False, id="refusal-off"), + pytest.param(None, None, False, id="one-batch-holds-the-pool"), + ], +) +def test_batch_plan_refuses_a_medicaid_claim_outside_the_household( + batch_size, refuse_population_aggregates, refused +) -> None: + # Person 4 (household 3) is claimed by tax unit 100 (household 1). + frame = _frame(medicaid_claiming_tax_unit_ids=(0, 0, 0, 100, 0)) + + def plan(): + return household_batch_plan( + frame, + batch_size, + refuse_population_aggregates=refuse_population_aggregates, + work=WORK, + ) + + if refused: + with pytest.raises( + ValueError, + match=( + f"^{WORK} is not batch-invariant: a positive " + "medicaid_claiming_tax_unit_id does not resolve" + ), + ): + plan() + else: + plan() + + +def test_a_medicaid_claim_within_the_household_passes() -> None: + frame = _frame(medicaid_claiming_tax_unit_ids=(100, 100, 0, 300, 0)) + + assert_medicaid_claiming_tax_units_local(frame, work=WORK) + assert_group_entities_nest_in_households(frame) + + +def test_refusal_names_the_pass_the_batch_and_the_aggregate() -> None: + engine = _StandInEngine({AGGREGATE: ["2024"]}) + + with pytest.raises(ValueError) as refusal: + refuse_batch_population_aggregates( + engine, + batch=2, + batches=3, + work=WORK, + remedy=INPUT_PASS_POPULATION_AGGREGATE_REMEDY, + ) + + message = str(refusal.value) + assert message.startswith(f"{WORK} is not batch-invariant: the engine for ") + assert f"household batch 2/3 computed {AGGREGATE}@2024." in message + assert message.endswith(INPUT_PASS_POPULATION_AGGREGATE_REMEDY) + + +def test_checked_engine_refuses_an_aggregate_from_a_dropped_branch( + released, +) -> None: + engine = _StandInEngine() + + with pytest.raises(ValueError, match=rf"batch 1/2 computed {AGGREGATE}@2024"): + with checked_batch_engine( + engine, + refuse_population_aggregates=True, + batch=1, + batches=2, + work=WORK, + remedy=INPUT_PASS_POPULATION_AGGREGATE_REMEDY, + ): + branch = engine.get_branch("probe") + branch.known_periods[AGGREGATE] = ["2024"] + del engine.branches["probe"] + + # The branch the batch dropped was kept for the check, then released, + # and the batch engine itself was released after the check. + assert released == [branch, engine] + assert "get_branch" not in vars(engine) + + +def test_checked_engine_passes_a_household_local_batch_and_releases_it( + released, +) -> None: + engine = _StandInEngine({"is_medicaid_eligible": ["2024"]}) + + with checked_batch_engine( + engine, + refuse_population_aggregates=True, + batch=1, + batches=2, + work=WORK, + remedy=INPUT_PASS_POPULATION_AGGREGATE_REMEDY, + ) as checked: + assert checked is engine + + assert released == [engine] + + +def test_checked_engine_with_the_refusal_off_keeps_an_aggregate(released) -> None: + engine = _StandInEngine({AGGREGATE: ["2024"]}) + + with checked_batch_engine( + engine, + refuse_population_aggregates=False, + batch=1, + batches=1, + work=WORK, + remedy=INPUT_PASS_POPULATION_AGGREGATE_REMEDY, + ): + assert "get_branch" not in vars(engine) + + assert released == [engine] + + +@pytest.mark.parametrize("refusing", [True, False]) +def test_checked_engine_releases_a_batch_that_raised(released, refusing) -> None: + # The batch raised before the check, so the aggregate is not reported. + engine = _StandInEngine({AGGREGATE: ["2024"]}) + + with pytest.raises(RuntimeError, match="batch failed"): + with checked_batch_engine( + engine, + refuse_population_aggregates=refusing, + batch=1, + batches=2, + work=WORK, + remedy=INPUT_PASS_POPULATION_AGGREGATE_REMEDY, + ): + raise RuntimeError("batch failed") + + assert released == [engine] + + +@pytest.mark.parametrize("enabled", [True, False]) +def test_automatic_gc_is_suspended_inside_a_batch_and_restored(enabled) -> None: + was_enabled = gc.isenabled() + try: + (gc.enable if enabled else gc.disable)() + with pytest.raises(RuntimeError): + with automatic_gc_suspended(): + assert not gc.isenabled() + raise RuntimeError("batch failed") + assert gc.isenabled() is enabled + finally: + (gc.enable if was_enabled else gc.disable)() diff --git a/packages/microcosm-build/tests/engine_workflow/us/test_us_input_batch_loops.py b/packages/microcosm-build/tests/engine_workflow/us/test_us_input_batch_loops.py new file mode 100644 index 0000000000..cd784c0a88 --- /dev/null +++ b/packages/microcosm-build/tests/engine_workflow/us/test_us_input_batch_loops.py @@ -0,0 +1,249 @@ +"""The release's input-stage household-batch loops (tracker task 1.6 · 2). + +Five loops run policyengine-us over household batches before target +compilation: ACA source inputs, Medicaid eligibility, December SSI candidate +amounts, SNAP eligibility and the other-health-insurance modeled premiums. +Each must write exactly what main wrote, refuse a batch engine that computed a +population-aggregate variable (as target compilation does), refuse a frame +that household batches would split, and release every batch engine before the +next one is built, also when a batch fails. +""" + +from __future__ import annotations + +import pytest + +from test_support.microcosm_build.us_input_batch_loops import ( + INPUT_LOOPS, + POPULATION_AGGREGATE_PROBE_VARIABLE, + PROBE_FAILURE_MESSAGE, + BatchEngineRecorder, + assert_same_bytes, + engine_released, + load_builder_module, + medicaid_claim_outside_household_frame, + real_engine_frame, + spm_unit_spanning_households_frame, +) + +LOOP_PARAMETERS = [pytest.param(loop, id=loop.name) for loop in INPUT_LOOPS] + + +@pytest.fixture(scope="module") +def builder(): + return load_builder_module() + + +def _options(batch_size, refuse_population_aggregates): + options = {"maximum_microsim_batch_size": batch_size} + if refuse_population_aggregates is not None: + options["refuse_population_aggregates"] = refuse_population_aggregates + return options + + +@pytest.mark.parametrize("loop", LOOP_PARAMETERS) +def test_input_loop_writes_mains_bytes_and_releases_each_batch_engine( + builder, loop, monkeypatch +) -> None: + """One batch and two batches of two households: the same arrays, dtypes + and column order as main's loop, and each engine released before the + next is built.""" + + frame = real_engine_frame() + for batch_size, expected_engines in ((None, 1), (2, 2)): + expected = loop.run_main(builder, frame, maximum_microsim_batch_size=batch_size) + recorder = BatchEngineRecorder(monkeypatch, period=builder.PERIOD) + actual = loop.run(builder, frame, maximum_microsim_batch_size=batch_size) + monkeypatch.undo() + + assert loop.reaches_engine_values(expected), loop.name + assert_same_bytes( + actual, expected, label=f"{loop.name}, batch size {batch_size}" + ) + assert len(recorder.engines) == expected_engines + assert all(recorder.earlier_engines_released_at_build) + assert all(engine_released(engine) for engine in recorder.engines) + + +@pytest.mark.parametrize("loop", LOOP_PARAMETERS) +@pytest.mark.parametrize( + ("probe", "batch_size", "refuse_population_aggregates", "batch_label"), + [ + pytest.param("engine", 2, None, "1/2", id="aggregate-on-batch-engine"), + pytest.param( + "detached_branch", 2, None, "1/2", id="aggregate-on-dropped-branch" + ), + pytest.param("engine", None, True, "1/1", id="one-batch-refusal-switched-on"), + ], +) +def test_input_loop_refuses_a_batch_engine_that_computed_a_population_aggregate( + builder, + loop, + probe, + batch_size, + refuse_population_aggregates, + batch_label, + monkeypatch, +) -> None: + recorder = BatchEngineRecorder( + monkeypatch, + period=builder.PERIOD, + first_requested_variable=loop.first_requested_variable, + probe=probe, + ) + with pytest.raises(ValueError) as refusal: + loop.run( + builder, + real_engine_frame(), + **_options(batch_size, refuse_population_aggregates), + ) + + message = str(refusal.value) + assert message.startswith(f"{loop.pass_label} is not batch-invariant"), message + assert ( + f"household batch {batch_label} computed " + f"{POPULATION_AGGREGATE_PROBE_VARIABLE}@{builder.PERIOD}" + ) in message + # The refusal stops the first batch, after its check and its release. + assert len(recorder.engines) == 1 + assert engine_released(recorder.engines[0]) + + +@pytest.mark.parametrize("loop", LOOP_PARAMETERS) +@pytest.mark.parametrize( + ("batch_size", "refuse_population_aggregates"), + [ + pytest.param(None, None, id="one-batch-by-default"), + pytest.param(2, False, id="refusal-switched-off"), + ], +) +def test_input_loop_keeps_an_aggregate_when_its_refusal_is_off( + builder, loop, batch_size, refuse_population_aggregates, monkeypatch +) -> None: + """One batch holds the whole pool, so the refusal is off by default; a + caller may also switch it off. Engines are released either way.""" + + recorder = BatchEngineRecorder( + monkeypatch, + period=builder.PERIOD, + first_requested_variable=loop.first_requested_variable, + probe="engine", + ) + loop.run( + builder, + real_engine_frame(), + **_options(batch_size, refuse_population_aggregates), + ) + + assert len(recorder.engines) == (1 if batch_size is None else 2) + assert all(recorder.earlier_engines_released_at_build) + assert all(engine_released(engine) for engine in recorder.engines) + + +@pytest.mark.parametrize("loop", LOOP_PARAMETERS) +def test_a_failing_input_batch_still_releases_its_engine( + builder, loop, monkeypatch +) -> None: + recorder = BatchEngineRecorder( + monkeypatch, + period=builder.PERIOD, + first_requested_variable=loop.first_requested_variable, + probe="failure", + ) + with pytest.raises(RuntimeError, match=PROBE_FAILURE_MESSAGE): + loop.run(builder, real_engine_frame(), maximum_microsim_batch_size=2) + + assert len(recorder.engines) == 1 + assert engine_released(recorder.engines[0]) + + +@pytest.mark.parametrize("loop", LOOP_PARAMETERS) +@pytest.mark.parametrize( + ("make_frame", "batch_size", "refuse_population_aggregates", "message"), + [ + pytest.param( + spm_unit_spanning_households_frame, + 2, + None, + "spm_unit units must be nested in households", + id="spm-unit-spans-households", + ), + pytest.param( + medicaid_claim_outside_household_frame, + 2, + None, + "medicaid_claiming_tax_unit_id does not resolve within the " + "person's own household", + id="medicaid-claim-outside-household", + ), + pytest.param( + medicaid_claim_outside_household_frame, + None, + True, + "medicaid_claiming_tax_unit_id does not resolve within the " + "person's own household", + id="medicaid-claim-outside-household-one-batch-refusal-on", + ), + ], +) +def test_input_loop_refuses_a_frame_that_household_batches_would_split( + builder, + loop, + make_frame, + batch_size, + refuse_population_aggregates, + message, + monkeypatch, +) -> None: + """Refused before any engine is built, as in target compilation.""" + + recorder = BatchEngineRecorder(monkeypatch, period=builder.PERIOD) + with pytest.raises(ValueError, match=message): + loop.run( + builder, + make_frame(), + **_options(batch_size, refuse_population_aggregates), + ) + + assert recorder.engines == [] + + +def test_other_health_insurance_stage_writes_mains_tables(builder, monkeypatch) -> None: + """The whole stage, in two batches of five households, writes the same + tables as with main's premium loop: the modeled premiums on each tax + unit's first person, the ASEC residual and the PUF-support imputation.""" + + import microcosm.build.us_runtime.other_health_insurance as other_health_insurance + from test_support.microcosm_build import ( + us_input_batch_loops_main_baseline as main_baseline, + ) + from test_support.microcosm_build.us_other_health_insurance import ( + _frame as other_health_insurance_frame, + ) + + frame = other_health_insurance_frame() + + def run_stage(): + return other_health_insurance.with_us_other_health_insurance_inputs( + frame, + seed=0, + time_period=builder.PERIOD, + maximum_microsim_batch_size=5, + ) + + actual = run_stage() + monkeypatch.setattr( + other_health_insurance, + "_materialize_modeled_premiums", + main_baseline.main_materialize_modeled_premiums, + ) + expected = run_stage() + + # A modeled premium reaches the stage's output: the residual of a person + # with a marketplace premium is below their reported premium. + reported, residual = other_health_insurance.US_OTHER_HEALTH_INSURANCE_OUTPUT_COLUMNS + person = expected.table("person") + assert (person[residual] < person[reported]).any() + assert list(actual.entities) == list(expected.entities) + for entity in expected.entities: + assert_same_bytes(actual.table(entity), expected.table(entity), label=entity) diff --git a/packages/microcosm-frame/tests/engine_workflow/us/test_policyengine_us_adapter.py b/packages/microcosm-frame/tests/engine_workflow/us/test_policyengine_us_adapter.py index 6440b93296..966ccaeebc 100644 --- a/packages/microcosm-frame/tests/engine_workflow/us/test_policyengine_us_adapter.py +++ b/packages/microcosm-frame/tests/engine_workflow/us/test_policyengine_us_adapter.py @@ -202,6 +202,25 @@ def test_materializes_row_aligned_arrays(self, adapter, us_bundle) -> None: ) assert results["household_net_income"].shape == (us_bundle.n("household"),) + def test_a_caller_owned_engine_gives_materializes_arrays( + self, adapter, us_bundle + ) -> None: + """A caller that must check or release the engine builds it itself; + the engine holds the period alone and gives materialize's bytes.""" + + variables = ["employment_income", "household_net_income", "aca_ptc"] + expected = adapter.materialize(us_bundle, variables, period=2024) + simulation = adapter.build_microsimulation(us_bundle, 2024) + assert simulation.dataset.years == [2024] + actual = adapter.calculate_variables( + simulation, us_bundle, variables, period=2024 + ) + + assert list(actual) == variables + for name in variables: + assert actual[name].dtype == expected[name].dtype, name + assert actual[name].tobytes() == expected[name].tobytes(), name + class TestWriteDataset: def test_round_trips_and_carries_household_weight( diff --git a/test_support/microcosm_build/us_input_batch_loops.py b/test_support/microcosm_build/us_input_batch_loops.py new file mode 100644 index 0000000000..9ac6212210 --- /dev/null +++ b/test_support/microcosm_build/us_input_batch_loops.py @@ -0,0 +1,322 @@ +"""Real-engine checks for the release's input-stage household-batch loops. + +Before target compilation the US release runs policyengine-us over household +batches in five loops: the ACA source inputs, Medicaid eligibility, December +SSI candidate amounts and SNAP eligibility (in the release tool), and the +other-health-insurance modeled premiums (``us_runtime.other_health_insurance``). +The tests compare each loop with its frozen copy from main +(:mod:`test_support.microcosm_build.us_input_batch_loops_main_baseline`) byte +for byte, and check that each batch engine is checked for population-aggregate +variables and released before the next one is built. + +:class:`BatchEngineRecorder` replaces ``policyengine_us.Microsimulation`` with +a subclass that records every engine the loops build. It can also make an +engine, or a branch the engine then drops, compute a population-aggregate +variable, or fail, the first time a loop asks it for its first variable. +""" + +from __future__ import annotations + +from collections.abc import Callable +from dataclasses import dataclass + +import numpy as np +import pandas as pd + +import microcosm.build.us_runtime.other_health_insurance as other_health_insurance +from microcosm.frame import US_SCHEMA, Frame, WeightKind, Weights +from test_support.microcosm_build import ( + us_input_batch_loops_main_baseline as main_baseline, +) +from test_support.microcosm_build.us_batched_target_materialization import ( + _load_builder_module, + _real_engine_frame, +) + +#: The population aggregate the probes compute: a sum of person weights by +#: state, so a household batch gets its own batch's sum. +POPULATION_AGGREGATE_PROBE_VARIABLE = "medicaid_slcsp_state_denominator" +PROBE_BRANCH_NAME = "population_aggregate_probe" +PROBE_FAILURE_MESSAGE = "probe: batch calculation failed" + + +def load_builder_module(): + return _load_builder_module() + + +def real_engine_frame() -> Frame: + """Four households over three states; household 1 holds two tax units.""" + + return _real_engine_frame() + + +def _rebuilt_frame(frame: Frame, tables: dict[str, pd.DataFrame]) -> Frame: + return Frame( + tables, + US_SCHEMA, + { + "household": Weights( + np.asarray(frame.weights_for("household").values, dtype=np.float64), + WeightKind.DESIGN, + ) + }, + ) + + +def spm_unit_spanning_households_frame() -> Frame: + """The real-engine frame with person 3 (household 2) moved into SPM unit + 100, which belongs to household 1, so that SPM unit spans two households.""" + + frame = real_engine_frame() + tables = {entity: frame.table(entity).copy() for entity in frame.entities} + person = tables["person"] + person.loc[person["person_id"] == 3, "person_spm_unit_id"] = 100 + spm_unit = tables["spm_unit"] + tables["spm_unit"] = spm_unit.loc[spm_unit["spm_unit_id"] != 200].reset_index( + drop=True + ) + return _rebuilt_frame(frame, tables) + + +def medicaid_claim_outside_household_frame() -> Frame: + """The real-engine frame with person 6 (household 3) claimed for Medicaid + by tax unit 10, which belongs to household 1.""" + + frame = real_engine_frame() + tables = {entity: frame.table(entity).copy() for entity in frame.entities} + person = tables["person"] + person["medicaid_claiming_tax_unit_id"] = np.where( + person["person_id"].to_numpy() == 6, 10, 0 + ).astype("int64") + return _rebuilt_frame(frame, tables) + + +def _microsimulation_class(): + import policyengine_us + + return policyengine_us.Microsimulation + + +def _run_aca(builder, frame: Frame, **options): + return builder._aca_source_tax_unit_table_batched( + frame, {}, microsimulation_cls=_microsimulation_class(), **options + ) + + +def _run_main_aca(builder, frame: Frame, *, maximum_microsim_batch_size): + return main_baseline.main_aca_source_tax_unit_table_batched( + builder, + frame, + {}, + microsimulation_cls=_microsimulation_class(), + maximum_microsim_batch_size=maximum_microsim_batch_size, + ) + + +def _run_other_health(builder, frame: Frame, **options): + return other_health_insurance._materialize_modeled_premiums( + frame, time_period=builder.PERIOD, **options + ) + + +def _run_main_other_health(builder, frame: Frame, *, maximum_microsim_batch_size): + return main_baseline.main_materialize_modeled_premiums( + frame, + time_period=builder.PERIOD, + maximum_microsim_batch_size=maximum_microsim_batch_size, + ) + + +@dataclass(frozen=True) +class InputLoop: + """One input-stage loop, its frozen main copy, and what it asks first.""" + + name: str + #: The first variable the loop asks each batch engine for; the recorder's + #: probes run when an engine is first asked for it. + first_requested_variable: str + #: The start of the loop's refusal messages. + pass_label: str + run: Callable + run_main: Callable + #: Whether an output carries a nonzero engine value, so a byte comparison + #: of it compares engine results and not only zero fills. + reaches_engine_values: Callable[[object], bool] + + +INPUT_LOOPS = ( + InputLoop( + name="aca_source_inputs", + first_requested_variable="is_aca_ptc_eligible", + pass_label="The ACA source-input pass", + run=_run_aca, + run_main=_run_main_aca, + reaches_engine_values=lambda output: bool( + output["assigned_aca_ptc"].to_numpy().any() + ), + ), + InputLoop( + name="medicaid_eligibility", + first_requested_variable="is_medicaid_eligible", + pass_label="The Medicaid eligibility pass", + run=lambda builder, frame, **options: builder._medicaid_person_eligibility( + frame, **options + ), + run_main=lambda builder, frame, **options: ( + main_baseline.main_medicaid_person_eligibility(builder, frame, **options) + ), + reaches_engine_values=lambda output: bool(np.asarray(output).any()), + ), + InputLoop( + name="december_ssi_amounts", + first_requested_variable="uncapped_ssi", + pass_label="The December SSI pass", + run=lambda builder, frame, **options: builder._ssi_person_uncapped_amount( + frame, **options + ), + run_main=lambda builder, frame, **options: ( + main_baseline.main_ssi_person_uncapped_amount(builder, frame, **options) + ), + reaches_engine_values=lambda output: bool((np.asarray(output) > 0).any()), + ), + InputLoop( + name="snap_eligibility", + first_requested_variable="is_snap_eligible", + pass_label="The SNAP eligibility pass", + run=lambda builder, frame, **options: builder._snap_spm_unit_eligibility( + frame, **options + ), + run_main=lambda builder, frame, **options: ( + main_baseline.main_snap_spm_unit_eligibility(builder, frame, **options) + ), + reaches_engine_values=lambda output: bool(np.asarray(output).any()), + ), + InputLoop( + name="other_health_insurance_premiums", + first_requested_variable="chip_premium", + pass_label="The other-health-insurance premium pass", + run=_run_other_health, + run_main=_run_main_other_health, + reaches_engine_values=lambda output: bool( + np.asarray(output["marketplace_net_premium"]).any() + ), + ), +) + + +def engine_released(engine) -> bool: + """``release_engine_simulation`` empties an engine's population map.""" + + return getattr(engine, "populations", None) == {} + + +class BatchEngineRecorder: + """Record every batch engine the loops build, optionally with a probe. + + ``probe`` is ``None`` (record only), ``"engine"`` (the engine computes + :data:`POPULATION_AGGREGATE_PROBE_VARIABLE`), ``"detached_branch"`` (a + branch computes it and the engine then drops the branch) or ``"failure"`` + (the engine raises). A probe runs once per engine, the first time the + engine is asked for ``first_requested_variable``. + """ + + def __init__( + self, + monkeypatch, + *, + period: int, + first_requested_variable: str | None = None, + probe: str | None = None, + ) -> None: + import policyengine_us + + if probe not in (None, "engine", "detached_branch", "failure"): + raise ValueError(f"Unknown probe {probe!r}.") + self.engines: list[object] = [] + #: One entry per engine: whether every engine built before it had + #: been released when it was built. + self.earlier_engines_released_at_build: list[bool] = [] + recorder = self + base_class = policyengine_us.Microsimulation + + class RecordingMicrosimulation(base_class): + def __init__(self, *args, **kwargs): + recorder.earlier_engines_released_at_build.append( + all(engine_released(engine) for engine in recorder.engines) + ) + super().__init__(*args, **kwargs) + recorder.engines.append(self) + + def calculate(self, variable_name, *args, **kwargs): + if ( + probe is not None + and variable_name == first_requested_variable + and not getattr(self, "_population_aggregate_probe_ran", False) + ): + self._population_aggregate_probe_ran = True + if probe == "failure": + raise RuntimeError(PROBE_FAILURE_MESSAGE) + if probe == "engine": + self.calculate(POPULATION_AGGREGATE_PROBE_VARIABLE, period) + else: + branch = self.get_branch(PROBE_BRANCH_NAME) + branch.calculate(POPULATION_AGGREGATE_PROBE_VARIABLE, period) + del self.branches[PROBE_BRANCH_NAME] + return super().calculate(variable_name, *args, **kwargs) + + monkeypatch.setattr( + policyengine_us, "Microsimulation", RecordingMicrosimulation + ) + + +def _assert_same_array_bytes(actual, expected, *, label: str) -> None: + actual = np.asarray(actual) + expected = np.asarray(expected) + assert actual.dtype == expected.dtype, (label, actual.dtype, expected.dtype) + assert actual.shape == expected.shape, (label, actual.shape, expected.shape) + if expected.dtype == object: + # Object arrays hold pointers; compare the values and their types. + assert actual.tolist() == expected.tolist(), label + assert [type(value) for value in actual.tolist()] == [ + type(value) for value in expected.tolist() + ], label + return + assert actual.tobytes() == expected.tobytes(), label + + +def assert_same_bytes(actual, expected, *, label: str) -> None: + """Every array, column, dtype, index and column order is identical.""" + + if isinstance(expected, pd.DataFrame): + assert isinstance(actual, pd.DataFrame), label + assert list(actual.columns) == list(expected.columns), label + pd.testing.assert_index_equal(actual.index, expected.index, exact=True) + for column in expected.columns: + _assert_same_array_bytes( + actual[column].to_numpy(), + expected[column].to_numpy(), + label=f"{label}: {column}", + ) + return + if isinstance(expected, dict): + assert isinstance(actual, dict), label + assert list(actual) == list(expected), label + for key, values in expected.items(): + _assert_same_array_bytes(actual[key], values, label=f"{label}: {key}") + return + _assert_same_array_bytes(actual, expected, label=label) + + +__all__ = [ + "INPUT_LOOPS", + "POPULATION_AGGREGATE_PROBE_VARIABLE", + "PROBE_FAILURE_MESSAGE", + "BatchEngineRecorder", + "InputLoop", + "assert_same_bytes", + "engine_released", + "load_builder_module", + "medicaid_claim_outside_household_frame", + "real_engine_frame", + "spm_unit_spanning_households_frame", +] diff --git a/test_support/microcosm_build/us_input_batch_loops_main_baseline.py b/test_support/microcosm_build/us_input_batch_loops_main_baseline.py new file mode 100644 index 0000000000..ce3b2f9fb9 --- /dev/null +++ b/test_support/microcosm_build/us_input_batch_loops_main_baseline.py @@ -0,0 +1,539 @@ +"""Frozen input-stage batch loops: the byte-identity reference for 1.6 · 2. + +Copied from origin/main c58596526: the release tool's four input-stage loops +(ACA source inputs, Medicaid eligibility, December SSI amounts and SNAP +eligibility), the other-health-insurance premium loop and the PolicyEngine-US +adapter's ``materialize``. The release tool's loops take the loaded tool as +``builder`` and read its unchanged helpers from it. The household partition, +the household selection and the garbage-collection helpers, which the change +moves into ``microcosm.build.us_runtime.household_batches``, are copied here +as well, so this reference does not change with the code under test. Do not +edit these copies to follow production code. +""" + +from __future__ import annotations + +import gc +from collections.abc import Iterable, Mapping, Sequence +from contextlib import contextmanager + +import numpy as np +import pandas as pd + +from microcosm.build.us_runtime.engine_lifecycle import release_engine_simulation +from microcosm.build.us_runtime.other_health_insurance import ( + US_OTHER_HEALTH_INSURANCE_MODELED_PREMIUM_VARIABLES, +) +from microcosm.frame import Frame +from microcosm.frame.adapters.policyengine_us import PolicyEngineUSEngine + +DEFAULT_MAXIMUM_MICROSIM_BATCH_SIZE = 5_000 + + +def _main_household_position_batches( + n_households: int, batch_size: int | None +) -> Iterable[np.ndarray]: + if n_households <= 0: + return + if batch_size is None or batch_size <= 0 or batch_size >= n_households: + yield np.arange(n_households, dtype=np.int64) + return + for start in range(0, n_households, batch_size): + stop = min(start + batch_size, n_households) + yield np.arange(start, stop, dtype=np.int64) + + +def _main_select_households_by_position(frame: Frame, positions: np.ndarray) -> Frame: + household_ids = frame.table("household")["household_id"].to_numpy()[positions] + person_mask = frame.table("person")["person_household_id"].isin(household_ids) + return frame.select(person_mask) + + +def _main_collect_batch_garbage() -> None: + """Keep batch loops tidy without traversing the full object graph.""" + + gc.collect(0) + + +def _main_collect_family_garbage() -> None: + """Full collection at target-family boundaries (microcosm#456). + + ``release_engine_simulation`` frees each batch's array mass by refcount, + but the residual simulation skeletons are cyclic, and anything promoted + past generation 0 is invisible to ``_collect_batch_garbage`` forever — + CPython's own full collections are throttled against the build's multi-GB + long-lived heap, so without an explicit sweep the skeletons accumulate + for the run's lifetime. One full collection per materialized family is + cheap next to the family's engine work. + """ + + gc.collect() + + +@contextmanager +def _main_automatic_gc_suspended(): + """Avoid surprise full-graph cyclic GC inside memory-heavy PE batches.""" + + was_enabled = gc.isenabled() + if was_enabled: + gc.disable() + try: + yield + finally: + if was_enabled: + gc.enable() + + +def main_aca_source_tax_unit_table_batched( + builder, + frame: Frame, + target_tables: Mapping[str, pd.DataFrame], + *, + microsimulation_cls, + maximum_microsim_batch_size: int | None, +) -> pd.DataFrame: + builder._assert_no_formula_owned_columns(frame) + tax_unit = frame.table("tax_unit").copy() + household = frame.table("household") + positions = builder._tax_unit_to_household_positions(frame) + tax_unit["state_fips"] = builder._state_fips_text( + np.asarray(household["state_fips"].to_numpy())[positions] + ) + + fill_columns = ( + "tax_unit_weight", + "household_weight", + "is_aca_ptc_eligible", + "health_insurance_premiums_without_medicare_part_b", + "assigned_aca_ptc", + "weighted_assigned_aca_ptc", + "slcsp", + ) + tax_unit["tax_unit_weight"] = 0.0 + tax_unit["household_weight"] = frame.weights_for("household").values[positions] + tax_unit["is_aca_ptc_eligible"] = False + tax_unit["health_insurance_premiums_without_medicare_part_b"] = 0.0 + tax_unit["assigned_aca_ptc"] = 0.0 + tax_unit["weighted_assigned_aca_ptc"] = 0.0 + tax_unit["slcsp"] = 0.0 + + tax_unit_positions = pd.Series( + np.arange(len(tax_unit), dtype=np.int64), + index=tax_unit["tax_unit_id"].to_numpy(), + ) + n_households = frame.n("household") + batches = tuple( + _main_household_position_batches(n_households, maximum_microsim_batch_size) + ) + if len(batches) > 1: + print( + "Materializing ACA source inputs in " + f"{len(batches)} batches of up to " + f"{maximum_microsim_batch_size:,} households.", + flush=True, + ) + + for household_positions in batches: + with _main_automatic_gc_suspended(): + full_batch = len(household_positions) == n_households + batch_frame = ( + frame + if full_batch + else _main_select_households_by_position(frame, household_positions) + ) + batch_simulation = microsimulation_cls( + dataset=builder._dataset_from_frame( + batch_frame, + assert_no_formula_owned_columns=False, + period_only=True, + ) + ) + batch_tax_unit = builder._aca_source_tax_unit_table_from_simulation( + batch_frame, + target_tables, + simulation=batch_simulation, + ) + full_positions = tax_unit_positions.reindex( + batch_tax_unit["tax_unit_id"].to_numpy() + ).to_numpy() + if np.isnan(full_positions).any(): + raise RuntimeError( + "ACA source batch produced tax_unit_id values not present in " + "the full tax_unit table." + ) + full_positions = full_positions.astype(np.int64) + for column in fill_columns: + tax_unit.iloc[ + full_positions, + tax_unit.columns.get_loc(column), + ] = batch_tax_unit[column].to_numpy() + release_engine_simulation(batch_simulation) + del batch_tax_unit, batch_simulation, batch_frame + _main_collect_batch_garbage() + _main_collect_family_garbage() + return builder._with_state_take_up_rates(tax_unit, target_tables) + + +def main_medicaid_person_eligibility( + builder, + frame: Frame, + *, + simulation=None, + maximum_microsim_batch_size: int | None = DEFAULT_MAXIMUM_MICROSIM_BATCH_SIZE, +) -> np.ndarray: + """Engine-computed person-level ``is_medicaid_eligible``, batched like ACA.""" + if simulation is not None: + return ( + builder._calculate_array( + simulation, "is_medicaid_eligible", map_to="person" + ) + > 0 + ) + from policyengine_us import Microsimulation + + person_ids = frame.table("person")["person_id"].to_numpy() + eligibility = np.zeros(len(person_ids), dtype=bool) + person_positions = pd.Series( + np.arange(len(person_ids), dtype=np.int64), index=person_ids + ) + n_households = frame.n("household") + batches = tuple( + _main_household_position_batches(n_households, maximum_microsim_batch_size) + ) + if len(batches) > 1: + print( + "Materializing Medicaid eligibility in " + f"{len(batches)} batches of up to " + f"{maximum_microsim_batch_size:,} households.", + flush=True, + ) + for household_positions in batches: + with _main_automatic_gc_suspended(): + full_batch = len(household_positions) == n_households + batch_frame = ( + frame + if full_batch + else _main_select_households_by_position(frame, household_positions) + ) + batch_simulation = Microsimulation( + dataset=builder._dataset_from_frame( + batch_frame, + assert_no_formula_owned_columns=False, + period_only=True, + ) + ) + batch_eligible = ( + builder._calculate_array( + batch_simulation, "is_medicaid_eligible", map_to="person" + ) + > 0 + ) + positions = person_positions.reindex( + batch_frame.table("person")["person_id"].to_numpy() + ).to_numpy() + if np.isnan(positions).any(): + raise RuntimeError( + "Medicaid eligibility batch produced person_id values not " + "present in the full person table." + ) + eligibility[positions.astype(np.int64)] = batch_eligible + release_engine_simulation(batch_simulation) + del batch_frame, batch_simulation + _main_collect_batch_garbage() + _main_collect_family_garbage() + return eligibility + + +def main_ssi_person_uncapped_amount( + builder, + frame: Frame, + *, + simulation=None, + maximum_microsim_batch_size: int | None = DEFAULT_MAXIMUM_MICROSIM_BATCH_SIZE, +) -> np.ndarray: + """December person-level potential federal SSI, batched like Medicaid. + + SSA's age-band recipient counts are December 2024 point-in-time stocks. + ``uncapped_ssi > 0`` is the PolicyEngine-US 2.2.1 current-benefit + candidate mask and does not depend on the take-up input being assigned. + """ + + period = f"{builder.PERIOD}-12" + + def calculate(active_simulation) -> np.ndarray: + values = np.asarray( + active_simulation.calculate( + "uncapped_ssi", + period=period, + map_to="person", + ), + dtype=np.float64, + ) + if not np.isfinite(values).all(): + raise RuntimeError( + "SSI take-up materialization produced nonfinite uncapped_ssi values." + ) + return values + + if simulation is not None: + return calculate(simulation) + + from policyengine_us import Microsimulation + + person_ids = frame.table("person")["person_id"].to_numpy() + uncapped = np.zeros(len(person_ids), dtype=np.float64) + person_positions = pd.Series( + np.arange(len(person_ids), dtype=np.int64), index=person_ids + ) + n_households = frame.n("household") + batches = tuple( + _main_household_position_batches(n_households, maximum_microsim_batch_size) + ) + if len(batches) > 1: + print( + "Materializing December SSI candidate amounts in " + f"{len(batches)} batches of up to " + f"{maximum_microsim_batch_size:,} households.", + flush=True, + ) + for household_positions in batches: + with _main_automatic_gc_suspended(): + full_batch = len(household_positions) == n_households + batch_frame = ( + frame + if full_batch + else _main_select_households_by_position(frame, household_positions) + ) + batch_simulation = Microsimulation( + dataset=builder._dataset_from_frame( + batch_frame, + assert_no_formula_owned_columns=False, + period_only=True, + ) + ) + batch_uncapped = calculate(batch_simulation) + positions = person_positions.reindex( + batch_frame.table("person")["person_id"].to_numpy() + ).to_numpy() + if np.isnan(positions).any(): + raise RuntimeError( + "SSI candidate batch produced person_id values not present " + "in the full person table." + ) + uncapped[positions.astype(np.int64)] = batch_uncapped + release_engine_simulation(batch_simulation) + del batch_frame, batch_simulation + _main_collect_batch_garbage() + _main_collect_family_garbage() + return uncapped + + +def main_snap_spm_unit_eligibility( + builder, + frame: Frame, + *, + simulation=None, + maximum_microsim_batch_size: int | None = DEFAULT_MAXIMUM_MICROSIM_BATCH_SIZE, +) -> np.ndarray: + """Engine-computed SPM-unit ``is_snap_eligible``, batched like Medicaid.""" + if simulation is not None: + return ( + builder._calculate_array(simulation, "is_snap_eligible", map_to="spm_unit") + > 0 + ) + from policyengine_us import Microsimulation + + spm_unit_ids = frame.table("spm_unit")["spm_unit_id"].to_numpy() + eligibility = np.zeros(len(spm_unit_ids), dtype=bool) + unit_positions = pd.Series( + np.arange(len(spm_unit_ids), dtype=np.int64), index=spm_unit_ids + ) + n_households = frame.n("household") + batches = tuple( + _main_household_position_batches(n_households, maximum_microsim_batch_size) + ) + if len(batches) > 1: + print( + "Materializing SNAP eligibility in " + f"{len(batches)} batches of up to " + f"{maximum_microsim_batch_size:,} households.", + flush=True, + ) + for household_positions in batches: + with _main_automatic_gc_suspended(): + full_batch = len(household_positions) == n_households + batch_frame = ( + frame + if full_batch + else _main_select_households_by_position(frame, household_positions) + ) + batch_simulation = Microsimulation( + dataset=builder._dataset_from_frame( + batch_frame, + assert_no_formula_owned_columns=False, + period_only=True, + ) + ) + batch_eligible = ( + builder._calculate_array( + batch_simulation, "is_snap_eligible", map_to="spm_unit" + ) + > 0 + ) + positions = unit_positions.reindex( + batch_frame.table("spm_unit")["spm_unit_id"].to_numpy() + ).to_numpy() + if np.isnan(positions).any(): + raise RuntimeError( + "SNAP eligibility batch produced spm_unit_id values not " + "present in the full spm_unit table." + ) + eligibility[positions.astype(np.int64)] = batch_eligible + release_engine_simulation(batch_simulation) + del batch_frame, batch_simulation + _main_collect_batch_garbage() + _main_collect_family_garbage() + return eligibility + + +def main_materialize( + engine: PolicyEngineUSEngine, + bundle: Frame, + variables: Sequence[str], + period: int | str, +) -> Mapping[str, np.ndarray]: + """Compute ``variables`` for ``period`` with a Microsimulation. + + Builds a dataset for ``period`` from the bundle's entity tables + (with the bundle's household weights as ``household_weight``), runs a + ``Microsimulation`` over it, and calculates each variable. The + simulation holds ``period`` alone, not policyengine-us's projection + to later years (see :meth:`_read_year_dataset`). + + Args: + bundle: A US-schema bundle. + variables: PolicyEngine variable names to compute. + period: Period to compute for (e.g. ``2026``). + + Returns: + One array per variable, row-aligned to the variable's entity + table in the bundle. + + Raises: + ImportError: If ``policyengine_us`` is not installed. + ValueError: If a computed array's length does not match its + entity table (a structural mismatch the kernel refuses to + pass through). + """ + microsimulation_class = engine._import_policyengine_us().Microsimulation + tables = engine._engine_tables(bundle) + dataset = engine._read_year_dataset(tables, period) + simulation = microsimulation_class( + dataset=dataset, + **({"spm": dict(engine._spm)} if engine._spm is not None else {}), + ) + results: dict[str, np.ndarray] = {} + for name in variables: + entity = engine._entity_of(name) + values = np.asarray(simulation.calculate(name, period=period)) + expected = bundle.n(entity) + if values.shape != (expected,): + raise ValueError( + f"Materialized variable {name!r} has shape {values.shape} " + f"but entity {entity!r} has {expected} row(s)." + ) + results[name] = values + return results + + +def main_materialize_modeled_premiums( + frame: Frame, + *, + time_period: int, + maximum_microsim_batch_size: int | None, +) -> dict[str, np.ndarray]: + """Materialize tax-unit premiums in household batches and realign by ID.""" + + household = frame.table("household") + tax_unit = frame.table("tax_unit") + person = frame.table("person") + household_ids = household["household_id"].to_numpy() + tax_unit_ids = tax_unit["tax_unit_id"].to_numpy() + tax_unit_positions = pd.Series( + np.arange(len(tax_unit_ids), dtype=np.int64), + index=tax_unit_ids, + ) + modeled = { + variable: np.zeros(len(tax_unit_ids), dtype=np.float64) + for variable in US_OTHER_HEALTH_INSURANCE_MODELED_PREMIUM_VARIABLES + } + assigned = np.zeros(len(tax_unit_ids), dtype=bool) + batch_size = ( + len(household_ids) + if maximum_microsim_batch_size is None or maximum_microsim_batch_size <= 0 + else min(int(maximum_microsim_batch_size), len(household_ids)) + ) + if batch_size == 0: + raise ValueError( + "US other-health-insurance premium materialization requires at " + "least one household." + ) + + engine = PolicyEngineUSEngine() + for start in range(0, len(household_ids), batch_size): + positions = np.arange( + start, + min(start + batch_size, len(household_ids)), + dtype=np.int64, + ) + full_batch = len(positions) == len(household_ids) + batch_frame = ( + frame + if full_batch + else frame.select( + person["person_household_id"].isin(household_ids[positions]) + ) + ) + batch_tax_unit_ids = batch_frame.table("tax_unit")["tax_unit_id"].to_numpy() + full_positions = tax_unit_positions.reindex(batch_tax_unit_ids).to_numpy() + if np.isnan(full_positions).any(): + raise ValueError( + "US other-health-insurance premium batch produced tax-unit IDs " + "outside the full frame." + ) + full_positions = full_positions.astype(np.int64) + if assigned[full_positions].any(): + raise ValueError( + "US other-health-insurance premium batches overlap tax units; " + "tax units must not span household batches." + ) + materialized = main_materialize( + engine, + batch_frame, + list(US_OTHER_HEALTH_INSURANCE_MODELED_PREMIUM_VARIABLES), + period=int(time_period), + ) + for variable in US_OTHER_HEALTH_INSURANCE_MODELED_PREMIUM_VARIABLES: + if variable not in materialized: + raise ValueError( + "PolicyEngine-US did not materialize required formula " + f"{variable!r}." + ) + values = np.asarray(materialized[variable], dtype=np.float64) + if values.shape != (len(batch_tax_unit_ids),): + raise ValueError( + f"Materialized {variable!r} has shape {values.shape}; expected " + f"{(len(batch_tax_unit_ids),)} for the tax-unit batch." + ) + modeled[variable][full_positions] = values + assigned[full_positions] = True + del materialized, batch_frame + gc.collect() + + if not assigned.all(): + missing_ids = tax_unit_ids[~assigned].tolist() + raise ValueError( + "US other-health-insurance premium batches did not cover tax-unit " + f"IDs {missing_ids}." + ) + return modeled From 158401c22ea0a703eca61199b22ead400ce11036 Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Fri, 27 Nov 2026 01:17:57 +0400 Subject: [PATCH 2/6] Refuse population aggregates in the input-stage batch loops and release their engines The release's five input-stage passes over household batches (ACA source inputs, Medicaid eligibility, December SSI amounts, SNAP eligibility and the other-health-insurance premiums) now run each batch engine in checked_batch_engine: with more than one batch, or refuse_population_aggregates=True, an engine or a branch it dropped that computed a population-aggregate variable is refused before the engine is released, and every engine is released in a finally. household_batch_plan refuses a frame whose groups span households, or whose positive medicaid_claiming_tax_unit_id points outside the household, before any engine is built, as target compilation does. The household partition, the selection, both frame checks, the branch recorder, the refusal and the three garbage-collection helpers move from the release tool into microcosm.build.us_runtime.household_batches under public names, and every reference moves to them (_collect_family_garbage is now collect_pass_garbage). Target compilation's refusals name their pass and keep their message. The PolicyEngine-US adapter gains build_microsimulation and calculate_variables, which materialize calls. The other-health premium loop calls them itself, so it checks and releases its engines, and it uses the tool's garbage-collection pattern instead of a full collection per batch. The local-area build passes refuse_population_aggregates=True to the SSI and Medicaid passes, because its donor and ACS views are each part of the population, and drops its duplicate frame checks. policyengine-us 2.2.1 reaches no population-aggregate variable in these passes; every loop's output is byte-identical to main's on the test fixtures. Also fix two assertions in the new tests: the probe's refusal lists the state cost index beside the denominator, and the stage test's stand-in for main's loop takes the new keyword. Co-Authored-By: Claude Opus 5.5 --- ...s-input-batch-aggregate-refusal.changed.md | 1 + .../build/us_runtime/household_batches.py | 395 ++++++++++++++ .../us_runtime/other_health_insurance.py | 141 +++-- .../test_us_batched_target_materialization.py | 10 +- .../us/test_us_fiscal_refresh_builder.py | 5 + .../us/test_us_other_health_insurance.py | 23 +- .../us/test_us_post_export_batch_files.py | 4 +- .../us/test_us_post_export_scoring.py | 6 +- .../test_us_batched_target_materialization.py | 13 +- .../us/test_us_input_batch_loops.py | 17 +- .../us/test_us_post_export_scoring.py | 4 +- .../frame/adapters/policyengine_us.py | 31 +- .../us_other_health_insurance.py | 44 +- .../microcosm_build/us_post_export_scoring.py | 2 +- .../us_release_head_to_head_main_baseline.py | 16 +- tools/build_us_acs_local_release.py | 26 +- tools/build_us_fiscal_refresh_release.py | 497 +++++++----------- tools/check_us_acs_county_agi_support.py | 5 +- tools/probe_us_post_export.py | 2 +- tools/score_us_release_head_to_head.py | 30 +- 20 files changed, 845 insertions(+), 427 deletions(-) create mode 100644 changelog.d/us-input-batch-aggregate-refusal.changed.md create mode 100644 packages/microcosm-build/src/microcosm/build/us_runtime/household_batches.py diff --git a/changelog.d/us-input-batch-aggregate-refusal.changed.md b/changelog.d/us-input-batch-aggregate-refusal.changed.md new file mode 100644 index 0000000000..607f1b831d --- /dev/null +++ b/changelog.d/us-input-batch-aggregate-refusal.changed.md @@ -0,0 +1 @@ +The US release's five input-stage passes over household batches (ACA source inputs, Medicaid eligibility, December SSI amounts, SNAP eligibility and the other-health-insurance premiums) now refuse a batch engine that computed a population-aggregate variable, a policyengine-us formula that sums or ranks over everyone in its engine, as target compilation already did. They also refuse, before building any engine, a frame whose groups or Medicaid claiming tax units cross households, and release every batch engine before building the next, also when a batch fails. In policyengine-us 2.2.1 none of these passes reaches a population-aggregate variable, so their outputs are byte-identical to before. The other-health-insurance premiums now release their engines too: the PolicyEngine-US adapter gains `build_microsimulation` and `calculate_variables`, which `materialize` calls, so a caller can check and release the engine it computes on. The pass runs a youngest-generation garbage collection after each batch and a full one when it ends, instead of a full collection after every batch. The local-area build switches the refusal on for its donor and ACS views even when a view fits in one chunk, because neither view is the whole population. The household partition, the selection, the frame checks, the refusal and the garbage-collection helpers move from the release tool into `microcosm.build.us_runtime.household_batches`. diff --git a/packages/microcosm-build/src/microcosm/build/us_runtime/household_batches.py b/packages/microcosm-build/src/microcosm/build/us_runtime/household_batches.py new file mode 100644 index 0000000000..b64a6807c4 --- /dev/null +++ b/packages/microcosm-build/src/microcosm/build/us_runtime/household_batches.py @@ -0,0 +1,395 @@ +"""Household batches for the US release's policyengine-us passes. + +The US release runs policyengine-us over its households one batch at a time: +the input stages (ACA source inputs, Medicaid eligibility, December SSI +amounts, SNAP eligibility and the other-health-insurance premiums), target +compilation and its reform passes, and post-export scoring. This module holds +what those passes share: + +* :func:`household_position_batches` splits the household table into + contiguous position ranges, and :func:`select_households_by_position` gives + a batch frame holding those households, their people and their groups. +* :func:`household_batch_plan` makes the ranges and runs the frame checks that + batching needs before any engine is built. A batch result can depend only on + its own households when every group entity nests in one household + (:func:`assert_group_entities_nest_in_households`) and every positive + ``medicaid_claiming_tax_unit_id`` names a tax unit in the person's own + household (:func:`assert_medicaid_claiming_tax_units_local`). +* :func:`checked_batch_engine` runs one batch on its engine and releases the + engine afterwards, also when the batch raised. With the refusal on, it first + refuses an engine that computed a population-aggregate variable + (:func:`refuse_batch_population_aggregates`), including one computed on a + branch the batch created through ``get_branch`` + (:func:`record_engine_branches`). +* :func:`automatic_gc_suspended`, :func:`collect_batch_garbage` and + :func:`collect_pass_garbage` are the garbage-collection pattern of a batch + loop: no automatic collection inside a batch, a youngest-generation + collection after it, and one full collection when the pass ends. + +A population-aggregate variable is a policyengine-us formula that sums or ranks +over every person or household in its engine +(:data:`microcosm.data.compatibility_recertification.POPULATION_AGGREGATE_VARIABLES`). +A batch engine holds one batch, so it would compute that batch's value instead +of the whole population's. The refusal is on by default when a pass has more +than one batch. A caller that hands a pass only part of the population switches +it on whatever the batch count (``refuse_population_aggregates=True``). +""" + +from __future__ import annotations + +import gc +from collections.abc import Iterable, Iterator +from contextlib import contextmanager +from dataclasses import dataclass +from types import MethodType +from typing import Any + +import numpy as np +import pandas as pd + +from microcosm.build.us_runtime.engine_lifecycle import release_engine_simulation +from microcosm.data.compatibility_recertification import ( + POPULATION_AGGREGATE_VARIABLES, + engine_known_periods, +) +from microcosm.frame import Frame + +__all__ = [ + "INPUT_PASS_POPULATION_AGGREGATE_REMEDY", + "HouseholdBatchPlan", + "assert_group_entities_nest_in_households", + "assert_medicaid_claiming_tax_units_local", + "automatic_gc_suspended", + "checked_batch_engine", + "collect_batch_garbage", + "collect_pass_garbage", + "group_to_household_positions", + "household_batch_plan", + "household_position_batches", + "record_engine_branches", + "refuse_batch_population_aggregates", + "select_households_by_position", +] + +#: How an input-stage pass's population-aggregate refusal ends. An input pass +#: writes take-up and premium inputs for every household, so no batch size +#: makes such a variable correct there. +INPUT_PASS_POPULATION_AGGREGATE_REMEDY = ( + "so the values this pass computes would depend on which households share " + "an engine. An input-stage pass must not request a variable that reaches " + "them." +) + + +def household_position_batches( + n_households: int, batch_size: int | None +) -> Iterable[np.ndarray]: + """Contiguous household position ranges of at most ``batch_size``. + + ``None``, zero, a negative size or one of at least ``n_households`` gives + one batch of every household; no households give no batches. + """ + + if n_households <= 0: + return + if batch_size is None or batch_size <= 0 or batch_size >= n_households: + yield np.arange(n_households, dtype=np.int64) + return + for start in range(0, n_households, batch_size): + stop = min(start + batch_size, n_households) + yield np.arange(start, stop, dtype=np.int64) + + +def select_households_by_position(frame: Frame, positions: np.ndarray) -> Frame: + """The households at ``positions``, with their people and groups.""" + + household_ids = frame.table("household")["household_id"].to_numpy()[positions] + person_mask = frame.table("person")["person_household_id"].isin(household_ids) + return frame.select(person_mask) + + +def group_to_household_positions(frame: Frame, group_entity: str) -> np.ndarray: + """Each ``group_entity`` row's household position in ``frame``. + + Refuses a group whose people live in more than one household, and a group + with no people. + """ + + person = frame.table("person") + household_ids = frame.table("household")["household_id"].to_numpy() + group_ids = frame.table(group_entity)[f"{group_entity}_id"].to_numpy() + person_group_column = f"person_{group_entity}_id" + + membership = person[[person_group_column, "person_household_id"]].drop_duplicates() + counts = membership.groupby(person_group_column)["person_household_id"].nunique() + ambiguous = counts[counts != 1] + if not ambiguous.empty: + raise ValueError( + f"{group_entity} units must be nested in households; ambiguous ids " + f"examples: {ambiguous.index[:5].tolist()}." + ) + group_to_household = ( + membership.drop_duplicates(person_group_column) + .set_index(person_group_column)["person_household_id"] + .reindex(group_ids) + ) + if group_to_household.isna().any(): + missing = group_ids[group_to_household.isna().to_numpy()][:5].tolist() + raise ValueError(f"{group_entity} units with no person membership: {missing}.") + household_positions = pd.Series( + np.arange(len(household_ids), dtype=np.int64), index=household_ids + ) + positions = household_positions.reindex(group_to_household.to_numpy()).to_numpy() + if np.isnan(positions).any(): + raise ValueError( + f"{group_entity} household ids are not present in household table." + ) + return positions.astype(np.int64) + + +def assert_group_entities_nest_in_households(frame: Frame) -> None: + """Refuse a frame whose group entities cross households. + + Batching selects persons by household and keeps every group they + reference, so a group spanning two batches would be simulated twice, each + time with only part of its members. ``Frame`` does not check nesting, and + :func:`group_to_household_positions` raises on exactly this. + """ + + for entity in frame.entities: + if entity in {"person", "household"}: + continue + group_to_household_positions(frame, entity) + + +def assert_medicaid_claiming_tax_units_local(frame: Frame, *, work: str) -> None: + """Require positive Medicaid claiming IDs to resolve within the household. + + The engine's claiming-tax-unit helpers join IDs across persons. Requiring + local references keeps those joins inside each household; an unresolved + positive ID is refused too, since a pre-sliced caller may have omitted it. + ``work`` names the pass in the refusal. + """ + + person = frame.table("person") + column = "medicaid_claiming_tax_unit_id" + if column not in person: + return + claims = person.loc[person[column] > 0] + if claims.empty: + return + local_units = pd.MultiIndex.from_frame( + person[["person_household_id", "person_tax_unit_id"]] + ) + claimed_units = pd.MultiIndex.from_frame(claims[["person_household_id", column]]) + if not claimed_units.isin(local_units).all(): + raise ValueError( + f"{work} is not batch-invariant: a positive " + "medicaid_claiming_tax_unit_id does not resolve within the " + "person's own household. Run the whole pool unbatched in one " + "simulation with one slice or chunk." + ) + + +@dataclass(frozen=True) +class HouseholdBatchPlan: + """A pass's household position batches and whether its refusal is on.""" + + batches: tuple[np.ndarray, ...] + refuse_population_aggregates: bool + + +def household_batch_plan( + frame: Frame, + maximum_batch_size: int | None, + *, + refuse_population_aggregates: bool | None = None, + work: str, +) -> HouseholdBatchPlan: + """Split ``frame``'s households and run the checks batching needs. + + The population-aggregate refusal is on when there is more than one batch, + unless ``refuse_population_aggregates`` says otherwise: a caller that + passes only part of the population sets it to ``True``. Before any engine + is built, a frame whose group entities span households is refused when its + households are split into more than one batch or the refusal is on, and a + positive ``medicaid_claiming_tax_unit_id`` outside the person's household + is refused when the refusal is on, as target compilation does. + """ + + batches = tuple( + household_position_batches(frame.n("household"), maximum_batch_size) + ) + batched = len(batches) > 1 + refusing = ( + batched + if refuse_population_aggregates is None + else bool(refuse_population_aggregates) + ) + if batched or refusing: + assert_group_entities_nest_in_households(frame) + if refusing: + assert_medicaid_claiming_tax_units_local(frame, work=work) + return HouseholdBatchPlan(batches=batches, refuse_population_aggregates=refusing) + + +@contextmanager +def record_engine_branches(simulation: Any) -> Iterator[None]: + """Retain branches created through get_branch until the batch is checked. + + Core's clone copies instance attributes, including a wrapped get_branch. + Rebind that method to each child before it can create its own branches. + Retained branches are released even if a formula detached them. + """ + + retained: list[object] = [] + originals: dict[int, tuple[object, object, bool]] = {} + seen: set[int] = set() + + def get_branch(current, *args, **kwargs): + branch = originals[id(current)][1](*args, **kwargs) + retain(branch) + return branch + + def retain(current): + if current is None or id(current) in seen: + return + seen.add(id(current)) + retained.append(current) + original = getattr(current, "get_branch", None) + if callable(original): + had_instance_method = "get_branch" in vars(current) + if getattr(original, "__func__", None) is get_branch: + # clone copied the parent's bound wrapper; recover the + # underlying method and bind it to the child. + _, parent_original, had_instance_method = originals[ + id(original.__self__) + ] + original = MethodType(parent_original.__func__, current) + originals[id(current)] = (current, original, had_instance_method) + current.get_branch = MethodType(get_branch, current) + branches = getattr(current, "branches", None) + if isinstance(branches, dict): + for branch in tuple(branches.values()): + retain(branch) + retain(getattr(current, "baseline", None)) + + retain(simulation) + # engine_known_periods walks this attribute. + simulation._target_materialization_branches = retained + try: + yield + finally: + for current, original, had_instance_method in originals.values(): + if had_instance_method: + current.get_branch = original + else: + del current.get_branch + for current in retained: + # Core's shallow clone also copies the retained-list reference. + if "_target_materialization_branches" in vars(current): + del current._target_materialization_branches + if current is not simulation: + release_engine_simulation(current) + + +def refuse_batch_population_aggregates( + simulation: Any, + *, + batch: int, + batches: int, + work: str, + remedy: str, +) -> None: + """Refuse any known population aggregate before releasing a batch engine. + + The check reads the periods the engine, its live branches, the branches + :func:`record_engine_branches` kept and a reform engine's ``baseline`` + hold for each population-aggregate variable. ``work`` names the pass and + ``remedy`` ends the message; it continues "here one household batch + instead of the pool, ...". + """ + + computed = sorted(engine_known_periods(simulation, POPULATION_AGGREGATE_VARIABLES)) + if not computed: + return + raise ValueError( + f"{work} is not batch-invariant: the engine for household batch " + f"{batch}/{batches} computed " + f"{', '.join(f'{variable}@{period}' for variable, period in computed)}. " + "These policyengine-us formulas aggregate over the whole simulated " + "population, here one household batch instead of the pool, " + f"{remedy}" + ) + + +@contextmanager +def checked_batch_engine( + simulation: Any, + *, + refuse_population_aggregates: bool, + batch: int, + batches: int, + work: str, + remedy: str, +) -> Iterator[Any]: + """Run one batch on ``simulation``; check it, then release it. + + With the refusal on, branches the batch creates through ``get_branch`` are + kept until the check, which runs once the batch's code has finished + without an exception and before the engine is released. The engine is + released on exit whether or not the batch raised (microcosm#456: an + engine's rules keep a reference to it, so a finished engine can outlive + the caller's last name for it). + """ + + try: + if not refuse_population_aggregates: + yield simulation + return + with record_engine_branches(simulation): + yield simulation + refuse_batch_population_aggregates( + simulation, + batch=batch, + batches=batches, + work=work, + remedy=remedy, + ) + finally: + release_engine_simulation(simulation) + + +def collect_batch_garbage() -> None: + """Keep batch loops tidy without traversing the full object graph.""" + + gc.collect(0) + + +def collect_pass_garbage() -> None: + """Full collection when a batched pass ends (microcosm#456). + + ``release_engine_simulation`` frees each batch's array mass by refcount, + but the residual simulation skeletons are cyclic, and anything promoted + past generation 0 is invisible to :func:`collect_batch_garbage` forever — + CPython's own full collections are throttled against the build's multi-GB + long-lived heap, so without an explicit sweep the skeletons accumulate + for the run's lifetime. One full collection per pass (a target family, + an input stage) is cheap next to the pass's engine work. + """ + + gc.collect() + + +@contextmanager +def automatic_gc_suspended() -> Iterator[None]: + """Avoid surprise full-graph cyclic GC inside memory-heavy PE batches.""" + + was_enabled = gc.isenabled() + if was_enabled: + gc.disable() + try: + yield + finally: + if was_enabled: + gc.enable() diff --git a/packages/microcosm-build/src/microcosm/build/us_runtime/other_health_insurance.py b/packages/microcosm-build/src/microcosm/build/us_runtime/other_health_insurance.py index c2ad1993e1..4615fc1dd6 100644 --- a/packages/microcosm-build/src/microcosm/build/us_runtime/other_health_insurance.py +++ b/packages/microcosm-build/src/microcosm/build/us_runtime/other_health_insurance.py @@ -18,7 +18,6 @@ from __future__ import annotations -import gc from importlib.resources import files from typing import Any @@ -37,6 +36,15 @@ SourceRuntimeError, run_source_stage, ) +from microcosm.build.us_runtime.household_batches import ( + INPUT_PASS_POPULATION_AGGREGATE_REMEDY, + automatic_gc_suspended, + checked_batch_engine, + collect_batch_garbage, + collect_pass_garbage, + household_batch_plan, + select_households_by_position, +) from microcosm.build.us_runtime.support_provenance import ( has_support_role_metadata, support_role_series, @@ -743,18 +751,28 @@ def _tax_unit_values_on_first_person( return allocated +#: The pass the premium loop's refusals name. +_OTHER_HEALTH_INSURANCE_PREMIUM_PASS = "The other-health-insurance premium pass" + + def _materialize_modeled_premiums( frame: Frame, *, time_period: int, maximum_microsim_batch_size: int | None, + refuse_population_aggregates: bool | None = None, ) -> dict[str, np.ndarray]: - """Materialize tax-unit premiums in household batches and realign by ID.""" + """Materialize tax-unit premiums in household batches and realign by ID. + + Each batch engine is built by the PolicyEngine-US adapter, exactly as its + ``materialize`` builds one, and runs in ``checked_batch_engine``: with more + than one batch, or ``refuse_population_aggregates=True``, an engine that + computed a population-aggregate variable is refused, and every engine is + released before the next one is built. + """ - household = frame.table("household") tax_unit = frame.table("tax_unit") - person = frame.table("person") - household_ids = household["household_id"].to_numpy() + n_households = frame.n("household") tax_unit_ids = tax_unit["tax_unit_id"].to_numpy() tax_unit_positions = pd.Series( np.arange(len(tax_unit_ids), dtype=np.int64), @@ -765,66 +783,73 @@ def _materialize_modeled_premiums( for variable in US_OTHER_HEALTH_INSURANCE_MODELED_PREMIUM_VARIABLES } assigned = np.zeros(len(tax_unit_ids), dtype=bool) - batch_size = ( - len(household_ids) - if maximum_microsim_batch_size is None or maximum_microsim_batch_size <= 0 - else min(int(maximum_microsim_batch_size), len(household_ids)) - ) - if batch_size == 0: + if n_households == 0: raise ValueError( "US other-health-insurance premium materialization requires at " "least one household." ) + plan = household_batch_plan( + frame, + maximum_microsim_batch_size, + refuse_population_aggregates=refuse_population_aggregates, + work=_OTHER_HEALTH_INSURANCE_PREMIUM_PASS, + ) + batches = plan.batches + period = int(time_period) engine = PolicyEngineUSEngine() - for start in range(0, len(household_ids), batch_size): - positions = np.arange( - start, - min(start + batch_size, len(household_ids)), - dtype=np.int64, - ) - full_batch = len(positions) == len(household_ids) - batch_frame = ( - frame - if full_batch - else frame.select( - person["person_household_id"].isin(household_ids[positions]) + for batch, positions in enumerate(batches, start=1): + with automatic_gc_suspended(): + full_batch = len(positions) == n_households + batch_frame = ( + frame if full_batch else select_households_by_position(frame, positions) ) - ) - batch_tax_unit_ids = batch_frame.table("tax_unit")["tax_unit_id"].to_numpy() - full_positions = tax_unit_positions.reindex(batch_tax_unit_ids).to_numpy() - if np.isnan(full_positions).any(): - raise ValueError( - "US other-health-insurance premium batch produced tax-unit IDs " - "outside the full frame." - ) - full_positions = full_positions.astype(np.int64) - if assigned[full_positions].any(): - raise ValueError( - "US other-health-insurance premium batches overlap tax units; " - "tax units must not span household batches." - ) - materialized = engine.materialize( - batch_frame, - list(US_OTHER_HEALTH_INSURANCE_MODELED_PREMIUM_VARIABLES), - period=int(time_period), - ) - for variable in US_OTHER_HEALTH_INSURANCE_MODELED_PREMIUM_VARIABLES: - if variable not in materialized: + batch_tax_unit_ids = batch_frame.table("tax_unit")["tax_unit_id"].to_numpy() + full_positions = tax_unit_positions.reindex(batch_tax_unit_ids).to_numpy() + if np.isnan(full_positions).any(): raise ValueError( - "PolicyEngine-US did not materialize required formula " - f"{variable!r}." + "US other-health-insurance premium batch produced tax-unit IDs " + "outside the full frame." ) - values = np.asarray(materialized[variable], dtype=np.float64) - if values.shape != (len(batch_tax_unit_ids),): + full_positions = full_positions.astype(np.int64) + if assigned[full_positions].any(): raise ValueError( - f"Materialized {variable!r} has shape {values.shape}; expected " - f"{(len(batch_tax_unit_ids),)} for the tax-unit batch." + "US other-health-insurance premium batches overlap tax units; " + "tax units must not span household batches." ) - modeled[variable][full_positions] = values - assigned[full_positions] = True - del materialized, batch_frame - gc.collect() + simulation = engine.build_microsimulation(batch_frame, period) + with checked_batch_engine( + simulation, + refuse_population_aggregates=plan.refuse_population_aggregates, + batch=batch, + batches=len(batches), + work=_OTHER_HEALTH_INSURANCE_PREMIUM_PASS, + remedy=INPUT_PASS_POPULATION_AGGREGATE_REMEDY, + ): + materialized = engine.calculate_variables( + simulation, + batch_frame, + list(US_OTHER_HEALTH_INSURANCE_MODELED_PREMIUM_VARIABLES), + period, + ) + for variable in US_OTHER_HEALTH_INSURANCE_MODELED_PREMIUM_VARIABLES: + if variable not in materialized: + raise ValueError( + "PolicyEngine-US did not materialize required formula " + f"{variable!r}." + ) + values = np.asarray(materialized[variable], dtype=np.float64) + if values.shape != (len(batch_tax_unit_ids),): + raise ValueError( + f"Materialized {variable!r} has shape {values.shape}; " + f"expected {(len(batch_tax_unit_ids),)} for the tax-unit " + "batch." + ) + modeled[variable][full_positions] = values + assigned[full_positions] = True + del materialized, batch_frame, simulation + collect_batch_garbage() + collect_pass_garbage() if not assigned.all(): missing_ids = tax_unit_ids[~assigned].tolist() @@ -842,8 +867,13 @@ def with_us_other_health_insurance_inputs( time_period: int, maximum_microsim_batch_size: int | None = None, allow_existing_without_source: bool = False, + refuse_population_aggregates: bool | None = None, ) -> Frame: - """Materialize modeled premiums, derive ASEC residuals, and impute PUF.""" + """Materialize modeled premiums, derive ASEC residuals, and impute PUF. + + ``refuse_population_aggregates`` overrides when the premium batches refuse + a population-aggregate variable (see :func:`_materialize_modeled_premiums`). + """ if frame.schema != US_SCHEMA: raise ValueError("US other-health-insurance inputs require the US schema.") @@ -871,6 +901,7 @@ def with_us_other_health_insurance_inputs( frame, time_period=int(time_period), maximum_microsim_batch_size=maximum_microsim_batch_size, + refuse_population_aggregates=refuse_population_aggregates, ) stage_person = person.copy(deep=True) for variable in US_OTHER_HEALTH_INSURANCE_MODELED_PREMIUM_VARIABLES: diff --git a/packages/microcosm-build/tests/engine_free/us/test_us_batched_target_materialization.py b/packages/microcosm-build/tests/engine_free/us/test_us_batched_target_materialization.py index 6cda417458..dfaf610354 100644 --- a/packages/microcosm-build/tests/engine_free/us/test_us_batched_target_materialization.py +++ b/packages/microcosm-build/tests/engine_free/us/test_us_batched_target_materialization.py @@ -415,7 +415,7 @@ def test_batched_reform_simulation_refuses_population_aggregates( ("target", "wrap", "message"), [ ( - "_select_households_by_position", + "select_households_by_position", # Each batch is handed the next batch's households. lambda real: lambda frame, positions: real(frame, positions + 1), "does not carry exactly its households in pool order", @@ -582,6 +582,10 @@ def engine(known, **extra): with pytest.raises( ValueError, match=r"computed medicaid_slcsp_state_denominator@2024" ): - builder._refuse_batch_population_aggregates( - root, batch=1, batches=3, n_households=6 + builder.refuse_batch_population_aggregates( + root, + batch=1, + batches=3, + work=builder.TARGET_MATERIALIZATION_PASS, + remedy=builder.TARGET_POPULATION_AGGREGATE_REMEDY, ) diff --git a/packages/microcosm-build/tests/engine_free/us/test_us_fiscal_refresh_builder.py b/packages/microcosm-build/tests/engine_free/us/test_us_fiscal_refresh_builder.py index c95b3267a6..052bfe52ff 100644 --- a/packages/microcosm-build/tests/engine_free/us/test_us_fiscal_refresh_builder.py +++ b/packages/microcosm-build/tests/engine_free/us/test_us_fiscal_refresh_builder.py @@ -11491,6 +11491,11 @@ def __init__(self, *, dataset): def _invalidate_all_caches(self): pass + def get_holder(self, variable): + # The batches are checked for population aggregates; this + # stand-in computes none. + return SimpleNamespace(get_known_periods=lambda: []) + def fake_calculate_array(simulation, variable, *, map_to=None): if map_to == "person": return np.asarray( diff --git a/packages/microcosm-build/tests/engine_free/us/test_us_other_health_insurance.py b/packages/microcosm-build/tests/engine_free/us/test_us_other_health_insurance.py index 8fdc9ed67d..c7f328b846 100644 --- a/packages/microcosm-build/tests/engine_free/us/test_us_other_health_insurance.py +++ b/packages/microcosm-build/tests/engine_free/us/test_us_other_health_insurance.py @@ -189,19 +189,14 @@ def test_modeled_premiums_batch_by_household_and_realign_tax_units( ) frame.table("person")["person_tax_unit_id"] = person_tax_unit_ids calls: list[np.ndarray] = [] + engines: list[_StandInPremiumEngine] = [] - class IdPremiumEngine: - def materialize( - self, - batch: Frame, - variables: list[str], - *, - period: int, - ) -> dict[str, np.ndarray]: - assert period == 2024 - assert variables == list( - module.US_OTHER_HEALTH_INSURANCE_MODELED_PREMIUM_VARIABLES - ) + class IdPremiumEngine(_StandInPremiumEngine): + def __init__(self) -> None: + super().__init__() + engines.append(self) + + def premiums(self, batch: Frame) -> dict[str, np.ndarray]: tax_unit_ids = batch.table("tax_unit")["tax_unit_id"].to_numpy() calls.append(tax_unit_ids.copy()) factor = tax_unit_ids.astype(np.float64) - 200.0 @@ -222,6 +217,10 @@ def materialize( assert [len(call) for call in calls] == [3, 3, 3, 1] assert set(np.concatenate(calls)) == set(range(201, 211)) + # One adapter for the stage; each batch engine was released. + (engine,) = engines + assert len(engine.simulations) == 4 + assert all(simulation.populations == {} for simulation in engine.simulations) expected_modeled = (person_tax_unit_ids - 200.0) * 6.0 np.testing.assert_allclose( result.table("person")[_OTHER], diff --git a/packages/microcosm-build/tests/engine_free/us/test_us_post_export_batch_files.py b/packages/microcosm-build/tests/engine_free/us/test_us_post_export_batch_files.py index e2a108560a..f13f6dc63f 100644 --- a/packages/microcosm-build/tests/engine_free/us/test_us_post_export_batch_files.py +++ b/packages/microcosm-build/tests/engine_free/us/test_us_post_export_batch_files.py @@ -157,8 +157,8 @@ def _expected_batches(builder, frame: Frame, batch_size: int) -> list[Frame]: return [ frame if len(positions) == frame.n("household") - else builder._select_households_by_position(frame, positions) - for positions in builder._household_position_batches( + else builder.select_households_by_position(frame, positions) + for positions in builder.household_position_batches( frame.n("household"), batch_size ) ] diff --git a/packages/microcosm-build/tests/engine_free/us/test_us_post_export_scoring.py b/packages/microcosm-build/tests/engine_free/us/test_us_post_export_scoring.py index 88434291d8..07cc284d47 100644 --- a/packages/microcosm-build/tests/engine_free/us/test_us_post_export_scoring.py +++ b/packages/microcosm-build/tests/engine_free/us/test_us_post_export_scoring.py @@ -1599,8 +1599,8 @@ def test_scorer_refuses_a_unit_that_spans_households(builder, tmp_path) -> None: # The partition check is a second line: a batch set that misses or # repeats a household is refused. batches = [ - builder._select_households_by_position(frame, np.asarray([0, 1, 2])), - builder._select_households_by_position(frame, np.asarray([2, 3, 4, 5, 6])), + builder.select_households_by_position(frame, np.asarray([0, 1, 2])), + builder.select_households_by_position(frame, np.asarray([2, 3, 4, 5, 6])), ] with pytest.raises(ValueError, match="do not partition the pool"): builder._assert_post_export_batching_premises(frame, batches) @@ -1608,7 +1608,7 @@ def test_scorer_refuses_a_unit_that_spans_households(builder, tmp_path) -> None: # Batches that partition the pool must also keep the written household # order and household weights, or the concatenated arrays would misalign. batches = [ - builder._select_households_by_position(frame, np.asarray(positions)) + builder.select_households_by_position(frame, np.asarray(positions)) for positions in ([0, 1, 2], [3, 4, 5, 6]) ] builder._assert_post_export_batching_premises(frame, batches) diff --git a/packages/microcosm-build/tests/engine_workflow/us/test_us_batched_target_materialization.py b/packages/microcosm-build/tests/engine_workflow/us/test_us_batched_target_materialization.py index 21e4f2263d..4a1064e387 100644 --- a/packages/microcosm-build/tests/engine_workflow/us/test_us_batched_target_materialization.py +++ b/packages/microcosm-build/tests/engine_workflow/us/test_us_batched_target_materialization.py @@ -56,6 +56,7 @@ def test_real_engine_batched_base_simulation_matches_unbatched(monkeypatch) -> N pd.testing.assert_frame_equal(household, unbatched, check_exact=True) assert version == unbatched_version + def test_real_engine_base_batches_build_no_system_and_release_engines( monkeypatch, ) -> None: @@ -117,6 +118,7 @@ def alive_microsimulations() -> int: for column, values in unbatched.items(): np.testing.assert_array_equal(batched[column], values) + def test_real_engine_refuses_a_batched_medicaid_cost_target() -> None: """Compare guarded materialization with unguarded one-household engines.""" @@ -150,7 +152,7 @@ def test_real_engine_refuses_a_batched_medicaid_cost_target() -> None: enrolled = 0 aggregate_periods = [] for position in range(frame.n("household")): - batch_frame = builder._select_households_by_position( + batch_frame = builder.select_households_by_position( frame, np.asarray([position], dtype=np.int64) ) simulation = Microsimulation( @@ -212,6 +214,7 @@ def test_real_engine_refuses_a_batched_medicaid_cost_target() -> None: maximum_microsim_batch_size=batch_size, ) + def test_population_aggregate_list_matches_installed_engine_sources() -> None: """Pin the guard list to weight reads and aggregation markers in US sources. @@ -306,7 +309,9 @@ def test_forward_reads_match_the_reviewed_engine_sources() -> None: } assert {name: set(evidence) for name, evidence in found.items()} == reviewed reviewed_digest = hashlib.sha256( - "\n".join(f"{name}:{source_digests[name]}" for name in sorted(reviewed)).encode() + "\n".join( + f"{name}:{source_digests[name]}" for name in sorted(reviewed) + ).encode() ).hexdigest() assert reviewed_digest == ( "4c3a61a320e3d7d57f887ba3a364293d59b9cc363e2e38e7aecd8fac13409d5e" @@ -356,7 +361,9 @@ def test_in_build_datasets_hold_period_alone_and_match_the_projection( cut = builder._dataset_from_frame( frame, assert_no_formula_owned_columns=False, period_only=True ) - projected = builder._dataset_from_frame(frame, assert_no_formula_owned_columns=False) + projected = builder._dataset_from_frame( + frame, assert_no_formula_owned_columns=False + ) assert isinstance(cut, USMultiYearDataset) assert cut.years == [builder.PERIOD] assert isinstance(projected, USSingleYearDataset) diff --git a/packages/microcosm-build/tests/engine_workflow/us/test_us_input_batch_loops.py b/packages/microcosm-build/tests/engine_workflow/us/test_us_input_batch_loops.py index cd784c0a88..fc7e66845a 100644 --- a/packages/microcosm-build/tests/engine_workflow/us/test_us_input_batch_loops.py +++ b/packages/microcosm-build/tests/engine_workflow/us/test_us_input_batch_loops.py @@ -100,10 +100,10 @@ def test_input_loop_refuses_a_batch_engine_that_computed_a_population_aggregate( message = str(refusal.value) assert message.startswith(f"{loop.pass_label} is not batch-invariant"), message - assert ( - f"household batch {batch_label} computed " - f"{POPULATION_AGGREGATE_PROBE_VARIABLE}@{builder.PERIOD}" - ) in message + assert f"household batch {batch_label} computed " in message + # The probe's variable reads the state average cost index too, so the + # refusal lists both. + assert f"{POPULATION_AGGREGATE_PROBE_VARIABLE}@{builder.PERIOD}" in message # The refusal stops the first batch, after its check and its release. assert len(recorder.engines) == 1 assert engine_released(recorder.engines[0]) @@ -231,11 +231,14 @@ def run_stage(): maximum_microsim_batch_size=5, ) + def main_premium_loop(frame, *, refuse_population_aggregates, **options): + # Main's loop has no refusal; the stage passes its default through. + assert refuse_population_aggregates is None + return main_baseline.main_materialize_modeled_premiums(frame, **options) + actual = run_stage() monkeypatch.setattr( - other_health_insurance, - "_materialize_modeled_premiums", - main_baseline.main_materialize_modeled_premiums, + other_health_insurance, "_materialize_modeled_premiums", main_premium_loop ) expected = run_stage() diff --git a/packages/microcosm-build/tests/engine_workflow/us/test_us_post_export_scoring.py b/packages/microcosm-build/tests/engine_workflow/us/test_us_post_export_scoring.py index 9a42ed32f9..6bff9f73e0 100644 --- a/packages/microcosm-build/tests/engine_workflow/us/test_us_post_export_scoring.py +++ b/packages/microcosm-build/tests/engine_workflow/us/test_us_post_export_scoring.py @@ -458,8 +458,8 @@ def test_batches_read_from_their_files_equal_the_written_h5s_batches( path = _write_engine_h5(builder, tmp_path, _GUARD_HOUSEHOLDS) written = builder._load_frame(path, expected_sha256=builder._sha256(path)) expected = [ - builder._select_households_by_position(written, positions) - for positions in builder._household_position_batches(written.n("household"), 3) + builder.select_households_by_position(written, positions) + for positions in builder.household_position_batches(written.n("household"), 3) ] scorer = builder._HouseholdBatchedPostExportScorer( path, maximum_microsim_batch_size=3 diff --git a/packages/microcosm-frame/src/microcosm/frame/adapters/policyengine_us.py b/packages/microcosm-frame/src/microcosm/frame/adapters/policyengine_us.py index 268e5fc9e9..cea5220d4f 100644 --- a/packages/microcosm-frame/src/microcosm/frame/adapters/policyengine_us.py +++ b/packages/microcosm-frame/src/microcosm/frame/adapters/policyengine_us.py @@ -952,14 +952,43 @@ def materialize( ValueError: If a computed array's length does not match its entity table (a structural mismatch the kernel refuses to pass through). + + A caller that has to inspect or release the engine afterwards calls + :meth:`build_microsimulation` and :meth:`calculate_variables` itself; + this method is those two calls. + """ + simulation = self.build_microsimulation(bundle, period) + return self.calculate_variables(simulation, bundle, variables, period) + + def build_microsimulation(self, bundle: Frame, period: int | str) -> Any: + """The ``Microsimulation`` :meth:`materialize` computes on. + + The dataset holds the bundle's entity tables for ``period`` alone, + with the bundle's household weights as ``household_weight``, and the + engine receives this adapter's SPM selection. The caller owns the + engine: it can read what the engine computed and release it. """ microsimulation_class = self._import_policyengine_us().Microsimulation tables = self._engine_tables(bundle) dataset = self._read_year_dataset(tables, period) - simulation = microsimulation_class( + return microsimulation_class( dataset=dataset, **({"spm": dict(self._spm)} if self._spm is not None else {}), ) + + def calculate_variables( + self, + simulation: Any, + bundle: Frame, + variables: Sequence[str], + period: int | str, + ) -> dict[str, np.ndarray]: + """Calculate ``variables`` for ``period`` on an engine built from ``bundle``. + + Returns one array per variable, row-aligned to the variable's entity + table in the bundle, and raises ``ValueError`` when an array's length + differs from that table's, as :meth:`materialize` does. + """ results: dict[str, np.ndarray] = {} for name in variables: entity = self._entity_of(name) diff --git a/test_support/microcosm_build/us_other_health_insurance.py b/test_support/microcosm_build/us_other_health_insurance.py index 3359f519f3..7a6e6cf150 100644 --- a/test_support/microcosm_build/us_other_health_insurance.py +++ b/test_support/microcosm_build/us_other_health_insurance.py @@ -9,6 +9,7 @@ from importlib.metadata import version from importlib.resources import files from pathlib import Path +from types import SimpleNamespace import numpy as np import pandas as pd @@ -129,21 +130,54 @@ def _frame() -> Frame: ) -class _ZeroPremiumEngine: - def materialize( +class _StandInPremiumSimulation: + """Stands in for a batch engine: it holds no population-aggregate values, + and ``release_engine_simulation`` empties its population map.""" + + def __init__(self, frame: Frame, period: int) -> None: + self.frame = frame + self.period = period + self.branches: dict[str, object] = {} + self.populations = {"person": SimpleNamespace(_holders={})} + + def get_holder(self, variable: str): + return SimpleNamespace(get_known_periods=lambda: []) + + +class _StandInPremiumEngine: + """Builds stand-in batch engines and returns :meth:`premiums` for them.""" + + def __init__(self) -> None: + self.simulations: list[_StandInPremiumSimulation] = [] + + def build_microsimulation(self, frame: Frame, period: int): + simulation = _StandInPremiumSimulation(frame, period) + self.simulations.append(simulation) + return simulation + + def calculate_variables( self, + simulation: _StandInPremiumSimulation, frame: Frame, variables: list[str], - *, period: int, ) -> dict[str, np.ndarray]: - assert period == 2024 + assert simulation.frame is frame + assert period == simulation.period == 2024 assert variables == list( module.US_OTHER_HEALTH_INSURANCE_MODELED_PREMIUM_VARIABLES ) + return self.premiums(frame) + + def premiums(self, frame: Frame) -> dict[str, np.ndarray]: + raise NotImplementedError + + +class _ZeroPremiumEngine(_StandInPremiumEngine): + def premiums(self, frame: Frame) -> dict[str, np.ndarray]: return { variable: np.zeros(frame.n("tax_unit"), dtype=np.float64) - for variable in variables + for variable in module.US_OTHER_HEALTH_INSURANCE_MODELED_PREMIUM_VARIABLES } diff --git a/test_support/microcosm_build/us_post_export_scoring.py b/test_support/microcosm_build/us_post_export_scoring.py index 0e7bd9d993..eabcf8feee 100644 --- a/test_support/microcosm_build/us_post_export_scoring.py +++ b/test_support/microcosm_build/us_post_export_scoring.py @@ -469,7 +469,7 @@ def fake_reforms(monkeypatch, builder): Full garbage collections are stubbed too; these stand-ins do not create the engine state collected between production passes. """ - monkeypatch.setattr(builder, "_collect_family_garbage", lambda: None) + monkeypatch.setattr(builder, "collect_pass_garbage", lambda: None) monkeypatch.setattr( reform_validation_module, "gc", SimpleNamespace(collect=lambda *args: 0) ) diff --git a/test_support/microcosm_build/us_release_head_to_head_main_baseline.py b/test_support/microcosm_build/us_release_head_to_head_main_baseline.py index 9fef161c8a..4b689443e1 100644 --- a/test_support/microcosm_build/us_release_head_to_head_main_baseline.py +++ b/test_support/microcosm_build/us_release_head_to_head_main_baseline.py @@ -23,6 +23,12 @@ scored_column_contract, ) +from microcosm.build.us_runtime.household_batches import ( + assert_group_entities_nest_in_households, + assert_medicaid_claiming_tax_units_local, + household_position_batches, + select_households_by_position, +) from microcosm.calibrate import score_targets from microcosm.frame import Frame @@ -47,7 +53,7 @@ def _score_chunk_household_sliced( n_households = base_frame.n("household") expected_keys = _spec_keys(chunk_specs) slice_batches = tuple( - release._household_position_batches( + household_position_batches( n_households, maximum_microsim_batch_size, ) @@ -55,8 +61,10 @@ def _score_chunk_household_sliced( if not slice_batches: raise ValueError(f"{artifact_name} has no households to score.") if len(slice_batches) > 1: - release._assert_group_entities_nest_in_households(base_frame) - release._assert_medicaid_claiming_tax_units_local(base_frame) + assert_group_entities_nest_in_households(base_frame) + assert_medicaid_claiming_tax_units_local( + base_frame, work=release.TARGET_MATERIALIZATION_PASS + ) accumulated_estimates: np.ndarray | None = None reference_targets: np.ndarray | None = None reference_scales: np.ndarray | None = None @@ -71,7 +79,7 @@ def _score_chunk_household_sliced( slice_frame = ( base_frame if full_slice - else release._select_households_by_position(base_frame, positions) + else select_households_by_position(base_frame, positions) ) slice_target_frame, slice_registry, slice_compilation = ( release._materialize_target_frame( diff --git a/tools/build_us_acs_local_release.py b/tools/build_us_acs_local_release.py index 5ee1c236fb..9b3962c8ea 100644 --- a/tools/build_us_acs_local_release.py +++ b/tools/build_us_acs_local_release.py @@ -238,6 +238,10 @@ shadow_value, tool_gate_shadows_enabled, ) +from microcosm.build.us_runtime.household_batches import ( + assert_group_entities_nest_in_households, + assert_medicaid_claiming_tax_units_local, +) from microcosm.build.us_runtime.org_wages import ( US_ORG_OCCUPATION_AND_WORK_EXPERIENCE_OUTPUT_COLUMNS, require_us_occupation_and_work_experience_inputs, @@ -1431,8 +1435,10 @@ def materialize_chunked( chunk_stats = [] n_chunks = (n_households + hh_chunk - 1) // hh_chunk if n_chunks > 1: - release_tool._assert_group_entities_nest_in_households(projected) - release_tool._assert_medicaid_claiming_tax_units_local(projected) + assert_group_entities_nest_in_households(projected) + assert_medicaid_claiming_tax_units_local( + projected, work=release_tool.TARGET_MATERIALIZATION_PASS + ) for chunk_index, low in enumerate(range(0, n_households, hh_chunk)): high = min(low + hh_chunk, n_households) started = time.time() @@ -2081,10 +2087,18 @@ def _acs_engine_values( if held: table.drop(columns=held, inplace=True) fill_reviewed_nulls(view, summary_path, period=PERIOD) - if view.n("household") > hh_chunk: - release_tool._assert_group_entities_nest_in_households(view) - release_tool._assert_medicaid_claiming_tax_units_local(view) - values = helper(view, maximum_microsim_batch_size=hh_chunk) + # The view holds the donor households or the ACS households, never the + # whole population, so a population-aggregate variable (a sum or rank + # over everyone in the engine) would cover only this view even when it + # fits in one chunk. The refusal is therefore on for every view, not only + # for views split into several chunks; switching it on also refuses a + # view whose groups or Medicaid claims cross households before any + # engine is built. + values = helper( + view, + maximum_microsim_batch_size=hh_chunk, + refuse_population_aggregates=True, + ) gc.collect() log( f"Engine pre-pass {variable}: {len(values):,} persons " diff --git a/tools/build_us_fiscal_refresh_release.py b/tools/build_us_fiscal_refresh_release.py index 7d544a5041..3b69d76ee4 100644 --- a/tools/build_us_fiscal_refresh_release.py +++ b/tools/build_us_fiscal_refresh_release.py @@ -52,7 +52,6 @@ import argparse import dataclasses -import gc import hashlib import importlib.metadata import importlib.util @@ -71,11 +70,11 @@ import uuid import weakref from collections.abc import Callable, Iterable, Iterator, Mapping, Sequence -from contextlib import contextmanager, nullcontext +from contextlib import nullcontext from datetime import UTC, datetime from importlib.resources import files as package_files from pathlib import PurePosixPath -from types import MethodType, SimpleNamespace +from types import SimpleNamespace from typing import Any import numpy as np @@ -339,6 +338,21 @@ require_authenticated_us_multispine_pool_h5, us_multispine_pool_release_receipt, ) +from microcosm.build.us_runtime.household_batches import ( + INPUT_PASS_POPULATION_AGGREGATE_REMEDY, + assert_group_entities_nest_in_households, + assert_medicaid_claiming_tax_units_local, + automatic_gc_suspended, + checked_batch_engine, + collect_batch_garbage, + collect_pass_garbage, + group_to_household_positions, + household_batch_plan, + household_position_batches, + record_engine_branches, + refuse_batch_population_aggregates, + select_households_by_position, +) from microcosm.build.us_runtime.input_mass import ( us_input_mass_parity_gate, us_input_mass_totals, @@ -714,41 +728,6 @@ class PoolReleaseIdentityMismatchError(ValueError): DEFAULT_US_FISCAL_CALIBRATION_EPOCHS = 1_500 -def _collect_batch_garbage() -> None: - """Keep batch loops tidy without traversing the full object graph.""" - - gc.collect(0) - - -def _collect_family_garbage() -> None: - """Full collection at target-family boundaries (microcosm#456). - - ``release_engine_simulation`` frees each batch's array mass by refcount, - but the residual simulation skeletons are cyclic, and anything promoted - past generation 0 is invisible to ``_collect_batch_garbage`` forever — - CPython's own full collections are throttled against the build's multi-GB - long-lived heap, so without an explicit sweep the skeletons accumulate - for the run's lifetime. One full collection per materialized family is - cheap next to the family's engine work. - """ - - gc.collect() - - -@contextmanager -def _automatic_gc_suspended(): - """Avoid surprise full-graph cyclic GC inside memory-heavy PE batches.""" - - was_enabled = gc.isenabled() - if was_enabled: - gc.disable() - try: - yield - finally: - if was_enabled: - gc.enable() - - US_BASE_PERSON_POPULATION_BENCHMARK = float(sum(CENSUS_NATIONAL_AGE_BENCHMARK.values())) US_BASE_PERSON_POPULATION_MAX_ABS_RELATIVE_ERROR = 0.25 US_BASE_PERSON_POPULATION_REPAIR_REASON = ( @@ -4261,12 +4240,26 @@ def _aca_source_tax_unit_table_from_simulation( return _with_state_take_up_rates(tax_unit, target_tables) +# The input-stage passes below run policyengine-us over household batches +# (``household_batch_plan``). Each batch engine runs in +# ``checked_batch_engine``: with more than one batch, or when a caller that +# hands over only part of the population passes +# ``refuse_population_aggregates=True``, an engine that computed a +# population-aggregate variable is refused, and every engine is released +# before the next one is built, also when its batch raised. +_ACA_SOURCE_INPUT_PASS = "The ACA source-input pass" +_MEDICAID_ELIGIBILITY_PASS = "The Medicaid eligibility pass" +_DECEMBER_SSI_PASS = "The December SSI pass" +_SNAP_ELIGIBILITY_PASS = "The SNAP eligibility pass" + + def _aca_source_tax_unit_table_batched( frame: Frame, target_tables: Mapping[str, pd.DataFrame], *, microsimulation_cls, maximum_microsim_batch_size: int | None, + refuse_population_aggregates: bool | None = None, ) -> pd.DataFrame: _assert_no_formula_owned_columns(frame) tax_unit = frame.table("tax_unit").copy() @@ -4298,9 +4291,13 @@ def _aca_source_tax_unit_table_batched( index=tax_unit["tax_unit_id"].to_numpy(), ) n_households = frame.n("household") - batches = tuple( - _household_position_batches(n_households, maximum_microsim_batch_size) + plan = household_batch_plan( + frame, + maximum_microsim_batch_size, + refuse_population_aggregates=refuse_population_aggregates, + work=_ACA_SOURCE_INPUT_PASS, ) + batches = plan.batches if len(batches) > 1: print( "Materializing ACA source inputs in " @@ -4309,13 +4306,13 @@ def _aca_source_tax_unit_table_batched( flush=True, ) - for household_positions in batches: - with _automatic_gc_suspended(): + for batch, household_positions in enumerate(batches, start=1): + with automatic_gc_suspended(): full_batch = len(household_positions) == n_households batch_frame = ( frame if full_batch - else _select_households_by_position(frame, household_positions) + else select_households_by_position(frame, household_positions) ) batch_simulation = microsimulation_cls( dataset=_dataset_from_frame( @@ -4324,11 +4321,19 @@ def _aca_source_tax_unit_table_batched( period_only=True, ) ) - batch_tax_unit = _aca_source_tax_unit_table_from_simulation( - batch_frame, - target_tables, - simulation=batch_simulation, - ) + with checked_batch_engine( + batch_simulation, + refuse_population_aggregates=plan.refuse_population_aggregates, + batch=batch, + batches=len(batches), + work=_ACA_SOURCE_INPUT_PASS, + remedy=INPUT_PASS_POPULATION_AGGREGATE_REMEDY, + ): + batch_tax_unit = _aca_source_tax_unit_table_from_simulation( + batch_frame, + target_tables, + simulation=batch_simulation, + ) full_positions = tax_unit_positions.reindex( batch_tax_unit["tax_unit_id"].to_numpy() ).to_numpy() @@ -4343,10 +4348,9 @@ def _aca_source_tax_unit_table_batched( full_positions, tax_unit.columns.get_loc(column), ] = batch_tax_unit[column].to_numpy() - release_engine_simulation(batch_simulation) del batch_tax_unit, batch_simulation, batch_frame - _collect_batch_garbage() - _collect_family_garbage() + collect_batch_garbage() + collect_pass_garbage() return _with_state_take_up_rates(tax_unit, target_tables) @@ -4502,6 +4506,7 @@ def _medicaid_person_eligibility( *, simulation=None, maximum_microsim_batch_size: int | None = DEFAULT_MAXIMUM_MICROSIM_BATCH_SIZE, + refuse_population_aggregates: bool | None = None, ) -> np.ndarray: """Engine-computed person-level ``is_medicaid_eligible``, batched like ACA.""" if simulation is not None: @@ -4514,9 +4519,13 @@ def _medicaid_person_eligibility( np.arange(len(person_ids), dtype=np.int64), index=person_ids ) n_households = frame.n("household") - batches = tuple( - _household_position_batches(n_households, maximum_microsim_batch_size) + plan = household_batch_plan( + frame, + maximum_microsim_batch_size, + refuse_population_aggregates=refuse_population_aggregates, + work=_MEDICAID_ELIGIBILITY_PASS, ) + batches = plan.batches if len(batches) > 1: print( "Materializing Medicaid eligibility in " @@ -4524,13 +4533,13 @@ def _medicaid_person_eligibility( f"{maximum_microsim_batch_size:,} households.", flush=True, ) - for household_positions in batches: - with _automatic_gc_suspended(): + for batch, household_positions in enumerate(batches, start=1): + with automatic_gc_suspended(): full_batch = len(household_positions) == n_households batch_frame = ( frame if full_batch - else _select_households_by_position(frame, household_positions) + else select_households_by_position(frame, household_positions) ) batch_simulation = Microsimulation( dataset=_dataset_from_frame( @@ -4539,12 +4548,20 @@ def _medicaid_person_eligibility( period_only=True, ) ) - batch_eligible = ( - _calculate_array( - batch_simulation, "is_medicaid_eligible", map_to="person" + with checked_batch_engine( + batch_simulation, + refuse_population_aggregates=plan.refuse_population_aggregates, + batch=batch, + batches=len(batches), + work=_MEDICAID_ELIGIBILITY_PASS, + remedy=INPUT_PASS_POPULATION_AGGREGATE_REMEDY, + ): + batch_eligible = ( + _calculate_array( + batch_simulation, "is_medicaid_eligible", map_to="person" + ) + > 0 ) - > 0 - ) positions = person_positions.reindex( batch_frame.table("person")["person_id"].to_numpy() ).to_numpy() @@ -4554,10 +4571,9 @@ def _medicaid_person_eligibility( "present in the full person table." ) eligibility[positions.astype(np.int64)] = batch_eligible - release_engine_simulation(batch_simulation) del batch_frame, batch_simulation - _collect_batch_garbage() - _collect_family_garbage() + collect_batch_garbage() + collect_pass_garbage() return eligibility @@ -4566,6 +4582,7 @@ def _ssi_person_uncapped_amount( *, simulation=None, maximum_microsim_batch_size: int | None = DEFAULT_MAXIMUM_MICROSIM_BATCH_SIZE, + refuse_population_aggregates: bool | None = None, ) -> np.ndarray: """December person-level potential federal SSI, batched like Medicaid. @@ -4602,9 +4619,13 @@ def calculate(active_simulation) -> np.ndarray: np.arange(len(person_ids), dtype=np.int64), index=person_ids ) n_households = frame.n("household") - batches = tuple( - _household_position_batches(n_households, maximum_microsim_batch_size) + plan = household_batch_plan( + frame, + maximum_microsim_batch_size, + refuse_population_aggregates=refuse_population_aggregates, + work=_DECEMBER_SSI_PASS, ) + batches = plan.batches if len(batches) > 1: print( "Materializing December SSI candidate amounts in " @@ -4612,13 +4633,13 @@ def calculate(active_simulation) -> np.ndarray: f"{maximum_microsim_batch_size:,} households.", flush=True, ) - for household_positions in batches: - with _automatic_gc_suspended(): + for batch, household_positions in enumerate(batches, start=1): + with automatic_gc_suspended(): full_batch = len(household_positions) == n_households batch_frame = ( frame if full_batch - else _select_households_by_position(frame, household_positions) + else select_households_by_position(frame, household_positions) ) batch_simulation = Microsimulation( dataset=_dataset_from_frame( @@ -4627,7 +4648,15 @@ def calculate(active_simulation) -> np.ndarray: period_only=True, ) ) - batch_uncapped = calculate(batch_simulation) + with checked_batch_engine( + batch_simulation, + refuse_population_aggregates=plan.refuse_population_aggregates, + batch=batch, + batches=len(batches), + work=_DECEMBER_SSI_PASS, + remedy=INPUT_PASS_POPULATION_AGGREGATE_REMEDY, + ): + batch_uncapped = calculate(batch_simulation) positions = person_positions.reindex( batch_frame.table("person")["person_id"].to_numpy() ).to_numpy() @@ -4637,10 +4666,9 @@ def calculate(active_simulation) -> np.ndarray: "in the full person table." ) uncapped[positions.astype(np.int64)] = batch_uncapped - release_engine_simulation(batch_simulation) del batch_frame, batch_simulation - _collect_batch_garbage() - _collect_family_garbage() + collect_batch_garbage() + collect_pass_garbage() return uncapped @@ -4806,6 +4834,7 @@ def _snap_spm_unit_eligibility( *, simulation=None, maximum_microsim_batch_size: int | None = DEFAULT_MAXIMUM_MICROSIM_BATCH_SIZE, + refuse_population_aggregates: bool | None = None, ) -> np.ndarray: """Engine-computed SPM-unit ``is_snap_eligible``, batched like Medicaid.""" if simulation is not None: @@ -4818,9 +4847,13 @@ def _snap_spm_unit_eligibility( np.arange(len(spm_unit_ids), dtype=np.int64), index=spm_unit_ids ) n_households = frame.n("household") - batches = tuple( - _household_position_batches(n_households, maximum_microsim_batch_size) + plan = household_batch_plan( + frame, + maximum_microsim_batch_size, + refuse_population_aggregates=refuse_population_aggregates, + work=_SNAP_ELIGIBILITY_PASS, ) + batches = plan.batches if len(batches) > 1: print( "Materializing SNAP eligibility in " @@ -4828,13 +4861,13 @@ def _snap_spm_unit_eligibility( f"{maximum_microsim_batch_size:,} households.", flush=True, ) - for household_positions in batches: - with _automatic_gc_suspended(): + for batch, household_positions in enumerate(batches, start=1): + with automatic_gc_suspended(): full_batch = len(household_positions) == n_households batch_frame = ( frame if full_batch - else _select_households_by_position(frame, household_positions) + else select_households_by_position(frame, household_positions) ) batch_simulation = Microsimulation( dataset=_dataset_from_frame( @@ -4843,12 +4876,20 @@ def _snap_spm_unit_eligibility( period_only=True, ) ) - batch_eligible = ( - _calculate_array( - batch_simulation, "is_snap_eligible", map_to="spm_unit" + with checked_batch_engine( + batch_simulation, + refuse_population_aggregates=plan.refuse_population_aggregates, + batch=batch, + batches=len(batches), + work=_SNAP_ELIGIBILITY_PASS, + remedy=INPUT_PASS_POPULATION_AGGREGATE_REMEDY, + ): + batch_eligible = ( + _calculate_array( + batch_simulation, "is_snap_eligible", map_to="spm_unit" + ) + > 0 ) - > 0 - ) positions = unit_positions.reindex( batch_frame.table("spm_unit")["spm_unit_id"].to_numpy() ).to_numpy() @@ -4858,10 +4899,9 @@ def _snap_spm_unit_eligibility( "present in the full spm_unit table." ) eligibility[positions.astype(np.int64)] = batch_eligible - release_engine_simulation(batch_simulation) del batch_frame, batch_simulation - _collect_batch_garbage() - _collect_family_garbage() + collect_batch_garbage() + collect_pass_garbage() return eligibility @@ -4980,40 +5020,7 @@ def _calculate_array( def _tax_unit_to_household_positions(frame: Frame) -> np.ndarray: - return _group_to_household_positions(frame, "tax_unit") - - -def _group_to_household_positions(frame: Frame, group_entity: str) -> np.ndarray: - person = frame.table("person") - household_ids = frame.table("household")["household_id"].to_numpy() - group_ids = frame.table(group_entity)[f"{group_entity}_id"].to_numpy() - person_group_column = f"person_{group_entity}_id" - - membership = person[[person_group_column, "person_household_id"]].drop_duplicates() - counts = membership.groupby(person_group_column)["person_household_id"].nunique() - ambiguous = counts[counts != 1] - if not ambiguous.empty: - raise ValueError( - f"{group_entity} units must be nested in households; ambiguous ids " - f"examples: {ambiguous.index[:5].tolist()}." - ) - group_to_household = ( - membership.drop_duplicates(person_group_column) - .set_index(person_group_column)["person_household_id"] - .reindex(group_ids) - ) - if group_to_household.isna().any(): - missing = group_ids[group_to_household.isna().to_numpy()][:5].tolist() - raise ValueError(f"{group_entity} units with no person membership: {missing}.") - household_positions = pd.Series( - np.arange(len(household_ids), dtype=np.int64), index=household_ids - ) - positions = household_positions.reindex(group_to_household.to_numpy()).to_numpy() - if np.isnan(positions).any(): - raise ValueError( - f"{group_entity} household ids are not present in household table." - ) - return positions.astype(np.int64) + return group_to_household_positions(frame, "tax_unit") def _collapse_tax_unit( @@ -5044,25 +5051,6 @@ def _collapse_person(frame: Frame, values: np.ndarray) -> np.ndarray: return out -def _household_position_batches( - n_households: int, batch_size: int | None -) -> Iterable[np.ndarray]: - if n_households <= 0: - return - if batch_size is None or batch_size <= 0 or batch_size >= n_households: - yield np.arange(n_households, dtype=np.int64) - return - for start in range(0, n_households, batch_size): - stop = min(start + batch_size, n_households) - yield np.arange(start, stop, dtype=np.int64) - - -def _select_households_by_position(frame: Frame, positions: np.ndarray) -> Frame: - household_ids = frame.table("household")["household_id"].to_numpy()[positions] - person_mask = frame.table("person")["person_household_id"].isin(household_ids) - return frame.select(person_mask) - - # --------------------------------------------------------------------------- # Household-batched post-export scoring (route A remediation, microcosm#956) # --------------------------------------------------------------------------- @@ -5129,17 +5117,29 @@ def _select_households_by_position(frame: Frame, positions: np.ndarray) -> Frame #: (``sum_by_state``) and feed ``medicaid_cost_if_enrolled``, and through it #: ``medicaid_cost``, ``medicaid`` and ``household_health_benefits``; the two #: income deciles are weighted ranks over every household or SPM unit. Batched -#: target materialization (``_refuse_batch_population_aggregates``) and -#: multi-batch post-export scoring -#: (``_assert_post_export_scoring_is_batch_invariant``) refuse an engine that -#: computed any of them. ``test_us_batched_target_materialization.py`` pins -#: this list against the installed engine's variable sources; that pattern -#: scan is a drift detector, not a proof of household locality -#: (microcosm#956). ``test_us_post_export_scoring.py`` exercises the -#: post-export Medicaid refusal on a written fixture H5. Shared with the -#: recertification tool (microcosm#1585). +#: target materialization and the input-stage passes (through +#: ``household_batches.refuse_batch_population_aggregates``) and multi-batch +#: post-export scoring (``_assert_post_export_scoring_is_batch_invariant``) +#: refuse an engine that computed any of them. +#: ``test_us_batched_target_materialization.py`` pins this list against the +#: installed engine's variable sources; that pattern scan is a drift +#: detector, not a proof of household locality (microcosm#956). +#: ``test_us_post_export_scoring.py`` exercises the post-export Medicaid +#: refusal on a written fixture H5, and ``test_us_input_batch_loops.py`` the +#: input-stage refusals. Shared with the recertification tool +#: (microcosm#1585). US_POPULATION_AGGREGATE_VARIABLES = recert.POPULATION_AGGREGATE_VARIABLES +#: The pass that target compilation's refusals name, and how its +#: population-aggregate refusal ends. +TARGET_MATERIALIZATION_PASS = "Target materialization" +TARGET_POPULATION_AGGREGATE_REMEDY = ( + "so a target that reaches them cannot be materialized in household " + "batches. Drop the target from the surface, or run the whole pool " + "unbatched in one simulation with one slice or chunk. Disabling only " + "inner batching still leaves slice- or chunk-local aggregates." +) + #: policyengine-us formulas whose value reads the engine's ``baseline`` branch, #: which a batch reform engine does not have. ``medicaid_slcsp_state_denominator`` #: holds a reform at the baseline's denominator; the others reach @@ -5577,7 +5577,7 @@ def _assert_post_export_batching_premises( for entity in US_SCHEMA.group_entities: if entity != "household": # Raises when a unit's persons sit in more than one household. - _group_to_household_positions(frame, entity) + group_to_household_positions(frame, entity) for entity in frame.entities: batched = sum(batch.n(entity) for batch in batch_frames) if batched != frame.n(entity): @@ -5636,7 +5636,7 @@ def __init__( def n_batches(self) -> int: return sum( 1 - for _ in _household_position_batches( + for _ in household_position_batches( self.n_households, self.maximum_batch_size ) ) @@ -5956,8 +5956,8 @@ def __init__( batch_frames = tuple( frame if len(positions) == self.n_households - else _select_households_by_position(frame, positions) - for positions in _household_position_batches( + else select_households_by_position(frame, positions) + for positions in household_position_batches( self.n_households, maximum_microsim_batch_size ) ) @@ -6088,7 +6088,7 @@ def close(self) -> None: self._finish_open_reform() self._batch_frames = None self._merged_baseline = None - _collect_family_garbage() + collect_pass_garbage() self._remove_batch_files() def _open_reform_for( @@ -6164,7 +6164,7 @@ def _baseline_for( # Outside the handler, so the failed pass's traceback and the # per-batch values its frame collected are no longer # referenced; a full collection frees any held in a cycle. - _collect_family_garbage() + collect_pass_garbage() return self._score(baseline_plan, label=f"{name} baseline plan"), False del self._unserved_baseline_plans[name] served = {key: self._merged_baseline[key] for key in baseline_plan} @@ -6262,7 +6262,7 @@ def _score( # Read by position: ``enumerate`` keeps its last item, so the # previous batch's frame would stay alive while the next is read. batch_frame = batches[batch - 1] - with _automatic_gc_suspended(): + with automatic_gc_suspended(): simulation = self._construct(batch_frame, reform_system=reform_system) # The engine holds its own copy of the batch; the frame read # from the batch's file is freed before the next one is read. @@ -6289,9 +6289,9 @@ def _score( # when a key raises. release_engine_simulation(simulation) del simulation, engine - _collect_batch_garbage() + collect_batch_garbage() sweep.advance(pass_name=label, batch=batch, batches=len(batches)) - _collect_family_garbage() + collect_pass_garbage() return { key: _concatenate_post_export_parts(key_parts) for key, key_parts in parts.items() @@ -6549,14 +6549,16 @@ def _reform_household_income_tax( # ``default_tax_benefit_system(reform=...)`` construction the engine ran # per batch — and hand it to every batch simulation explicitly. reform_system = microsimulation_cls.default_tax_benefit_system(reform=reform) - batches = tuple(_household_position_batches(n_households, batch_size)) + batches = tuple(household_position_batches(n_households, batch_size)) guard_armed = ( len(batches) > 1 if refuse_population_aggregates is None else refuse_population_aggregates ) if guard_armed: - _assert_medicaid_claiming_tax_units_local(base_frame) + assert_medicaid_claiming_tax_units_local( + base_frame, work=TARGET_MATERIALIZATION_PASS + ) if len(batches) > 1: print( "Materializing reform target " @@ -6565,12 +6567,12 @@ def _reform_household_income_tax( flush=True, ) for batch, household_positions in enumerate(batches, start=1): - with _automatic_gc_suspended(): + with automatic_gc_suspended(): full_batch = len(household_positions) == n_households batch_frame = ( base_frame if full_batch - else _select_households_by_position(base_frame, household_positions) + else select_households_by_position(base_frame, household_positions) ) batch_tax_unit_positions = _tax_unit_to_household_positions(batch_frame) reformed_dataset = _dataset_from_frame( @@ -6586,29 +6588,28 @@ def _reform_household_income_tax( reform=reform, ) try: - with ( - _record_engine_branches(reformed) if guard_armed else nullcontext() - ): + with record_engine_branches(reformed) if guard_armed else nullcontext(): batch_income_tax = _collapse_tax_unit( _calculate_array(reformed, "income_tax"), batch_tax_unit_positions, batch_frame.n("household"), ) if guard_armed: - _refuse_batch_population_aggregates( + refuse_batch_population_aggregates( reformed, batch=batch, batches=len(batches), - n_households=n_households, + work=TARGET_MATERIALIZATION_PASS, + remedy=TARGET_POPULATION_AGGREGATE_REMEDY, ) finally: release_engine_simulation(reformed) reform_income_tax[household_positions] = batch_income_tax del batch_income_tax, reformed, reformed_dataset, batch_frame - _collect_batch_garbage() + collect_batch_garbage() _advance_work(pass_name=reform_spec.measure, batch=batch, batches=len(batches)) del reform_system - _collect_family_garbage() + collect_pass_garbage() return reform_income_tax @@ -6675,7 +6676,7 @@ def _household_values( if entity in {"spm_unit", "family", "marital_unit"}: return _collapse_group( raw, - _group_to_household_positions(frame, entity), + group_to_household_positions(frame, entity), frame.n("household"), ) raise ValueError(f"Unsupported variable entity {entity!r} for {variable!r}.") @@ -6777,7 +6778,7 @@ def _combined_household_values( if entity in {"spm_unit", "family", "marital_unit"}: return _collapse_group( raw, - _group_to_household_positions(frame, entity), + group_to_household_positions(frame, entity), frame.n("household"), ) raise ValueError(f"Unsupported variable entity {entity!r} for {variables!r}.") @@ -7693,138 +7694,9 @@ def _base_simulation_household_columns( return columns -@contextmanager -def _record_engine_branches(simulation): - """Retain branches created through get_branch until the batch is checked. - - Core's clone copies instance attributes, including a wrapped get_branch. - Rebind that method to each child before it can create its own branches. - Retained branches are released even if a formula detached them. - """ - - retained: list[object] = [] - originals: dict[int, tuple[object, object, bool]] = {} - seen: set[int] = set() - - def get_branch(current, *args, **kwargs): - branch = originals[id(current)][1](*args, **kwargs) - retain(branch) - return branch - - def retain(current): - if current is None or id(current) in seen: - return - seen.add(id(current)) - retained.append(current) - original = getattr(current, "get_branch", None) - if callable(original): - had_instance_method = "get_branch" in vars(current) - if getattr(original, "__func__", None) is get_branch: - # clone copied the parent's bound wrapper; recover the - # underlying method and bind it to the child. - _, parent_original, had_instance_method = originals[ - id(original.__self__) - ] - original = MethodType(parent_original.__func__, current) - originals[id(current)] = (current, original, had_instance_method) - current.get_branch = MethodType(get_branch, current) - branches = getattr(current, "branches", None) - if isinstance(branches, dict): - for branch in tuple(branches.values()): - retain(branch) - retain(getattr(current, "baseline", None)) - - retain(simulation) - simulation._target_materialization_branches = retained - try: - yield - finally: - for current, original, had_instance_method in originals.values(): - if had_instance_method: - current.get_branch = original - else: - del current.get_branch - for current in retained: - # Core's shallow clone also copies the retained-list reference. - if "_target_materialization_branches" in vars(current): - del current._target_materialization_branches - if current is not simulation: - release_engine_simulation(current) - - _engine_known_periods = recert.engine_known_periods -def _refuse_batch_population_aggregates( - simulation, - *, - batch: int, - batches: int, - n_households: int, -) -> None: - """Refuse any known population aggregate before releasing a batch engine.""" - - computed = sorted( - _engine_known_periods(simulation, US_POPULATION_AGGREGATE_VARIABLES) - ) - if not computed: - return - raise ValueError( - "Target materialization is not batch-invariant: the engine for " - f"household batch {batch}/{batches} computed " - f"{', '.join(f'{variable}@{period}' for variable, period in computed)}. " - "These policyengine-us formulas aggregate over the whole simulated " - "population, here one household batch instead of the pool, so a " - "target that reaches them cannot be materialized in household batches. " - "Drop the target from the surface, or run the whole pool unbatched " - "in one simulation with one slice or chunk. Disabling only inner " - "batching still leaves slice- or chunk-local aggregates." - ) - - -def _assert_group_entities_nest_in_households(frame: Frame) -> None: - """Refuse a frame whose group entities cross households. - - Batching selects persons by household and keeps every group they - reference, so a group spanning two batches would be simulated twice, each - time with only part of its members. ``Frame`` does not check nesting, and - :func:`_group_to_household_positions` raises on exactly this. - """ - - for entity in frame.entities: - if entity in {"person", "household"}: - continue - _group_to_household_positions(frame, entity) - - -def _assert_medicaid_claiming_tax_units_local(frame: Frame) -> None: - """Require positive Medicaid claiming IDs to resolve within the household. - - The engine's claiming-tax-unit helpers join IDs across persons. Requiring - local references keeps those joins inside each household; an unresolved - positive ID is refused too, since a pre-sliced caller may have omitted it. - """ - - person = frame.table("person") - column = "medicaid_claiming_tax_unit_id" - if column not in person: - return - claims = person.loc[person[column] > 0] - if claims.empty: - return - local_units = pd.MultiIndex.from_frame( - person[["person_household_id", "person_tax_unit_id"]] - ) - claimed_units = pd.MultiIndex.from_frame(claims[["person_household_id", column]]) - if not claimed_units.isin(local_units).all(): - raise ValueError( - "Target materialization is not batch-invariant: a positive " - "medicaid_claiming_tax_unit_id does not resolve within the " - "person's own household. Run the whole pool unbatched in one " - "simulation with one slice or chunk." - ) - - def _materialize_base_simulation_columns( base_frame: Frame, target_specs: tuple, @@ -7854,7 +7726,7 @@ def _materialize_base_simulation_columns( n_households = base_frame.n("household") household_ids = base_frame.table("household")["household_id"].to_numpy() batches = tuple( - _household_position_batches(n_households, maximum_microsim_batch_size) + household_position_batches(n_households, maximum_microsim_batch_size) ) if not batches: raise ValueError("Target materialization requires at least one household.") @@ -7865,9 +7737,11 @@ def _materialize_base_simulation_columns( else refuse_population_aggregates ) if batched or guard_armed: - _assert_group_entities_nest_in_households(base_frame) + assert_group_entities_nest_in_households(base_frame) if guard_armed: - _assert_medicaid_claiming_tax_units_local(base_frame) + assert_medicaid_claiming_tax_units_local( + base_frame, work=TARGET_MATERIALIZATION_PASS + ) if batched: print( "Materializing base target columns in " @@ -7879,12 +7753,12 @@ def _materialize_base_simulation_columns( column_order: tuple[str, ...] | None = None columns: dict[str, np.ndarray] = {} for batch, household_positions in enumerate(batches, start=1): - with _automatic_gc_suspended(): + with automatic_gc_suspended(): full_batch = len(household_positions) == n_households batch_frame = ( base_frame if full_batch - else _select_households_by_position(base_frame, household_positions) + else select_households_by_position(base_frame, household_positions) ) if not np.array_equal( batch_frame.table("household")["household_id"].to_numpy(), @@ -7904,7 +7778,7 @@ def _materialize_base_simulation_columns( ) try: with ( - _record_engine_branches(batch_simulation) + record_engine_branches(batch_simulation) if guard_armed else nullcontext() ): @@ -7916,11 +7790,12 @@ def _materialize_base_simulation_columns( ) if guard_armed: # Before the release below drops the engine's holders. - _refuse_batch_population_aggregates( + refuse_batch_population_aggregates( batch_simulation, batch=batch, batches=len(batches), - n_households=n_households, + work=TARGET_MATERIALIZATION_PASS, + remedy=TARGET_POPULATION_AGGREGATE_REMEDY, ) finally: # microcosm#456: an engine's system keeps a ``simulation`` @@ -7961,9 +7836,9 @@ def _materialize_base_simulation_columns( pool_values[household_positions] = values columns[column] = pool_values del batch_columns, batch_frame - _collect_batch_garbage() + collect_batch_garbage() _advance_work(pass_name="base", batch=batch, batches=len(batches)) - _collect_family_garbage() + collect_pass_garbage() assert column_order is not None receipt: dict[str, object] = { @@ -8017,7 +7892,7 @@ def _materialize_target_frame( for spec in US_JCT_TAX_EXPENDITURE_REFORMS ) batch_count = len( - tuple(_household_position_batches(n_households, maximum_microsim_batch_size)) + tuple(household_position_batches(n_households, maximum_microsim_batch_size)) ) _ACTIVE_WORK = _WorkCounter( stage_id="target_compilation", @@ -8144,7 +8019,7 @@ def _materialize_target_frame( entries.append(cache_entry) hh[reform_spec.measure] = reform_income_tax - base_income_tax_household del reform_income_tax - _collect_batch_garbage() + collect_batch_garbage() target_frame = Frame( materialized, diff --git a/tools/check_us_acs_county_agi_support.py b/tools/check_us_acs_county_agi_support.py index 905ac73c26..e384ece652 100644 --- a/tools/check_us_acs_county_agi_support.py +++ b/tools/check_us_acs_county_agi_support.py @@ -93,6 +93,9 @@ 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.build.us_runtime.household_batches import ( # noqa: E402 + assert_group_entities_nest_in_households, +) from microcosm.frame import Frame # noqa: E402 TOOL = "tools/check_us_acs_county_agi_support.py" @@ -244,7 +247,7 @@ def household_agi( 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) + 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): diff --git a/tools/probe_us_post_export.py b/tools/probe_us_post_export.py index bb0f3268dc..991f483a3a 100644 --- a/tools/probe_us_post_export.py +++ b/tools/probe_us_post_export.py @@ -648,7 +648,7 @@ def choose_batch_size( ) -> int: """The largest batch size up to ``requested`` giving ``minimum_batches``. - ``_household_position_batches`` cuts ``n`` households into + ``household_batches.household_position_batches`` cuts ``n`` households into ``ceil(n / size)`` batches, which is at least ``m`` exactly when ``size < n / (m - 1)``; the largest such size is ``ceil(n / (m - 1)) - 1`` (``n`` itself when ``m`` is 1). ``ceil(n / m)`` is not enough: four diff --git a/tools/score_us_release_head_to_head.py b/tools/score_us_release_head_to_head.py index 2eabc7117d..f9637cf8a3 100644 --- a/tools/score_us_release_head_to_head.py +++ b/tools/score_us_release_head_to_head.py @@ -29,8 +29,8 @@ the same two-axis decomposition through unmodified canonical calls: * households are sliced with the production reform-sweep batching machinery - (`_household_position_batches` + `_select_households_by_position`, - tools/build_us_fiscal_refresh_release.py:3730-3750), and each slice is + (`household_position_batches` + `select_households_by_position`, + microcosm.build.us_runtime.household_batches), and each slice is materialized and scored through the canonical calls before it is freed; * registry specs are scored in fixed contiguous chunks. A chunk's estimates are additive matrix products, so slice estimates are accumulated in fixed @@ -90,6 +90,12 @@ load_authenticated_us_multispine_pool_for_scoring, read_nullable_us_h5_metadata, ) +from microcosm.build.us_runtime.household_batches import ( + assert_group_entities_nest_in_households, + assert_medicaid_claiming_tax_units_local, + household_position_batches, + select_households_by_position, +) from microcosm.build.us_runtime.multispine_pool import ( materialize_multispine_agreement_outputs, ) @@ -886,7 +892,7 @@ def _score_household_slice( slice_frame = ( base_frame if full_slice - else release._select_households_by_position(base_frame, positions) + else select_households_by_position(base_frame, positions) ) slice_target_frame, slice_registry, slice_compilation = ( release._materialize_target_frame( @@ -994,7 +1000,7 @@ def _score_chunk_household_sliced( """Materialize and score slices, reducing in the original sequential order.""" slice_batches = tuple( - release._household_position_batches( + household_position_batches( base_frame.n("household"), maximum_microsim_batch_size, ) @@ -1002,8 +1008,10 @@ def _score_chunk_household_sliced( if not slice_batches: raise ValueError(f"{artifact_name} has no households to score.") if len(slice_batches) > 1: - release._assert_group_entities_nest_in_households(base_frame) - release._assert_medicaid_claiming_tax_units_local(base_frame) + assert_group_entities_nest_in_households(base_frame) + assert_medicaid_claiming_tax_units_local( + base_frame, work=release.TARGET_MATERIALIZATION_PASS + ) def scored_slices() -> Iterator[ScoredSlice]: for slice_index, positions in enumerate(slice_batches): @@ -1053,7 +1061,7 @@ def _initialize_slice_worker( """ slice_batches = tuple( - release._household_position_batches( + household_position_batches( base_frame.n("household"), maximum_microsim_batch_size ) ) @@ -1223,7 +1231,7 @@ def _score_chunks_parallel( slice_count = len( tuple( - release._household_position_batches( + household_position_batches( base_frame.n("household"), maximum_microsim_batch_size ) ) @@ -1231,8 +1239,10 @@ def _score_chunks_parallel( if not slice_count: raise ValueError(f"{artifact_name} has no households to score.") if slice_count > 1: - release._assert_group_entities_nest_in_households(base_frame) - release._assert_medicaid_claiming_tax_units_local(base_frame) + assert_group_entities_nest_in_households(base_frame) + assert_medicaid_claiming_tax_units_local( + base_frame, work=release.TARGET_MATERIALIZATION_PASS + ) chunk_size = MATERIALIZE_SCORE_CHUNK_SPECS chunk_count = max(1, math.ceil(len(specs) / chunk_size)) # Tasks span chunk boundaries so short chunks still use the pool. From 19a70fdccae36c531ba9dbece2ff6f1cc194e34e Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Fri, 27 Nov 2026 01:34:07 +0400 Subject: [PATCH 3/6] Make the input-loop tests catch placement, dtype and garbage-collection changes Review round 1 found that the byte-identity tests could pass while the behavior they name was broken: - assert_same_bytes compared NumPy dtypes after to_numpy(), which drops a pandas extension dtype, and accepted a Series in place of an array. It now compares container types and pandas dtypes too. - The fixture's rows were in household order, so a loop that placed batch results at a running row offset instead of by id wrote the same bytes. The identity tests now use input_loop_identity_frame: group ids run against household order, person rows are reversed, weights differ, and a New York family, reported premiums and ACA target tables make every compared array hold more than one value (medicaid_premium is zero everywhere in policyengine-us 2.2.1). - Nothing tested the other-health loop's garbage-collection pattern; an engine-free test now does. The adapter test's docstring now says that it checks the split's contract, and that the comparison with main's materialize is the other-health byte-identity test. Co-Authored-By: Claude Opus 5.5 --- .../us/test_us_other_health_insurance.py | 29 ++++ .../us/test_us_input_batch_loops.py | 15 +- .../us/test_policyengine_us_adapter.py | 9 +- .../microcosm_build/us_input_batch_loops.py | 136 +++++++++++++++--- 4 files changed, 161 insertions(+), 28 deletions(-) diff --git a/packages/microcosm-build/tests/engine_free/us/test_us_other_health_insurance.py b/packages/microcosm-build/tests/engine_free/us/test_us_other_health_insurance.py index c7f328b846..27ff4e6d32 100644 --- a/packages/microcosm-build/tests/engine_free/us/test_us_other_health_insurance.py +++ b/packages/microcosm-build/tests/engine_free/us/test_us_other_health_insurance.py @@ -230,6 +230,35 @@ def premiums(self, batch: Frame) -> dict[str, np.ndarray]: assert gate.passed, gate.failures +def test_premium_batches_collect_garbage_like_the_release_tools_loops( + monkeypatch: pytest.MonkeyPatch, +) -> None: + """Automatic collection is off inside each batch, a youngest-generation + collection follows each batch, and one full collection ends the pass.""" + + import gc + + automatic_collection_in_batches: list[bool] = [] + collections: list[tuple] = [] + + class RecordingEngine(_ZeroPremiumEngine): + def premiums(self, batch: Frame) -> dict[str, np.ndarray]: + automatic_collection_in_batches.append(gc.isenabled()) + return super().premiums(batch) + + monkeypatch.setattr(module, "PolicyEngineUSEngine", RecordingEngine) + monkeypatch.setattr(gc, "collect", lambda *args: collections.append(args) or 0) + assert gc.isenabled() + + module._materialize_modeled_premiums( + _frame(), time_period=2024, maximum_microsim_batch_size=3 + ) + + assert automatic_collection_in_batches == [False] * 4 + assert collections == [(0,)] * 4 + [()] + assert gc.isenabled() + + def test_joint_qrf_replaces_only_puf_and_does_not_invent_clipping( monkeypatch: pytest.MonkeyPatch, ) -> None: diff --git a/packages/microcosm-build/tests/engine_workflow/us/test_us_input_batch_loops.py b/packages/microcosm-build/tests/engine_workflow/us/test_us_input_batch_loops.py index fc7e66845a..99d1054fff 100644 --- a/packages/microcosm-build/tests/engine_workflow/us/test_us_input_batch_loops.py +++ b/packages/microcosm-build/tests/engine_workflow/us/test_us_input_batch_loops.py @@ -11,6 +11,7 @@ from __future__ import annotations +import numpy as np import pytest from test_support.microcosm_build.us_input_batch_loops import ( @@ -20,6 +21,7 @@ BatchEngineRecorder, assert_same_bytes, engine_released, + input_loop_identity_frame, load_builder_module, medicaid_claim_outside_household_frame, real_engine_frame, @@ -45,18 +47,19 @@ def _options(batch_size, refuse_population_aggregates): def test_input_loop_writes_mains_bytes_and_releases_each_batch_engine( builder, loop, monkeypatch ) -> None: - """One batch and two batches of two households: the same arrays, dtypes - and column order as main's loop, and each engine released before the - next is built.""" + """One batch, and batches of two households over rows out of household + order: the same arrays, dtypes and column order as main's loop, and each + engine released before the next is built.""" - frame = real_engine_frame() - for batch_size, expected_engines in ((None, 1), (2, 2)): + frame = input_loop_identity_frame() + for batch_size, expected_engines in ((None, 1), (2, 3)): expected = loop.run_main(builder, frame, maximum_microsim_batch_size=batch_size) recorder = BatchEngineRecorder(monkeypatch, period=builder.PERIOD) actual = loop.run(builder, frame, maximum_microsim_batch_size=batch_size) monkeypatch.undo() - assert loop.reaches_engine_values(expected), loop.name + for name, values in loop.engine_value_arrays(expected).items(): + assert len(set(np.asarray(values).tolist())) > 1, (loop.name, name) assert_same_bytes( actual, expected, label=f"{loop.name}, batch size {batch_size}" ) diff --git a/packages/microcosm-frame/tests/engine_workflow/us/test_policyengine_us_adapter.py b/packages/microcosm-frame/tests/engine_workflow/us/test_policyengine_us_adapter.py index 966ccaeebc..afeccf3a11 100644 --- a/packages/microcosm-frame/tests/engine_workflow/us/test_policyengine_us_adapter.py +++ b/packages/microcosm-frame/tests/engine_workflow/us/test_policyengine_us_adapter.py @@ -205,8 +205,13 @@ def test_materializes_row_aligned_arrays(self, adapter, us_bundle) -> None: def test_a_caller_owned_engine_gives_materializes_arrays( self, adapter, us_bundle ) -> None: - """A caller that must check or release the engine builds it itself; - the engine holds the period alone and gives materialize's bytes.""" + """A caller that must check or release the engine builds it itself. + + ``materialize`` is these two calls, so the byte comparison checks the + split's contract, not main's code; the comparison with main's + ``materialize`` is microcosm-build's other-health byte-identity test. + The engine holds the period alone. + """ variables = ["employment_income", "household_net_income", "aca_ptc"] expected = adapter.materialize(us_bundle, variables, period=2024) diff --git a/test_support/microcosm_build/us_input_batch_loops.py b/test_support/microcosm_build/us_input_batch_loops.py index 9ac6212210..af93bde5ad 100644 --- a/test_support/microcosm_build/us_input_batch_loops.py +++ b/test_support/microcosm_build/us_input_batch_loops.py @@ -50,6 +50,80 @@ def real_engine_frame() -> Frame: return _real_engine_frame() +def input_loop_identity_frame() -> Frame: + """Five households over three states whose rows are out of household order. + + Group ids run against household order (household 1 holds the highest tax + unit, SPM unit, family and marital unit ids, so the sorted group tables + list it last), and the person rows are reversed. A loop that placed a + batch's results at a running row offset, instead of by id, writes other + bytes than main's. Household 5 is a New York parent with two children, so + the CHIP premium is nonzero; three people report non-Medicare premiums; + household weights differ. + """ + + household = np.asarray([1, 1, 2, 3, 3, 3, 4, 5, 5, 5], dtype="int64") + reverse_household = 6 - household + person = pd.DataFrame( + { + "person_id": np.arange(1, 11, dtype="int64"), + "person_household_id": household, + "person_tax_unit_id": reverse_household * 10 + + np.asarray([0, 1, 0, 0, 1, 2, 0, 0, 0, 0]), + "person_spm_unit_id": reverse_household * 100 + + np.asarray([0, 0, 0, 0, 0, 1, 0, 0, 0, 0]), + "person_family_id": reverse_household * 1_000 + + np.asarray([0, 0, 0, 0, 0, 1, 0, 0, 0, 0]), + "person_marital_unit_id": reverse_household * 10_000 + + np.asarray([0, 1, 0, 0, 1, 2, 0, 0, 1, 2]), + "age": np.asarray( + [34.0, 71.0, 45.0, 29.0, 67.0, 19.0, 52.0, 35.0, 6.0, 10.0] + ), + "employment_income_before_lsr": np.asarray( + [48_000.0, 0.0, 180_000.0, 9_000.0, 0.0, 14_000.0, 72_000.0, 62_000.0] + + [0.0, 0.0] + ), + "health_insurance_premiums_without_medicare_part_b": np.asarray( + [1_200.0, 0.0, 0.0, 2_400.0, 0.0, 0.0, 0.0, 3_600.0, 0.0, 0.0] + ), + } + ) + tables = {"person": person.iloc[::-1].reset_index(drop=True)} + for entity in ("tax_unit", "spm_unit", "family", "marital_unit"): + ids = np.unique(person[f"person_{entity}_id"].to_numpy()) + tables[entity] = pd.DataFrame({f"{entity}_id": ids}) + tables["household"] = pd.DataFrame( + { + "household_id": np.arange(1, 6, dtype="int64"), + "state_fips": np.asarray([6, 36, 24, 6, 36], dtype="int64"), + } + ) + return Frame( + tables, + US_SCHEMA, + { + "household": Weights( + np.asarray([3.0, 1.0, 5.0, 2.0, 4.0]), WeightKind.DESIGN + ) + }, + ) + + +def aca_target_tables(builder) -> dict[str, pd.DataFrame]: + """CMS APTC recipients in two of the frame's states, plus the bronze + consumer table, whose presence switches the source table to person-count + weights, so the take-up rates and weights carry values.""" + + return { + builder.US_ACA_APTC_TARGET_TABLE: pd.DataFrame( + {"state_fips": ["06", "36"], "target": [2.0, 1.5]} + ), + "cms_aca_bronze_aptc_consumers_by_state": pd.DataFrame( + {"state_fips": ["06"], "target": [1.0]} + ), + } + + def _rebuilt_frame(frame: Frame, tables: dict[str, pd.DataFrame]) -> Frame: return Frame( tables, @@ -99,7 +173,10 @@ def _microsimulation_class(): def _run_aca(builder, frame: Frame, **options): return builder._aca_source_tax_unit_table_batched( - frame, {}, microsimulation_cls=_microsimulation_class(), **options + frame, + aca_target_tables(builder), + microsimulation_cls=_microsimulation_class(), + **options, ) @@ -107,7 +184,7 @@ def _run_main_aca(builder, frame: Frame, *, maximum_microsim_batch_size): return main_baseline.main_aca_source_tax_unit_table_batched( builder, frame, - {}, + aca_target_tables(builder), microsimulation_cls=_microsimulation_class(), maximum_microsim_batch_size=maximum_microsim_batch_size, ) @@ -139,9 +216,10 @@ class InputLoop: pass_label: str run: Callable run_main: Callable - #: Whether an output carries a nonzero engine value, so a byte comparison - #: of it compares engine results and not only zero fills. - reaches_engine_values: Callable[[object], bool] + #: The output's arrays that :func:`input_loop_identity_frame` must make + #: carry engine values (not only zero fills), so a byte comparison compares + #: engine results; each must hold two different values. + engine_value_arrays: Callable[[object], dict[str, np.ndarray]] INPUT_LOOPS = ( @@ -151,9 +229,18 @@ class InputLoop: pass_label="The ACA source-input pass", run=_run_aca, run_main=_run_main_aca, - reaches_engine_values=lambda output: bool( - output["assigned_aca_ptc"].to_numpy().any() - ), + engine_value_arrays=lambda output: { + column: output[column].to_numpy() + for column in ( + "tax_unit_weight", + "is_aca_ptc_eligible", + "health_insurance_premiums_without_medicare_part_b", + "assigned_aca_ptc", + "weighted_assigned_aca_ptc", + "slcsp", + "aca_take_up_rate", + ) + }, ), InputLoop( name="medicaid_eligibility", @@ -165,7 +252,7 @@ class InputLoop: run_main=lambda builder, frame, **options: ( main_baseline.main_medicaid_person_eligibility(builder, frame, **options) ), - reaches_engine_values=lambda output: bool(np.asarray(output).any()), + engine_value_arrays=lambda output: {"is_medicaid_eligible": output}, ), InputLoop( name="december_ssi_amounts", @@ -177,7 +264,7 @@ class InputLoop: run_main=lambda builder, frame, **options: ( main_baseline.main_ssi_person_uncapped_amount(builder, frame, **options) ), - reaches_engine_values=lambda output: bool((np.asarray(output) > 0).any()), + engine_value_arrays=lambda output: {"uncapped_ssi": output}, ), InputLoop( name="snap_eligibility", @@ -189,7 +276,7 @@ class InputLoop: run_main=lambda builder, frame, **options: ( main_baseline.main_snap_spm_unit_eligibility(builder, frame, **options) ), - reaches_engine_values=lambda output: bool(np.asarray(output).any()), + engine_value_arrays=lambda output: {"is_snap_eligible": output}, ), InputLoop( name="other_health_insurance_premiums", @@ -197,9 +284,12 @@ class InputLoop: pass_label="The other-health-insurance premium pass", run=_run_other_health, run_main=_run_main_other_health, - reaches_engine_values=lambda output: bool( - np.asarray(output["marketplace_net_premium"]).any() - ), + # medicaid_premium is zero for everyone in policyengine-us 2.2.1's + # current-year schedules; the CHIP and marketplace premiums differ. + engine_value_arrays=lambda output: { + variable: output[variable] + for variable in ("chip_premium", "marketplace_net_premium") + }, ), ) @@ -270,6 +360,11 @@ def calculate(self, variable_name, *args, **kwargs): def _assert_same_array_bytes(actual, expected, *, label: str) -> None: + assert type(actual) is type(expected), (label, type(actual), type(expected)) + if isinstance(expected, pd.Series): + # to_numpy() drops a pandas extension dtype (str, category, Int64). + assert actual.dtype == expected.dtype, (label, actual.dtype, expected.dtype) + pd.testing.assert_index_equal(actual.index, expected.index, exact=True) actual = np.asarray(actual) expected = np.asarray(expected) assert actual.dtype == expected.dtype, (label, actual.dtype, expected.dtype) @@ -285,21 +380,20 @@ def _assert_same_array_bytes(actual, expected, *, label: str) -> None: def assert_same_bytes(actual, expected, *, label: str) -> None: - """Every array, column, dtype, index and column order is identical.""" + """The same container types, and every array, column, pandas and NumPy + dtype, index and column order identical.""" + assert type(actual) is type(expected), (label, type(actual), type(expected)) if isinstance(expected, pd.DataFrame): - assert isinstance(actual, pd.DataFrame), label assert list(actual.columns) == list(expected.columns), label + pd.testing.assert_series_equal(actual.dtypes, expected.dtypes, obj=label) pd.testing.assert_index_equal(actual.index, expected.index, exact=True) for column in expected.columns: _assert_same_array_bytes( - actual[column].to_numpy(), - expected[column].to_numpy(), - label=f"{label}: {column}", + actual[column], expected[column], label=f"{label}: {column}" ) return if isinstance(expected, dict): - assert isinstance(actual, dict), label assert list(actual) == list(expected), label for key, values in expected.items(): _assert_same_array_bytes(actual[key], values, label=f"{label}: {key}") @@ -314,7 +408,9 @@ def assert_same_bytes(actual, expected, *, label: str) -> None: "BatchEngineRecorder", "InputLoop", "assert_same_bytes", + "aca_target_tables", "engine_released", + "input_loop_identity_frame", "load_builder_module", "medicaid_claim_outside_household_frame", "real_engine_frame", From 7c61a3e20b2d1f516b0f82e7b5cdfe7cc259729d Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Fri, 27 Nov 2026 01:49:57 +0400 Subject: [PATCH 4/6] Test the other-health stage's refusal switch and state the changelog's conditions Review round 2: no test passed refuse_population_aggregates=True through with_us_other_health_insurance_inputs, so dropping the forwarding would have passed. An engine-free test now runs the stage in one batch with an engine that holds a population aggregate: kept by default, refused with the switch on. The changelog fragment now says when the refusal and the frame checks run, and that the claiming-ID check refuses an ID that names no tax unit in the household. Co-Authored-By: Claude Opus 5.5 --- ...s-input-batch-aggregate-refusal.changed.md | 2 +- .../us/test_us_other_health_insurance.py | 42 +++++++++++++++++++ 2 files changed, 43 insertions(+), 1 deletion(-) diff --git a/changelog.d/us-input-batch-aggregate-refusal.changed.md b/changelog.d/us-input-batch-aggregate-refusal.changed.md index 607f1b831d..faac6f420c 100644 --- a/changelog.d/us-input-batch-aggregate-refusal.changed.md +++ b/changelog.d/us-input-batch-aggregate-refusal.changed.md @@ -1 +1 @@ -The US release's five input-stage passes over household batches (ACA source inputs, Medicaid eligibility, December SSI amounts, SNAP eligibility and the other-health-insurance premiums) now refuse a batch engine that computed a population-aggregate variable, a policyengine-us formula that sums or ranks over everyone in its engine, as target compilation already did. They also refuse, before building any engine, a frame whose groups or Medicaid claiming tax units cross households, and release every batch engine before building the next, also when a batch fails. In policyengine-us 2.2.1 none of these passes reaches a population-aggregate variable, so their outputs are byte-identical to before. The other-health-insurance premiums now release their engines too: the PolicyEngine-US adapter gains `build_microsimulation` and `calculate_variables`, which `materialize` calls, so a caller can check and release the engine it computes on. The pass runs a youngest-generation garbage collection after each batch and a full one when it ends, instead of a full collection after every batch. The local-area build switches the refusal on for its donor and ACS views even when a view fits in one chunk, because neither view is the whole population. The household partition, the selection, the frame checks, the refusal and the garbage-collection helpers move from the release tool into `microcosm.build.us_runtime.household_batches`. +The US release's five input-stage passes over household batches (ACA source inputs, Medicaid eligibility, December SSI amounts, SNAP eligibility and the other-health-insurance premiums) now refuse a batch engine that computed a population-aggregate variable, a policyengine-us formula that sums or ranks over everyone in its engine, as target compilation already did. The refusal is on when a pass splits its households into more than one batch, or when a caller passes `refuse_population_aggregates=True`; a pass that runs the whole pool in one batch keeps it off. Before building any engine, a pass with more than one batch or the refusal on also refuses a frame whose groups span households, and a pass with the refusal on refuses a positive Medicaid claiming tax unit ID that names no tax unit in the person's own household. Every batch engine is released before the next one is built, also when a batch fails. In policyengine-us 2.2.1 none of these passes reaches a population-aggregate variable, so their outputs are byte-identical to before. The other-health-insurance premiums now release their engines too: the PolicyEngine-US adapter gains `build_microsimulation` and `calculate_variables`, which `materialize` calls, so a caller can check and release the engine it computes on. That pass runs a youngest-generation garbage collection after each batch and a full one when it ends, instead of a full collection after every batch. The local-area build switches the refusal on for its donor and ACS views even when a view fits in one chunk, because neither view is the whole population. The household partition, the selection, the frame checks, the refusal and the garbage-collection helpers move from the release tool into `microcosm.build.us_runtime.household_batches`. diff --git a/packages/microcosm-build/tests/engine_free/us/test_us_other_health_insurance.py b/packages/microcosm-build/tests/engine_free/us/test_us_other_health_insurance.py index 27ff4e6d32..e7443c2aa4 100644 --- a/packages/microcosm-build/tests/engine_free/us/test_us_other_health_insurance.py +++ b/packages/microcosm-build/tests/engine_free/us/test_us_other_health_insurance.py @@ -259,6 +259,48 @@ def premiums(self, batch: Frame) -> dict[str, np.ndarray]: assert gc.isenabled() +@pytest.mark.parametrize("refuse_population_aggregates", [None, True]) +def test_stage_passes_the_refusal_switch_to_its_premium_batches( + monkeypatch: pytest.MonkeyPatch, refuse_population_aggregates +) -> None: + """One batch holds the whole pool, so by default its engine may hold a + population aggregate; a caller that switches the refusal on through the + stage gets it refused.""" + + class AggregateEngine(_ZeroPremiumEngine): + def build_microsimulation(self, frame: Frame, period: int): + simulation = super().build_microsimulation(frame, period) + simulation.get_holder = lambda variable: SimpleNamespace( + get_known_periods=lambda: ( + ["2024"] if variable == "medicaid_slcsp_state_denominator" else [] + ) + ) + return simulation + + monkeypatch.setattr(module, "PolicyEngineUSEngine", AggregateEngine) + + def run_stage(): + return with_us_other_health_insurance_inputs( + _frame(), + seed=0, + time_period=2024, + refuse_population_aggregates=refuse_population_aggregates, + ) + + if refuse_population_aggregates: + with pytest.raises( + ValueError, + match=( + "^The other-health-insurance premium pass is not batch-invariant: " + "the engine for household batch 1/1 computed " + "medicaid_slcsp_state_denominator@2024" + ), + ): + run_stage() + else: + run_stage() + + def test_joint_qrf_replaces_only_puf_and_does_not_invent_clipping( monkeypatch: pytest.MonkeyPatch, ) -> None: From 33cf43235f9796239c0e000cf3ae5fc6316c5962 Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Fri, 27 Nov 2026 17:54:50 +0400 Subject: [PATCH 5/6] Classify household_batches and re-pin the US seed protocol digests CI failures on #1776: - test_us_runtime_module_classification_is_complete requires every us_runtime module to be classified; household_batches.py is now listed with the reviewed non-registry modules (it applies no population treatment and reads no spine column). - The spec-engine inventory pins the seed protocol, whose digest covers the source of us_runtime.other_health_insurance. That source changed (the premium loop's batching and release), not its random draws, so the seed protocol and seed map digests and the US bundle's spec_sha256 are re-pinned with tools/repin_us_spec_engine_contracts.py and the coverage evidence regenerated with tools/spec_engine_coverage.py (41/41 inventory checks). Co-Authored-By: Claude Opus 5.5 --- docs/evidence/spec-engine/us-f0-coverage.json | 16 ++++++++-------- .../build/spec_engine/inventory_coverage.py | 4 ++-- .../shared/test_spec_engine_loader.py | 2 +- .../engine_free/us/test_us_spine_blindness.py | 5 +++++ .../us/test_us_multispine_pool_tool.py | 2 +- 5 files changed, 17 insertions(+), 12 deletions(-) diff --git a/docs/evidence/spec-engine/us-f0-coverage.json b/docs/evidence/spec-engine/us-f0-coverage.json index 71be9d4600..5144bba434 100644 --- a/docs/evidence/spec-engine/us-f0-coverage.json +++ b/docs/evidence/spec-engine/us-f0-coverage.json @@ -1642,13 +1642,13 @@ "compiler_ir.node_slices" ], "expected": { - "map_sha256": "9c809470367a211c88ba047211ad9461850ca56100af41d56d807312ee8ccd5f", - "protocol_sha256": "eea4cf01a4924295e760edbe74e368dc6a48d66334ffe9a04d2fa13beebee2c5" + "map_sha256": "44e5d87c927a800aa5f232e61896e70c949e1d5607722691e0c8b732284a70c4", + "protocol_sha256": "5a1264820d12f7e448126f56a65feaba96d6d2fbb30540b2dc84d8485f141ba1" }, "failures": [], "observed": { - "map_sha256": "9c809470367a211c88ba047211ad9461850ca56100af41d56d807312ee8ccd5f", - "protocol_sha256": "eea4cf01a4924295e760edbe74e368dc6a48d66334ffe9a04d2fa13beebee2c5" + "map_sha256": "44e5d87c927a800aa5f232e61896e70c949e1d5607722691e0c8b732284a70c4", + "protocol_sha256": "5a1264820d12f7e448126f56a65feaba96d6d2fbb30540b2dc84d8485f141ba1" }, "status": "covered" }, @@ -1663,7 +1663,7 @@ "compiler_ir.seed_stream_map" ], "expected": { - "implementation_sha256": "eea4cf01a4924295e760edbe74e368dc6a48d66334ffe9a04d2fa13beebee2c5", + "implementation_sha256": "5a1264820d12f7e448126f56a65feaba96d6d2fbb30540b2dc84d8485f141ba1", "protocol": "legacy-v1", "streams": [ "build_model", @@ -1684,7 +1684,7 @@ }, "failures": [], "observed": { - "implementation_sha256": "eea4cf01a4924295e760edbe74e368dc6a48d66334ffe9a04d2fa13beebee2c5", + "implementation_sha256": "5a1264820d12f7e448126f56a65feaba96d6d2fbb30540b2dc84d8485f141ba1", "protocol": "legacy-v1", "streams": [ "build_model", @@ -2585,7 +2585,7 @@ "country": "us", "schema_id": "country_spec", "schema_version": 1, - "spec_sha256": "4c3c3beab01e381aadfea510f61ca28117670d35c6bed1e4bb0df2fa1be07b2e" + "spec_sha256": "7e282f7fd459c63a25f1ad8b57fc88cb118088c353e81dce26080ad87f266375" } }, "report_schema_version": 3, @@ -2595,7 +2595,7 @@ "country": "us", "schema_id": "country_spec", "schema_version": 1, - "spec_sha256": "4c3c3beab01e381aadfea510f61ca28117670d35c6bed1e4bb0df2fa1be07b2e" + "spec_sha256": "7e282f7fd459c63a25f1ad8b57fc88cb118088c353e81dce26080ad87f266375" }, "status": "pass" } diff --git a/packages/microcosm-build/src/microcosm/build/spec_engine/inventory_coverage.py b/packages/microcosm-build/src/microcosm/build/spec_engine/inventory_coverage.py index b08a37c45b..50fbda5c5a 100644 --- a/packages/microcosm-build/src/microcosm/build/spec_engine/inventory_coverage.py +++ b/packages/microcosm-build/src/microcosm/build/spec_engine/inventory_coverage.py @@ -418,8 +418,8 @@ # Importing torch inside the solve functions that use it, and the QRF chain # handing each worker a record of its caller's lock-file check, move both # again: solve's and puf_qrf_chain's attested bytes change; no draw does. - "seed_map": "9c809470367a211c88ba047211ad9461850ca56100af41d56d807312ee8ccd5f", - "seed_protocol": "eea4cf01a4924295e760edbe74e368dc6a48d66334ffe9a04d2fa13beebee2c5", + "seed_map": '44e5d87c927a800aa5f232e61896e70c949e1d5607722691e0c8b732284a70c4', + "seed_protocol": '5a1264820d12f7e448126f56a65feaba96d6d2fbb30540b2dc84d8485f141ba1', "source_manifest": "dc3879886d2a69f20fb982a675d7fb322c0e4017afef6471be54b0ee3cbd2af6", "take_up": "9522ce40f7dea569312dd7a7beb474e5a5afadd2f1e10cb5876534c3ef623d35", "tail": "565f0ceeadab69d3e96a886a00dd0305f7425fa3acde24d12ba48db2b37d5fc0", diff --git a/packages/microcosm-build/tests/engine_free/shared/test_spec_engine_loader.py b/packages/microcosm-build/tests/engine_free/shared/test_spec_engine_loader.py index 6f2df4ecf2..e65f8bbd66 100644 --- a/packages/microcosm-build/tests/engine_free/shared/test_spec_engine_loader.py +++ b/packages/microcosm-build/tests/engine_free/shared/test_spec_engine_loader.py @@ -44,7 +44,7 @@ def test_semantic_hash_has_golden_vector_and_surface_separation(tmp_path) -> Non # Importing torch inside the solve functions that use it, and the QRF chain # passing its workers a lock-file check record, move it again. assert first.spec_sha256 == ( - "55fe6aee2557efed00c0a4da13f1bac5d28b6c12a28608bc1016e346c9fbb952" + '86beda0ff2c9964a6feaf6eaa09ff6639fa8b89f32bd303b9d7d8d92e77245e8' ) second_root = _rich_minimal(tmp_path / "xy", note="second", store="local:b") diff --git a/packages/microcosm-build/tests/engine_free/us/test_us_spine_blindness.py b/packages/microcosm-build/tests/engine_free/us/test_us_spine_blindness.py index e0ff6f7d90..5502c44aba 100644 --- a/packages/microcosm-build/tests/engine_free/us/test_us_spine_blindness.py +++ b/packages/microcosm-build/tests/engine_free/us/test_us_spine_blindness.py @@ -363,6 +363,11 @@ "geography_ladder.py", "hours_worked.py", "h5_io.py", # US artifact I/O; no population treatment. + # Household batches for the release's policyengine-us passes: the + # partition, the frame checks, the population-aggregate refusal and + # engine release; reads no spine or support-channel column and applies + # no population treatment. + "household_batches.py", "immigration.py", "input_mass.py", "l0_refit_export.py", diff --git a/packages/microcosm-build/tests/engine_workflow/us/test_us_multispine_pool_tool.py b/packages/microcosm-build/tests/engine_workflow/us/test_us_multispine_pool_tool.py index 69dd4629d4..fda8755223 100644 --- a/packages/microcosm-build/tests/engine_workflow/us/test_us_multispine_pool_tool.py +++ b/packages/microcosm-build/tests/engine_workflow/us/test_us_multispine_pool_tool.py @@ -376,7 +376,7 @@ def capture_equality(expected: object, actual: object) -> None: # Importing torch inside the solve functions that use it, and the # QRF chain passing its workers a lock-file check record, move it # again. - "spec_sha256": "4c3c3beab01e381aadfea510f61ca28117670d35c6bed1e4bb0df2fa1be07b2e", + "spec_sha256": '7e282f7fd459c63a25f1ad8b57fc88cb118088c353e81dce26080ad87f266375', }, } From 5b54c912f60550b622c8a72ee87f5df170ecb4d9 Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Fri, 27 Nov 2026 18:49:47 +0400 Subject: [PATCH 6/6] List household_batches among the modules the check bindings now import test_the_batterys_binding_identity_adds_only_the_leaf_and_its_imports counts the modules the release-check bindings reach. us_runtime.other_health_insurance now imports us_runtime.household_batches, so the bindings reach one more module; list it in BINDING_MODULES_ADDED_AFTER_BASE. Co-Authored-By: Claude Opus 5.5 --- .../engine_free/shared/test_transport_evidence_kernels.py | 3 +++ 1 file changed, 3 insertions(+) diff --git a/packages/microcosm-build/tests/engine_free/shared/test_transport_evidence_kernels.py b/packages/microcosm-build/tests/engine_free/shared/test_transport_evidence_kernels.py index 5bc00641a1..7503231b8a 100644 --- a/packages/microcosm-build/tests/engine_free/shared/test_transport_evidence_kernels.py +++ b/packages/microcosm-build/tests/engine_free/shared/test_transport_evidence_kernels.py @@ -159,6 +159,9 @@ # microcosm#1686: the five SIPP donor modules import the shared read # of the SIPP person file. "microcosm.build.us_runtime.sipp_december_person_rows", + # microcosm#1776: us_runtime.other_health_insurance runs its premium + # batches through us_runtime.household_batches. + "microcosm.build.us_runtime.household_batches", # microcosm#1405: the gate battery refuses a signing key the committed # registry does not let sign, so it imports # microcosm.data.gate_signing_keys, and with it the microcosm.data