From 983de0f7c2f656424e3eaf59208f652f62d66855 Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Thu, 26 Nov 2026 22:52:20 +0400 Subject: [PATCH 1/5] Test that JCT reform batches get the reform system alone Target compilation's JCT reform batches pass both tax_benefit_system= and reform=, so policyengine-us 2.2.1 clones the reform's system for every batch engine and gives each a baseline branch. These tests require each batch engine to get the reform system alone, with no system clone per batch, and require the two refusals that replace the baseline branch: a reform system that moves a behavioral-response parameter, and a batch engine that computed a formula reading the baseline branch. A real-engine test compares every shipped JCT reform's household income tax, byte for byte, with the construction that passes reform= as well. The shared fake engine now computes under the reform its system was built with and carries a baseline branch only when given reform=. Co-Authored-By: Claude Opus 5.5 --- .../test_us_batched_target_materialization.py | 116 ++++- .../us/test_us_fiscal_refresh_builder.py | 41 +- .../us/test_us_jct_reform_batches.py | 492 ++++++++++++++++++ .../us_batched_target_materialization.py | 48 +- 4 files changed, 682 insertions(+), 15 deletions(-) create mode 100644 packages/microcosm-build/tests/engine_workflow/us/test_us_jct_reform_batches.py 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..c21cfdb16b 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 @@ -386,9 +386,8 @@ def test_batched_base_simulation_refuses_a_stored_aggregate_input( assert all(simulation.dataset is None for simulation in ledger.simulations) -@pytest.mark.parametrize("aggregate_in_baseline", [False, True]) def test_batched_reform_simulation_refuses_population_aggregates( - monkeypatch, aggregate_in_baseline + monkeypatch, ) -> None: builder = _load_builder_module() ledger = _install_fake_engine( @@ -396,10 +395,9 @@ def test_batched_reform_simulation_refuses_population_aggregates( monkeypatch, reform_specs=_REFORMS, aggregate_reads={"income_tax": ("medicaid_slcsp_state_denominator",)}, - aggregate_branch="baseline/temporary", + aggregate_branch="temporary_parent/temporary_child", aggregate_delete_branch=True, aggregate_reform_only=True, - aggregate_in_baseline=aggregate_in_baseline, clone_branches=True, ) with pytest.raises(ValueError, match=r"computed medicaid_slcsp_state_denominator@"): @@ -411,6 +409,116 @@ def test_batched_reform_simulation_refuses_population_aggregates( assert all(simulation.dataset is None for simulation in ledger.simulations) +@pytest.mark.parametrize("batch_size", [None, 2]) +def test_jct_reform_engines_get_the_family_system_alone( + monkeypatch, batch_size +) -> None: + """Each JCT batch engine gets the family's reform system and no ``reform=``. + + Given both, policyengine-us 2.2.1 clones the supplied system for every + batch and adds a ``baseline`` branch. The family system's + behavioral-response parameters are compared once, before its first + engine, with the engine's shared baseline system.""" + + builder = _load_builder_module() + _, _, _, ledger = _materialize(builder, monkeypatch, _nested_frame(), batch_size) + + family_system = ledger.reform_systems[1] + assert family_system.reform == "mock_credit" + reform_constructions = [ + entry for entry in ledger.constructions if entry["reform"] is not None + ] + assert len(reform_constructions) == (1 if batch_size is None else 3) + for entry in reform_constructions: + assert entry["reform_argument"] is None + assert entry["tax_benefit_system"] is family_system + assert all(simulation.baseline is None for simulation in ledger.simulations) + assert ledger.behavioral_response_checks == [ + (family_system, ledger.shared_baseline_system, builder.PERIOD) + ] + + +@pytest.mark.parametrize("batch_size", [None, 2]) +@pytest.mark.parametrize( + ("branch", "delete_branch"), + [ + pytest.param(None, False, id="root-engine"), + pytest.param("temporary_parent/temporary_child", True, id="deleted-branch"), + ], +) +def test_jct_reform_batches_refuse_baseline_branch_readers( + monkeypatch, batch_size, branch, delete_branch +) -> None: + """A JCT batch engine refuses a formula that reads the ``baseline`` branch. + + It carries none, at every batch count, so the refusal does not depend on + the population-aggregate refusal being on, and it reads branches a formula + created and deleted again. The first reform engine refuses, and every + engine is released.""" + + builder = _load_builder_module() + for reader in builder.POST_EXPORT_BASELINE_BRANCH_READERS: + ledger = _install_fake_engine( + builder, + monkeypatch, + reform_specs=_REFORMS, + aggregate_reads={"income_tax": (reader,)}, + aggregate_branch=branch, + aggregate_delete_branch=delete_branch, + aggregate_reform_only=True, + ) + with pytest.raises( + ValueError, match=rf"computed {reader}@{builder.PERIOD}" + ) as raised: + builder._materialize_target_frame( + _nested_frame(), _TARGETS, maximum_microsim_batch_size=batch_size + ) + if ( + batch_size is None + or reader not in builder.US_POPULATION_AGGREGATE_VARIABLES + ): + # Otherwise the population-aggregate refusal names it first. + assert "jct_mock_credit" in str(raised.value), reader + assert "baseline branch" in str(raised.value), reader + reform_engines = [ + simulation for simulation in ledger.simulations if simulation.reform + ] + assert len(reform_engines) == 1, reader + assert all(simulation.dataset is None for simulation in ledger.simulations), ( + reader + ) + + +def test_jct_reform_refuses_moved_behavioral_responses_before_its_engines( + monkeypatch, +) -> None: + """A JCT reform system that sets a behavioral-response parameter off + baseline is refused before any of its batch engines is built: those + engines carry no ``baseline`` branch, so policyengine-us would score the + response as zero.""" + + builder = _load_builder_module() + moved = "gov.simulation.labor_supply_responses.elasticities.income" + ledger = _install_fake_engine( + builder, + monkeypatch, + reform_specs=_REFORMS, + moved_behavioral_response_parameters=(moved,), + ) + with pytest.raises( + ValueError, + match=rf"jct_mock_credit.* off baseline at {builder.PERIOD}: {re.escape(moved)}\.", + ): + builder._materialize_target_frame( + _nested_frame(), _TARGETS, maximum_microsim_batch_size=2 + ) + assert [entry for entry in ledger.constructions if entry["reform"]] == [] + assert ledger.behavioral_response_checks == [ + (ledger.reform_systems[1], ledger.shared_baseline_system, builder.PERIOD) + ] + assert all(simulation.dataset is None for simulation in ledger.simulations) + + @pytest.mark.parametrize( ("target", "wrap", "message"), [ 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..a9c654483a 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 @@ -11815,6 +11815,8 @@ def test_jct_materialization_collapses_reform_tax_units_and_clears_caches( simulations = [] reform_systems = [] formula_owned_assertions: list[int] = [] + behavioral_response_checks: list[tuple[object, object, int]] = [] + shared_baseline_system = SimpleNamespace(name="shared baseline system") class FakeVariable: entity = SimpleNamespace(key="tax_unit") @@ -11831,6 +11833,7 @@ def __init__(self, reform=None): class FakeMicrosimulation: default_tax_benefit_system = FakeSystem + default_tax_benefit_system_instance = shared_baseline_system def __init__(self, *, dataset, reform=None, tax_benefit_system=None): self.dataset = dataset @@ -11844,7 +11847,9 @@ def calculate(self, variable, *, period, **kwargs): tax_unit_ids = ( self.dataset["frame"].table("tax_unit")["tax_unit_id"].to_numpy() ) - if self.reform is not None: + # A reform engine computes under the reform its system was built + # with, as policyengine-us does when given that system alone. + if getattr(self.tax_benefit_system, "reform", None) is not None: assert variable == "income_tax" assert kwargs == {} reform_income_tax_by_id = {10: 90.0, 20: 25.0, 30: 40.0} @@ -11897,6 +11902,12 @@ def fake_make_zero_variable_reform(system, variable_name): def fake_assert_no_formula_owned_columns(frame_arg): formula_owned_assertions.append(frame_arg.n("household")) + def fake_moved_behavioral_response_parameters( + reform_system, baseline_system, period + ): + behavioral_response_checks.append((reform_system, baseline_system, period)) + return [] + monkeypatch.setitem( sys.modules, "policyengine_us", @@ -11914,6 +11925,11 @@ def fake_assert_no_formula_owned_columns(frame_arg): monkeypatch.setattr( builder, "_make_zero_variable_reform", fake_make_zero_variable_reform ) + monkeypatch.setattr( + builder, + "_moved_behavioral_response_parameters", + fake_moved_behavioral_response_parameters, + ) monkeypatch.setattr(builder, "US_JCT_TAX_EXPENDITURE_REFORMS", (reform_spec,)) monkeypatch.setattr(builder, "SOI_VARIABLE_MAP", {}) @@ -11979,6 +11995,12 @@ def fake_assert_no_formula_owned_columns(frame_arg): reform_systems[1], reform_systems[1], ] + # Each reform batch engine gets the family system alone, not ``reform=`` + # as well, which would make policyengine-us clone that system per batch. + assert [simulation.reform for simulation in simulations] == [None] * 4 + assert behavioral_response_checks == [ + (reform_systems[1], shared_baseline_system, builder.PERIOD) + ] # Each simulation was released (dataset reference severed), not merely # cache-invalidated. assert [simulation.dataset for simulation in simulations] == [None] * 4 @@ -12027,6 +12049,7 @@ def fake_assert_no_formula_owned_columns(frame_arg): True, False, ] + assert len(behavioral_response_checks) == 1 assert [simulation.dataset for simulation in simulations] == [None] * 6 assert [simulation.cache_invalidations for simulation in simulations] == [0] * 6 assert ( @@ -16496,6 +16519,9 @@ def __init__(self, reform=None): class FakeMicrosimulation: default_tax_benefit_system = FakeSystem + default_tax_benefit_system_instance = SimpleNamespace( + name="shared baseline system" + ) def __init__(self, *, dataset, reform=None, tax_benefit_system=None): self.dataset = dataset @@ -16508,9 +16534,12 @@ def calculate(self, variable, *, period, **kwargs): tax_unit_ids = ( self.dataset["frame"].table("tax_unit")["tax_unit_id"].to_numpy() ) - if self.reform is not None: + # A reform engine computes under the reform its system was built + # with, as policyengine-us does when given that system alone. + policy_reform = getattr(self.tax_benefit_system, "reform", None) + if policy_reform is not None: assert variable == "income_tax" - lookup = reform_income_tax_by_id[self.reform] + lookup = reform_income_tax_by_id[policy_reform] return np.asarray([lookup[id_] for id_ in tax_unit_ids]) arrays_by_id = { "income_tax": base_income_tax_by_id, @@ -16561,6 +16590,12 @@ def fake_make_zero_variable_reform(system, variable_name): monkeypatch.setattr( builder, "_make_zero_variable_reform", fake_make_zero_variable_reform ) + # No fake reform moves a behavioral-response parameter. + monkeypatch.setattr( + builder, + "_moved_behavioral_response_parameters", + lambda reform_system, baseline_system, period: [], + ) monkeypatch.setattr(builder, "US_JCT_TAX_EXPENDITURE_REFORMS", reform_specs) monkeypatch.setattr(builder, "SOI_VARIABLE_MAP", {}) diff --git a/packages/microcosm-build/tests/engine_workflow/us/test_us_jct_reform_batches.py b/packages/microcosm-build/tests/engine_workflow/us/test_us_jct_reform_batches.py new file mode 100644 index 0000000000..c48800dcff --- /dev/null +++ b/packages/microcosm-build/tests/engine_workflow/us/test_us_jct_reform_batches.py @@ -0,0 +1,492 @@ +"""JCT reform batches against policyengine-us. + +Target compilation scores each JCT tax-expenditure reform in household batches, +each batch engine given the reform's tax-benefit system. These tests compare +it with the construction it replaced, which passed ``reform=`` as well: given +both, policyengine-us 2.2.1 clones the supplied system on every construction +and adds a ``baseline`` branch to the engine. They count system clones, and +exercise the two refusals that stand in for the missing ``baseline`` branch. +""" + +from __future__ import annotations + +import numpy as np +import pandas as pd +import pytest + +from microcosm.frame import US_SCHEMA, Frame, WeightKind, Weights +from test_support.microcosm_build.us_batched_target_materialization import ( + _load_builder_module, + _medicaid_frame, +) + +#: (state_fips, persons, tax-unit HSA deduction, SPM-unit childcare). One tax +#: unit, SPM unit and family per household; the first two persons of a +#: household are its head and spouse. Each JCT reform's variable is nonzero +#: for at least one household. +_JCT_HOUSEHOLDS = ( + ( + 6, + ( + { + "age": 45, + "employment_income_before_lsr": 300_000.0, + "real_estate_taxes": 12_000.0, + "home_mortgage_interest": 20_000.0, + "charitable_cash_donations": 8_000.0, + "other_medical_expenses": 40_000.0, + }, + {"age": 44}, + ), + 0.0, + 0.0, + ), + ( + 36, + ( + { + "age": 50, + "self_employment_income_before_lsr": 120_000.0, + # Self-employed premiums are defined only for people marked + # self-employed. + "is_self_employed": True, + "health_insurance_premiums": 9_000.0, + "self_employed_pension_contributions_desired": 10_000.0, + }, + ), + 0.0, + 0.0, + ), + ( + 48, + ( + { + "age": 29, + "employment_income_before_lsr": 60_000.0, + "student_loan_interest": 2_500.0, + "traditional_ira_contributions_desired": 6_000.0, + }, + ), + 3_000.0, + 0.0, + ), + ( + 6, + ( + {"age": 38, "employment_income_before_lsr": 70_000.0}, + {"age": 36, "employment_income_before_lsr": 40_000.0}, + {"age": 4}, + {"age": 7}, + ), + 0.0, + 8_000.0, + ), + ( + 24, + ( + { + "age": 61, + "employment_income_before_lsr": 95_000.0, + "charitable_cash_donations": 30_000.0, + "real_estate_taxes": 9_000.0, + "home_mortgage_interest": 15_000.0, + }, + ), + 0.0, + 0.0, + ), +) +#: Boolean person inputs and the value of a person who does not set one. +_BOOLEAN_INPUTS = {"is_self_employed": False} +#: Five households in batches of two: three batch engines per reform. +_BATCH_SIZE = 2 +_BATCHES = 3 + + +def _jct_frame() -> Frame: + input_columns = sorted( + { + column + for _, persons, _, _ in _JCT_HOUSEHOLDS + for person in persons + for column in person + } + - {"age"} + ) + rows = [] + for household_id, (_, persons, _, _) in enumerate(_JCT_HOUSEHOLDS, start=1): + for position, person in enumerate(persons): + rows.append( + { + "person_id": len(rows) + 1, + "person_household_id": household_id, + "person_tax_unit_id": household_id * 10, + "person_spm_unit_id": household_id * 100, + "person_family_id": household_id * 1_000, + # Head and spouse share a marital unit. + "person_marital_unit_id": household_id * 10_000 + + max(position - 1, 0), + "age": float(person["age"]), + **{ + column: person.get(column, _BOOLEAN_INPUTS.get(column, 0.0)) + for column in input_columns + }, + } + ) + person = pd.DataFrame(rows) + for column in input_columns: + person[column] = person[column].astype( + bool if column in _BOOLEAN_INPUTS else np.float64 + ) + household_ids = np.arange(1, len(_JCT_HOUSEHOLDS) + 1, dtype="int64") + return Frame( + { + "person": person, + "household": pd.DataFrame( + { + "household_id": household_ids, + "state_fips": np.asarray( + [state for state, _, _, _ in _JCT_HOUSEHOLDS], "int64" + ), + } + ), + "tax_unit": pd.DataFrame( + { + "tax_unit_id": household_ids * 10, + "health_savings_account_ald": [ + hsa for _, _, hsa, _ in _JCT_HOUSEHOLDS + ], + } + ), + "spm_unit": pd.DataFrame( + { + "spm_unit_id": household_ids * 100, + "spm_unit_pre_subsidy_childcare_expenses": [ + childcare for _, _, _, childcare in _JCT_HOUSEHOLDS + ], + } + ), + "family": pd.DataFrame({"family_id": household_ids * 1_000}), + "marital_unit": pd.DataFrame( + { + "marital_unit_id": np.unique( + person["person_marital_unit_id"].to_numpy() + ) + } + ), + }, + US_SCHEMA, + { + "household": Weights( + np.ones(len(_JCT_HOUSEHOLDS), dtype=np.float64), WeightKind.DESIGN + ) + }, + ) + + +def _record_reform_systems(monkeypatch) -> list[tuple[object, object]]: + """Record each ``(reform, system)`` that ``Microsimulation`` builds through + ``default_tax_benefit_system(reform=...)``, as + ``_reform_household_income_tax`` does once per reform.""" + + from policyengine_us import Microsimulation + + built: list[tuple[object, object]] = [] + build_system = Microsimulation.default_tax_benefit_system + + def recording_build(*args, **kwargs): + reform_system = build_system(*args, **kwargs) + built.append((kwargs.get("reform"), reform_system)) + return reform_system + + monkeypatch.setattr( + Microsimulation, "default_tax_benefit_system", staticmethod(recording_build) + ) + return built + + +def _income_tax_given_reform_argument( + builder, + frame: Frame, + reform_spec, + system, + *, + reform, + reform_system, + batch_size: int, +) -> np.ndarray: + """The household income tax as each batch engine computed it when given + ``reform=`` as well as the reform's system, which the reform's batches + shared (the construction before microcosm 1.6 · 1). Each engine carries a + ``baseline`` branch; at the installed engine's zero default elasticities + it scores no labor-supply or capital-gains response, which a batch engine + without that branch scores as zero too.""" + + from policyengine_us import Microsimulation + + assert ( + builder._moved_behavioral_response_parameters( + reform_system, + Microsimulation.default_tax_benefit_system_instance, + builder.PERIOD, + ) + == [] + ), reform_spec.measure + n_households = frame.n("household") + income_tax = np.zeros(n_households, dtype=np.float64) + for positions in builder._household_position_batches(n_households, batch_size): + batch_frame = builder._select_households_by_position(frame, positions) + simulation = Microsimulation( + tax_benefit_system=reform_system, + dataset=builder._dataset_from_frame( + batch_frame, + zero_variables=(reform_spec.neutralized_variable,), + system=system, + assert_no_formula_owned_columns=False, + period_only=True, + ), + reform=reform, + ) + try: + assert simulation.baseline is not None + income_tax[positions] = builder._collapse_tax_unit( + builder._calculate_array(simulation, "income_tax"), + builder._tax_unit_to_household_positions(batch_frame), + batch_frame.n("household"), + ) + for response in builder.POST_EXPORT_BEHAVIORAL_RESPONSE_PARAMETERS: + values = builder._calculate_array(simulation, response) + assert not np.any(values), (reform_spec.measure, response) + finally: + builder.release_engine_simulation(simulation) + return income_tax + + +def _count_system_clones(monkeypatch) -> list[int]: + """Count whole tax-benefit-system clones (policyengine-core's + ``TaxBenefitSystem.clone``, which policyengine-us 2.2.1's + ``clone_spm_system`` calls).""" + + from policyengine_core.taxbenefitsystems import TaxBenefitSystem + + clones = [0] + real_clone = TaxBenefitSystem.clone + + def counting_clone(self, *args, **kwargs): + clones[0] += 1 + return real_clone(self, *args, **kwargs) + + monkeypatch.setattr(TaxBenefitSystem, "clone", counting_clone) + return clones + + +def _reform_income_tax_both_ways( + builder, frame: Frame, reform_spec, system, built, *, batch_size: int +) -> tuple[np.ndarray, np.ndarray]: + """``_reform_household_income_tax``'s household income tax, then the same + batches' given ``reform=`` as well, on the one reform system it built.""" + + from policyengine_us import Microsimulation + + systems_before = len(built) + observed = builder._reform_household_income_tax( + base_frame=frame, + reform_spec=reform_spec, + system=system, + microsimulation_cls=Microsimulation, + n_households=frame.n("household"), + batch_size=batch_size, + ) + assert len(built) == systems_before + 1, reform_spec.measure + reform, reform_system = built[-1] + expected = _income_tax_given_reform_argument( + builder, + frame, + reform_spec, + system, + reform=reform, + reform_system=reform_system, + batch_size=batch_size, + ) + return observed, expected + + +def test_jct_reform_batches_match_the_reform_argument_construction( + monkeypatch, +) -> None: + """Every shipped JCT reform scores the same household income tax, byte for + byte, on batch engines given the reform's system alone as on batch + engines given ``reform=`` as well. Each reform changes income tax for at + least one fixture household and passes both refusals that stand in for + the missing ``baseline`` branch.""" + + builder = _load_builder_module() + from policyengine_us import CountryTaxBenefitSystem, Microsimulation + + frame = _jct_frame() + n_households = frame.n("household") + system = CountryTaxBenefitSystem() + builder._assert_no_formula_owned_columns(frame) + built = _record_reform_systems(monkeypatch) + baseline = Microsimulation( + dataset=builder._dataset_from_frame( + frame, assert_no_formula_owned_columns=False, period_only=True + ) + ) + try: + baseline_income_tax = builder._collapse_tax_unit( + builder._calculate_array(baseline, "income_tax"), + builder._tax_unit_to_household_positions(frame), + n_households, + ) + finally: + builder.release_engine_simulation(baseline) + + assert len(builder.US_JCT_TAX_EXPENDITURE_REFORMS) == 11 + for reform_spec in builder.US_JCT_TAX_EXPENDITURE_REFORMS: + observed, expected = _reform_income_tax_both_ways( + builder, frame, reform_spec, system, built, batch_size=_BATCH_SIZE + ) + assert observed.dtype == expected.dtype == np.float64 + assert observed.tobytes() == expected.tobytes(), ( + reform_spec.measure, + observed, + expected, + ) + assert np.any(observed != baseline_income_tax), ( + f"{reform_spec.measure}: the fixture does not reach " + f"{reform_spec.neutralized_variable}" + ) + + +def test_jct_reform_batches_clone_no_tax_benefit_system(monkeypatch) -> None: + """One JCT reform in three batches clones no tax-benefit system. The + construction with ``reform=`` as well cloned the reform's system once per + batch engine, which the counter sees.""" + + builder = _load_builder_module() + from policyengine_us import CountryTaxBenefitSystem, Microsimulation + + frame = _jct_frame() + system = CountryTaxBenefitSystem() + reform_spec = builder.US_JCT_TAX_EXPENDITURE_REFORMS[0] + assert ( + len( + tuple( + builder._household_position_batches(frame.n("household"), _BATCH_SIZE) + ) + ) + == _BATCHES + ) + built = _record_reform_systems(monkeypatch) + clones = _count_system_clones(monkeypatch) + + builder._reform_household_income_tax( + base_frame=frame, + reform_spec=reform_spec, + system=system, + microsimulation_cls=Microsimulation, + n_households=frame.n("household"), + batch_size=_BATCH_SIZE, + ) + assert clones[0] == 0 + assert len(built) == 1 + + reform, reform_system = built[0] + _income_tax_given_reform_argument( + builder, + frame, + reform_spec, + system, + reform=reform, + reform_system=reform_system, + batch_size=_BATCH_SIZE, + ) + assert clones[0] == _BATCHES + + +def test_jct_reform_refuses_moved_behavioral_responses_on_policyengine_us( + monkeypatch, +) -> None: + """A reform whose system moves a labor-supply elasticity is refused by + name, as read from the real reform system's parameters, before any batch + engine is built.""" + + from policyengine_core.reforms import Reform + from policyengine_us import CountryTaxBenefitSystem, Microsimulation + + builder = _load_builder_module() + income_elasticity = "gov.simulation.labor_supply_responses.elasticities.income" + monkeypatch.setattr( + builder, + "_make_zero_variable_reform", + lambda system, variable_name: Reform.from_dict( + {income_elasticity: {f"{builder.PERIOD}-01-01": -0.05}}, + country_id="us", + ), + ) + constructions = [0] + + class CountingMicrosimulation(Microsimulation): + def __init__(self, *args, **kwargs): + constructions[0] += 1 + super().__init__(*args, **kwargs) + + frame = _jct_frame() + reform_spec = builder.US_JCT_TAX_EXPENDITURE_REFORMS[0] + with pytest.raises( + ValueError, + match=( + rf"{reform_spec.measure}.* off baseline at {builder.PERIOD}: " + r"gov\.simulation\.labor_supply_responses\.elasticities\.income\." + ), + ): + builder._reform_household_income_tax( + base_frame=frame, + reform_spec=reform_spec, + system=CountryTaxBenefitSystem(), + microsimulation_cls=CountingMicrosimulation, + n_households=frame.n("household"), + batch_size=_BATCH_SIZE, + ) + assert constructions[0] == 0 + + +def test_jct_reform_batch_refuses_a_baseline_branch_reader_on_policyengine_us( + monkeypatch, +) -> None: + """A JCT batch engine that computed a formula reading the ``baseline`` + branch is refused, in one batch, where the population-aggregate refusal is + off. ``income_tax`` reaches none of those formulas on the installed engine, + so the engine here also computes ``medicaid_cost``, which reaches the + Medicaid state denominator: given ``reform=``, that denominator would be + read from the ``baseline`` branch.""" + + from policyengine_us import CountryTaxBenefitSystem, Microsimulation + + builder = _load_builder_module() + real_calculate_array = builder._calculate_array + + def calculate_array_reaching_medicaid(simulation, variable, **kwargs): + if variable == "income_tax": + real_calculate_array(simulation, "medicaid_cost") + return real_calculate_array(simulation, variable, **kwargs) + + monkeypatch.setattr(builder, "_calculate_array", calculate_array_reaching_medicaid) + frame = _medicaid_frame() + reform_spec = builder.US_JCT_TAX_EXPENDITURE_REFORMS[0] + with pytest.raises( + ValueError, + match=( + rf"{reform_spec.measure}.*household batch 1/1 computed " + rf"medicaid_slcsp_state_denominator@{builder.PERIOD}\." + ), + ): + builder._reform_household_income_tax( + base_frame=frame, + reform_spec=reform_spec, + system=CountryTaxBenefitSystem(), + microsimulation_cls=Microsimulation, + n_households=frame.n("household"), + batch_size=None, + ) diff --git a/test_support/microcosm_build/us_batched_target_materialization.py b/test_support/microcosm_build/us_batched_target_materialization.py index 78731fc729..10f0e6efdf 100644 --- a/test_support/microcosm_build/us_batched_target_materialization.py +++ b/test_support/microcosm_build/us_batched_target_materialization.py @@ -97,12 +97,17 @@ def _record_value(variable: str, record_id: int): class _FakeEngineLedger: - """Records every engine the materializer builds, in order.""" + """Records every engine the materializer builds, in order, and each + behavioral-response parameter comparison it makes.""" def __init__(self) -> None: self.simulations: list[object] = [] self.constructions: list[dict[str, object]] = [] self.reform_systems: list[object] = [] + # The fake engine's shared baseline system, which a JCT reform system's + # behavioral-response parameters are compared with. + self.shared_baseline_system = SimpleNamespace(name="shared baseline system") + self.behavioral_response_checks: list[tuple[object, object, int]] = [] class _FakeHolders: @@ -139,13 +144,19 @@ def _install_fake_engine( aggregate_delete_branch: bool = False, aggregate_household: int | None = None, aggregate_reform_only: bool = False, - aggregate_in_baseline: bool = False, clone_branches: bool = False, stored_inputs: dict[str, tuple[str, ...]] | None = None, + moved_behavioral_response_parameters: tuple[str, ...] = (), ): - """``aggregate_reads`` maps a variable to the population aggregates its - formula computes (in the slash-delimited ``aggregate_branch`` if given); - ``stored_inputs`` are known from construction, as dataset inputs are.""" + """``aggregate_reads`` maps a variable to the watched formulas (population + aggregates or baseline-branch readers) its formula computes, in the + slash-delimited ``aggregate_branch`` if given; ``stored_inputs`` are known + from construction, as dataset inputs are. Every reform system reports + ``moved_behavioral_response_parameters`` as set off baseline. + + As in policyengine-us, an engine computes under the reform it is given + with ``reform=`` or else the one its supplied system was built with, and + only an engine given ``reform=`` carries a ``baseline`` branch.""" ledger = _FakeEngineLedger() aggregate_reads = dict(aggregate_reads or {}) @@ -165,6 +176,7 @@ def __init__(self, reform=None) -> None: class FakeMicrosimulation(_FakeHolders): default_tax_benefit_system = FakeSystem + default_tax_benefit_system_instance = ledger.shared_baseline_system def __init__(self, *, dataset, reform=None, tax_benefit_system=None): super().__init__(stored_inputs) @@ -174,9 +186,16 @@ def __init__(self, *, dataset, reform=None, tax_benefit_system=None): if simulation.dataset is not None ] frame = dataset["frame"] + policy_reform = ( + reform + if reform is not None + else getattr(tax_benefit_system, "reform", None) + ) ledger.constructions.append( { - "reform": reform, + "reform": policy_reform, + "reform_argument": reform, + "tax_benefit_system": tax_benefit_system, "households": tuple( int(value) for value in frame.table("household")["household_id"] ), @@ -184,7 +203,7 @@ def __init__(self, *, dataset, reform=None, tax_benefit_system=None): } ) self.dataset = dataset - self.reform = reform + self.reform = policy_reform self.tax_benefit_system = tax_benefit_system self.branches: dict[str, _FakeHolders] = {} self.clone_branches = clone_branches @@ -220,7 +239,7 @@ def calculate(self, variable, *, period, map_to=None): and aggregate_household not in self._ids("household") ): continue - holders = self.baseline if aggregate_in_baseline else self + holders = self branch_parent = holders if aggregate_branch is not None: for branch_name in aggregate_branch.split("/"): @@ -263,6 +282,14 @@ def fake_dataset_from_frame( ): return {"frame": frame_arg, "zero_variables": tuple(zero_variables)} + def fake_moved_behavioral_response_parameters( + reform_system, baseline_system, period + ): + ledger.behavioral_response_checks.append( + (reform_system, baseline_system, period) + ) + return list(moved_behavioral_response_parameters) + monkeypatch.setitem( sys.modules, "policyengine_us", @@ -273,6 +300,11 @@ def fake_dataset_from_frame( ) monkeypatch.setattr(builder, "_assert_no_formula_owned_columns", lambda frame: None) monkeypatch.setattr(builder, "_dataset_from_frame", fake_dataset_from_frame) + monkeypatch.setattr( + builder, + "_moved_behavioral_response_parameters", + fake_moved_behavioral_response_parameters, + ) monkeypatch.setattr( builder, "_make_zero_variable_reform", From 0ef2776c8fd7618e292e215bb17fa835a590e3d1 Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Thu, 26 Nov 2026 23:05:58 +0400 Subject: [PATCH 2/5] Give JCT reform batch engines the reform system alone Target compilation constructed each JCT reform batch engine with both tax_benefit_system=reform_system and reform=reform. Given both, policyengine-us 2.2.1 clones the supplied system on every construction (SPMSimulationMixin._prepare_spm_system -> clone_spm_system), applies the reform again to the clone and adds a baseline branch that copies every input array: 11 reforms x 177 batches = 1,947 clones in a release build. Each batch engine now gets the reform system alone, as the post-export scorer's do, so the reform's batches share its policy and carry no baseline branch. Two refusals stand in for that branch, reusing the scorer's lists: before a reform's first batch engine, a reform system that moves a labor-supply or capital-gains response parameter off baseline is refused; after each batch, an engine that computed a POST_EXPORT_BASELINE_BRANCH_READERS formula is refused, at every batch count, so branches are now recorded for one batch too. The household income-tax arrays are unchanged, so the reform cache identity is unchanged. Co-Authored-By: Claude Opus 5.5 --- .../us-jct-reform-system-only.changed.md | 1 + docs/us-release-build-rule.md | 6 + tools/build_us_fiscal_refresh_release.py | 103 ++++++++++++++++-- 3 files changed, 102 insertions(+), 8 deletions(-) create mode 100644 changelog.d/us-jct-reform-system-only.changed.md diff --git a/changelog.d/us-jct-reform-system-only.changed.md b/changelog.d/us-jct-reform-system-only.changed.md new file mode 100644 index 0000000000..c8b4fd0c64 --- /dev/null +++ b/changelog.d/us-jct-reform-system-only.changed.md @@ -0,0 +1 @@ +Target compilation's JCT tax-expenditure reform batches now give each batch engine the reform's tax-benefit system alone, without `reform=` as well, as post-export scoring does. Given both, policyengine-us 2.2.1 cloned the reform's system for every batch engine and gave each a `baseline` branch: 11 reforms × 177 batches = 1,947 clones in a release build. Without a `baseline` branch, each reform is refused before its first batch engine if its system moves a labor-supply or capital-gains response parameter off baseline, and a batch engine is refused if it computed a formula that reads the `baseline` branch (`POST_EXPORT_BASELINE_BRANCH_READERS`), at every batch count. On a five-household policyengine-us fixture in three batches, all 11 reforms give byte-identical household income tax to the previous construction. The reform income-tax cache identity is unchanged. diff --git a/docs/us-release-build-rule.md b/docs/us-release-build-rule.md index b63d1297ef..e09999d72e 100644 --- a/docs/us-release-build-rule.md +++ b/docs/us-release-build-rule.md @@ -539,6 +539,12 @@ known violations at run time: those responses score 0. A whole-file engine also scores 0 at the engine's zero default elasticities. +Target compilation's JCT tax-expenditure reform batches +(`_reform_household_income_tax`) build their engines the same way, from one +reform system per reform, and refuse the same two things: a reform system that +moves the behavioral-response parameters, before its first batch engine, and +a batch engine that computed a baseline-branch reader, at every batch count. + Tests pin the watched lists against the installed engine's formula sources, exercise each guard on a real engine, and compare the shipped baseline plans (20 smoke keys, 75 validation keys and 1 demographics key), served from the diff --git a/tools/build_us_fiscal_refresh_release.py b/tools/build_us_fiscal_refresh_release.py index 7d544a5041..67670815d8 100644 --- a/tools/build_us_fiscal_refresh_release.py +++ b/tools/build_us_fiscal_refresh_release.py @@ -5145,7 +5145,9 @@ def _select_households_by_position(frame: Frame, positions: np.ndarray) -> Frame #: holds a reform at the baseline's denominator; the others reach #: ``get_behavioral_response_measurements``, which measures a reform against #: ``get_branch("baseline")`` and would measure it against itself here. A reform -#: pass refuses an engine that computed any of them, whatever its batch count. +#: pass refuses an engine that computed any of them, whatever its batch count; +#: so does each JCT reform batch of target compilation, whose engines also get +#: the reform's system alone (``_refuse_batch_baseline_branch_readers``). #: Pinned in ``test_us_post_export_scoring.py``. POST_EXPORT_BASELINE_BRANCH_READERS = ( "income_elasticity_lsr", @@ -5158,9 +5160,10 @@ def _select_households_by_position(frame: Frame, positions: np.ndarray) -> Frame #: The other two formulas that read ``simulation.baseline``, and the parameter #: subtree each response is computed from. Without a baseline branch both -#: return 0; with one they return 0 at zero elasticities. Every reform pass -#: requires these parameters to remain at their baseline values before it -#: builds a batch engine. +#: return 0; with one they return 0 at zero elasticities. Every reform pass, and +#: each JCT reform of target compilation +#: (``_refuse_reform_moving_behavioral_responses``), requires these parameters +#: to remain at their baseline values before it builds a batch engine. POST_EXPORT_BEHAVIORAL_RESPONSE_PARAMETERS = { "capital_gains_behavioral_response": "gov.simulation.capital_gains_responses", "labor_supply_behavioral_response": "gov.simulation.labor_supply_responses", @@ -6549,6 +6552,25 @@ 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) + # Each batch engine gets this system alone, not ``reform=`` as well, as the + # post-export scorer's do (``_HouseholdBatchedPostExportScorer._construct``). + # Given both, policyengine-us 2.2.1 clones the supplied system on every + # construction (``SPMSimulationMixin._prepare_spm_system`` -> + # ``clone_spm_system``: the parameter tree rebuilt and every variable + # deep-copied, so each batch starts on cold parameter caches), core applies + # the reform again to the clone, and core adds a ``baseline`` branch whose + # holders copy every input array: one clone per reform per batch, 1,947 in + # a release's target compilation. Given the system alone, the engine shares + # the system's policy (``share_spm_policy``) and has no ``baseline`` + # branch, so this pass refuses the two ways a missing one changes what an + # engine scores: a reform that moves the behavioral-response parameters + # (below), and an engine that computed a formula reading the branch + # (``_refuse_batch_baseline_branch_readers``). + _refuse_reform_moving_behavioral_responses( + reform_system, + microsimulation_cls.default_tax_benefit_system_instance, + measure=reform_spec.measure, + ) batches = tuple(_household_position_batches(n_households, batch_size)) guard_armed = ( len(batches) > 1 @@ -6583,12 +6605,11 @@ def _reform_household_income_tax( reformed = microsimulation_cls( tax_benefit_system=reform_system, dataset=reformed_dataset, - reform=reform, ) try: - with ( - _record_engine_branches(reformed) if guard_armed else nullcontext() - ): + # Branches are recorded at every batch count, because the + # baseline-branch refusal applies to a single batch too. + with _record_engine_branches(reformed): batch_income_tax = _collapse_tax_unit( _calculate_array(reformed, "income_tax"), batch_tax_unit_positions, @@ -6601,6 +6622,12 @@ def _reform_household_income_tax( batches=len(batches), n_households=n_households, ) + _refuse_batch_baseline_branch_readers( + reformed, + measure=reform_spec.measure, + batch=batch, + batches=len(batches), + ) finally: release_engine_simulation(reformed) reform_income_tax[household_positions] = batch_income_tax @@ -7782,6 +7809,66 @@ def _refuse_batch_population_aggregates( ) +def _refuse_reform_moving_behavioral_responses( + reform_system, baseline_system, *, measure: str +) -> None: + """Refuse a JCT reform system that moves a behavioral-response parameter. + + A JCT batch engine gets the reform's system alone, so it has no + ``baseline`` branch, and policyengine-us scores its labor-supply and + capital-gains responses as 0. An engine given ``reform=`` as well has one + and scores them from these parameters, as 0 while they are at the engine's + zero default elasticities. Called once per reform, before its first batch + engine. + """ + + moved = _moved_behavioral_response_parameters( + reform_system, baseline_system, PERIOD + ) + if not moved: + return + raise ValueError( + f"Target materialization refuses JCT reform {measure}: its tax-benefit " + f"system sets behavioral-response parameters off baseline at {PERIOD}: " + f"{', '.join(moved)}. JCT reform batch engines carry no baseline " + "branch, so policyengine-us would score these responses as zero." + ) + + +def _refuse_batch_baseline_branch_readers( + simulation, + *, + measure: str, + batch: int, + batches: int, +) -> None: + """Refuse a JCT batch engine that computed a formula reading ``baseline``. + + The engine has no ``baseline`` branch (see ``_reform_household_income_tax``), + so these formulas compute from the reform where an engine given + ``reform=`` reads the baseline: the Medicaid state denominator from the + reform's own enrollment, and the behavioral-response measurements against + the reform itself. ``_record_engine_branches`` must be active, so that + branches a formula created and then deleted are read too. The base frame + holds no formula-owned column (``_assert_no_formula_owned_columns``), so + any known period was computed, not loaded. + """ + + computed = sorted( + _engine_known_periods(simulation, POST_EXPORT_BASELINE_BRANCH_READERS) + ) + if not computed: + return + raise ValueError( + f"Target materialization of JCT reform {measure}: the engine for " + f"household batch {batch}/{batches} computed " + f"{', '.join(f'{variable}@{period}' for variable, period in computed)}. " + "These policyengine-us formulas read the engine's baseline branch, which " + "a JCT reform batch engine does not carry: it is given the reform's " + "tax-benefit system alone, without reform=." + ) + + def _assert_group_entities_nest_in_households(frame: Frame) -> None: """Refuse a frame whose group entities cross households. From 16464fe5504a01552f9105d7099d5d5f3116ad1a Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Thu, 26 Nov 2026 23:18:33 +0400 Subject: [PATCH 3/5] Compare JCT batches with a separately built reform system Review round 1: the byte-identity test ran the reform= construction on the reform system the system-alone batches had already used, so a change those batches left in the shared system would also reach the clones it was compared with. The comparison now builds its own reform system, as the previous code did, and runs first. It runs in two batches to keep its cost down; the clone-count test keeps three. Co-Authored-By: Claude Opus 5.5 --- .../us/test_us_jct_reform_batches.py | 123 ++++++------------ 1 file changed, 39 insertions(+), 84 deletions(-) diff --git a/packages/microcosm-build/tests/engine_workflow/us/test_us_jct_reform_batches.py b/packages/microcosm-build/tests/engine_workflow/us/test_us_jct_reform_batches.py index c48800dcff..45d84eae46 100644 --- a/packages/microcosm-build/tests/engine_workflow/us/test_us_jct_reform_batches.py +++ b/packages/microcosm-build/tests/engine_workflow/us/test_us_jct_reform_batches.py @@ -101,6 +101,9 @@ #: Five households in batches of two: three batch engines per reform. _BATCH_SIZE = 2 _BATCHES = 3 +#: The 11-reform comparison runs two batches, which keeps its cost down: the +#: construction it compares with clones the reform's system once per batch. +_IDENTITY_BATCH_SIZE = 3 def _jct_frame() -> Frame: @@ -184,46 +187,24 @@ def _jct_frame() -> Frame: ) -def _record_reform_systems(monkeypatch) -> list[tuple[object, object]]: - """Record each ``(reform, system)`` that ``Microsimulation`` builds through - ``default_tax_benefit_system(reform=...)``, as - ``_reform_household_income_tax`` does once per reform.""" - - from policyengine_us import Microsimulation - - built: list[tuple[object, object]] = [] - build_system = Microsimulation.default_tax_benefit_system - - def recording_build(*args, **kwargs): - reform_system = build_system(*args, **kwargs) - built.append((kwargs.get("reform"), reform_system)) - return reform_system - - monkeypatch.setattr( - Microsimulation, "default_tax_benefit_system", staticmethod(recording_build) - ) - return built - - def _income_tax_given_reform_argument( - builder, - frame: Frame, - reform_spec, - system, - *, - reform, - reform_system, - batch_size: int, + builder, frame: Frame, reform_spec, system, *, batch_size: int ) -> np.ndarray: """The household income tax as each batch engine computed it when given - ``reform=`` as well as the reform's system, which the reform's batches - shared (the construction before microcosm 1.6 · 1). Each engine carries a - ``baseline`` branch; at the installed engine's zero default elasticities - it scores no labor-supply or capital-gains response, which a batch engine - without that branch scores as zero too.""" + ``reform=`` as well as the reform's system (the construction before + microcosm 1.6 · 1). As there, the reform's batches share one reform + system, built here and used by nothing else, so a later batch's clone + copies only what earlier batches of this construction left in it. Each + engine carries a ``baseline`` branch; at the installed engine's zero + default elasticities it scores no labor-supply or capital-gains response, + which a batch engine without that branch scores as zero too.""" from policyengine_us import Microsimulation + reform = builder._make_zero_variable_reform( + system, reform_spec.neutralized_variable + ) + reform_system = Microsimulation.default_tax_benefit_system(reform=reform) assert ( builder._moved_behavioral_response_parameters( reform_system, @@ -280,54 +261,29 @@ def counting_clone(self, *args, **kwargs): return clones -def _reform_income_tax_both_ways( - builder, frame: Frame, reform_spec, system, built, *, batch_size: int -) -> tuple[np.ndarray, np.ndarray]: - """``_reform_household_income_tax``'s household income tax, then the same - batches' given ``reform=`` as well, on the one reform system it built.""" - - from policyengine_us import Microsimulation - - systems_before = len(built) - observed = builder._reform_household_income_tax( - base_frame=frame, - reform_spec=reform_spec, - system=system, - microsimulation_cls=Microsimulation, - n_households=frame.n("household"), - batch_size=batch_size, - ) - assert len(built) == systems_before + 1, reform_spec.measure - reform, reform_system = built[-1] - expected = _income_tax_given_reform_argument( - builder, - frame, - reform_spec, - system, - reform=reform, - reform_system=reform_system, - batch_size=batch_size, - ) - return observed, expected - - -def test_jct_reform_batches_match_the_reform_argument_construction( - monkeypatch, -) -> None: +def test_jct_reform_batches_match_the_reform_argument_construction() -> None: """Every shipped JCT reform scores the same household income tax, byte for byte, on batch engines given the reform's system alone as on batch - engines given ``reform=`` as well. Each reform changes income tax for at - least one fixture household and passes both refusals that stand in for - the missing ``baseline`` branch.""" + engines given ``reform=`` as well, each construction on its own reform + system, in two batches. Each reform changes income tax for at least one + fixture household and passes both refusals that stand in for the missing + ``baseline`` branch.""" builder = _load_builder_module() from policyengine_us import CountryTaxBenefitSystem, Microsimulation frame = _jct_frame() n_households = frame.n("household") + assert ( + len( + tuple( + builder._household_position_batches(n_households, _IDENTITY_BATCH_SIZE) + ) + ) + == 2 + ) system = CountryTaxBenefitSystem() builder._assert_no_formula_owned_columns(frame) - built = _record_reform_systems(monkeypatch) baseline = Microsimulation( dataset=builder._dataset_from_frame( frame, assert_no_formula_owned_columns=False, period_only=True @@ -344,8 +300,16 @@ def test_jct_reform_batches_match_the_reform_argument_construction( assert len(builder.US_JCT_TAX_EXPENDITURE_REFORMS) == 11 for reform_spec in builder.US_JCT_TAX_EXPENDITURE_REFORMS: - observed, expected = _reform_income_tax_both_ways( - builder, frame, reform_spec, system, built, batch_size=_BATCH_SIZE + expected = _income_tax_given_reform_argument( + builder, frame, reform_spec, system, batch_size=_IDENTITY_BATCH_SIZE + ) + observed = builder._reform_household_income_tax( + base_frame=frame, + reform_spec=reform_spec, + system=system, + microsimulation_cls=Microsimulation, + n_households=n_households, + batch_size=_IDENTITY_BATCH_SIZE, ) assert observed.dtype == expected.dtype == np.float64 assert observed.tobytes() == expected.tobytes(), ( @@ -378,7 +342,6 @@ def test_jct_reform_batches_clone_no_tax_benefit_system(monkeypatch) -> None: ) == _BATCHES ) - built = _record_reform_systems(monkeypatch) clones = _count_system_clones(monkeypatch) builder._reform_household_income_tax( @@ -390,17 +353,9 @@ def test_jct_reform_batches_clone_no_tax_benefit_system(monkeypatch) -> None: batch_size=_BATCH_SIZE, ) assert clones[0] == 0 - assert len(built) == 1 - reform, reform_system = built[0] _income_tax_given_reform_argument( - builder, - frame, - reform_spec, - system, - reform=reform, - reform_system=reform_system, - batch_size=_BATCH_SIZE, + builder, frame, reform_spec, system, batch_size=_BATCH_SIZE ) assert clones[0] == _BATCHES From 21cc4af935e31bda7fef16bf73058d7c86ce7229 Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Thu, 26 Nov 2026 23:37:58 +0400 Subject: [PATCH 4/5] Tighten the JCT batch tests and wording after review round 2 - The fake-engine test of the population-aggregate refusal in the JCT loop matched any message naming the Medicaid denominator, which is now also a baseline-branch reader, so it passed with that refusal removed. It now matches the population-aggregate refusal's own message. - The fake ledger records whether each engine got a baseline branch at construction; checking simulation.baseline after release could not fail. - The clone-count test also counts private copies of a shared parameter tree (SharedParameterPolicy.detach_parameters), and requires none. - The changelog gives the identity test's two batches; the docs say the JCT engines, unlike the scorer's, pass no spm= selection. Co-Authored-By: Claude Opus 5.5 --- .../us-jct-reform-system-only.changed.md | 2 +- docs/us-release-build-rule.md | 9 ++++--- .../test_us_batched_target_materialization.py | 12 +++++++-- .../us/test_us_jct_reform_batches.py | 27 ++++++++++++++++--- .../us_batched_target_materialization.py | 2 ++ 5 files changed, 42 insertions(+), 10 deletions(-) diff --git a/changelog.d/us-jct-reform-system-only.changed.md b/changelog.d/us-jct-reform-system-only.changed.md index c8b4fd0c64..2969945e6b 100644 --- a/changelog.d/us-jct-reform-system-only.changed.md +++ b/changelog.d/us-jct-reform-system-only.changed.md @@ -1 +1 @@ -Target compilation's JCT tax-expenditure reform batches now give each batch engine the reform's tax-benefit system alone, without `reform=` as well, as post-export scoring does. Given both, policyengine-us 2.2.1 cloned the reform's system for every batch engine and gave each a `baseline` branch: 11 reforms × 177 batches = 1,947 clones in a release build. Without a `baseline` branch, each reform is refused before its first batch engine if its system moves a labor-supply or capital-gains response parameter off baseline, and a batch engine is refused if it computed a formula that reads the `baseline` branch (`POST_EXPORT_BASELINE_BRANCH_READERS`), at every batch count. On a five-household policyengine-us fixture in three batches, all 11 reforms give byte-identical household income tax to the previous construction. The reform income-tax cache identity is unchanged. +Target compilation's JCT tax-expenditure reform batches now give each batch engine the reform's tax-benefit system alone, without `reform=` as well, as post-export scoring does. Given both, policyengine-us 2.2.1 cloned the reform's system for every batch engine and gave each a `baseline` branch: 11 reforms × 177 batches = 1,947 clones in a release build. Without a `baseline` branch, each reform is refused before its first batch engine if its system moves a labor-supply or capital-gains response parameter off baseline, and a batch engine is refused if it computed a formula that reads the `baseline` branch (`POST_EXPORT_BASELINE_BRANCH_READERS`), at every batch count. On a five-household policyengine-us fixture in two batches, all 11 reforms give byte-identical household income tax to the previous construction. The reform income-tax cache identity is unchanged. diff --git a/docs/us-release-build-rule.md b/docs/us-release-build-rule.md index e09999d72e..3ed39de5a8 100644 --- a/docs/us-release-build-rule.md +++ b/docs/us-release-build-rule.md @@ -540,10 +540,11 @@ known violations at run time: zero default elasticities. Target compilation's JCT tax-expenditure reform batches -(`_reform_household_income_tax`) build their engines the same way, from one -reform system per reform, and refuse the same two things: a reform system that -moves the behavioral-response parameters, before its first batch engine, and -a batch engine that computed a baseline-branch reader, at every batch count. +(`_reform_household_income_tax`) also give each batch engine the reform's +system alone, built once per reform; unlike the scorer's, they pass no `spm=` +selection. They refuse the same two things: a reform system that moves the +behavioral-response parameters, before its first batch engine, and a batch +engine that computed a baseline-branch reader, at every batch count. Tests pin the watched lists against the installed engine's formula sources, exercise each guard on a real engine, and compare the shipped baseline plans 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 c21cfdb16b..8c115cfacf 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 @@ -400,7 +400,15 @@ def test_batched_reform_simulation_refuses_population_aggregates( aggregate_reform_only=True, clone_branches=True, ) - with pytest.raises(ValueError, match=r"computed medicaid_slcsp_state_denominator@"): + # The Medicaid denominator is also a baseline-branch reader; this matches + # the population-aggregate refusal's own message, which comes first. + with pytest.raises( + ValueError, + match=( + r"is not batch-invariant: the engine for household batch \d+/\d+ " + r"computed medicaid_slcsp_state_denominator@" + ), + ): builder._materialize_target_frame( _nested_frame(), _TARGETS, maximum_microsim_batch_size=2 ) @@ -432,7 +440,7 @@ def test_jct_reform_engines_get_the_family_system_alone( for entry in reform_constructions: assert entry["reform_argument"] is None assert entry["tax_benefit_system"] is family_system - assert all(simulation.baseline is None for simulation in ledger.simulations) + assert not any(entry["baseline_branch"] for entry in ledger.constructions) assert ledger.behavioral_response_checks == [ (family_system, ledger.shared_baseline_system, builder.PERIOD) ] diff --git a/packages/microcosm-build/tests/engine_workflow/us/test_us_jct_reform_batches.py b/packages/microcosm-build/tests/engine_workflow/us/test_us_jct_reform_batches.py index 45d84eae46..54a31b17f8 100644 --- a/packages/microcosm-build/tests/engine_workflow/us/test_us_jct_reform_batches.py +++ b/packages/microcosm-build/tests/engine_workflow/us/test_us_jct_reform_batches.py @@ -261,6 +261,25 @@ def counting_clone(self, *args, **kwargs): return clones +def _count_parameter_tree_copies(monkeypatch) -> list[int]: + """Count private copies of a shared parameter tree: policyengine-us 2.2.1's + ``SharedParameterPolicy.detach_parameters`` returning true. An engine that + shares its system's policy copies the tree when a reform reaches it.""" + + from policyengine_us.spm import SharedParameterPolicy + + copies = [0] + real_detach = SharedParameterPolicy.detach_parameters + + def counting_detach(self, *args, **kwargs): + copied = real_detach(self, *args, **kwargs) + copies[0] += bool(copied) + return copied + + monkeypatch.setattr(SharedParameterPolicy, "detach_parameters", counting_detach) + return copies + + def test_jct_reform_batches_match_the_reform_argument_construction() -> None: """Every shipped JCT reform scores the same household income tax, byte for byte, on batch engines given the reform's system alone as on batch @@ -324,9 +343,9 @@ def test_jct_reform_batches_match_the_reform_argument_construction() -> None: def test_jct_reform_batches_clone_no_tax_benefit_system(monkeypatch) -> None: - """One JCT reform in three batches clones no tax-benefit system. The - construction with ``reform=`` as well cloned the reform's system once per - batch engine, which the counter sees.""" + """One JCT reform in three batches clones no tax-benefit system and copies + no parameter tree. The construction with ``reform=`` as well cloned the + reform's system once per batch engine, which the counter sees.""" builder = _load_builder_module() from policyengine_us import CountryTaxBenefitSystem, Microsimulation @@ -343,6 +362,7 @@ def test_jct_reform_batches_clone_no_tax_benefit_system(monkeypatch) -> None: == _BATCHES ) clones = _count_system_clones(monkeypatch) + tree_copies = _count_parameter_tree_copies(monkeypatch) builder._reform_household_income_tax( base_frame=frame, @@ -353,6 +373,7 @@ def test_jct_reform_batches_clone_no_tax_benefit_system(monkeypatch) -> None: batch_size=_BATCH_SIZE, ) assert clones[0] == 0 + assert tree_copies[0] == 0 _income_tax_given_reform_argument( builder, frame, reform_spec, system, batch_size=_BATCH_SIZE diff --git a/test_support/microcosm_build/us_batched_target_materialization.py b/test_support/microcosm_build/us_batched_target_materialization.py index 10f0e6efdf..a78a66f042 100644 --- a/test_support/microcosm_build/us_batched_target_materialization.py +++ b/test_support/microcosm_build/us_batched_target_materialization.py @@ -210,6 +210,8 @@ def __init__(self, *, dataset, reform=None, tax_benefit_system=None): self.baseline = _FakeHolders() if reform is not None else None if self.baseline is not None: self.baseline.clone_branches = clone_branches + # Recorded now: releasing an engine clears its ``baseline``. + ledger.constructions[-1]["baseline_branch"] = self.baseline is not None ledger.simulations.append(self) def _ids(self, entity: str) -> np.ndarray: From 5f414d696c1bd93421f8ada13ec408e5a5907991 Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Fri, 27 Nov 2026 00:00:49 +0400 Subject: [PATCH 5/5] Escape the measure name in the JCT refusal test patterns Review round 3 nit: the measure names contain dots, which matched any character in the two real-engine refusal tests' patterns. Co-Authored-By: Claude Opus 5.5 --- .../tests/engine_workflow/us/test_us_jct_reform_batches.py | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/packages/microcosm-build/tests/engine_workflow/us/test_us_jct_reform_batches.py b/packages/microcosm-build/tests/engine_workflow/us/test_us_jct_reform_batches.py index 54a31b17f8..4d58c609a4 100644 --- a/packages/microcosm-build/tests/engine_workflow/us/test_us_jct_reform_batches.py +++ b/packages/microcosm-build/tests/engine_workflow/us/test_us_jct_reform_batches.py @@ -10,6 +10,8 @@ from __future__ import annotations +import re + import numpy as np import pandas as pd import pytest @@ -413,7 +415,7 @@ def __init__(self, *args, **kwargs): with pytest.raises( ValueError, match=( - rf"{reform_spec.measure}.* off baseline at {builder.PERIOD}: " + rf"{re.escape(reform_spec.measure)}.* off baseline at {builder.PERIOD}: " r"gov\.simulation\.labor_supply_responses\.elasticities\.income\." ), ): @@ -454,7 +456,7 @@ def calculate_array_reaching_medicaid(simulation, variable, **kwargs): with pytest.raises( ValueError, match=( - rf"{reform_spec.measure}.*household batch 1/1 computed " + rf"{re.escape(reform_spec.measure)}.*household batch 1/1 computed " rf"medicaid_slcsp_state_denominator@{builder.PERIOD}\." ), ):