From e31bc0e6fc8202909b5cca41d5b391daa53e4f82 Mon Sep 17 00:00:00 2001 From: Max Ghenis Date: Sun, 1 Nov 2026 12:00:00 -0500 Subject: [PATCH 01/42] Net child care subsidies from the SPM expense in every state The SPM subtracts what parents paid for child care and lists no child care benefit among its noncash resources. PolicyEngine subtracted pre-subsidy expenses and added only the Colorado, Washington and West Virginia subsidies to resources, so a subsidy in the other 48 states lowered SPM resources. Net child_care_subsidies from the expense instead, and take the three states out of spm_unit_benefits and the four reform copies of that list. Co-Authored-By: Claude Opus 5.5 --- changelog.d/spm-child-care-subsidies.fixed.md | 1 + .../tlaib/boost/boost_middle_class_tax_credit.py | 1 - .../edaa_end_child_poverty_act.py | 1 - .../congress/tlaib/end_child_poverty_act.py | 1 - .../reforms/states/tx/rebate/tx_rebate.py | 5 ----- .../spm_unit_capped_work_childcare_expenses.py | 14 ++++++++++++-- .../household/income/spm_unit/spm_unit_benefits.py | 7 ++----- 7 files changed, 15 insertions(+), 15 deletions(-) create mode 100644 changelog.d/spm-child-care-subsidies.fixed.md diff --git a/changelog.d/spm-child-care-subsidies.fixed.md b/changelog.d/spm-child-care-subsidies.fixed.md new file mode 100644 index 00000000000..3761ac3df12 --- /dev/null +++ b/changelog.d/spm-child-care-subsidies.fixed.md @@ -0,0 +1 @@ +Count every state child care subsidy in the Supplemental Poverty Measure by netting it from the SPM child care expense. diff --git a/policyengine_us/reforms/congress/tlaib/boost/boost_middle_class_tax_credit.py b/policyengine_us/reforms/congress/tlaib/boost/boost_middle_class_tax_credit.py index 3bc42955517..939e41d3330 100644 --- a/policyengine_us/reforms/congress/tlaib/boost/boost_middle_class_tax_credit.py +++ b/policyengine_us/reforms/congress/tlaib/boost/boost_middle_class_tax_credit.py @@ -107,7 +107,6 @@ def formula(spm_unit, period, parameters): # California programs. "ca_cvrp", # California Clean Vehicle Rebate Project. # Colorado programs. - "co_ccap_subsidy", "co_state_supplement", "co_oap", "snap", diff --git a/policyengine_us/reforms/congress/tlaib/economic_dignity_for_all_agenda/edaa_end_child_poverty_act.py b/policyengine_us/reforms/congress/tlaib/economic_dignity_for_all_agenda/edaa_end_child_poverty_act.py index 47eba8ba25d..1dbc0b9ebb7 100644 --- a/policyengine_us/reforms/congress/tlaib/economic_dignity_for_all_agenda/edaa_end_child_poverty_act.py +++ b/policyengine_us/reforms/congress/tlaib/economic_dignity_for_all_agenda/edaa_end_child_poverty_act.py @@ -119,7 +119,6 @@ def formula(spm_unit, period, parameters): "ssi", "ma_state_supplement", "ca_cvrp", - "co_ccap_subsidy", "co_state_supplement", "co_oap", "snap", diff --git a/policyengine_us/reforms/congress/tlaib/end_child_poverty_act.py b/policyengine_us/reforms/congress/tlaib/end_child_poverty_act.py index 42729a88112..e8df22a6c4b 100644 --- a/policyengine_us/reforms/congress/tlaib/end_child_poverty_act.py +++ b/policyengine_us/reforms/congress/tlaib/end_child_poverty_act.py @@ -135,7 +135,6 @@ def formula(spm_unit, period, parameters): # California programs. "ca_cvrp", # California Clean Vehicle Rebate Project. # Colorado programs. - "co_ccap_subsidy", "co_state_supplement", "co_oap", "snap", diff --git a/policyengine_us/reforms/states/tx/rebate/tx_rebate.py b/policyengine_us/reforms/states/tx/rebate/tx_rebate.py index 4d5d1f4c86a..b2b47519ac3 100644 --- a/policyengine_us/reforms/states/tx/rebate/tx_rebate.py +++ b/policyengine_us/reforms/states/tx/rebate/tx_rebate.py @@ -77,19 +77,14 @@ def formula(spm_unit, period, parameters): # California programs. "ca_cvrp", # California Clean Vehicle Rebate Project. # Colorado programs. - "co_ccap_subsidy", "co_state_supplement", "co_oap", - # Washington programs. - "wa_child_care_subsidies", # New Mexico programs. "nm_ssi_state_supplement", # South Carolina programs. "sc_ssi_state_supplement", # Texas programs. "tx_ssi_state_supplement", - # West Virginia programs. - "wv_child_care_subsidies", "snap", "wic", "free_school_meals", diff --git a/policyengine_us/variables/household/expense/childcare/spm_unit_capped_work_childcare_expenses.py b/policyengine_us/variables/household/expense/childcare/spm_unit_capped_work_childcare_expenses.py index f29e642e20b..b457ab7680a 100644 --- a/policyengine_us/variables/household/expense/childcare/spm_unit_capped_work_childcare_expenses.py +++ b/policyengine_us/variables/household/expense/childcare/spm_unit_capped_work_childcare_expenses.py @@ -7,9 +7,19 @@ class spm_unit_capped_work_childcare_expenses(Variable): label = "SPM unit work and childcare expenses" definition_period = YEAR unit = USD + reference = "https://www2.census.gov/programs-surveys/supplemental-poverty-measure/datasets/spm/spm_techdoc.pdf#page=17" def formula_2024(spm_unit, period, parameters): work_expenses = spm_unit("spm_unit_work_expenses", period) - childcare_expenses = spm_unit("spm_unit_pre_subsidy_childcare_expenses", period) + pre_subsidy_expenses = spm_unit( + "spm_unit_pre_subsidy_childcare_expenses", period + ) + # The SPM subtracts what parents paid for child care, and child care + # is not among its noncash benefits, so a subsidy lowers this expense + # rather than adding to resources. This reads the SPM unit's expenses + # directly because childcare_expenses divides them among children and + # drops them from a unit with no child. + subsidies = spm_unit("child_care_subsidies", period) + childcare_expenses = max_(pre_subsidy_expenses - subsidies, 0) earned_cap = spm_unit("spm_unit_head_spouse_earned_cap", period) - return min_(work_expenses + np.maximum(childcare_expenses, 0), earned_cap) + return min_(work_expenses + childcare_expenses, earned_cap) diff --git a/policyengine_us/variables/household/income/spm_unit/spm_unit_benefits.py b/policyengine_us/variables/household/income/spm_unit/spm_unit_benefits.py index 118a9e0dc0d..d26c86ab5d9 100644 --- a/policyengine_us/variables/household/income/spm_unit/spm_unit_benefits.py +++ b/policyengine_us/variables/household/income/spm_unit/spm_unit_benefits.py @@ -9,6 +9,8 @@ class spm_unit_benefits(Variable): unit = USD def formula(spm_unit, period, parameters): + # Child care subsidies stay out of this list: they lower the expense + # in spm_unit_capped_work_childcare_expenses instead. BENEFITS = [ "social_security", "ssi", @@ -58,19 +60,14 @@ def formula(spm_unit, period, parameters): # summing it with ssi does not double-count. "ca_state_supplement", # Colorado programs. - "co_ccap_subsidy", "co_state_supplement", "co_oap", - # Washington programs. - "wa_child_care_subsidies", # New Mexico programs. "nm_ssi_state_supplement", # South Carolina programs. "sc_ssi_state_supplement", # Texas programs. "tx_ssi_state_supplement", - # West Virginia programs. - "wv_child_care_subsidies", "snap", "wic", "free_school_meals", From ac341ab25d7c45c3c66c389f12a29a0865340825 Mon Sep 17 00:00:00 2001 From: Max Ghenis Date: Sun, 1 Nov 2026 12:25:29 -0500 Subject: [PATCH 02/42] Test child care subsidies in the SPM Add YAML cases for the formula's edges and for New York, Texas, Alaska, Washington, West Virginia and Colorado through their real programs, and property tests for the invariants. The whole-model form of "a subsidy never lowers SPM resources" fails where SNAP, TANF and credits fall by more than the expense, so the property holds those fixed and one test pins the intended case. Co-Authored-By: Claude Opus 5.5 --- .../spm_child_care_subsidies_integration.yaml | 256 +++++++++++++ ...m_unit_capped_work_childcare_expenses.yaml | 71 ++++ .../test_spm_child_care_subsidy_invariants.py | 351 ++++++++++++++++++ 3 files changed, 678 insertions(+) create mode 100644 policyengine_us/tests/policy/baseline/household/expense/childcare/spm_child_care_subsidies_integration.yaml create mode 100644 policyengine_us/tests/test_spm_child_care_subsidy_invariants.py diff --git a/policyengine_us/tests/policy/baseline/household/expense/childcare/spm_child_care_subsidies_integration.yaml b/policyengine_us/tests/policy/baseline/household/expense/childcare/spm_child_care_subsidies_integration.yaml new file mode 100644 index 00000000000..f05bf02bb74 --- /dev/null +++ b/policyengine_us/tests/policy/baseline/household/expense/childcare/spm_child_care_subsidies_integration.yaml @@ -0,0 +1,256 @@ +# Real state programs through the SPM child care expense. New York, Texas and +# Alaska subsidies never reached the SPM before; Colorado, Washington and West +# Virginia reached it as resources, on top of pre-subsidy expenses. +# +# Each family is one working parent with earnings of $30,000 and a child aged 3 +# in care 8 hours a day, 5 days a week. Without weeks_worked, work expenses are +# zero, so the SPM expense is the out-of-pocket amount. + +- name: New York, Manhattan family with a subsidy just below the expense + period: 2026 + absolute_error_margin: 0.01 + input: + people: + parent: + age: 30 + employment_income: 30_000 + weekly_hours_worked_before_lsr: 40 + is_tax_unit_head: true + is_household_head: true + child: + age: 3 + childcare_hours_per_day: 8 + childcare_days_per_week: 5 + is_tax_unit_dependent: true + tax_units: + tax_unit: + members: [parent, child] + families: + family: + members: [parent, child] + spm_units: + spm_unit: + members: [parent, child] + spm_unit_pre_subsidy_childcare_expenses: 14_000 + households: + household: + members: [parent, child] + state_code: NY + county_fips: "36061" + output: + child_care_subsidies: 13_916.40 + # 14,000 - 13,916.40. + spm_unit_capped_work_childcare_expenses: 83.60 + +- name: New York, a child with no reported care hours gets no subsidy, so the expense stays + period: 2026 + absolute_error_margin: 0.01 + input: + people: + parent: + age: 30 + employment_income: 30_000 + weekly_hours_worked_before_lsr: 40 + is_tax_unit_head: true + is_household_head: true + child: + age: 3 + is_tax_unit_dependent: true + tax_units: + tax_unit: + members: [parent, child] + families: + family: + members: [parent, child] + spm_units: + spm_unit: + members: [parent, child] + spm_unit_pre_subsidy_childcare_expenses: 14_000 + households: + household: + members: [parent, child] + state_code: NY + county_fips: "36061" + output: + child_care_subsidies: 0 + spm_unit_capped_work_childcare_expenses: 14_000 + +- name: Texas, a subsidy the SPM left out before + period: 2026 + absolute_error_margin: 0.01 + input: + people: + parent: + age: 30 + employment_income: 30_000 + weekly_hours_worked_before_lsr: 40 + is_tax_unit_head: true + is_household_head: true + child: + age: 3 + childcare_hours_per_day: 8 + childcare_days_per_week: 5 + childcare_attending_days_per_month: 21 + is_tax_unit_dependent: true + tax_units: + tax_unit: + members: [parent, child] + families: + family: + members: [parent, child] + spm_units: + spm_unit: + members: [parent, child] + spm_unit_pre_subsidy_childcare_expenses: 14_000 + households: + household: + members: [parent, child] + state_code: TX + output: + child_care_subsidies: 6_014.49 + # 14,000 - 6,014.49. + spm_unit_capped_work_childcare_expenses: 7_985.51 + +- name: Alaska, a subsidy the SPM left out before + period: 2026 + absolute_error_margin: 0.01 + input: + people: + parent: + age: 30 + employment_income: 30_000 + weekly_hours_worked_before_lsr: 40 + is_tax_unit_head: true + is_household_head: true + child: + age: 3 + childcare_hours_per_day: 8 + childcare_days_per_week: 5 + childcare_attending_days_per_month: 21 + is_tax_unit_dependent: true + tax_units: + tax_unit: + members: [parent, child] + families: + family: + members: [parent, child] + spm_units: + spm_unit: + members: [parent, child] + spm_unit_pre_subsidy_childcare_expenses: 14_000 + households: + household: + members: [parent, child] + state_code: AK + output: + child_care_subsidies: 9_432 + # 14,000 - 9,432. + spm_unit_capped_work_childcare_expenses: 4_568 + +- name: Washington, a subsidy the SPM counted as a resource before + period: 2026 + absolute_error_margin: 0.01 + input: + people: + parent: + age: 30 + employment_income: 30_000 + weekly_hours_worked_before_lsr: 40 + is_tax_unit_head: true + is_household_head: true + child: + age: 3 + childcare_hours_per_day: 8 + childcare_days_per_week: 5 + childcare_attending_days_per_month: 21 + is_tax_unit_dependent: true + tax_units: + tax_unit: + members: [parent, child] + families: + family: + members: [parent, child] + spm_units: + spm_unit: + members: [parent, child] + spm_unit_pre_subsidy_childcare_expenses: 14_000 + households: + household: + members: [parent, child] + state_code: WA + output: + child_care_subsidies: 13_220 + # 14,000 - 13,220. + spm_unit_capped_work_childcare_expenses: 780 + +- name: West Virginia, a subsidy the SPM counted as a resource before + period: 2026 + absolute_error_margin: 0.01 + input: + people: + parent: + age: 30 + employment_income: 30_000 + weekly_hours_worked_before_lsr: 40 + is_tax_unit_head: true + is_household_head: true + child: + age: 3 + childcare_hours_per_day: 8 + childcare_days_per_week: 5 + childcare_attending_days_per_month: 21 + is_tax_unit_dependent: true + tax_units: + tax_unit: + members: [parent, child] + families: + family: + members: [parent, child] + spm_units: + spm_unit: + members: [parent, child] + spm_unit_pre_subsidy_childcare_expenses: 14_000 + households: + household: + members: [parent, child] + state_code: WV + output: + child_care_subsidies: 7_623 + # 14,000 - 7,623. + spm_unit_capped_work_childcare_expenses: 6_377 + +- name: Colorado, a subsidy the SPM counted as a resource before + period: 2026 + absolute_error_margin: 0.01 + input: + people: + parent: + age: 30 + employment_income: 30_000 + weekly_hours_worked_before_lsr: 40 + is_tax_unit_head: true + is_household_head: true + child: + age: 3 + childcare_hours_per_day: 8 + childcare_days_per_week: 5 + childcare_attending_days_per_month: 21 + is_tax_unit_dependent: true + tax_units: + tax_unit: + members: [parent, child] + families: + family: + members: [parent, child] + spm_units: + spm_unit: + members: [parent, child] + spm_unit_pre_subsidy_childcare_expenses: 14_000 + households: + household: + members: [parent, child] + state_code: CO + output: + child_care_subsidies: 12_613.16 + # 14,000 - 12,613.16. + spm_unit_capped_work_childcare_expenses: 1_386.84 diff --git a/policyengine_us/tests/policy/baseline/household/expense/childcare/spm_unit_capped_work_childcare_expenses.yaml b/policyengine_us/tests/policy/baseline/household/expense/childcare/spm_unit_capped_work_childcare_expenses.yaml index cd2e0be8f63..619b3d891ca 100644 --- a/policyengine_us/tests/policy/baseline/household/expense/childcare/spm_unit_capped_work_childcare_expenses.yaml +++ b/policyengine_us/tests/policy/baseline/household/expense/childcare/spm_unit_capped_work_childcare_expenses.yaml @@ -105,3 +105,74 @@ spm_unit_pre_subsidy_childcare_expenses: 2_000 output: spm_unit_capped_work_childcare_expenses: 2_000 + +- name: A child care subsidy lowers the out-of-pocket expense + period: 2026 + absolute_error_margin: 0.001 + input: + spm_unit_work_expenses: 1_000 + spm_unit_head_spouse_earned_cap: 30_000 + spm_unit_pre_subsidy_childcare_expenses: 14_000 + child_care_subsidies: 13_916.40 + output: + # 1,000 + (14,000 - 13,916.40). + spm_unit_capped_work_childcare_expenses: 1_083.60 + +- name: A subsidy above the expense leaves only work expenses + period: 2026 + absolute_error_margin: 0.001 + input: + spm_unit_work_expenses: 1_000 + spm_unit_head_spouse_earned_cap: 30_000 + spm_unit_pre_subsidy_childcare_expenses: 1_200 + child_care_subsidies: 22_828 + output: + # The floor keeps the part of the subsidy above the expense out of the + # SPM, so it cannot offset work expenses. + spm_unit_capped_work_childcare_expenses: 1_000 + +- name: The earnings cap applies after the subsidy + period: 2026 + absolute_error_margin: 0.001 + input: + spm_unit_work_expenses: 1_000 + spm_unit_head_spouse_earned_cap: 5_000 + spm_unit_pre_subsidy_childcare_expenses: 14_000 + child_care_subsidies: 2_000 + output: + # 1,000 + 12,000 exceeds the cap, so the subsidy leaves the expense at + # the cap. + spm_unit_capped_work_childcare_expenses: 5_000 + +- name: A subsidy can bring the expense below the earnings cap + period: 2026 + absolute_error_margin: 0.001 + input: + spm_unit_work_expenses: 1_000 + spm_unit_head_spouse_earned_cap: 5_000 + spm_unit_pre_subsidy_childcare_expenses: 14_000 + child_care_subsidies: 13_000 + output: + spm_unit_capped_work_childcare_expenses: 2_000 + +- name: Expenses in a unit with no child are capped as before and take no subsidy + period: 2026 + absolute_error_margin: 0.001 + input: + people: + head: + age: 46 + employment_income: 9_000 + is_household_head: true + is_tax_unit_head: true + tax_units: + tax_unit: + members: [head] + spm_units: + spm_unit: + members: [head] + spm_unit_work_expenses: 0 + spm_unit_pre_subsidy_childcare_expenses: 4_000 + output: + child_care_subsidies: 0 + spm_unit_capped_work_childcare_expenses: 4_000 diff --git a/policyengine_us/tests/test_spm_child_care_subsidy_invariants.py b/policyengine_us/tests/test_spm_child_care_subsidy_invariants.py new file mode 100644 index 00000000000..0e152dc6ad9 --- /dev/null +++ b/policyengine_us/tests/test_spm_child_care_subsidy_invariants.py @@ -0,0 +1,351 @@ +"""Invariants for child care subsidies in the Supplemental Poverty Measure. + +The Census Bureau's SPM technical documentation (last updated 2026-09-15): + +- Page 17 subtracts what parents paid for child care, combined with other work + expenses and capped at the earnings of the lower earner among the reference + person and spouse or partner. +- Section 4.3.1 lists the noncash benefits the SPM adds to resources: SNAP, + school lunch, WIC, energy assistance, internet assistance and housing + assistance. Child care is not among them. + +So a subsidy reaches the SPM once, as a lower expense. With E the pre-subsidy +expense, S the subsidy, W work expenses and C the earnings cap: + + expense(S) = min(W + max(E - S, 0), C) + +For every SPM unit: + +1. The model's expense equals that reference, written from the documentation + rather than from the formula. +2. A subsidy never raises the expense and lowers it by at most the subsidy: + 0 <= expense(0) - expense(S) <= S. A larger subsidy never raises it either. +3. No double counting. With taxes and every other benefit held fixed, a + subsidy leaves spm_unit_benefits unchanged and raises spm_unit_net_income + by exactly expense(0) - expense(S). So this direct effect is never negative + and never exceeds the subsidy. +4. A subsidy of zero leaves the expense at min(W + max(E, 0), C), the formula + before this rule, in every state. +5. No program is counted twice. No *_child_care_subsidies variable, and no + program one of them adds, appears in spm_unit_benefits or in a reform's copy + of that list, and all of them reach child_care_subsidies. +6. Differential. With real programs turned on and off, the SPM and household + measures agree on what else changed: the change in SPM net income is the + change in household net income, less the subsidy the household measure + counts, plus the fall in the expense. + +Intended violation of "a subsidy never lowers SPM resources". Property 3 holds +taxes and other benefits fixed, and it has to. SNAP, TANF and tax credits read +out-of-pocket expenses, so a subsidy can cut them by more than the SPM expense +falls, most plainly when the unit stays at the earnings cap and the expense +does not move at all. The household measure shows the same interaction. +test_subsidy_at_the_cap_can_lower_spm_income pins one such case; the fall comes +from those programs and not from this rule. +""" + +from functools import cache + +import numpy as np +import pytest +import yaml + +from policyengine_core.reforms import Reform +from policyengine_us import Simulation +from policyengine_us.system import CountryTaxBenefitSystem +from test_aggregate_list_integrity import ( + BASELINE_SPM_BENEFITS_SOURCE, + PACKAGE, + REFORM_AGGREGATE_OVERRIDES, + benefits_lists_in, + members_of, +) + +hypothesis = pytest.importorskip("hypothesis") +st = pytest.importorskip("hypothesis.strategies") +given, settings = hypothesis.given, hypothesis.settings + +YEAR = 2026 +TOLERANCE = 0.01 +PROGRAMS_LIST = "gov/hhs/ccdf/child_care_subsidy_programs.yaml" +STATE_SUBSIDIES = sorted(members_of(PROGRAMS_LIST)) +STATES = [name[:2].upper() for name in STATE_SUBSIDIES] + + +def reference_expense(pre_subsidy, subsidy, work, cap): + return min(work + max(pre_subsidy - subsidy, 0), cap) + + +def build_units(units): + """One SPM unit per entry. The parent's earnings are high enough that no + means-tested benefit pays, and taxes are an input, so only the child care + rule can move these units' SPM results.""" + people, tax_units, spm_units, families, households = {}, {}, {}, {}, {} + marital_units = {} + for i, unit in enumerate(units): + parent, child = f"parent_{i}", f"child_{i}" + people[parent] = { + "age": {YEAR: 35}, + "employment_income": {YEAR: 400_000}, + "is_tax_unit_head": {YEAR: True}, + "is_household_head": {YEAR: True}, + } + people[child] = {"age": {YEAR: 4}, "is_tax_unit_dependent": {YEAR: True}} + members = [parent, child] + state = unit["state"] + tax_units[f"tax_unit_{i}"] = {"members": members} + families[f"family_{i}"] = {"members": members} + marital_units[f"marital_unit_{i}"] = {"members": [parent]} + marital_units[f"child_marital_unit_{i}"] = {"members": [child]} + spm_units[f"spm_unit_{i}"] = { + "members": members, + "spm_unit_pre_subsidy_childcare_expenses": {YEAR: unit["expenses"]}, + "spm_unit_work_expenses": {YEAR: unit["work"]}, + "spm_unit_head_spouse_earned_cap": {YEAR: unit["cap"]}, + f"{state.lower()}_child_care_subsidies": {YEAR: unit["subsidy"]}, + "spm_unit_taxes": {YEAR: 0}, + } + households[f"household_{i}"] = { + "members": members, + "state_code": {YEAR: state}, + } + return { + "people": people, + "tax_units": tax_units, + "families": families, + "marital_units": marital_units, + "spm_units": spm_units, + "households": households, + } + + +amounts = st.integers(0, 40_000) +unit_strategy = st.fixed_dictionaries( + { + "state": st.sampled_from(STATES), + "expenses": amounts, + "subsidy": amounts, + "work": st.integers(0, 6_000), + "cap": st.integers(0, 60_000), + "extra_subsidy": st.integers(0, 10_000), + } +) + + +def spm_outputs(units): + simulation = Simulation(situation=build_units(units)) + return { + variable: np.asarray(simulation.calculate(variable, YEAR), dtype=float) + for variable in ( + "child_care_subsidies", + "spm_unit_capped_work_childcare_expenses", + "spm_unit_benefits", + "spm_unit_net_income", + ) + } + + +@settings(max_examples=25, deadline=None) +@given(st.lists(unit_strategy, min_size=1, max_size=4)) +def test_expense_nets_subsidies_exactly_once(units): + # Each unit runs three times in one simulation: as drawn, with no subsidy + # and with a larger subsidy. + without = [{**unit, "subsidy": 0} for unit in units] + larger = [{**u, "subsidy": u["subsidy"] + u["extra_subsidy"]} for u in units] + results = spm_outputs(units + without + larger) + expense = results["spm_unit_capped_work_childcare_expenses"] + benefits = results["spm_unit_benefits"] + net_income = results["spm_unit_net_income"] + + n = len(units) + for i, unit in enumerate(units): + reference = reference_expense( + unit["expenses"], unit["subsidy"], unit["work"], unit["cap"] + ) + no_subsidy = reference_expense(unit["expenses"], 0, unit["work"], unit["cap"]) + # 1. The expense matches the documented definition. + assert expense[i] == pytest.approx(reference, abs=TOLERANCE) + assert results["child_care_subsidies"][i] == pytest.approx( + unit["subsidy"], abs=TOLERANCE + ) + # 4. Without a subsidy the old formula still holds, in every state. + assert expense[n + i] == pytest.approx(no_subsidy, abs=TOLERANCE) + # 2. The fall is at least zero and at most the subsidy, and a larger + # subsidy never raises the expense. + fall = expense[n + i] - expense[i] + assert -TOLERANCE <= fall <= unit["subsidy"] + TOLERANCE + assert expense[2 * n + i] <= expense[i] + TOLERANCE + # 3. The subsidy is not a resource, so net income rises by the fall in + # the expense and by nothing else. + assert benefits[i] == pytest.approx(benefits[n + i], abs=TOLERANCE) + gain = net_income[i] - net_income[n + i] + assert gain == pytest.approx(fall, abs=TOLERANCE) + + +def state_subsidy_adds(): + """{*_child_care_subsidies: the programs it adds}, from the model.""" + from policyengine_us.system import system + + return {name: list(system.variables[name].adds) for name in STATE_SUBSIDIES} + + +def test_no_subsidy_is_a_spm_resource(): + subsidy_variables = set(STATE_SUBSIDIES) | {"child_care_subsidies"} + for programs in state_subsidy_adds().values(): + subsidy_variables.update(programs) + lists = { + "baseline spm_unit_benefits": benefits_lists_in(BASELINE_SPM_BENEFITS_SOURCE)[ + 0 + ][1] + } + for path, variable, members in REFORM_AGGREGATE_OVERRIDES: + if variable == "spm_unit_benefits": + lists[path] = members + assert len(lists) >= 5, f"expected the reform copies, found {sorted(lists)}" + counted_twice = { + name: sorted(subsidy_variables & set(members)) + for name, members in lists.items() + if subsidy_variables & set(members) + } + assert not counted_twice, ( + "Child care subsidies reach the SPM by lowering " + f"spm_unit_capped_work_childcare_expenses, not as resources: {counted_twice}" + ) + + +def test_every_state_subsidy_reaches_the_spm_expense(): + variables_dir = PACKAGE / "variables/gov/states" + defined = {path.stem for path in variables_dir.rglob("*_child_care_subsidies.py")} + latest_block = max( + yaml.load( + (PACKAGE / "parameters" / PROGRAMS_LIST).read_text(), yaml.BaseLoader + )["values"].items() + )[1] + assert defined == set(latest_block) + assert len(defined) == 51 + + +class NoSubsidies(Reform): + def apply(self): + for variable in STATE_SUBSIDIES: + self.neutralize_variable(variable) + + +@cache +def no_subsidy_system(): + return NoSubsidies(CountryTaxBenefitSystem()) + + +def family(state, earnings, expenses): + """A working parent and a child aged 3 in full-time care, with real + programs, taxes and benefits.""" + members = ["parent", "child"] + return { + "people": { + "parent": { + "age": {YEAR: 30}, + "employment_income": {YEAR: earnings}, + "weekly_hours_worked": {YEAR: 40}, + "weeks_worked": {YEAR: 52}, + "is_tax_unit_head": {YEAR: True}, + "is_household_head": {YEAR: True}, + }, + "child": { + "age": {YEAR: 3}, + "childcare_hours_per_day": {YEAR: 8}, + "childcare_days_per_week": {YEAR: 5}, + "childcare_attending_days_per_month": {YEAR: 21}, + "is_tax_unit_dependent": {YEAR: True}, + }, + }, + "tax_units": {"tax_unit": {"members": members}}, + "families": {"family": {"members": members}}, + "spm_units": { + "spm_unit": { + "members": members, + "spm_unit_pre_subsidy_childcare_expenses": {YEAR: expenses}, + "meets_ccdf_activity_test": {YEAR: True}, + } + }, + "households": {"household": {"members": members, "state_code": {YEAR: state}}}, + } + + +def with_and_without_subsidies(state, earnings, expenses): + situation = family(state, earnings, expenses) + on = Simulation(situation=situation) + off = Simulation(situation=situation, tax_benefit_system=no_subsidy_system()) + + def change(variable): + return float(on.calculate(variable, YEAR).sum()) - float( + off.calculate(variable, YEAR).sum() + ) + + assert float(off.calculate("child_care_subsidies", YEAR).sum()) == 0 + return on, change + + +def subsidy_counted_by_household_measure(simulation, state): + """The subsidy household_state_benefits sums, whether it lists the state's + variable or the national aggregate.""" + listed = simulation.tax_benefit_system.parameters( + f"{YEAR}-01-01" + ).gov.household.household_state_benefits + state_variable = f"{state.lower()}_child_care_subsidies" + if "child_care_subsidies" in listed or state_variable in listed: + return float(simulation.calculate("child_care_subsidies", YEAR).sum()) + return 0.0 + + +@settings(max_examples=12, deadline=None) +@given( + state=st.sampled_from(STATES), + earnings=st.integers(5_000, 60_000), + expenses=st.integers(0, 25_000), +) +def test_spm_and_household_measures_agree(state, earnings, expenses): + on, change = with_and_without_subsidies(state, earnings, expenses) + fall = -change("spm_unit_capped_work_childcare_expenses") + counted = subsidy_counted_by_household_measure(on, state) + assert change("spm_unit_net_income") == pytest.approx( + change("household_net_income") - counted + fall, abs=TOLERANCE + ) + + +def test_new_york_subsidy_raises_both_measures_by_the_same_amount(): + # The Manhattan family from the report that prompted this rule. + situation = family("NY", 30_000, 14_000) + situation["households"]["household"]["county_fips"] = {YEAR: "36061"} + del situation["people"]["parent"]["weeks_worked"] + on = Simulation(situation=situation) + off = Simulation(situation=situation, tax_benefit_system=no_subsidy_system()) + + def change(variable): + return float(on.calculate(variable, YEAR).sum()) - float( + off.calculate(variable, YEAR).sum() + ) + + subsidy = float(on.calculate("child_care_subsidies", YEAR).sum()) + assert subsidy > 13_000 + assert change("spm_unit_capped_work_childcare_expenses") == pytest.approx( + -subsidy, abs=TOLERANCE + ) + assert change("household_net_income") > 0 + assert change("spm_unit_net_income") == pytest.approx( + change("household_net_income"), abs=TOLERANCE + ) + + +def test_subsidy_at_the_cap_can_lower_spm_income(): + # Intended: this unit stays at the earnings cap, so the SPM expense does + # not move, while the fall in out-of-pocket expenses cuts SNAP. See the + # module docstring. + on, change = with_and_without_subsidies("CA", 8_000, 25_000) + assert float(on.calculate("child_care_subsidies", YEAR).sum()) > 0 + assert change("spm_unit_capped_work_childcare_expenses") == pytest.approx( + 0, abs=TOLERANCE + ) + assert change("snap") < 0 + assert change("spm_unit_net_income") == pytest.approx( + change("spm_unit_benefits") - change("spm_unit_taxes"), abs=TOLERANCE + ) + assert change("spm_unit_net_income") < 0 From 343f8fee08195de402bb6936b9986f2bab55b7d1 Mon Sep 17 00:00:00 2001 From: Max Ghenis Date: Sun, 1 Nov 2026 13:11:08 -0500 Subject: [PATCH 03/42] Pin the size of the SPM expense fall in the differential test The differential passed on the old code because its identity holds when the expense does not move. It now also requires the fall the Census definition gives, with explicit examples in states that left the subsidy out and states that counted it as a resource. Income comparisons get a tolerance above float32 rounding, which tripped the exact comparison at the fixture's $400,000 of earnings. Co-Authored-By: Claude Opus 5.5 --- .../test_spm_child_care_subsidy_invariants.py | 57 ++++++++++++------- 1 file changed, 35 insertions(+), 22 deletions(-) diff --git a/policyengine_us/tests/test_spm_child_care_subsidy_invariants.py b/policyengine_us/tests/test_spm_child_care_subsidy_invariants.py index 0e152dc6ad9..9aa0dbbde69 100644 --- a/policyengine_us/tests/test_spm_child_care_subsidy_invariants.py +++ b/policyengine_us/tests/test_spm_child_care_subsidy_invariants.py @@ -29,10 +29,11 @@ 5. No program is counted twice. No *_child_care_subsidies variable, and no program one of them adds, appears in spm_unit_benefits or in a reform's copy of that list, and all of them reach child_care_subsidies. -6. Differential. With real programs turned on and off, the SPM and household - measures agree on what else changed: the change in SPM net income is the - change in household net income, less the subsidy the household measure - counts, plus the fall in the expense. +6. Differential. With real programs turned on and off, the expense falls by + the amount the reference gives for the subsidy the program paid, and the + SPM and household measures agree on what else changed: the change in SPM + net income is the change in household net income, less the subsidy the + household measure counts, plus the fall in the expense. Intended violation of "a subsidy never lowers SPM resources". Property 3 holds taxes and other benefits fixed, and it has to. SNAP, TANF and tax credits read @@ -62,10 +63,14 @@ hypothesis = pytest.importorskip("hypothesis") st = pytest.importorskip("hypothesis.strategies") -given, settings = hypothesis.given, hypothesis.settings +example, given, settings = hypothesis.example, hypothesis.given, hypothesis.settings YEAR = 2026 TOLERANCE = 0.01 +# Income variables are float32, which rounds to about $0.03 at the $400,000 the +# fixtures below earn. Every input is a whole dollar, so this still catches a +# $1 error. +INCOME_TOLERANCE = 0.25 PROGRAMS_LIST = "gov/hhs/ccdf/child_care_subsidy_programs.yaml" STATE_SUBSIDIES = sorted(members_of(PROGRAMS_LIST)) STATES = [name[:2].upper() for name in STATE_SUBSIDIES] @@ -178,7 +183,7 @@ def test_expense_nets_subsidies_exactly_once(units): # the expense and by nothing else. assert benefits[i] == pytest.approx(benefits[n + i], abs=TOLERANCE) gain = net_income[i] - net_income[n + i] - assert gain == pytest.approx(fall, abs=TOLERANCE) + assert gain == pytest.approx(fall, abs=INCOME_TOLERANCE) def state_subsidy_adds(): @@ -212,7 +217,7 @@ def test_no_subsidy_is_a_spm_resource(): ) -def test_every_state_subsidy_reaches_the_spm_expense(): +def test_every_state_subsidy_is_in_the_programs_list(): variables_dir = PACKAGE / "variables/gov/states" defined = {path.stem for path in variables_dir.rglob("*_child_care_subsidies.py")} latest_block = max( @@ -270,8 +275,7 @@ def family(state, earnings, expenses): } -def with_and_without_subsidies(state, earnings, expenses): - situation = family(state, earnings, expenses) +def with_and_without_subsidies(situation): on = Simulation(situation=situation) off = Simulation(situation=situation, tax_benefit_system=no_subsidy_system()) @@ -302,12 +306,28 @@ def subsidy_counted_by_household_measure(simulation, state): earnings=st.integers(5_000, 60_000), expenses=st.integers(0, 25_000), ) +# States that left the subsidy out before and states that counted it as a +# resource, at amounts where each program pays. +@example("NY", 30_000, 14_000) +@example("TX", 30_000, 14_000) +@example("AK", 30_000, 14_000) +@example("WA", 30_000, 14_000) +@example("WV", 30_000, 14_000) +@example("CO", 30_000, 14_000) def test_spm_and_household_measures_agree(state, earnings, expenses): - on, change = with_and_without_subsidies(state, earnings, expenses) + on, change = with_and_without_subsidies(family(state, earnings, expenses)) + subsidy = float(on.calculate("child_care_subsidies", YEAR).sum()) + work = float(on.calculate("spm_unit_work_expenses", YEAR).sum()) + cap = float(on.calculate("spm_unit_head_spouse_earned_cap", YEAR).sum()) fall = -change("spm_unit_capped_work_childcare_expenses") + assert fall == pytest.approx( + reference_expense(expenses, 0, work, cap) + - reference_expense(expenses, subsidy, work, cap), + abs=TOLERANCE, + ) counted = subsidy_counted_by_household_measure(on, state) assert change("spm_unit_net_income") == pytest.approx( - change("household_net_income") - counted + fall, abs=TOLERANCE + change("household_net_income") - counted + fall, abs=INCOME_TOLERANCE ) @@ -316,14 +336,7 @@ def test_new_york_subsidy_raises_both_measures_by_the_same_amount(): situation = family("NY", 30_000, 14_000) situation["households"]["household"]["county_fips"] = {YEAR: "36061"} del situation["people"]["parent"]["weeks_worked"] - on = Simulation(situation=situation) - off = Simulation(situation=situation, tax_benefit_system=no_subsidy_system()) - - def change(variable): - return float(on.calculate(variable, YEAR).sum()) - float( - off.calculate(variable, YEAR).sum() - ) - + on, change = with_and_without_subsidies(situation) subsidy = float(on.calculate("child_care_subsidies", YEAR).sum()) assert subsidy > 13_000 assert change("spm_unit_capped_work_childcare_expenses") == pytest.approx( @@ -331,7 +344,7 @@ def change(variable): ) assert change("household_net_income") > 0 assert change("spm_unit_net_income") == pytest.approx( - change("household_net_income"), abs=TOLERANCE + change("household_net_income"), abs=INCOME_TOLERANCE ) @@ -339,13 +352,13 @@ def test_subsidy_at_the_cap_can_lower_spm_income(): # Intended: this unit stays at the earnings cap, so the SPM expense does # not move, while the fall in out-of-pocket expenses cuts SNAP. See the # module docstring. - on, change = with_and_without_subsidies("CA", 8_000, 25_000) + on, change = with_and_without_subsidies(family("CA", 8_000, 25_000)) assert float(on.calculate("child_care_subsidies", YEAR).sum()) > 0 assert change("spm_unit_capped_work_childcare_expenses") == pytest.approx( 0, abs=TOLERANCE ) assert change("snap") < 0 assert change("spm_unit_net_income") == pytest.approx( - change("spm_unit_benefits") - change("spm_unit_taxes"), abs=TOLERANCE + change("spm_unit_benefits") - change("spm_unit_taxes"), abs=INCOME_TOLERANCE ) assert change("spm_unit_net_income") < 0 From 606699d6406a51ccef8809f9ab96701634dbfb12 Mon Sep 17 00:00:00 2001 From: Max Ghenis Date: Sun, 1 Nov 2026 14:36:05 -0500 Subject: [PATCH 04/42] Close the review's gaps in the SPM child care rule Reviews by GPT-6.1 Sol and Opus 5.5 found three problems at 343f8fee08. - Before 2024 the SPM expense has no formula, so removing the Colorado, Washington and West Virginia subsidies from resources made them reach no SPM path. A 2023 Washington subsidy lowered SPM income. Those three now stay resources until 2024, and years before 2024 match main. - The 2024 program block left out the DC, Tennessee and Texas subsidies, which pay in 2024. All 51 now start at 2024, the first year the SPM expense reads the list, and the test checks every block from then on. - The formula read the pre-subsidy input and ignored a direct out-of-pocket amount. It now reads childcare_expenses, the model's out-of-pocket variable, for a unit with a child. Also add paying-subsidy cases for 2024 and 2025, correct the intended violation's wording, record that datasets fill the pre-subsidy input from reported spending, and route the property tests to the group for retained full systems. Co-Authored-By: Claude Opus 5.5 --- Makefile | 3 +- changelog.d/spm-child-care-subsidies.fixed.md | 2 +- .../hhs/ccdf/child_care_subsidy_programs.yaml | 49 -------- .../spm_child_care_subsidies_integration.yaml | 108 ++++++++++++++++++ ...m_unit_capped_work_childcare_expenses.yaml | 81 +++++++++++++ .../income/spm_unit/spm_unit_benefits.yaml | 46 ++++++++ .../test_spm_child_care_subsidy_invariants.py | 37 +++--- ...spm_unit_capped_work_childcare_expenses.py | 17 ++- .../income/spm_unit/spm_unit_benefits.py | 14 ++- 9 files changed, 286 insertions(+), 71 deletions(-) diff --git a/Makefile b/Makefile index 056dcb663a5..f431d31b2e4 100644 --- a/Makefile +++ b/Makefile @@ -91,13 +91,14 @@ REST_SOCIAL_SECURITY_PIA_RATIO_INPUT_TESTS := $(TESTS)/core/test_ss_pia_ratio_in # a default Microsimulation only to read parameters. Release their heap before # the remaining policy tests, rather than stacking both in the 13.9 GB group. REST_POLICY_PARAMETER_TESTS := $(TESTS)/policy/baseline/parameters -# The first four files retain three independent full systems (the two CTC +# The first five files retain four independent full systems (the two CTC # files share one). The last two use transient TX simulations and balance # elapsed time without warming the NY/AL pinned-system cache. REST_REMAINING_HEAVY_TESTS := $(TESTS)/test_niit_section_911_magi.py \ $(TESTS)/test_ctc_foreign_earned_income_exclusion.py \ $(TESTS)/test_ctc_foreign_earned_income_exclusion_property.py \ $(TESTS)/unit/test_medicaid_abd_ssi_rate_standard_properties.py \ + $(TESTS)/test_spm_child_care_subsidy_invariants.py \ $(TESTS)/test_capital_gain_distributions_loss_limit.py \ $(TESTS)/test_schedule_d_filer_net_capital_gain.py REST_LISTED_TESTS := $(REST_CACHED_ARRAY_TESTS) $(REST_HEAVY_A_TESTS) $(REST_HEAVY_B_TESTS) \ diff --git a/changelog.d/spm-child-care-subsidies.fixed.md b/changelog.d/spm-child-care-subsidies.fixed.md index 3761ac3df12..090ad31ef85 100644 --- a/changelog.d/spm-child-care-subsidies.fixed.md +++ b/changelog.d/spm-child-care-subsidies.fixed.md @@ -1 +1 @@ -Count every state child care subsidy in the Supplemental Poverty Measure by netting it from the SPM child care expense. +Count every state child care subsidy in the Supplemental Poverty Measure from 2024 by netting it from the SPM child care expense, and add the District of Columbia, Tennessee and Texas subsidies to the 2024 program list. diff --git a/policyengine_us/parameters/gov/hhs/ccdf/child_care_subsidy_programs.yaml b/policyengine_us/parameters/gov/hhs/ccdf/child_care_subsidy_programs.yaml index 23ed336402b..6461d03490d 100644 --- a/policyengine_us/parameters/gov/hhs/ccdf/child_care_subsidy_programs.yaml +++ b/policyengine_us/parameters/gov/hhs/ccdf/child_care_subsidy_programs.yaml @@ -96,58 +96,9 @@ values: - nc_child_care_subsidies # North Carolina Subsidized Child Care Assistance - wy_child_care_subsidies # Wyoming Child Care, Purchase of Service - ny_child_care_subsidies # New York Child Care Assistance Program - 2025-01-01: - - ak_child_care_subsidies # Alaska Child Care Assistance Program (PASS) - - ar_child_care_subsidies # Arkansas School Readiness Assistance - - al_child_care_subsidies # Alabama Child Care Subsidy Program - - az_child_care_subsidies # Arizona Child Care Assistance Program - - ca_child_care_subsidies # California Child Care - - co_child_care_subsidies # Colorado Child Care Assistance Program - - ct_child_care_subsidies # Connecticut Care 4 Kids - - de_child_care_subsidies # Delaware Purchase of Care - - fl_child_care_subsidies # Florida School Readiness Program (SR) - - ga_child_care_subsidies # Georgia Childcare and Parent Services - - hi_child_care_subsidies # Hawaii Child Care Subsidy - - ia_child_care_subsidies # Iowa Child Care Assistance - - id_child_care_subsidies # Idaho Child Care Program - - il_child_care_subsidies # Illinois Child Care Assistance Program - - in_child_care_subsidies # Indiana Child Care and Development Fund Voucher Program - - ks_child_care_subsidies # Kansas Child Care Assistance Program - - ky_child_care_subsidies # Kentucky Child Care Assistance Program - - la_child_care_subsidies # Louisiana Child Care Assistance Program - - ma_child_care_subsidies # Massachusetts Child Care Financial Assistance - - md_child_care_subsidies # Maryland Child Care Scholarship - - me_child_care_subsidies # Maine Child Care Affordability Program - - mi_child_care_subsidies # Michigan Child Development and Care program - - mn_child_care_subsidies # Minnesota Child Care Assistance Program - - mo_child_care_subsidies # Missouri Child Care Subsidy - - ms_child_care_subsidies # Mississippi Child Care Payment Program (CCPP) - - mt_child_care_subsidies # Montana Best Beginnings Child Care Scholarship - - ne_child_care_subsidies # Nebraska Child Care Subsidy - - nm_child_care_subsidies # New Mexico Child Care Assistance Program - - vt_child_care_subsidies # Vermont Child Care Financial Assistance Program - - nh_child_care_subsidies # New Hampshire Child Care Scholarship Program - - pa_child_care_subsidies # Pennsylvania Child Care Works - - nj_child_care_subsidies # New Jersey Child Care Assistance Program - - oh_child_care_subsidies # Ohio Publicly Funded Child Care - - nv_child_care_subsidies # Nevada Child Care and Development Program (CCDP) - - or_child_care_subsidies # Oregon Employment Related Day Care - - ri_child_care_subsidies # Rhode Island Child Care Assistance Program - - sc_child_care_subsidies # South Carolina Child Care Scholarship Program - - ut_child_care_subsidies # Utah Child Care Assistance (CC) - - va_child_care_subsidies # Virginia Child Care Subsidy Program - - wa_child_care_subsidies # Washington Working Connections Child Care - - wi_child_care_subsidies # Wisconsin Shares Child Care Subsidy Program - - wv_child_care_subsidies # West Virginia Child Care Assistance Program - - nd_child_care_subsidies # North Dakota Child Care Assistance Program - - ok_child_care_subsidies # Oklahoma Child Care Subsidy Program - - sd_child_care_subsidies # South Dakota Child Care Assistance (CCA) - - nc_child_care_subsidies # North Carolina Subsidized Child Care Assistance - dc_child_care_subsidies # DC Child Care Subsidy Program - tn_child_care_subsidies # Tennessee Child Care Certificate Program (Smart Steps) - - wy_child_care_subsidies # Wyoming Child Care, Purchase of Service - tx_child_care_subsidies # Texas Child Care Services (CCS) - - ny_child_care_subsidies # New York Child Care Assistance Program metadata: unit: list diff --git a/policyengine_us/tests/policy/baseline/household/expense/childcare/spm_child_care_subsidies_integration.yaml b/policyengine_us/tests/policy/baseline/household/expense/childcare/spm_child_care_subsidies_integration.yaml index f05bf02bb74..04e331f1380 100644 --- a/policyengine_us/tests/policy/baseline/household/expense/childcare/spm_child_care_subsidies_integration.yaml +++ b/policyengine_us/tests/policy/baseline/household/expense/childcare/spm_child_care_subsidies_integration.yaml @@ -254,3 +254,111 @@ child_care_subsidies: 12_613.16 # 14,000 - 12,613.16. spm_unit_capped_work_childcare_expenses: 1_386.84 + +- name: District of Columbia, a program the 2024 list left out + period: 2024 + absolute_error_margin: 0.01 + input: + people: + parent: + age: 30 + employment_income: 24_000 + weekly_hours_worked_before_lsr: 40 + is_tax_unit_head: true + is_household_head: true + child: + age: 3 + childcare_hours_per_day: 8 + childcare_days_per_week: 5 + childcare_attending_days_per_month: 21 + is_tax_unit_dependent: true + tax_units: + tax_unit: + members: [parent, child] + families: + family: + members: [parent, child] + spm_units: + spm_unit: + members: [parent, child] + spm_unit_pre_subsidy_childcare_expenses: 20_000 + households: + household: + members: [parent, child] + state_code: DC + output: + child_care_subsidies: 15_876 + # 20,000 - 15,876. + spm_unit_capped_work_childcare_expenses: 4_124 + +- name: Tennessee, paying from October 2024 + period: 2024 + absolute_error_margin: 0.01 + input: + people: + parent: + age: 30 + employment_income: 24_000 + weekly_hours_worked_before_lsr: 40 + is_tax_unit_head: true + is_household_head: true + child: + age: 3 + childcare_hours_per_day: 8 + childcare_days_per_week: 5 + childcare_attending_days_per_month: 21 + is_tax_unit_dependent: true + tax_units: + tax_unit: + members: [parent, child] + families: + family: + members: [parent, child] + spm_units: + spm_unit: + members: [parent, child] + spm_unit_pre_subsidy_childcare_expenses: 20_000 + households: + household: + members: [parent, child] + state_code: TN + output: + child_care_subsidies: 2_704 + # 20,000 - 2,704. + spm_unit_capped_work_childcare_expenses: 17_296 + +- name: Texas, a program the 2024 list left out + period: 2024 + absolute_error_margin: 0.01 + input: + people: + parent: + age: 30 + employment_income: 24_000 + weekly_hours_worked_before_lsr: 40 + is_tax_unit_head: true + is_household_head: true + child: + age: 3 + childcare_hours_per_day: 8 + childcare_days_per_week: 5 + childcare_attending_days_per_month: 21 + is_tax_unit_dependent: true + tax_units: + tax_unit: + members: [parent, child] + families: + family: + members: [parent, child] + spm_units: + spm_unit: + members: [parent, child] + spm_unit_pre_subsidy_childcare_expenses: 20_000 + households: + household: + members: [parent, child] + state_code: TX + output: + child_care_subsidies: 5_793.01 + # 20,000 - 5,793.01. + spm_unit_capped_work_childcare_expenses: 14_206.99 diff --git a/policyengine_us/tests/policy/baseline/household/expense/childcare/spm_unit_capped_work_childcare_expenses.yaml b/policyengine_us/tests/policy/baseline/household/expense/childcare/spm_unit_capped_work_childcare_expenses.yaml index 619b3d891ca..0c7d4b1ce85 100644 --- a/policyengine_us/tests/policy/baseline/household/expense/childcare/spm_unit_capped_work_childcare_expenses.yaml +++ b/policyengine_us/tests/policy/baseline/household/expense/childcare/spm_unit_capped_work_childcare_expenses.yaml @@ -176,3 +176,84 @@ output: child_care_subsidies: 0 spm_unit_capped_work_childcare_expenses: 4_000 + +- name: A subsidy in a unit with no child still lowers the expense + period: 2026 + absolute_error_margin: 0.001 + input: + people: + head: + age: 46 + employment_income: 9_000 + is_household_head: true + is_tax_unit_head: true + tax_units: + tax_unit: + members: [head] + spm_units: + spm_unit: + members: [head] + spm_unit_work_expenses: 0 + spm_unit_pre_subsidy_childcare_expenses: 4_000 + child_care_subsidies: 1_500 + output: + spm_unit_capped_work_childcare_expenses: 2_500 + +- name: A direct out-of-pocket amount replaces the amount net of subsidies + period: 2026 + absolute_error_margin: 0.001 + input: + people: + head: + age: 30 + employment_income: 30_000 + is_household_head: true + is_tax_unit_head: true + child: + age: 3 + is_tax_unit_dependent: true + tax_units: + tax_unit: + members: [head, child] + spm_units: + spm_unit: + members: [head, child] + spm_unit_work_expenses: 0 + spm_unit_pre_subsidy_childcare_expenses: 14_000 + child_care_subsidies: 10_000 + childcare_expenses: 6_000 + output: + spm_unit_capped_work_childcare_expenses: 6_000 + +- name: A subsidy lowers the expense in 2024, the formula's first year + period: 2024 + absolute_error_margin: 0.001 + input: + spm_unit_work_expenses: 1_000 + spm_unit_head_spouse_earned_cap: 50_000 + spm_unit_pre_subsidy_childcare_expenses: 14_000 + child_care_subsidies: 2_000 + output: + spm_unit_capped_work_childcare_expenses: 13_000 + +- name: A subsidy lowers the expense in 2025 + period: 2025 + absolute_error_margin: 0.001 + input: + spm_unit_work_expenses: 1_000 + spm_unit_head_spouse_earned_cap: 50_000 + spm_unit_pre_subsidy_childcare_expenses: 14_000 + child_care_subsidies: 2_000 + output: + spm_unit_capped_work_childcare_expenses: 13_000 + +- name: Before 2024 the expense has no formula, so a subsidy cannot lower it + period: 2023 + absolute_error_margin: 0.001 + input: + spm_unit_work_expenses: 1_000 + spm_unit_head_spouse_earned_cap: 50_000 + spm_unit_pre_subsidy_childcare_expenses: 14_000 + child_care_subsidies: 2_000 + output: + spm_unit_capped_work_childcare_expenses: 0 diff --git a/policyengine_us/tests/policy/baseline/household/income/spm_unit/spm_unit_benefits.yaml b/policyengine_us/tests/policy/baseline/household/income/spm_unit/spm_unit_benefits.yaml index 3f0849f633c..d92dd58106c 100644 --- a/policyengine_us/tests/policy/baseline/household/income/spm_unit/spm_unit_benefits.yaml +++ b/policyengine_us/tests/policy/baseline/household/income/spm_unit/spm_unit_benefits.yaml @@ -162,3 +162,49 @@ unemployment_compensation_months: 6 snap: 1_368 spm_unit_benefits: 11_586 + +- name: Before 2024 three child care subsidies stay resources, because the SPM expense has no formula to lower. + period: 2023 + input: + co_ccap_subsidy: 1 + wa_child_care_subsidies: 2 + wv_child_care_subsidies: 4 + spm_unit_capped_housing_subsidy: 0 + social_security: 0 + ssi: 0 + ca_cvrp: 0 + snap: 0 + wic: 0 + free_school_meals: 0 + reduced_price_school_meals: 0 + spm_unit_energy_subsidy: 0 + tanf: 0 + high_efficiency_electric_home_rebate: 0 + residential_efficiency_electrification_rebate: 0 + unemployment_compensation: 0 + basic_income: 0 + output: + spm_unit_benefits: 1 + 2 + 4 + +- name: From 2024 child care subsidies leave resources and lower the SPM expense instead. + period: 2024 + input: + co_ccap_subsidy: 1 + wa_child_care_subsidies: 2 + wv_child_care_subsidies: 4 + spm_unit_capped_housing_subsidy: 0 + social_security: 0 + ssi: 0 + ca_cvrp: 0 + snap: 0 + wic: 0 + free_school_meals: 0 + reduced_price_school_meals: 0 + spm_unit_energy_subsidy: 0 + tanf: 0 + high_efficiency_electric_home_rebate: 0 + residential_efficiency_electrification_rebate: 0 + unemployment_compensation: 0 + basic_income: 0 + output: + spm_unit_benefits: 0 diff --git a/policyengine_us/tests/test_spm_child_care_subsidy_invariants.py b/policyengine_us/tests/test_spm_child_care_subsidy_invariants.py index 9aa0dbbde69..b61870c1087 100644 --- a/policyengine_us/tests/test_spm_child_care_subsidy_invariants.py +++ b/policyengine_us/tests/test_spm_child_care_subsidy_invariants.py @@ -26,9 +26,11 @@ and never exceeds the subsidy. 4. A subsidy of zero leaves the expense at min(W + max(E, 0), C), the formula before this rule, in every state. -5. No program is counted twice. No *_child_care_subsidies variable, and no - program one of them adds, appears in spm_unit_benefits or in a reform's copy - of that list, and all of them reach child_care_subsidies. +5. No program is counted twice. From 2024, no *_child_care_subsidies variable, + and no program one of them adds, appears in spm_unit_benefits or in a + reform's copy of that list, and all of them reach child_care_subsidies. + Before 2024 the expense has no formula, so Colorado's, Washington's and West + Virginia's subsidies stay resources and still count once. 6. Differential. With real programs turned on and off, the expense falls by the amount the reference gives for the subsidy the program paid, and the SPM and household measures agree on what else changed: the change in SPM @@ -38,10 +40,16 @@ Intended violation of "a subsidy never lowers SPM resources". Property 3 holds taxes and other benefits fixed, and it has to. SNAP, TANF and tax credits read out-of-pocket expenses, so a subsidy can cut them by more than the SPM expense -falls, most plainly when the unit stays at the earnings cap and the expense -does not move at all. The household measure shows the same interaction. -test_subsidy_at_the_cap_can_lower_spm_income pins one such case; the fall comes -from those programs and not from this rule. +falls. A unit that stays at the earnings cap shows this most plainly, because +its expense does not move at all, and a benefit cliff can do it below the cap. +Household net income loses the same benefits but also counts the subsidy, so it +can rise while SPM income falls. test_subsidy_at_the_cap_can_lower_spm_income +pins one such case; the fall comes from those programs and not from this rule. + +These properties read spm_unit_pre_subsidy_childcare_expenses as a pre-subsidy +price, which is what it means in a household calculation. Datasets fill it from +the ASEC's reported spending, so on microdata the rule nets a modeled subsidy +from a reported payment. """ from functools import cache @@ -220,12 +228,15 @@ def test_no_subsidy_is_a_spm_resource(): def test_every_state_subsidy_is_in_the_programs_list(): variables_dir = PACKAGE / "variables/gov/states" defined = {path.stem for path in variables_dir.rglob("*_child_care_subsidies.py")} - latest_block = max( - yaml.load( - (PACKAGE / "parameters" / PROGRAMS_LIST).read_text(), yaml.BaseLoader - )["values"].items() - )[1] - assert defined == set(latest_block) + blocks = yaml.load( + (PACKAGE / "parameters" / PROGRAMS_LIST).read_text(), yaml.BaseLoader + )["values"] + # The SPM expense reads the list from 2024, at the start of each year, so a + # program that starts paying during a year has to be in that year's block. + assert "2024-01-01" in blocks + for start, programs in blocks.items(): + if start >= "2024": + assert defined == set(programs), start assert len(defined) == 51 diff --git a/policyengine_us/variables/household/expense/childcare/spm_unit_capped_work_childcare_expenses.py b/policyengine_us/variables/household/expense/childcare/spm_unit_capped_work_childcare_expenses.py index b457ab7680a..8776b697086 100644 --- a/policyengine_us/variables/household/expense/childcare/spm_unit_capped_work_childcare_expenses.py +++ b/policyengine_us/variables/household/expense/childcare/spm_unit_capped_work_childcare_expenses.py @@ -16,10 +16,17 @@ def formula_2024(spm_unit, period, parameters): ) # The SPM subtracts what parents paid for child care, and child care # is not among its noncash benefits, so a subsidy lowers this expense - # rather than adding to resources. This reads the SPM unit's expenses - # directly because childcare_expenses divides them among children and - # drops them from a unit with no child. + # rather than adding to resources. childcare_expenses holds that + # out-of-pocket amount, but it allocates expenses to children, so a + # unit with no child nets its own expenses here. + # Datasets fill the pre-subsidy input from the ASEC's reported spending, + # so on microdata this nets a modeled subsidy from a reported payment. subsidies = spm_unit("child_care_subsidies", period) - childcare_expenses = max_(pre_subsidy_expenses - subsidies, 0) + has_child = add(spm_unit, period, ["is_child"]) > 0 + out_of_pocket_expenses = where( + has_child, + spm_unit("childcare_expenses", period), + max_(pre_subsidy_expenses - subsidies, 0), + ) earned_cap = spm_unit("spm_unit_head_spouse_earned_cap", period) - return min_(work_expenses + childcare_expenses, earned_cap) + return min_(work_expenses + out_of_pocket_expenses, earned_cap) diff --git a/policyengine_us/variables/household/income/spm_unit/spm_unit_benefits.py b/policyengine_us/variables/household/income/spm_unit/spm_unit_benefits.py index d26c86ab5d9..d6beace2ce0 100644 --- a/policyengine_us/variables/household/income/spm_unit/spm_unit_benefits.py +++ b/policyengine_us/variables/household/income/spm_unit/spm_unit_benefits.py @@ -9,8 +9,6 @@ class spm_unit_benefits(Variable): unit = USD def formula(spm_unit, period, parameters): - # Child care subsidies stay out of this list: they lower the expense - # in spm_unit_capped_work_childcare_expenses instead. BENEFITS = [ "social_security", "ssi", @@ -101,4 +99,16 @@ def formula(spm_unit, period, parameters): BENEFITS.append("assigned_aca_ptc") if not parameters(period).gov.hud.abolition: BENEFITS.append("spm_unit_capped_housing_subsidy") + # From 2024, child care subsidies lower the expense in + # spm_unit_capped_work_childcare_expenses instead of adding to + # resources. That expense has no formula before 2024, so these three + # stay resources until then. + if period.start.year < 2024: + BENEFITS.extend( + [ + "co_ccap_subsidy", + "wa_child_care_subsidies", + "wv_child_care_subsidies", + ] + ) return add(spm_unit, period, BENEFITS) From 640753a617b8a052d1f1496645924d4a943ae1a7 Mon Sep 17 00:00:00 2001 From: Max Ghenis Date: Sun, 1 Nov 2026 16:27:45 -0500 Subject: [PATCH 05/42] Keep pre-2024 child care subsidies in the reform copies The baseline keeps Colorado, Washington and West Virginia subsidies as resources before 2024, because the SPM expense has no formula then. The four reform copies of spm_unit_benefits dropped them in every year, so each override now restores what main carried: all three in the Texas rebate, Colorado in the Tlaib copies. Qualify the docstring's identity for a direct childcare_expenses input, and correct the integration YAML header. Co-Authored-By: Claude Opus 5.5 --- .../boost/boost_middle_class_tax_credit.py | 6 +++++ .../edaa_end_child_poverty_act.py | 6 +++++ .../congress/tlaib/end_child_poverty_act.py | 6 +++++ .../reforms/states/tx/rebate/tx_rebate.py | 12 +++++++++ .../spm_child_care_subsidies_integration.yaml | 7 +++--- .../boost/boost_middle_class_tax_credit.yaml | 23 +++++++++++++++++ .../edaa_end_child_poverty_act.yaml | 23 +++++++++++++++++ .../end_child_poverty_act/integration.yaml | 23 +++++++++++++++++ .../contrib/states/tx/rebate/tx_rebate.yaml | 25 +++++++++++++++++++ .../test_spm_child_care_subsidy_invariants.py | 3 +++ 10 files changed, 131 insertions(+), 3 deletions(-) diff --git a/policyengine_us/reforms/congress/tlaib/boost/boost_middle_class_tax_credit.py b/policyengine_us/reforms/congress/tlaib/boost/boost_middle_class_tax_credit.py index 939e41d3330..55cbd3091d5 100644 --- a/policyengine_us/reforms/congress/tlaib/boost/boost_middle_class_tax_credit.py +++ b/policyengine_us/reforms/congress/tlaib/boost/boost_middle_class_tax_credit.py @@ -135,6 +135,12 @@ def formula(spm_unit, period, parameters): BENEFITS.append("aca_ptc") if not parameters(period).gov.hud.abolition: BENEFITS.append("spm_unit_capped_housing_subsidy") + # From 2024, child care subsidies lower the expense in + # spm_unit_capped_work_childcare_expenses instead of adding to + # resources. That expense has no formula before 2024, so this one + # stays a resource until then. + if period.start.year < 2024: + BENEFITS.append("co_ccap_subsidy") p = parameters( period ).gov.contrib.congress.tlaib.boost.middle_class_tax_credit diff --git a/policyengine_us/reforms/congress/tlaib/economic_dignity_for_all_agenda/edaa_end_child_poverty_act.py b/policyengine_us/reforms/congress/tlaib/economic_dignity_for_all_agenda/edaa_end_child_poverty_act.py index 1dbc0b9ebb7..1c2a7e00bf3 100644 --- a/policyengine_us/reforms/congress/tlaib/economic_dignity_for_all_agenda/edaa_end_child_poverty_act.py +++ b/policyengine_us/reforms/congress/tlaib/economic_dignity_for_all_agenda/edaa_end_child_poverty_act.py @@ -151,6 +151,12 @@ def formula(spm_unit, period, parameters): BENEFITS.append("aca_ptc") if not parameters(period).gov.hud.abolition: BENEFITS.append("spm_unit_capped_housing_subsidy") + # From 2024, child care subsidies lower the expense in + # spm_unit_capped_work_childcare_expenses instead of adding to + # resources. That expense has no formula before 2024, so this one + # stays a resource until then. + if period.start.year < 2024: + BENEFITS.append("co_ccap_subsidy") return add(spm_unit, period, BENEFITS) diff --git a/policyengine_us/reforms/congress/tlaib/end_child_poverty_act.py b/policyengine_us/reforms/congress/tlaib/end_child_poverty_act.py index e8df22a6c4b..02bef27ec03 100644 --- a/policyengine_us/reforms/congress/tlaib/end_child_poverty_act.py +++ b/policyengine_us/reforms/congress/tlaib/end_child_poverty_act.py @@ -164,6 +164,12 @@ def formula(spm_unit, period, parameters): BENEFITS.append("aca_ptc") if not parameters(period).gov.hud.abolition: BENEFITS.append("spm_unit_capped_housing_subsidy") + # From 2024, child care subsidies lower the expense in + # spm_unit_capped_work_childcare_expenses instead of adding to + # resources. That expense has no formula before 2024, so this one + # stays a resource until then. + if period.start.year < 2024: + BENEFITS.append("co_ccap_subsidy") return add(spm_unit, period, BENEFITS) class income_tax_refundable_credits(Variable): diff --git a/policyengine_us/reforms/states/tx/rebate/tx_rebate.py b/policyengine_us/reforms/states/tx/rebate/tx_rebate.py index b2b47519ac3..093653576fd 100644 --- a/policyengine_us/reforms/states/tx/rebate/tx_rebate.py +++ b/policyengine_us/reforms/states/tx/rebate/tx_rebate.py @@ -119,6 +119,18 @@ def formula(spm_unit, period, parameters): BENEFITS.append("assigned_aca_ptc") if not parameters(period).gov.hud.abolition: BENEFITS.append("spm_unit_capped_housing_subsidy") + # From 2024, child care subsidies lower the expense in + # spm_unit_capped_work_childcare_expenses instead of adding to + # resources. That expense has no formula before 2024, so these + # three stay resources until then. + if period.start.year < 2024: + BENEFITS.extend( + [ + "co_ccap_subsidy", + "wa_child_care_subsidies", + "wv_child_care_subsidies", + ] + ) return add(spm_unit, period, BENEFITS) class reform(Reform): diff --git a/policyengine_us/tests/policy/baseline/household/expense/childcare/spm_child_care_subsidies_integration.yaml b/policyengine_us/tests/policy/baseline/household/expense/childcare/spm_child_care_subsidies_integration.yaml index 04e331f1380..baeed13dd31 100644 --- a/policyengine_us/tests/policy/baseline/household/expense/childcare/spm_child_care_subsidies_integration.yaml +++ b/policyengine_us/tests/policy/baseline/household/expense/childcare/spm_child_care_subsidies_integration.yaml @@ -2,9 +2,10 @@ # Alaska subsidies never reached the SPM before; Colorado, Washington and West # Virginia reached it as resources, on top of pre-subsidy expenses. # -# Each family is one working parent with earnings of $30,000 and a child aged 3 -# in care 8 hours a day, 5 days a week. Without weeks_worked, work expenses are -# zero, so the SPM expense is the out-of-pocket amount. +# Each family is one working parent and a child aged 3 in care 8 hours a day, 5 +# days a week. The 2026 cases earn $30,000 and the 2024 cases earn $24,000. +# Without weeks_worked, work expenses are zero, so the SPM expense is the +# out-of-pocket amount. - name: New York, Manhattan family with a subsidy just below the expense period: 2026 diff --git a/policyengine_us/tests/policy/contrib/congress/tlaib/boost/boost_middle_class_tax_credit.yaml b/policyengine_us/tests/policy/contrib/congress/tlaib/boost/boost_middle_class_tax_credit.yaml index b37e8c153b3..c87af91955b 100644 --- a/policyengine_us/tests/policy/contrib/congress/tlaib/boost/boost_middle_class_tax_credit.yaml +++ b/policyengine_us/tests/policy/contrib/congress/tlaib/boost/boost_middle_class_tax_credit.yaml @@ -211,3 +211,26 @@ output: household_benefits: 0 spm_unit_benefits: 0 + +- name: Before 2024 the Colorado subsidy stays a resource under this reform's list. + period: 2023 + reforms: policyengine_us.reforms.congress.tlaib.boost.boost_middle_class_tax_credit.boost_middle_class_tax_credit + input: + co_ccap_subsidy: 1 + boost_middle_class_tax_credit: 0 + spm_unit_capped_housing_subsidy: 0 + social_security: 0 + ssi: 0 + ca_cvrp: 0 + snap: 0 + wic: 0 + free_school_meals: 0 + reduced_price_school_meals: 0 + spm_unit_energy_subsidy: 0 + tanf: 0 + high_efficiency_electric_home_rebate: 0 + residential_efficiency_electrification_rebate: 0 + unemployment_compensation: 0 + basic_income: 0 + output: + spm_unit_benefits: 1 diff --git a/policyengine_us/tests/policy/contrib/congress/tlaib/economic_dignity_for_all_agenda/edaa_end_child_poverty_act.yaml b/policyengine_us/tests/policy/contrib/congress/tlaib/economic_dignity_for_all_agenda/edaa_end_child_poverty_act.yaml index cf8c3331d02..56d00bdd3a1 100644 --- a/policyengine_us/tests/policy/contrib/congress/tlaib/economic_dignity_for_all_agenda/edaa_end_child_poverty_act.yaml +++ b/policyengine_us/tests/policy/contrib/congress/tlaib/economic_dignity_for_all_agenda/edaa_end_child_poverty_act.yaml @@ -263,3 +263,26 @@ output: household_benefits: 0 spm_unit_benefits: 0 + +- name: Before 2024 the Colorado subsidy stays a resource under this reform's list. + period: 2023 + reforms: policyengine_us.reforms.congress.tlaib.economic_dignity_for_all_agenda.end_child_poverty_act + input: + co_ccap_subsidy: 1 + ecpa_child_benefit: 0 + spm_unit_capped_housing_subsidy: 0 + social_security: 0 + ssi: 0 + ca_cvrp: 0 + snap: 0 + wic: 0 + free_school_meals: 0 + reduced_price_school_meals: 0 + spm_unit_energy_subsidy: 0 + tanf: 0 + high_efficiency_electric_home_rebate: 0 + residential_efficiency_electrification_rebate: 0 + unemployment_compensation: 0 + basic_income: 0 + output: + spm_unit_benefits: 1 diff --git a/policyengine_us/tests/policy/contrib/congress/tlaib/end_child_poverty_act/integration.yaml b/policyengine_us/tests/policy/contrib/congress/tlaib/end_child_poverty_act/integration.yaml index 1d9d3f1e04e..4a475fdf252 100644 --- a/policyengine_us/tests/policy/contrib/congress/tlaib/end_child_poverty_act/integration.yaml +++ b/policyengine_us/tests/policy/contrib/congress/tlaib/end_child_poverty_act/integration.yaml @@ -159,3 +159,26 @@ output: household_benefits: 0 spm_unit_benefits: 0 + +- name: Before 2024 the Colorado subsidy stays a resource under this reform's list. + period: 2023 + reforms: policyengine_us.reforms.congress.tlaib.end_child_poverty_act.end_child_poverty_act + input: + co_ccap_subsidy: 1 + ecpa_child_benefit: 0 + spm_unit_capped_housing_subsidy: 0 + social_security: 0 + ssi: 0 + ca_cvrp: 0 + snap: 0 + wic: 0 + free_school_meals: 0 + reduced_price_school_meals: 0 + spm_unit_energy_subsidy: 0 + tanf: 0 + high_efficiency_electric_home_rebate: 0 + residential_efficiency_electrification_rebate: 0 + unemployment_compensation: 0 + basic_income: 0 + output: + spm_unit_benefits: 1 diff --git a/policyengine_us/tests/policy/contrib/states/tx/rebate/tx_rebate.yaml b/policyengine_us/tests/policy/contrib/states/tx/rebate/tx_rebate.yaml index b1e56bc9dde..a5b27076005 100644 --- a/policyengine_us/tests/policy/contrib/states/tx/rebate/tx_rebate.yaml +++ b/policyengine_us/tests/policy/contrib/states/tx/rebate/tx_rebate.yaml @@ -181,3 +181,28 @@ # not recur -- neither directly nor through the spm_unit_benefits path. tx_rebate: 0 spm_unit_benefits: 0 + +- name: Before 2024 these child care subsidies stay resources under this reform's list. + period: 2023 + reforms: policyengine_us.reforms.states.tx.rebate.tx_rebate.tx_rebate + input: + co_ccap_subsidy: 1 + wa_child_care_subsidies: 2 + wv_child_care_subsidies: 4 + tx_rebate: 0 + spm_unit_capped_housing_subsidy: 0 + social_security: 0 + ssi: 0 + ca_cvrp: 0 + snap: 0 + wic: 0 + free_school_meals: 0 + reduced_price_school_meals: 0 + spm_unit_energy_subsidy: 0 + tanf: 0 + high_efficiency_electric_home_rebate: 0 + residential_efficiency_electrification_rebate: 0 + unemployment_compensation: 0 + basic_income: 0 + output: + spm_unit_benefits: 1 + 2 + 4 diff --git a/policyengine_us/tests/test_spm_child_care_subsidy_invariants.py b/policyengine_us/tests/test_spm_child_care_subsidy_invariants.py index b61870c1087..91a813139b6 100644 --- a/policyengine_us/tests/test_spm_child_care_subsidy_invariants.py +++ b/policyengine_us/tests/test_spm_child_care_subsidy_invariants.py @@ -14,6 +14,9 @@ expense(S) = min(W + max(E - S, 0), C) +A direct childcare_expenses input replaces max(E - S, 0) in a unit with a +child, so these properties cover units that leave that variable to its formula. + For every SPM unit: 1. The model's expense equals that reference, written from the documentation From 1a68fe7e47ef61b49e6ee7e706eb7b1a47ec9301 Mon Sep 17 00:00:00 2001 From: Max Ghenis Date: Mon, 2 Nov 2026 09:36:29 -0500 Subject: [PATCH 06/42] Pin the 2024 gate in each reform copy of the SPM benefits list The list test reads list literals only, so it could not see the pre-2024 clause in the four reform copies. A 2024 case in each reform's YAML file now fails if the clause loosens and a subsidy counts as a resource on top of the lower expense. Also qualify the docstring for person-level pre-subsidy inputs and for the Tlaib copies, which carry only Colorado's subsidy before 2024, and note in the integration header that one case sets no care hours. Co-Authored-By: Claude Opus 5.5 --- .../spm_child_care_subsidies_integration.yaml | 5 ++-- .../boost/boost_middle_class_tax_credit.yaml | 23 +++++++++++++++++ .../edaa_end_child_poverty_act.yaml | 23 +++++++++++++++++ .../end_child_poverty_act/integration.yaml | 23 +++++++++++++++++ .../contrib/states/tx/rebate/tx_rebate.yaml | 25 +++++++++++++++++++ .../test_spm_child_care_subsidy_invariants.py | 9 ++++--- 6 files changed, 103 insertions(+), 5 deletions(-) diff --git a/policyengine_us/tests/policy/baseline/household/expense/childcare/spm_child_care_subsidies_integration.yaml b/policyengine_us/tests/policy/baseline/household/expense/childcare/spm_child_care_subsidies_integration.yaml index baeed13dd31..0a569868a10 100644 --- a/policyengine_us/tests/policy/baseline/household/expense/childcare/spm_child_care_subsidies_integration.yaml +++ b/policyengine_us/tests/policy/baseline/household/expense/childcare/spm_child_care_subsidies_integration.yaml @@ -2,8 +2,9 @@ # Alaska subsidies never reached the SPM before; Colorado, Washington and West # Virginia reached it as resources, on top of pre-subsidy expenses. # -# Each family is one working parent and a child aged 3 in care 8 hours a day, 5 -# days a week. The 2026 cases earn $30,000 and the 2024 cases earn $24,000. +# Each family is one working parent and a child aged 3. Unless a case says +# otherwise, the child is in care 8 hours a day, 5 days a week. The 2026 cases +# earn $30,000 and the 2024 cases earn $24,000. # Without weeks_worked, work expenses are zero, so the SPM expense is the # out-of-pocket amount. diff --git a/policyengine_us/tests/policy/contrib/congress/tlaib/boost/boost_middle_class_tax_credit.yaml b/policyengine_us/tests/policy/contrib/congress/tlaib/boost/boost_middle_class_tax_credit.yaml index c87af91955b..5758e3c9376 100644 --- a/policyengine_us/tests/policy/contrib/congress/tlaib/boost/boost_middle_class_tax_credit.yaml +++ b/policyengine_us/tests/policy/contrib/congress/tlaib/boost/boost_middle_class_tax_credit.yaml @@ -234,3 +234,26 @@ basic_income: 0 output: spm_unit_benefits: 1 + +- name: From 2024 the Colorado subsidy leaves this reform's list and lowers the SPM expense instead. + period: 2024 + reforms: policyengine_us.reforms.congress.tlaib.boost.boost_middle_class_tax_credit.boost_middle_class_tax_credit + input: + co_ccap_subsidy: 1 + boost_middle_class_tax_credit: 0 + spm_unit_capped_housing_subsidy: 0 + social_security: 0 + ssi: 0 + ca_cvrp: 0 + snap: 0 + wic: 0 + free_school_meals: 0 + reduced_price_school_meals: 0 + spm_unit_energy_subsidy: 0 + tanf: 0 + high_efficiency_electric_home_rebate: 0 + residential_efficiency_electrification_rebate: 0 + unemployment_compensation: 0 + basic_income: 0 + output: + spm_unit_benefits: 0 diff --git a/policyengine_us/tests/policy/contrib/congress/tlaib/economic_dignity_for_all_agenda/edaa_end_child_poverty_act.yaml b/policyengine_us/tests/policy/contrib/congress/tlaib/economic_dignity_for_all_agenda/edaa_end_child_poverty_act.yaml index 56d00bdd3a1..2fc3b39667b 100644 --- a/policyengine_us/tests/policy/contrib/congress/tlaib/economic_dignity_for_all_agenda/edaa_end_child_poverty_act.yaml +++ b/policyengine_us/tests/policy/contrib/congress/tlaib/economic_dignity_for_all_agenda/edaa_end_child_poverty_act.yaml @@ -286,3 +286,26 @@ basic_income: 0 output: spm_unit_benefits: 1 + +- name: From 2024 the Colorado subsidy leaves this reform's list and lowers the SPM expense instead. + period: 2024 + reforms: policyengine_us.reforms.congress.tlaib.economic_dignity_for_all_agenda.end_child_poverty_act + input: + co_ccap_subsidy: 1 + ecpa_child_benefit: 0 + spm_unit_capped_housing_subsidy: 0 + social_security: 0 + ssi: 0 + ca_cvrp: 0 + snap: 0 + wic: 0 + free_school_meals: 0 + reduced_price_school_meals: 0 + spm_unit_energy_subsidy: 0 + tanf: 0 + high_efficiency_electric_home_rebate: 0 + residential_efficiency_electrification_rebate: 0 + unemployment_compensation: 0 + basic_income: 0 + output: + spm_unit_benefits: 0 diff --git a/policyengine_us/tests/policy/contrib/congress/tlaib/end_child_poverty_act/integration.yaml b/policyengine_us/tests/policy/contrib/congress/tlaib/end_child_poverty_act/integration.yaml index 4a475fdf252..239e984cd8c 100644 --- a/policyengine_us/tests/policy/contrib/congress/tlaib/end_child_poverty_act/integration.yaml +++ b/policyengine_us/tests/policy/contrib/congress/tlaib/end_child_poverty_act/integration.yaml @@ -182,3 +182,26 @@ basic_income: 0 output: spm_unit_benefits: 1 + +- name: From 2024 the Colorado subsidy leaves this reform's list and lowers the SPM expense instead. + period: 2024 + reforms: policyengine_us.reforms.congress.tlaib.end_child_poverty_act.end_child_poverty_act + input: + co_ccap_subsidy: 1 + ecpa_child_benefit: 0 + spm_unit_capped_housing_subsidy: 0 + social_security: 0 + ssi: 0 + ca_cvrp: 0 + snap: 0 + wic: 0 + free_school_meals: 0 + reduced_price_school_meals: 0 + spm_unit_energy_subsidy: 0 + tanf: 0 + high_efficiency_electric_home_rebate: 0 + residential_efficiency_electrification_rebate: 0 + unemployment_compensation: 0 + basic_income: 0 + output: + spm_unit_benefits: 0 diff --git a/policyengine_us/tests/policy/contrib/states/tx/rebate/tx_rebate.yaml b/policyengine_us/tests/policy/contrib/states/tx/rebate/tx_rebate.yaml index a5b27076005..f9a602be4ce 100644 --- a/policyengine_us/tests/policy/contrib/states/tx/rebate/tx_rebate.yaml +++ b/policyengine_us/tests/policy/contrib/states/tx/rebate/tx_rebate.yaml @@ -206,3 +206,28 @@ basic_income: 0 output: spm_unit_benefits: 1 + 2 + 4 + +- name: From 2024 these child care subsidies leave this reform's list and lower the SPM expense instead. + period: 2024 + reforms: policyengine_us.reforms.states.tx.rebate.tx_rebate.tx_rebate + input: + co_ccap_subsidy: 1 + wa_child_care_subsidies: 2 + wv_child_care_subsidies: 4 + tx_rebate: 0 + spm_unit_capped_housing_subsidy: 0 + social_security: 0 + ssi: 0 + ca_cvrp: 0 + snap: 0 + wic: 0 + free_school_meals: 0 + reduced_price_school_meals: 0 + spm_unit_energy_subsidy: 0 + tanf: 0 + high_efficiency_electric_home_rebate: 0 + residential_efficiency_electrification_rebate: 0 + unemployment_compensation: 0 + basic_income: 0 + output: + spm_unit_benefits: 0 diff --git a/policyengine_us/tests/test_spm_child_care_subsidy_invariants.py b/policyengine_us/tests/test_spm_child_care_subsidy_invariants.py index 91a813139b6..a69ae7aad75 100644 --- a/policyengine_us/tests/test_spm_child_care_subsidy_invariants.py +++ b/policyengine_us/tests/test_spm_child_care_subsidy_invariants.py @@ -14,8 +14,10 @@ expense(S) = min(W + max(E - S, 0), C) -A direct childcare_expenses input replaces max(E - S, 0) in a unit with a -child, so these properties cover units that leave that variable to its formula. +A unit with a child takes E from its members' pre_subsidy_childcare_expenses, +which an input can set apart from the unit's amount, and a direct +childcare_expenses input replaces max(E - S, 0) altogether. These properties +cover units that leave both to their formulas. For every SPM unit: @@ -33,7 +35,8 @@ and no program one of them adds, appears in spm_unit_benefits or in a reform's copy of that list, and all of them reach child_care_subsidies. Before 2024 the expense has no formula, so Colorado's, Washington's and West - Virginia's subsidies stay resources and still count once. + Virginia's subsidies stay resources and count once, as on main. The Tlaib + reform copies carry only Colorado's in those years, also as on main. 6. Differential. With real programs turned on and off, the expense falls by the amount the reference gives for the subsidy the program paid, and the SPM and household measures agree on what else changed: the change in SPM From 652e968a94bafb9e127604d73ccf45abe49a9100 Mon Sep 17 00:00:00 2001 From: Max Ghenis Date: Mon, 2 Nov 2026 18:42:31 -0500 Subject: [PATCH 07/42] Keep reported child care spending as the SPM expense over a dataset Datasets fill spm_unit_pre_subsidy_childcare_expenses from the ASEC's SPM_CHILDCAREXPNS, which already holds what parents paid after any subsidy, so netting a modeled subsidy from it counted the subsidy twice. Over a dataset the expense now keeps the reported amount under baseline policy, and a reform moves it by the change in subsidy: min(W + max(E - (S1 - S0), 0), C). Household calculations keep the input as a price and net the subsidy, as before. Add properties for both rules and a differential between them, and a microsimulation test over the shipped population. Co-Authored-By: Claude Opus 5.5 --- changelog.d/spm-child-care-subsidies.fixed.md | 2 +- .../test_spm_child_care_reported_expense.py | 115 ++++++++++ .../test_spm_child_care_subsidy_invariants.py | 214 +++++++++++++++++- ...spm_unit_capped_work_childcare_expenses.py | 36 ++- ...spm_unit_pre_subsidy_childcare_expenses.py | 5 + 5 files changed, 351 insertions(+), 21 deletions(-) create mode 100644 policyengine_us/tests/microsimulation/test_spm_child_care_reported_expense.py diff --git a/changelog.d/spm-child-care-subsidies.fixed.md b/changelog.d/spm-child-care-subsidies.fixed.md index 090ad31ef85..95d3b483235 100644 --- a/changelog.d/spm-child-care-subsidies.fixed.md +++ b/changelog.d/spm-child-care-subsidies.fixed.md @@ -1 +1 @@ -Count every state child care subsidy in the Supplemental Poverty Measure from 2024 by netting it from the SPM child care expense, and add the District of Columbia, Tennessee and Texas subsidies to the 2024 program list. +Count every state child care subsidy in the Supplemental Poverty Measure from 2024 by netting it from the SPM child care expense in household calculations, keep the ASEC's reported spending as that expense over a dataset while a reform moves it by the change in subsidy, and add the District of Columbia, Tennessee and Texas subsidies to the 2024 program list. diff --git a/policyengine_us/tests/microsimulation/test_spm_child_care_reported_expense.py b/policyengine_us/tests/microsimulation/test_spm_child_care_reported_expense.py new file mode 100644 index 00000000000..5d8d0ed5bbd --- /dev/null +++ b/policyengine_us/tests/microsimulation/test_spm_child_care_reported_expense.py @@ -0,0 +1,115 @@ +"""Over a dataset, the SPM subtracts what parents reported paying for child care. + +Datasets fill spm_unit_pre_subsidy_childcare_expenses from the ASEC's +SPM_CHILDCAREXPNS, which holds what parents paid after any subsidy. So baseline +policy keeps that amount, and a reform moves it by the change in subsidy. These +tests run the rule over the shipped population rather than the situations in +test_spm_child_care_subsidy_invariants.py, so the dataset flag and the reform's +baseline arm come from loading a real file. +""" + +import numpy as np + +from policyengine_us.tests.microsimulation.populace_fixture import ( + default_population_sample, +) + +PERIOD = 2026 +TOLERANCE = 0.01 +FLAT_SUBSIDY = 1_000 + + +def spm_arrays(simulation): + return { + name: np.asarray(simulation.calculate(name, PERIOD), dtype=float) + for name in ( + "child_care_subsidies", + "spm_unit_capped_work_childcare_expenses", + "spm_unit_head_spouse_earned_cap", + "spm_unit_pre_subsidy_childcare_expenses", + "spm_unit_work_expenses", + ) + } + + +def test_baseline_expense_is_the_reported_amount_over_the_whole_population(): + from policyengine_us import Microsimulation + + simulation = Microsimulation() # populace_us_2024, full file + reported = simulation.calculate( + "spm_unit_pre_subsidy_childcare_expenses", PERIOD + ).values + work = simulation.calculate("spm_unit_work_expenses", PERIOD).values + cap = simulation.calculate("spm_unit_head_spouse_earned_cap", PERIOD).values + expense = simulation.calculate( + "spm_unit_capped_work_childcare_expenses", PERIOD + ).values + + # The identity would hold trivially if nobody reported paying. + assert (reported > 0).sum() > 1_000 + assert (expense == np.minimum(work + reported, cap)).all() + + +def test_reform_moves_the_reported_expense_by_the_change_in_subsidy(): + from policyengine_core.reforms import Reform + + from policyengine_us import Microsimulation + from policyengine_us.model_api import SPMUnit, USD, YEAR, Variable + + class child_care_subsidies(Variable): + value_type = float + entity = SPMUnit + definition_period = YEAR + label = "Child care subsidies" + unit = USD + + def formula(spm_unit, period, parameters): + return np.full(spm_unit.count, FLAT_SUBSIDY, dtype=float) + + class FlatSubsidy(Reform): + def apply(self): + self.update_variable(child_care_subsidies) + + dataset = default_population_sample() + baseline = spm_arrays(Microsimulation(dataset=dataset)) + simulation = Microsimulation(dataset=dataset, reform=FlatSubsidy) + reformed = spm_arrays(simulation) + arm = spm_arrays(simulation.baseline) + + # The reform's baseline arm matches a simulation with no reform. + for name, values in baseline.items(): + np.testing.assert_array_equal(arm[name], values, err_msg=name) + + reported = baseline["spm_unit_pre_subsidy_childcare_expenses"] + assert (reformed["child_care_subsidies"] == FLAT_SUBSIDY).all() + # The slice has to hold units the old rule got wrong: the model pays them a + # subsidy and they reported paying, so it netted one from the other. + paid = (baseline["child_care_subsidies"] > 0) & (reported > 0) + assert paid.any() + np.testing.assert_allclose( + baseline["spm_unit_capped_work_childcare_expenses"][paid], + np.minimum( + baseline["spm_unit_work_expenses"] + reported, + baseline["spm_unit_head_spouse_earned_cap"], + )[paid], + atol=TOLERANCE, + ) + # And units on each side of the floor. + assert ((reported > 0) & (reported < FLAT_SUBSIDY)).any() + assert (reported > FLAT_SUBSIDY).any() + + change = FLAT_SUBSIDY - baseline["child_care_subsidies"] + expected = np.minimum( + reformed["spm_unit_work_expenses"] + np.maximum(reported - change, 0), + reformed["spm_unit_head_spouse_earned_cap"], + ) + np.testing.assert_allclose( + reformed["spm_unit_capped_work_childcare_expenses"], + expected, + atol=TOLERANCE, + ) + # Some unit's expense has to move, or the comparison above proves nothing. + assert ( + reformed["spm_unit_capped_work_childcare_expenses"] + < baseline["spm_unit_capped_work_childcare_expenses"] + ).any() diff --git a/policyengine_us/tests/test_spm_child_care_subsidy_invariants.py b/policyengine_us/tests/test_spm_child_care_subsidy_invariants.py index a69ae7aad75..49f0e789921 100644 --- a/policyengine_us/tests/test_spm_child_care_subsidy_invariants.py +++ b/policyengine_us/tests/test_spm_child_care_subsidy_invariants.py @@ -52,10 +52,24 @@ can rise while SPM income falls. test_subsidy_at_the_cap_can_lower_spm_income pins one such case; the fall comes from those programs and not from this rule. -These properties read spm_unit_pre_subsidy_childcare_expenses as a pre-subsidy -price, which is what it means in a household calculation. Datasets fill it from -the ASEC's reported spending, so on microdata the rule nets a modeled subsidy -from a reported payment. +The properties above read spm_unit_pre_subsidy_childcare_expenses as a +pre-subsidy price, which is what it means in a household calculation. Datasets +fill it from the ASEC's reported spending, which is already what parents paid. +So over a dataset, with E the reported amount, S0 the subsidy baseline policy +pays and S1 the subsidy the simulated policy pays: + + expense(S1) = min(W + max(E - (S1 - S0), 0), C) + +7. Baseline policy over a dataset leaves the expense at min(W + E, C), the + amount Census subtracts, whatever subsidy the model pays. +8. Under any policy over a dataset, the expense equals that reference, with or + without a child in the unit. A policy that pays the same subsidy leaves the + expense where baseline policy put it. +9. Differential. Give a dataset the amount the household rule says a unit pays + at baseline policy. Then the two rules give the same expense under any + policy. With the same input and real programs, repealing a subsidy moves + SPM net income by the same amount under both rules, unless the earnings cap + binds under either. """ from functools import cache @@ -108,13 +122,15 @@ def build_units(units): "is_tax_unit_head": {YEAR: True}, "is_household_head": {YEAR: True}, } - people[child] = {"age": {YEAR: 4}, "is_tax_unit_dependent": {YEAR: True}} - members = [parent, child] + members = [parent] + marital_units[f"marital_unit_{i}"] = {"members": [parent]} + if unit.get("has_child", True): + people[child] = {"age": {YEAR: 4}, "is_tax_unit_dependent": {YEAR: True}} + members = [parent, child] + marital_units[f"child_marital_unit_{i}"] = {"members": [child]} state = unit["state"] tax_units[f"tax_unit_{i}"] = {"members": members} families[f"family_{i}"] = {"members": members} - marital_units[f"marital_unit_{i}"] = {"members": [parent]} - marital_units[f"child_marital_unit_{i}"] = {"members": [child]} spm_units[f"spm_unit_{i}"] = { "members": members, "spm_unit_pre_subsidy_childcare_expenses": {YEAR: unit["expenses"]}, @@ -379,3 +395,185 @@ def test_subsidy_at_the_cap_can_lower_spm_income(): change("spm_unit_benefits") - change("spm_unit_taxes"), abs=INCOME_TOLERANCE ) assert change("spm_unit_net_income") < 0 + + +def with_baseline_arm(simulation): + """A branch named baseline, wired as a reform simulation wires its own. These + properties set each arm's subsidy directly, and a real reform builds a whole + tax-benefit system; the repeal test below and the microsimulation tests run + that path.""" + simulation.baseline = simulation.get_branch("baseline") + return simulation + + +def over_dataset(situation): + """A simulation that reads its inputs as a dataset's. Core sets this flag + when it loads a file; a situation lets these properties choose the inputs.""" + simulation = Simulation(situation=situation) + simulation.is_over_dataset = True + return simulation + + +def set_subsidies(simulation, baseline_subsidies, policy_subsidies): + simulation.baseline.set_input("child_care_subsidies", YEAR, baseline_subsidies) + simulation.set_input("child_care_subsidies", YEAR, policy_subsidies) + + +def capped_expense(simulation): + return np.asarray( + simulation.calculate("spm_unit_capped_work_childcare_expenses", YEAR), + dtype=float, + ) + + +dataset_units = st.lists( + st.fixed_dictionaries( + { + "state": st.sampled_from(STATES), + "expenses": amounts, + "subsidy": amounts, + "policy_subsidy": amounts, + "work": st.integers(0, 6_000), + "cap": st.integers(0, 60_000), + "has_child": st.booleans(), + } + ), + min_size=1, + max_size=4, +) + + +@settings(max_examples=25, deadline=None) +@given(dataset_units) +def test_baseline_policy_over_a_dataset_keeps_the_reported_amount(units): + plain = over_dataset(build_units(units)) + simulation = with_baseline_arm(over_dataset(build_units(units))) + # 7. The subsidy input differs by unit and the expense ignores it. A + # simulation with no baseline and a baseline arm both hold baseline policy. + for baseline in (plain, simulation.baseline): + for unit, expense in zip(units, capped_expense(baseline)): + assert expense == pytest.approx( + min(unit["work"] + unit["expenses"], unit["cap"]), abs=TOLERANCE + ) + # 8. A policy that pays the same subsidy leaves the expense identical, with + # no rounding error from netting. + assert (capped_expense(simulation) == capped_expense(simulation.baseline)).all() + + +@settings(max_examples=25, deadline=None) +@given(dataset_units) +@example( + # A policy that pays more than the unit reported paying, so the floor binds. + [ + { + "state": "NY", + "expenses": 1_000, + "subsidy": 0, + "policy_subsidy": 5_000, + "work": 100, + "cap": 60_000, + "has_child": True, + } + ] +) +@example( + # A repeal that takes a unit with no child to the earnings cap. + [ + { + "state": "TX", + "expenses": 5_000, + "subsidy": 8_000, + "policy_subsidy": 0, + "work": 100, + "cap": 6_000, + "has_child": False, + } + ] +) +def test_policy_over_a_dataset_moves_the_expense_by_the_subsidy_change(units): + # 8. + simulation = with_baseline_arm(over_dataset(build_units(units))) + set_subsidies( + simulation, + [unit["subsidy"] for unit in units], + [unit["policy_subsidy"] for unit in units], + ) + for unit, expense in zip(units, capped_expense(simulation)): + assert expense == pytest.approx( + reference_expense( + unit["expenses"], + unit["policy_subsidy"] - unit["subsidy"], + unit["work"], + unit["cap"], + ), + abs=TOLERANCE, + ) + + +@settings(max_examples=25, deadline=None) +@given(dataset_units) +def test_dataset_and_household_rules_agree_on_the_expense(units): + # 9. A subsidy no larger than the price keeps the floor out of the way at + # baseline policy, so the reported amount is the price less the subsidy. + baseline_subsidies = [min(u["subsidy"], u["expenses"]) for u in units] + policy_subsidies = [unit["policy_subsidy"] for unit in units] + reported = [ + {**unit, "expenses": unit["expenses"] - subsidy} + for unit, subsidy in zip(units, baseline_subsidies) + ] + household = with_baseline_arm(Simulation(situation=build_units(units))) + dataset = with_baseline_arm(over_dataset(build_units(reported))) + set_subsidies(household, baseline_subsidies, policy_subsidies) + set_subsidies(dataset, baseline_subsidies, policy_subsidies) + assert capped_expense(dataset) == pytest.approx( + capped_expense(household), abs=TOLERANCE + ) + assert capped_expense(dataset.baseline) == pytest.approx( + capped_expense(household.baseline), abs=TOLERANCE + ) + + +@pytest.mark.parametrize("state, county_fips", [("NY", "36061"), ("TX", None)]) +def test_repeal_moves_dataset_and_household_income_by_the_same_amount( + state, county_fips +): + # 9. Real programs and a real reform. The dataset reads $14,000 as what + # parents paid and the household calculation as the price. Neither rule's + # cap binds and both expenses rise by the subsidy, so SPM income falls by + # the same amount. + situation = family(state, 30_000, 14_000) + parent = situation["people"]["parent"] + del parent["weeks_worked"] + # The columns datasets hold. Simulation moves employment_income to its + # pre-response variable after core builds the baseline arm, so the arm would + # read no earnings wherever a formula reads that variable. + parent["employment_income_before_lsr"] = parent.pop("employment_income") + parent["weekly_hours_worked_before_lsr"] = parent.pop("weekly_hours_worked") + if county_fips: + situation["households"]["household"]["county_fips"] = {YEAR: county_fips} + _, household_change = with_and_without_subsidies(situation) + dataset = Simulation(situation=situation, reform=NoSubsidies) + dataset.is_over_dataset = True + dataset.baseline.is_over_dataset = True + + def dataset_change(variable): + return float(dataset.baseline.calculate(variable, YEAR).sum()) - float( + dataset.calculate(variable, YEAR).sum() + ) + + subsidy = float(dataset.baseline.calculate("child_care_subsidies", YEAR).sum()) + assert subsidy > 0 + assert float(dataset.calculate("child_care_subsidies", YEAR).sum()) == 0 + assert capped_expense(dataset.baseline).sum() == pytest.approx( + 14_000, abs=TOLERANCE + ) + assert dataset_change("spm_unit_capped_work_childcare_expenses") == pytest.approx( + -subsidy, abs=TOLERANCE + ) + assert household_change("spm_unit_capped_work_childcare_expenses") == pytest.approx( + -subsidy, abs=TOLERANCE + ) + assert household_change("spm_unit_net_income") != 0 + assert dataset_change("spm_unit_net_income") == pytest.approx( + household_change("spm_unit_net_income"), abs=INCOME_TOLERANCE + ) diff --git a/policyengine_us/variables/household/expense/childcare/spm_unit_capped_work_childcare_expenses.py b/policyengine_us/variables/household/expense/childcare/spm_unit_capped_work_childcare_expenses.py index 8776b697086..4fe149f1dc3 100644 --- a/policyengine_us/variables/household/expense/childcare/spm_unit_capped_work_childcare_expenses.py +++ b/policyengine_us/variables/household/expense/childcare/spm_unit_capped_work_childcare_expenses.py @@ -16,17 +16,29 @@ def formula_2024(spm_unit, period, parameters): ) # The SPM subtracts what parents paid for child care, and child care # is not among its noncash benefits, so a subsidy lowers this expense - # rather than adding to resources. childcare_expenses holds that - # out-of-pocket amount, but it allocates expenses to children, so a - # unit with no child nets its own expenses here. - # Datasets fill the pre-subsidy input from the ASEC's reported spending, - # so on microdata this nets a modeled subsidy from a reported payment. - subsidies = spm_unit("child_care_subsidies", period) - has_child = add(spm_unit, period, ["is_child"]) > 0 - out_of_pocket_expenses = where( - has_child, - spm_unit("childcare_expenses", period), - max_(pre_subsidy_expenses - subsidies, 0), - ) + # rather than adding to resources. + simulation = spm_unit.simulation + if simulation.is_over_dataset: + # Datasets fill the pre-subsidy input from the ASEC's reported + # spending, which is already what parents paid. Baseline policy + # keeps that amount, and a reform moves it by the change in subsidy. + out_of_pocket_expenses = pre_subsidy_expenses + if simulation.baseline is not None and simulation.branch_name != "baseline": + baseline_spm_unit = simulation.baseline.populations["spm_unit"] + subsidy_change = spm_unit( + "child_care_subsidies", period + ) - baseline_spm_unit("child_care_subsidies", period) + out_of_pocket_expenses = max_(pre_subsidy_expenses - subsidy_change, 0) + else: + # childcare_expenses holds the out-of-pocket amount, but it + # allocates expenses to children, so a unit with no child nets its + # own expenses here. + subsidies = spm_unit("child_care_subsidies", period) + has_child = add(spm_unit, period, ["is_child"]) > 0 + out_of_pocket_expenses = where( + has_child, + spm_unit("childcare_expenses", period), + max_(pre_subsidy_expenses - subsidies, 0), + ) earned_cap = spm_unit("spm_unit_head_spouse_earned_cap", period) return min_(work_expenses + out_of_pocket_expenses, earned_cap) diff --git a/policyengine_us/variables/household/expense/childcare/spm_unit_pre_subsidy_childcare_expenses.py b/policyengine_us/variables/household/expense/childcare/spm_unit_pre_subsidy_childcare_expenses.py index 6d413264037..d68a9287ca0 100644 --- a/policyengine_us/variables/household/expense/childcare/spm_unit_pre_subsidy_childcare_expenses.py +++ b/policyengine_us/variables/household/expense/childcare/spm_unit_pre_subsidy_childcare_expenses.py @@ -5,6 +5,11 @@ class spm_unit_pre_subsidy_childcare_expenses(Variable): value_type = float entity = SPMUnit label = "SPM unit pre subsidy child care expenses" + documentation = ( + "In a household calculation, the price of care before any subsidy. " + "Datasets fill it from the ASEC's SPM_CHILDCAREXPNS, which holds what " + "parents reported paying after any subsidy." + ) definition_period = YEAR uprating = "gov.bls.cpi.cpi_u" unit = USD From 08367acb317b4ba88b237f83daafed8c6dc2612a Mon Sep 17 00:00:00 2001 From: Max Ghenis Date: Mon, 2 Nov 2026 23:57:55 -0500 Subject: [PATCH 08/42] Pin the baseline arm the dataset rule reads, and set W and C on the policy side Main's #9698 now branches a reform's baseline arm again after the constructors move the pre-response inputs. Over a dataset, the SPM expense reads its baseline subsidy from that arm, so pin it there: - Add tests/core/test_reform_baseline_arm_inputs.py. Under a reform that changes nothing, the reform and its arm match a plain run on 102 households of raw columns, two families in every state, and on a situation that names New York only through state_code_str. With _rebuild_baseline_branch disabled, both cases fail. - Keep the parent's raw earnings and hours in the repeal test, which then fails in New York without the rebuild. - Set work expenses and the earnings cap on the policy side only in property 8, with an example that fails if the rule reads either from the arm. - Drop the dead branch_name guard, document the entry points that build no arm, and word the reported-spending reading as an inference from the ASEC question. - Update _baseline_measurement_branch's docstring, which still said the arm keeps the raw inputs. Co-Authored-By: Claude Opus 5.5 --- .../core/test_reform_baseline_arm_inputs.py | 191 ++++++++++++++++++ .../test_spm_child_care_reported_expense.py | 5 +- .../test_spm_child_care_subsidy_invariants.py | 57 ++++-- .../behavioral_response_measurements.py | 6 +- ...spm_unit_capped_work_childcare_expenses.py | 18 +- 5 files changed, 254 insertions(+), 23 deletions(-) create mode 100644 policyengine_us/tests/core/test_reform_baseline_arm_inputs.py diff --git a/policyengine_us/tests/core/test_reform_baseline_arm_inputs.py b/policyengine_us/tests/core/test_reform_baseline_arm_inputs.py new file mode 100644 index 00000000000..17b9ef0e330 --- /dev/null +++ b/policyengine_us/tests/core/test_reform_baseline_arm_inputs.py @@ -0,0 +1,191 @@ +"""A reform's baseline arm reads the inputs a simulation with no reform reads. + +Core builds the arm inside its ``__init__``. The country simulations then move +``employment_income``, ``self_employment_income``, ``weekly_hours_worked`` and +``long_term_capital_gains`` to their pre-response variables and fill +``state_code`` from ``state_code_str``, and a branch keeps none of what its +parent stores later. So the arm read 0 from the pre-response variables: under +any reform it saw no hours worked and paid no New York child care subsidy to a +family a simulation with no reform paid one. Over a dataset the SPM expense +moves by the change in subsidy it reads from that arm, so the gap became a +double count. ``system._rebuild_baseline_arm`` rebuilds the arm from the final +inputs. + +Invariant: under a reform that changes nothing, the reform and its baseline +arm compute what a simulation with no reform computes, for every household, +whether a situation or a dataset of raw columns supplies the inputs. +""" + +from itertools import product + +import numpy as np +import pandas as pd +from policyengine_core.data import Dataset +from policyengine_core.reforms import Reform + +from policyengine_us import Microsimulation, Simulation + +YEAR = 2026 +TOLERANCE = 0.01 +# Every state and DC, as state_name reads them. +STATE_FIPS = ( + *(1, 2, 4, 5, 6, 8, 9, 10, 11, 12, 13, 15, 16, 17, 18, 19, 20, 21, 22, 23), + *(24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41), + *(42, 44, 45, 46, 47, 48, 49, 50, 51, 53, 54, 55, 56), +) +NEW_YORK = 36 +# A parent and a child aged 3 in full-time care. Each tuple holds the parent's +# wages, self-employment income, long-term capital gains, weekly hours and +# Social Security retirement benefit, then what the unit paid for care. +FAMILIES = ( + (30_000, 0, 0, 40, 0, 14_000), + (15_000, 3_000, 1_000, 20, 1_200, 6_000), +) +PRE_RESPONSE = ( + "employment_income_before_lsr", + "self_employment_income_before_lsr", + "weekly_hours_worked_before_lsr", + "long_term_capital_gains_before_response", +) +OUTPUTS = ( + "child_care_subsidies", + "spm_unit_capped_work_childcare_expenses", + "social_security", + "snap", + "income_tax", + "spm_unit_net_income", + "household_net_income", +) + + +class NoChange(Reform): + def apply(self): + pass + + +def dataset(): + columns = {} + + def add(name, parent, child): + columns.setdefault(name, []).extend([parent, child]) + + for unit, (fips, family) in enumerate(product(STATE_FIPS, FAMILIES)): + wages, self_employment, gains, hours, retirement, expenses = family + add("person_id", 2 * unit, 2 * unit + 1) + for entity in ("household", "tax_unit", "spm_unit", "family"): + add(f"{entity}_id", unit, unit) + add("marital_unit_id", 2 * unit, 2 * unit + 1) + add(f"age__{YEAR}", 30, 3) + add(f"employment_income__{YEAR}", wages, 0) + add(f"self_employment_income__{YEAR}", self_employment, 0) + add(f"long_term_capital_gains__{YEAR}", gains, 0) + add(f"weekly_hours_worked__{YEAR}", hours, 0) + add(f"social_security_retirement__{YEAR}", retirement, 0) + add(f"is_tax_unit_head__{YEAR}", True, False) + add(f"is_household_head__{YEAR}", True, False) + add(f"is_tax_unit_dependent__{YEAR}", False, True) + add(f"childcare_hours_per_day__{YEAR}", 0, 8) + add(f"childcare_days_per_week__{YEAR}", 0, 5) + add(f"childcare_attending_days_per_month__{YEAR}", 0, 21) + add(f"spm_unit_pre_subsidy_childcare_expenses__{YEAR}", expenses, expenses) + add(f"state_fips__{YEAR}", fips, fips) + add(f"household_weight__{YEAR}", 1, 1) + return Dataset.from_dataframe(pd.DataFrame(columns), time_period=YEAR) + + +def situation(): + """The first family in New York, naming its state only through + state_code_str, with the second family's other income.""" + members = ["parent", "child"] + return { + "people": { + "parent": { + "age": {YEAR: 30}, + "employment_income": {YEAR: 30_000}, + "self_employment_income": {YEAR: 3_000}, + "long_term_capital_gains": {YEAR: 1_000}, + "weekly_hours_worked": {YEAR: 40}, + "social_security_retirement": {YEAR: 1_200}, + "is_tax_unit_head": {YEAR: True}, + "is_household_head": {YEAR: True}, + }, + "child": { + "age": {YEAR: 3}, + "childcare_hours_per_day": {YEAR: 8}, + "childcare_days_per_week": {YEAR: 5}, + "childcare_attending_days_per_month": {YEAR: 21}, + "is_tax_unit_dependent": {YEAR: True}, + }, + }, + "tax_units": {"tax_unit": {"members": members}}, + "families": {"family": {"members": members}}, + "marital_units": { + "parent_marital_unit": {"members": ["parent"]}, + "child_marital_unit": {"members": ["child"]}, + }, + "spm_units": { + "spm_unit": { + "members": members, + "spm_unit_pre_subsidy_childcare_expenses": {YEAR: 14_000}, + } + }, + "households": { + "household": {"members": members, "state_code_str": {YEAR: "NY"}} + }, + } + + +def values(simulation): + return { + variable: np.asarray(simulation.calculate(variable, YEAR), dtype=float) + for variable in PRE_RESPONSE + OUTPUTS + } + + +def assert_both_arms_match(plain, reformed): + arm = reformed.baseline + assert reformed.branches["baseline"] is arm + assert arm.parent_branch is reformed + assert arm.baseline is None + # The arm owns its policy, which names the arm rather than the one it + # replaced. + assert arm.tax_benefit_system is not reformed.tax_benefit_system + assert arm.tax_benefit_system.simulation is arm + # No calculation has run yet, so the arm holds only inputs, and no value + # the reform's policy produced. + assert arm.drop_computed_arrays() == 0 + expected = values(plain) + for name, simulation in (("reform", reformed), ("baseline arm", arm)): + for variable, array in values(simulation).items(): + np.testing.assert_allclose( + array, + expected[variable], + atol=TOLERANCE, + err_msg=f"{name}: {variable}", + ) + return expected + + +def test_dataset_arms_match_a_simulation_with_no_reform(): + plain = Microsimulation(dataset=dataset()) + expected = assert_both_arms_match( + plain, Microsimulation(dataset=dataset(), reform=NoChange) + ) + states = plain.calculate("state_code", YEAR).values + assert len(set(states)) == len(STATE_FIPS) + # The comparison covers households these programs pay, New York's first + # family among them, which the arm used to pay nothing. + subsidies = expected["child_care_subsidies"] + assert (subsidies > 0).sum() >= 10 + assert subsidies[STATE_FIPS.index(NEW_YORK) * len(FAMILIES)] > 0 + assert (expected["social_security"] > 0).any() + + +def test_situation_arms_match_a_simulation_with_no_reform(): + plain = Simulation(situation=situation()) + reformed = Simulation(situation=situation(), reform=NoChange) + expected = assert_both_arms_match(plain, reformed) + assert expected["child_care_subsidies"].sum() > 0 + for simulation in (plain, reformed, reformed.baseline): + state = simulation.calculate("state_code", YEAR).decode_to_str() + assert state.tolist() == ["NY"] diff --git a/policyengine_us/tests/microsimulation/test_spm_child_care_reported_expense.py b/policyengine_us/tests/microsimulation/test_spm_child_care_reported_expense.py index 5d8d0ed5bbd..328c171fc6b 100644 --- a/policyengine_us/tests/microsimulation/test_spm_child_care_reported_expense.py +++ b/policyengine_us/tests/microsimulation/test_spm_child_care_reported_expense.py @@ -1,8 +1,9 @@ """Over a dataset, the SPM subtracts what parents reported paying for child care. Datasets fill spm_unit_pre_subsidy_childcare_expenses from the ASEC's -SPM_CHILDCAREXPNS, which holds what parents paid after any subsidy. So baseline -policy keeps that amount, and a reform moves it by the change in subsidy. These +SPM_CHILDCAREXPNS, what parents reported spending on child care, which the +rule reads as what they paid after any subsidy. So baseline policy keeps that +amount, and a reform moves it by the change in subsidy. These tests run the rule over the shipped population rather than the situations in test_spm_child_care_subsidy_invariants.py, so the dataset flag and the reform's baseline arm come from loading a real file. diff --git a/policyengine_us/tests/test_spm_child_care_subsidy_invariants.py b/policyengine_us/tests/test_spm_child_care_subsidy_invariants.py index 49f0e789921..b10bc5f7c0a 100644 --- a/policyengine_us/tests/test_spm_child_care_subsidy_invariants.py +++ b/policyengine_us/tests/test_spm_child_care_subsidy_invariants.py @@ -54,7 +54,8 @@ The properties above read spm_unit_pre_subsidy_childcare_expenses as a pre-subsidy price, which is what it means in a household calculation. Datasets -fill it from the ASEC's reported spending, which is already what parents paid. +fill it from the ASEC, which asks parents how much they spent on child care, +and these properties read that amount as what parents paid after any subsidy. So over a dataset, with E the reported amount, S0 the subsidy baseline policy pays and S1 the subsidy the simulated policy pays: @@ -63,7 +64,8 @@ 7. Baseline policy over a dataset leaves the expense at min(W + E, C), the amount Census subtracts, whatever subsidy the model pays. 8. Under any policy over a dataset, the expense equals that reference, with or - without a child in the unit. A policy that pays the same subsidy leaves the + without a child in the unit, and W and C come from the policy simulated. A + policy that pays the same subsidy and leaves W and C alone leaves the expense where baseline policy put it. 9. Differential. Give a dataset the amount the household rule says a unit pays at baseline policy. Then the two rules give the same expense under any @@ -435,6 +437,8 @@ def capped_expense(simulation): "policy_subsidy": amounts, "work": st.integers(0, 6_000), "cap": st.integers(0, 60_000), + "policy_work": st.integers(0, 6_000), + "policy_cap": st.integers(0, 60_000), "has_child": st.booleans(), } ), @@ -472,6 +476,8 @@ def test_baseline_policy_over_a_dataset_keeps_the_reported_amount(units): "policy_subsidy": 5_000, "work": 100, "cap": 60_000, + "policy_work": 100, + "policy_cap": 60_000, "has_child": True, } ] @@ -486,25 +492,54 @@ def test_baseline_policy_over_a_dataset_keeps_the_reported_amount(units): "policy_subsidy": 0, "work": 100, "cap": 6_000, + "policy_work": 100, + "policy_cap": 6_000, "has_child": False, } ] ) +@example( + # A policy that pays the same subsidy but moves work expenses and the cap: + # 3,500 reads both from the policy, 3,100 would read W and 3,900 would read + # C from baseline policy. + [ + { + "state": "NY", + "expenses": 3_000, + "subsidy": 500, + "policy_subsidy": 500, + "work": 100, + "cap": 60_000, + "policy_work": 900, + "policy_cap": 3_500, + "has_child": True, + } + ] +) def test_policy_over_a_dataset_moves_the_expense_by_the_subsidy_change(units): - # 8. + # 8. Work expenses and the cap change on the policy's side only, which + # stores them after the baseline arm branches off. simulation = with_baseline_arm(over_dataset(build_units(units))) set_subsidies( simulation, [unit["subsidy"] for unit in units], [unit["policy_subsidy"] for unit in units], ) + simulation.set_input( + "spm_unit_work_expenses", YEAR, [unit["policy_work"] for unit in units] + ) + simulation.set_input( + "spm_unit_head_spouse_earned_cap", + YEAR, + [unit["policy_cap"] for unit in units], + ) for unit, expense in zip(units, capped_expense(simulation)): assert expense == pytest.approx( reference_expense( unit["expenses"], unit["policy_subsidy"] - unit["subsidy"], - unit["work"], - unit["cap"], + unit["policy_work"], + unit["policy_cap"], ), abs=TOLERANCE, ) @@ -540,15 +575,11 @@ def test_repeal_moves_dataset_and_household_income_by_the_same_amount( # 9. Real programs and a real reform. The dataset reads $14,000 as what # parents paid and the household calculation as the price. Neither rule's # cap binds and both expenses rise by the subsidy, so SPM income falls by - # the same amount. + # the same amount. The parent's earnings and hours stay raw inputs, which + # the simulation moves to their pre-response variables: the baseline arm + # has to read the moved values, or New York's arm sees no hours worked. situation = family(state, 30_000, 14_000) - parent = situation["people"]["parent"] - del parent["weeks_worked"] - # The columns datasets hold. Simulation moves employment_income to its - # pre-response variable after core builds the baseline arm, so the arm would - # read no earnings wherever a formula reads that variable. - parent["employment_income_before_lsr"] = parent.pop("employment_income") - parent["weekly_hours_worked_before_lsr"] = parent.pop("weekly_hours_worked") + del situation["people"]["parent"]["weeks_worked"] if county_fips: situation["households"]["household"]["county_fips"] = {YEAR: county_fips} _, household_change = with_and_without_subsidies(situation) diff --git a/policyengine_us/variables/gov/simulation/behavioral_response_measurements.py b/policyengine_us/variables/gov/simulation/behavioral_response_measurements.py index 780033b204e..328d88cf0a3 100644 --- a/policyengine_us/variables/gov/simulation/behavioral_response_measurements.py +++ b/policyengine_us/variables/gov/simulation/behavioral_response_measurements.py @@ -69,10 +69,8 @@ def _baseline_measurement_branch(simulation): - A branch shares its parent's baseline, and on policyengine-core before #587 so does a clone, so their baseline holds the parent's inputs. - - A reform simulation's baseline is a branch taken while it was built, - before this package moved ``employment_income`` and the other - pre-response inputs to their ``_before_lsr`` variables, so a household - baseline keeps them as overrides; later inputs never reach it. + - A reform simulation branches its baseline at the end of construction, + so inputs set on the simulation afterwards never reach it. ``simulation.get_branch("baseline")``, used before, was worse: for a branch or an early clone it made a new branch under the *reform* policy, so the diff --git a/policyengine_us/variables/household/expense/childcare/spm_unit_capped_work_childcare_expenses.py b/policyengine_us/variables/household/expense/childcare/spm_unit_capped_work_childcare_expenses.py index 4fe149f1dc3..0d98c64d0b3 100644 --- a/policyengine_us/variables/household/expense/childcare/spm_unit_capped_work_childcare_expenses.py +++ b/policyengine_us/variables/household/expense/childcare/spm_unit_capped_work_childcare_expenses.py @@ -7,6 +7,14 @@ class spm_unit_capped_work_childcare_expenses(Variable): label = "SPM unit work and childcare expenses" definition_period = YEAR unit = USD + documentation = ( + "Over a dataset, the child care part keeps the reported amount under " + "baseline policy and moves by the change in subsidy under a reform, " + "which it reads from the reform's baseline arm. Core builds that arm " + "only for a reform passed as reform=. A reformed system passed as " + "tax_benefit_system=, or a reform applied with apply_reform after " + "construction, gets no arm, so the expense keeps the reported amount." + ) reference = "https://www2.census.gov/programs-surveys/supplemental-poverty-measure/datasets/spm/spm_techdoc.pdf#page=17" def formula_2024(spm_unit, period, parameters): @@ -19,11 +27,13 @@ def formula_2024(spm_unit, period, parameters): # rather than adding to resources. simulation = spm_unit.simulation if simulation.is_over_dataset: - # Datasets fill the pre-subsidy input from the ASEC's reported - # spending, which is already what parents paid. Baseline policy - # keeps that amount, and a reform moves it by the change in subsidy. + # Datasets fill the pre-subsidy input from the ASEC, which asks + # parents how much they spent on child care, and this rule reads + # that as what they paid after any subsidy. Baseline policy keeps + # that amount, and a reform moves it by the change in subsidy. A + # baseline arm has no baseline of its own, so it keeps the amount. out_of_pocket_expenses = pre_subsidy_expenses - if simulation.baseline is not None and simulation.branch_name != "baseline": + if simulation.baseline is not None: baseline_spm_unit = simulation.baseline.populations["spm_unit"] subsidy_change = spm_unit( "child_care_subsidies", period From 6946cd74a45d5dee91c657781ce22a111c61066b Mon Sep 17 00:00:00 2001 From: Max Ghenis Date: Tue, 3 Nov 2026 00:00:50 -0500 Subject: [PATCH 09/42] Name main's arm rebuild in the arm test's docstring The docstring still named _rebuild_baseline_arm, which this branch dropped when it merged main. Main's PolicyEngine/policyengine-us#9698 calls it _rebuild_baseline_branch. Name the moved inputs through PRE_RESPONSE_INPUTS, which also lists sstb_self_employment_income. Co-Authored-By: Claude Opus 5.5 --- .../core/test_reform_baseline_arm_inputs.py | 17 +++++++++-------- 1 file changed, 9 insertions(+), 8 deletions(-) diff --git a/policyengine_us/tests/core/test_reform_baseline_arm_inputs.py b/policyengine_us/tests/core/test_reform_baseline_arm_inputs.py index 17b9ef0e330..d84e46e86d6 100644 --- a/policyengine_us/tests/core/test_reform_baseline_arm_inputs.py +++ b/policyengine_us/tests/core/test_reform_baseline_arm_inputs.py @@ -1,15 +1,16 @@ """A reform's baseline arm reads the inputs a simulation with no reform reads. Core builds the arm inside its ``__init__``. The country simulations then move -``employment_income``, ``self_employment_income``, ``weekly_hours_worked`` and -``long_term_capital_gains`` to their pre-response variables and fill +the aggregates in ``PRE_RESPONSE_INPUTS``, such as ``employment_income`` and +``weekly_hours_worked``, to their pre-response variables and fill ``state_code`` from ``state_code_str``, and a branch keeps none of what its -parent stores later. So the arm read 0 from the pre-response variables: under -any reform it saw no hours worked and paid no New York child care subsidy to a -family a simulation with no reform paid one. Over a dataset the SPM expense -moves by the change in subsidy it reads from that arm, so the gap became a -double count. ``system._rebuild_baseline_arm`` rebuilds the arm from the final -inputs. +parent stores later. Before PolicyEngine/policyengine-us#9698 the arm therefore +read 0 from the pre-response variables: under any reform it saw no hours +worked and paid no New York child care subsidy to a family that a simulation +with no reform paid one. Over a dataset the SPM expense moves by the change in +subsidy it reads from that arm, so the gap became a double count. +``system._rebuild_baseline_branch`` now branches the arm again after the +moves. Invariant: under a reform that changes nothing, the reform and its baseline arm compute what a simulation with no reform computes, for every household, From 678d423e66f1212afa413ba50d385ee4f6e4bf6e Mon Sep 17 00:00:00 2001 From: Max Ghenis Date: Tue, 3 Nov 2026 04:29:02 -0500 Subject: [PATCH 10/42] Drop holders built for another policy when rebuilding the baseline arm _rebuild_baseline_branch cloned the reform simulation and rebound the clone's holders to baseline variables, but it kept each holder the reform had built in another entity or with other ETERNITY storage. Construction, subsample and _baseline_measurement_branch all drop those. Under a reform that stores child_care_subsidies for all time, a New York family with a $500 input got S0 = $500 from the arm, where baseline policy pays it $13,916.40, so its reform expense came out $14,000.00 where the dataset rule gives $27,416.40. - Call _drop_holders_built_for_another_policy before _rebind_holders. - Add test_the_arm_calculates_what_the_reform_stores_for_all_time, and check in every arm test that each holder suits its arm's variable. - Check holder binding before subsampling as well. Under the redefining reform, the arm copied an empty yearly holder for the baseline's ETERNITY is_household_head. - Document that apply_reform builds no arm while a simulation built with reform= keeps its arm, and word the input's after-subsidy reading as the model's. Co-Authored-By: Claude Opus 5.5 --- changelog.d/spm-child-care-subsidies.fixed.md | 2 +- policyengine_us/system.py | 12 ++- .../core/test_reform_baseline_arm_inputs.py | 88 +++++++++++++++++-- policyengine_us/tests/core/test_spm_system.py | 9 +- ...spm_unit_capped_work_childcare_expenses.py | 8 +- ...spm_unit_pre_subsidy_childcare_expenses.py | 6 +- 6 files changed, 111 insertions(+), 14 deletions(-) diff --git a/changelog.d/spm-child-care-subsidies.fixed.md b/changelog.d/spm-child-care-subsidies.fixed.md index 95d3b483235..5f55e8d652c 100644 --- a/changelog.d/spm-child-care-subsidies.fixed.md +++ b/changelog.d/spm-child-care-subsidies.fixed.md @@ -1 +1 @@ -Count every state child care subsidy in the Supplemental Poverty Measure from 2024 by netting it from the SPM child care expense in household calculations, keep the ASEC's reported spending as that expense over a dataset while a reform moves it by the change in subsidy, and add the District of Columbia, Tennessee and Texas subsidies to the 2024 program list. +Count every state child care subsidy in the Supplemental Poverty Measure from 2024 by netting it from the SPM child care expense in household calculations, keep the ASEC's reported spending as that expense over a dataset while a reform moves it by the change in subsidy, and add the District of Columbia, Tennessee and Texas subsidies to the 2024 program list. Rebuild a reform's baseline arm without the holders the reform built for its own definition of a variable in another entity or with other ETERNITY storage, as core's own branch does. diff --git a/policyengine_us/system.py b/policyengine_us/system.py index 65a99683f52..8ae78e287c6 100644 --- a/policyengine_us/system.py +++ b/policyengine_us/system.py @@ -265,7 +265,10 @@ def _rebuild_baseline_branch(simulation): ``input_variables``. Its TANF counted no earnings, and the baseline marginal tax rate that labor supply responses compare against erased pre-response wages. Branching again from the simulation, as core's - ``subsample`` does, gives the baseline the same inputs as the reform. + ``subsample`` does, gives the baseline the same inputs as the reform, + except those the reform stored for its own definition of a variable in + another entity or with other ``ETERNITY`` storage, which core's branch + dropped too. """ baseline = simulation.branches.pop("baseline", None) if baseline is None: @@ -278,7 +281,12 @@ def _rebuild_baseline_branch(simulation): rebuilt.tracer = simulation.tracer rebuilt.tax_benefit_system = baseline.tax_benefit_system # Cloning bound holders to reform variables. Restoring policy must also - # restore those bindings and remove inputs that exist only in the reform. + # drop holders whose entity or storage the baseline's variables cannot + # use, restore the other bindings and remove inputs that exist only in + # the reform. A kept holder would hand the baseline the reform's input: + # under a reform that stores ``child_care_subsidies`` for all time, the + # baseline read that input in place of its own formula. + rebuilt._drop_holders_built_for_another_policy() rebuilt._rebind_holders() rebuilt._isolate_parameter_tracing() simulation.baseline = rebuilt diff --git a/policyengine_us/tests/core/test_reform_baseline_arm_inputs.py b/policyengine_us/tests/core/test_reform_baseline_arm_inputs.py index d84e46e86d6..1406a05ea0e 100644 --- a/policyengine_us/tests/core/test_reform_baseline_arm_inputs.py +++ b/policyengine_us/tests/core/test_reform_baseline_arm_inputs.py @@ -10,11 +10,14 @@ with no reform paid one. Over a dataset the SPM expense moves by the change in subsidy it reads from that arm, so the gap became a double count. ``system._rebuild_baseline_branch`` now branches the arm again after the -moves. +moves. Like core's branch, it drops each holder the reform built in another +entity or with other ``ETERNITY`` storage than the baseline's variable has. +A kept holder hands the arm the reform's input in place of its formula. -Invariant: under a reform that changes nothing, the reform and its baseline +Invariants: under a reform that changes nothing, the reform and its baseline arm compute what a simulation with no reform computes, for every household, -whether a situation or a dataset of raw columns supplies the inputs. +whether a situation or a dataset of raw columns supplies the inputs. Under any +reform, each holder in either arm suits that arm's definition of its variable. """ from itertools import product @@ -22,9 +25,12 @@ import numpy as np import pandas as pd from policyengine_core.data import Dataset +from policyengine_core.periods import ETERNITY from policyengine_core.reforms import Reform +from policyengine_core.variables import Variable from policyengine_us import Microsimulation, Simulation +from policyengine_us.entities import SPMUnit YEAR = 2026 TOLERANCE = 0.01 @@ -64,13 +70,26 @@ def apply(self): pass -def dataset(): +class child_care_subsidies(Variable): + # Stored for all time, where baseline policy calculates it each year. + value_type = float + entity = SPMUnit + label = "Child care subsidies" + definition_period = ETERNITY + + +class StoreSubsidiesForAllTime(Reform): + def apply(self): + self.update_variable(child_care_subsidies) + + +def dataset(states=STATE_FIPS, families=FAMILIES, eternal_subsidy=None): columns = {} def add(name, parent, child): columns.setdefault(name, []).extend([parent, child]) - for unit, (fips, family) in enumerate(product(STATE_FIPS, FAMILIES)): + for unit, (fips, family) in enumerate(product(states, families)): wages, self_employment, gains, hours, retirement, expenses = family add("person_id", 2 * unit, 2 * unit + 1) for entity in ("household", "tax_unit", "spm_unit", "family"): @@ -91,6 +110,8 @@ def add(name, parent, child): add(f"spm_unit_pre_subsidy_childcare_expenses__{YEAR}", expenses, expenses) add(f"state_fips__{YEAR}", fips, fips) add(f"household_weight__{YEAR}", 1, 1) + if eternal_subsidy is not None: + add("child_care_subsidies__eternity", eternal_subsidy, eternal_subsidy) return Dataset.from_dataframe(pd.DataFrame(columns), time_period=YEAR) @@ -143,6 +164,20 @@ def values(simulation): } +def assert_holders_suit_their_variables(simulation): + """Each holder sits in its variable's entity, with ``ETERNITY`` storage + exactly when the simulation's own definition of the variable has it.""" + variables = simulation.tax_benefit_system.variables + for population in simulation.populations.values(): + for name, holder in population._holders.items(): + variable = variables.get(name) + assert holder.variable is variable, name + assert variable.entity.key == population.entity.key, name + assert holder._memory_storage.is_eternal == ( + variable.definition_period == ETERNITY + ), name + + def assert_both_arms_match(plain, reformed): arm = reformed.baseline assert reformed.branches["baseline"] is arm @@ -155,6 +190,8 @@ def assert_both_arms_match(plain, reformed): # No calculation has run yet, so the arm holds only inputs, and no value # the reform's policy produced. assert arm.drop_computed_arrays() == 0 + for simulation in (reformed, arm): + assert_holders_suit_their_variables(simulation) expected = values(plain) for name, simulation in (("reform", reformed), ("baseline arm", arm)): for variable, array in values(simulation).items(): @@ -190,3 +227,44 @@ def test_situation_arms_match_a_simulation_with_no_reform(): for simulation in (plain, reformed, reformed.baseline): state = simulation.calculate("state_code", YEAR).decode_to_str() assert state.tolist() == ["NY"] + + +def test_the_arm_calculates_what_the_reform_stores_for_all_time(): + """New York's first family enters with a $500 subsidy that the reform + stores for all time. The baseline's yearly ``child_care_subsidies`` cannot + use that storage, so the arm drops the input and pays what a simulation + with no reform pays. Keeping it gave the arm $500 as S0 where baseline + policy pays $13,916.40, and left the reform's expense $13,416.40 low.""" + plain = Microsimulation(dataset=dataset((NEW_YORK,), FAMILIES[:1])) + reformed = Microsimulation( + dataset=dataset((NEW_YORK,), FAMILIES[:1], eternal_subsidy=500), + reform=StoreSubsidiesForAllTime, + ) + arm = reformed.baseline + for simulation in (reformed, arm): + assert_holders_suit_their_variables(simulation) + + def value(simulation, variable): + return np.asarray(simulation.calculate(variable, YEAR), dtype=float) + + baseline_subsidy = value(plain, "child_care_subsidies") + assert baseline_subsidy[0] > 500 + np.testing.assert_allclose( + value(arm, "child_care_subsidies"), baseline_subsidy, atol=TOLERANCE + ) + np.testing.assert_allclose(value(reformed, "child_care_subsidies"), 500) + expense = "spm_unit_capped_work_childcare_expenses" + np.testing.assert_allclose( + value(arm, expense), value(plain, expense), atol=TOLERANCE + ) + # The dataset rule moves the reported amount by the change in subsidy. + expected = np.minimum( + value(reformed, "spm_unit_work_expenses") + + np.maximum( + value(reformed, "spm_unit_pre_subsidy_childcare_expenses") + - (500 - baseline_subsidy), + 0, + ), + value(reformed, "spm_unit_head_spouse_earned_cap"), + ) + np.testing.assert_allclose(value(reformed, expense), expected, atol=TOLERANCE) diff --git a/policyengine_us/tests/core/test_spm_system.py b/policyengine_us/tests/core/test_spm_system.py index ee343a4c1b4..864ec5f4a08 100644 --- a/policyengine_us/tests/core/test_spm_system.py +++ b/policyengine_us/tests/core/test_spm_system.py @@ -856,7 +856,9 @@ def test_subsampling_never_changes_which_policy_a_holder_belongs_to( belongs to that policy. The rebuilt baseline arm has no baseline of its own, holds nothing that only the reform defines, and keeps no holder the reform built for its own definition of a variable: here, yearly storage - for the baseline's ``ETERNITY`` ``is_household_head``. + for the baseline's ``ETERNITY`` ``is_household_head``. Construction branches + the arm again after it moves inputs, and that arm holds to the same + invariant before any subsampling. Core 3.33.1 and later rebuild from recorded inputs without exporting calculated values as inputs; earlier versions also exported calculated @@ -872,6 +874,11 @@ def test_subsampling_never_changes_which_policy_a_holder_belongs_to( reform=SUBSAMPLED_REFORMS[reform], spm={"geography_kind": "national"}, ) + # Core lists input variables by asking for every variable's holder, so the + # redefining reform gets an empty yearly holder for is_household_head. The + # arm branched after the moves copies it and must drop it. + for simulation in (changed, changed.baseline): + assert_bound_to_own_policy(simulation) policies = { "reform": changed.tax_benefit_system, "baseline": changed.baseline.tax_benefit_system, diff --git a/policyengine_us/variables/household/expense/childcare/spm_unit_capped_work_childcare_expenses.py b/policyengine_us/variables/household/expense/childcare/spm_unit_capped_work_childcare_expenses.py index 0d98c64d0b3..49ee176948b 100644 --- a/policyengine_us/variables/household/expense/childcare/spm_unit_capped_work_childcare_expenses.py +++ b/policyengine_us/variables/household/expense/childcare/spm_unit_capped_work_childcare_expenses.py @@ -11,9 +11,11 @@ class spm_unit_capped_work_childcare_expenses(Variable): "Over a dataset, the child care part keeps the reported amount under " "baseline policy and moves by the change in subsidy under a reform, " "which it reads from the reform's baseline arm. Core builds that arm " - "only for a reform passed as reform=. A reformed system passed as " - "tax_benefit_system=, or a reform applied with apply_reform after " - "construction, gets no arm, so the expense keeps the reported amount." + "only for a reform passed as reform=, and apply_reform builds none. A " + "simulation built with reform= keeps its arm, under baseline policy, " + "through any reform applied later. A reformed system passed as " + "tax_benefit_system=, or apply_reform on a simulation built without " + "reform=, leaves no arm, so the expense keeps the reported amount." ) reference = "https://www2.census.gov/programs-surveys/supplemental-poverty-measure/datasets/spm/spm_techdoc.pdf#page=17" diff --git a/policyengine_us/variables/household/expense/childcare/spm_unit_pre_subsidy_childcare_expenses.py b/policyengine_us/variables/household/expense/childcare/spm_unit_pre_subsidy_childcare_expenses.py index d68a9287ca0..9cd621dac43 100644 --- a/policyengine_us/variables/household/expense/childcare/spm_unit_pre_subsidy_childcare_expenses.py +++ b/policyengine_us/variables/household/expense/childcare/spm_unit_pre_subsidy_childcare_expenses.py @@ -7,8 +7,10 @@ class spm_unit_pre_subsidy_childcare_expenses(Variable): label = "SPM unit pre subsidy child care expenses" documentation = ( "In a household calculation, the price of care before any subsidy. " - "Datasets fill it from the ASEC's SPM_CHILDCAREXPNS, which holds what " - "parents reported paying after any subsidy." + "Datasets fill it from the ASEC's SPM_CHILDCAREXPNS, what parents " + "reported spending on child care, which " + "spm_unit_capped_work_childcare_expenses reads as what they paid after " + "any subsidy." ) definition_period = YEAR uprating = "gov.bls.cpi.cpi_u" From 13fc027c39929d43dd655e701127a99d95744189 Mon Sep 17 00:00:00 2001 From: Max Ghenis Date: Tue, 3 Nov 2026 12:21:07 -0500 Subject: [PATCH 11/42] Read household_child_care_subsidies in the SPM invariant tests PolicyEngine/policyengine-us#9503 lists household_child_care_subsidies in every household_state_benefits block in place of the per-state entries. It counts each subsidy up to the family's pre-subsidy bill. The differential test's helper looked only for child_care_subsidies or the state's own variable, so after the merge it returned 0 while household_net_income counted the subsidy, and test_spm_and_household_measures_agree would miss by that amount. - subsidy_counted_by_household_measure now reads whichever child care variable the list names: household_child_care_subsidies, the aggregate, the state's variable or a program that variable adds. It fails if the list names two. - test_no_subsidy_is_a_spm_resource also checks that no SPM benefit list names household_child_care_subsidies. - test_household_measure_counts_each_subsidy_once checks that every household_state_benefits block from 2024 names household_child_care_subsidies once and no other subsidy variable or program. Adding co_ccap_subsidy to the 2026 household block fails the new test, and adding household_child_care_subsidies to spm_unit_benefits fails the SPM check. Co-Authored-By: Claude Opus 5.5 --- .../test_spm_child_care_subsidy_invariants.py | 53 +++++++++++++++---- 1 file changed, 44 insertions(+), 9 deletions(-) diff --git a/policyengine_us/tests/test_spm_child_care_subsidy_invariants.py b/policyengine_us/tests/test_spm_child_care_subsidy_invariants.py index b10bc5f7c0a..478cbb0a855 100644 --- a/policyengine_us/tests/test_spm_child_care_subsidy_invariants.py +++ b/policyengine_us/tests/test_spm_child_care_subsidy_invariants.py @@ -34,7 +34,8 @@ 5. No program is counted twice. From 2024, no *_child_care_subsidies variable, and no program one of them adds, appears in spm_unit_benefits or in a reform's copy of that list, and all of them reach child_care_subsidies. - Before 2024 the expense has no formula, so Colorado's, Washington's and West + household_state_benefits counts them only through + household_child_care_subsidies. Before 2024 the expense has no formula, so Colorado's, Washington's and West Virginia's subsidies stay resources and count once, as on main. The Tlaib reform copies carry only Colorado's in those years, also as on main. 6. Differential. With real programs turned on and off, the expense falls by @@ -225,10 +226,19 @@ def state_subsidy_adds(): return {name: list(system.variables[name].adds) for name in STATE_SUBSIDIES} -def test_no_subsidy_is_a_spm_resource(): - subsidy_variables = set(STATE_SUBSIDIES) | {"child_care_subsidies"} +def all_subsidy_variables(): + """Every variable that pays a state subsidy or sums them.""" + variables = set(STATE_SUBSIDIES) | { + "child_care_subsidies", + "household_child_care_subsidies", + } for programs in state_subsidy_adds().values(): - subsidy_variables.update(programs) + variables.update(programs) + return variables + + +def test_no_subsidy_is_a_spm_resource(): + subsidy_variables = all_subsidy_variables() lists = { "baseline spm_unit_benefits": benefits_lists_in(BASELINE_SPM_BENEFITS_SOURCE)[ 0 @@ -249,6 +259,23 @@ def test_no_subsidy_is_a_spm_resource(): ) +def test_household_measure_counts_each_subsidy_once(): + # Property 6 subtracts what household net income counts, so the household + # list has to count each subsidy once too. + others = all_subsidy_variables() - {"household_child_care_subsidies"} + blocks = yaml.load( + ( + PACKAGE / "parameters/gov/household/household_state_benefits.yaml" + ).read_text(), + yaml.BaseLoader, + )["values"] + assert "2024-01-01" in blocks + for start, members in blocks.items(): + if start >= "2024": + assert members.count("household_child_care_subsidies") == 1, start + assert not others & set(members), (start, sorted(others & set(members))) + + def test_every_state_subsidy_is_in_the_programs_list(): variables_dir = PACKAGE / "variables/gov/states" defined = {path.stem for path in variables_dir.rglob("*_child_care_subsidies.py")} @@ -324,15 +351,23 @@ def change(variable): def subsidy_counted_by_household_measure(simulation, state): - """The subsidy household_state_benefits sums, whether it lists the state's - variable or the national aggregate.""" + """The subsidy household_state_benefits sums, through whichever variable it + lists: household_child_care_subsidies, the aggregate, the state's own + variable or a program that variable adds.""" listed = simulation.tax_benefit_system.parameters( f"{YEAR}-01-01" ).gov.household.household_state_benefits state_variable = f"{state.lower()}_child_care_subsidies" - if "child_care_subsidies" in listed or state_variable in listed: - return float(simulation.calculate("child_care_subsidies", YEAR).sum()) - return 0.0 + candidates = { + "household_child_care_subsidies", + "child_care_subsidies", + state_variable, + *state_subsidy_adds()[state_variable], + } + counted = sorted(candidates & set(listed)) + # Listing two of them would count the subsidy twice. + assert len(counted) <= 1, counted + return sum(float(simulation.calculate(name, YEAR).sum()) for name in counted) @settings(max_examples=12, deadline=None) From 5a6557a92a0e921c0016b9c4adec1a7478c5789e Mon Sep 17 00:00:00 2001 From: Max Ghenis Date: Tue, 3 Nov 2026 14:43:40 -0500 Subject: [PATCH 12/42] Set again the inputs a reform stores apart from baseline policy Sol's r7 review found that dropping a holder the reform built with other ETERNITY storage also drops inputs that baseline policy can hold. With a yearly $500 subsidy for 2026 in the dataset both runs read, under a reform that stores child_care_subsidies for all time, the arm calculated $13,916.40 as S0 and the reform's expense came out $27,416.40 instead of $14,000.00. A reform simulation now keeps each input whose variable baseline policy defines in the same entity but with other ETERNITY storage. Every place that drops such holders (the constructor's arm, the rebuilt arm, a subsample's arm and the baseline measurement branch) then sets those inputs again, skipping any the baseline's definition can't hold. subsample carries them over to the sample by person ID, and keeps them when it fails before core rebuilds. Also: #9503's program-list test checked no block on this branch and now checks every block from 2024; invariant 9 states its price condition; the changelog names the replay. Co-Authored-By: Claude Opus 5.5 --- changelog.d/spm-child-care-subsidies.fixed.md | 2 +- policyengine_us/spm.py | 160 +++++++++++++++++- policyengine_us/system.py | 9 +- .../core/test_reform_baseline_arm_inputs.py | 134 +++++++++++++-- ...child_care_subsidies_household_benefits.py | 13 +- .../test_spm_child_care_subsidy_invariants.py | 12 +- .../behavioral_response_measurements.py | 2 + 7 files changed, 306 insertions(+), 26 deletions(-) diff --git a/changelog.d/spm-child-care-subsidies.fixed.md b/changelog.d/spm-child-care-subsidies.fixed.md index 5f55e8d652c..36eea7c754b 100644 --- a/changelog.d/spm-child-care-subsidies.fixed.md +++ b/changelog.d/spm-child-care-subsidies.fixed.md @@ -1 +1 @@ -Count every state child care subsidy in the Supplemental Poverty Measure from 2024 by netting it from the SPM child care expense in household calculations, keep the ASEC's reported spending as that expense over a dataset while a reform moves it by the change in subsidy, and add the District of Columbia, Tennessee and Texas subsidies to the 2024 program list. Rebuild a reform's baseline arm without the holders the reform built for its own definition of a variable in another entity or with other ETERNITY storage, as core's own branch does. +Count every state child care subsidy in the Supplemental Poverty Measure from 2024 by netting it from the SPM child care expense in household calculations, keep the ASEC's reported spending as that expense over a dataset while a reform moves it by the change in subsidy, and add the District of Columbia, Tennessee and Texas subsidies to the 2024 program list. Rebuild a reform's baseline arm without the holders the reform built for its own definition of a variable in another entity or with other ETERNITY storage, as core's own branch does, then set again each input a dataset or set_input gave the reform for such a variable, wherever the baseline's definition can hold it. diff --git a/policyengine_us/spm.py b/policyengine_us/spm.py index 94d547c331e..83024d05ec4 100644 --- a/policyengine_us/spm.py +++ b/policyengine_us/spm.py @@ -12,7 +12,9 @@ from functools import lru_cache from inspect import ismethod, signature +import numpy as np from policyengine_core import periods as periods_ +from policyengine_core.errors import PeriodMismatchError from policyengine_core.parameters import Parameter, ParameterScale from policyengine_core.simulations import Simulation as CoreSimulation from policyengine_core.taxbenefitsystems import TaxBenefitSystem @@ -90,6 +92,12 @@ # branch and invalidation paths below handle them explicitly. BEHAVIORAL_RESPONSE_CACHE_ATTR = "_behavioral_response_measurements" +# Where a reform simulation keeps, as given, each input whose variable baseline +# policy stores apart from it, for its baseline arm to set again +# (``SPMSimulationMixin._keep_input_for_baseline_policy``). Each simulation and +# branch has its own list. +KEPT_BASELINE_INPUTS_ATTR = "_inputs_kept_for_baseline_policy" + COUNTY_INPUT_FIX = ( 'send county_fips as a five-digit string (for example "06037"), or select ' 'geography_kind="national" in the spm configuration' @@ -765,6 +773,18 @@ def pin_spm_policy(system): ) +def _stored_apart(variable, other): + """Whether two definitions of a variable share an entity but only one of + them is stored for ``ETERNITY``.""" + return ( + variable is not None + and other is not None + and variable.entity.key == other.entity.key + and (variable.definition_period == periods_.ETERNITY) + != (other.definition_period == periods_.ETERNITY) + ) + + class SPMSimulationMixin: """Keep forecast selection and receipts private to each simulation.""" @@ -775,6 +795,8 @@ def __init__(self, *args, **kwargs): if baseline is not None: baseline._drop_holders_built_for_another_policy() self._rebind_holders() + if baseline is not None: + baseline._set_inputs_kept_for_baseline_policy(self) # Core sets ``trace`` before this simulation owns its policy state. self._isolate_parameter_tracing() # Every input path - situation builder, dataset loader, direct @@ -853,6 +875,8 @@ def _drop_holders_built_for_another_policy(self): ``ETERNITY`` variable, therefore cannot hold the baseline's definition. Drop it with its recorded inputs, as core 3.32.21 and later do in ``_bind_to_tax_benefit_system``; core 3.32.8 keeps it. + ``_set_inputs_kept_for_baseline_policy`` then sets again each input + the source gave that the baseline's definition can hold. Only a baseline arm does this. ``apply_reform`` keeps a simulation's own inputs, as core's does. @@ -877,6 +901,114 @@ def _drop_holders_built_for_another_policy(self): name for name in self.input_variables if name not in dropped ] + def _keep_input_for_baseline_policy(self, variable_name, period, value): + """Keep an input whose variable baseline policy stores apart from this one. + + A reform's baseline arm drops each holder the reform built with storage + for (or not for) ``ETERNITY`` that the baseline's variable lacks, and + the holder's inputs go with it. An ``ETERNITY`` holder keeps no + period, so it cannot give back a yearly input: under a reform that + stores ``child_care_subsidies`` for all time, the arm calculated the + 2026 subsidy a dataset supplied, and S0 moved by thousands of dollars + with no change in the subsidy paid. So keep each such input as given, + for the arm to set under baseline policy. A holder in another entity + holds values the baseline's entity cannot take, so this keeps none of + those. + + Core's builder sets a situation's inputs on their holders directly, + not through ``set_input``, so this keeps none of them, and the arm + calculates such a variable as core's own arm does. The household rule + for the SPM expense reads no baseline subsidy, so what the arm pays + never reaches a situation's SPM expense. + """ + if getattr(self, "reform", None) is None: + # Only a simulation built with ``reform=`` has a baseline arm. + return + baseline_policy = getattr(self, "default_tax_benefit_system_instance", None) + if baseline_policy is None or not _stored_apart( + self.tax_benefit_system.variables.get(variable_name), + baseline_policy.variables.get(variable_name), + ): + return + count = self.get_variable_population(variable_name).count + # A copy, broadcast as a population takes a scalar input, so a later + # write to the caller's array cannot change what the arm sets. + kept = np.array(np.broadcast_to(value, count, subok=True), subok=True) + self.__dict__.setdefault(KEPT_BASELINE_INPUTS_ATTR, []).append( + (variable_name, period, kept) + ) + + def _set_inputs_kept_for_baseline_policy(self, source): + """Set the inputs ``source`` kept for this simulation's policy. + + ``source`` is the simulation this baseline arm, or baseline measurement + branch, was branched from. Each input it kept belongs to a variable it + stores apart from this policy, so this simulation dropped the holder. + Setting each input again, in the order ``source`` received them, gives + this simulation what a simulation with no reform loads from the same + inputs. This policy cannot hold an ``ETERNITY`` input for a yearly + variable, so that input stays out and this simulation calculates the + variable. + """ + variables = self.tax_benefit_system.variables + source_variables = source.tax_benefit_system.variables + for variable_name, period, value in source.__dict__.get( + KEPT_BASELINE_INPUTS_ATTR, () + ): + if not _stored_apart( + source_variables.get(variable_name), variables.get(variable_name) + ): + continue + try: + self.set_input(variable_name, period, value.copy()) + except PeriodMismatchError: + continue + + def _kept_inputs_on_person_rows(self): + """Each kept input with its values on person rows. + + Core's subsampling exports a group's value on each member's row, so + this does the same. + """ + person_key = self.persons.entity.key + rows = [] + for variable_name, period, value in self.__dict__.get( + KEPT_BASELINE_INPUTS_ATTR, () + ): + entity_key = self.tax_benefit_system.variables[variable_name].entity.key + if entity_key != person_key: + value = self.populations[entity_key].project(value) + rows.append((variable_name, period, entity_key, value)) + return rows + + def _keep_inputs_for_sampled_rows(self, rows, person_ids): + """Keep the inputs on ``rows`` for the people a subsample retained. + + Core retains people by their IDs, as ``_select_subsample_sources`` in + ``tools/social_security_inputs.py`` reads them, and its flat-file + loader gives a group its first member's value, so this does the same. + These replace what the rebuild kept for the same variables and join + what it kept for any other. + """ + positions = {person_id: index for index, person_id in enumerate(person_ids)} + retained = np.array( + [positions[person_id] for person_id in self.persons.ids], dtype=int + ) + person_key = self.persons.entity.key + kept = [] + for variable_name, period, entity_key, values in rows: + values = values[retained] + if entity_key != person_key: + values = self.populations[entity_key].value_from_first_person(values) + kept.append((variable_name, period, values)) + carried = {variable_name for variable_name, *_ in rows} + recorded = [ + entry + for entry in self.__dict__.get(KEPT_BASELINE_INPUTS_ATTR, ()) + if entry[0] not in carried + ] + self.__dict__[KEPT_BASELINE_INPUTS_ATTR] = kept + recorded + def apply_reform(self, reform): policy = self.tax_benefit_system detaching = getattr(policy, "detaching_parameters", None) @@ -1015,6 +1147,11 @@ def clone(self, debug=False, trace=False, clone_tax_benefit_system=True): # other inputs reused them, and what it measured reached this # simulation. A clone measures its own (``get_branch`` seeds a branch). cloned.__dict__.pop(BEHAVIORAL_RESPONSE_CACHE_ATTR, None) + # It shared the kept inputs the same way, so an input set on either + # would reach the other's baseline arm. Each keeps its own list. + kept = self.__dict__.get(KEPT_BASELINE_INPUTS_ATTR) + if kept is not None: + cloned.__dict__[KEPT_BASELINE_INPUTS_ATTR] = list(kept) return cloned def _invalidate_all_caches(self): @@ -1099,7 +1236,26 @@ def _simulation_family(self): yield from branch._simulation_family() def subsample(self, *args, **kwargs): - result = super().subsample(*args, **kwargs) + # Core rebuilds this simulation from the inputs its holders record, and + # an ETERNITY holder records no year: a yearly input the reform stores + # for all time comes back as one input for all time, which baseline + # policy cannot hold. So carry the kept inputs over to the sample as + # given, in place of what the rebuild keeps for their variables. + kept = self._kept_inputs_on_person_rows() + person_ids = tuple(self.persons.ids) if kept else () + dataset = self.dataset + previous = self.__dict__.pop(KEPT_BASELINE_INPUTS_ATTR, None) + try: + result = super().subsample(*args, **kwargs) + except BaseException: + # Core checks its arguments and draws the sample before it sets + # the sample's dataset and rebuilds. A failure before then leaves + # this simulation as it was, so it keeps what it kept. + if previous is not None and self.dataset is dataset: + self.__dict__[KEPT_BASELINE_INPUTS_ATTR] = previous + raise + if kept: + self._keep_inputs_for_sampled_rows(kept, person_ids) baseline = self.branches.get("baseline") if baseline is not None: # Core rebuilds the baseline arm by branching this simulation, so @@ -1117,6 +1273,7 @@ def subsample(self, *args, **kwargs): baseline.baseline = None baseline._drop_holders_built_for_another_policy() baseline._rebind_holders() + baseline._set_inputs_kept_for_baseline_policy(self) baseline._isolate_parameter_tracing() # Core hands the rebuilt baseline arm the previous arm's policy and so # its provider, which recorded the counties the previous arm read. @@ -1138,6 +1295,7 @@ def set_input(self, variable_name, period, value): "Use primitive inputs and retain observed outputs under report-only names." ) result = super().set_input(variable_name, period, value) + self._keep_input_for_baseline_policy(variable_name, period, value) # Core snapshots input_variables during construction, but later # explicit inputs must also survive counterfactual branches. Keep # only stored inputs; neutralized and expired writes are ignored. diff --git a/policyengine_us/system.py b/policyengine_us/system.py index 1f4a94f14b2..e61f87bb0c4 100644 --- a/policyengine_us/system.py +++ b/policyengine_us/system.py @@ -269,7 +269,9 @@ def _rebuild_baseline_branch(simulation): ``subsample`` does, gives the baseline the same inputs as the reform, except those the reform stored for its own definition of a variable in another entity or with other ``ETERNITY`` storage, which core's branch - dropped too. + dropped too. Of those, the baseline then sets again each input the + reform received that the baseline's definition can hold, such as a yearly + subsidy the reform stores for all time. """ baseline = simulation.branches.pop("baseline", None) if baseline is None: @@ -286,9 +288,12 @@ def _rebuild_baseline_branch(simulation): # use, restore the other bindings and remove inputs that exist only in # the reform. A kept holder would hand the baseline the reform's input: # under a reform that stores ``child_care_subsidies`` for all time, the - # baseline read that input in place of its own formula. + # baseline read that input in place of its own formula. A dropped holder + # takes its inputs with it, so the baseline sets again each one it can + # hold: dropping a yearly 2026 subsidy left the baseline calculating one. rebuilt._drop_holders_built_for_another_policy() rebuilt._rebind_holders() + rebuilt._set_inputs_kept_for_baseline_policy(simulation) rebuilt._isolate_parameter_tracing() simulation.baseline = rebuilt diff --git a/policyengine_us/tests/core/test_reform_baseline_arm_inputs.py b/policyengine_us/tests/core/test_reform_baseline_arm_inputs.py index 1406a05ea0e..344df4cba76 100644 --- a/policyengine_us/tests/core/test_reform_baseline_arm_inputs.py +++ b/policyengine_us/tests/core/test_reform_baseline_arm_inputs.py @@ -12,18 +12,25 @@ ``system._rebuild_baseline_branch`` now branches the arm again after the moves. Like core's branch, it drops each holder the reform built in another entity or with other ``ETERNITY`` storage than the baseline's variable has. -A kept holder hands the arm the reform's input in place of its formula. +A kept holder hands the arm the reform's input in place of its formula. A +dropped holder takes its inputs with it, so the arm then sets again each input +the reform received for a variable it stores apart from baseline policy, +wherever the baseline's definition can hold that input. Without that step, a +yearly subsidy the reform stores for all time left the arm calculating one. Invariants: under a reform that changes nothing, the reform and its baseline arm compute what a simulation with no reform computes, for every household, whether a situation or a dataset of raw columns supplies the inputs. Under any -reform, each holder in either arm suits that arm's definition of its variable. +reform, each holder in either arm suits that arm's definition of its variable, +and the arm reads each dataset input that baseline policy can hold as a +simulation with no reform reads it, before and after subsampling. """ from itertools import product import numpy as np import pandas as pd +import pytest from policyengine_core.data import Dataset from policyengine_core.periods import ETERNITY from policyengine_core.reforms import Reform @@ -31,6 +38,10 @@ from policyengine_us import Microsimulation, Simulation from policyengine_us.entities import SPMUnit +from policyengine_us.variables.gov.simulation.behavioral_response_measurements import ( + BASELINE_BEHAVIORAL_RESPONSE_MEASUREMENT_BRANCH, + _baseline_measurement_branch, +) YEAR = 2026 TOLERANCE = 0.01 @@ -83,7 +94,16 @@ def apply(self): self.update_variable(child_care_subsidies) -def dataset(states=STATE_FIPS, families=FAMILIES, eternal_subsidy=None): +def dataset( + states=STATE_FIPS, + families=FAMILIES, + eternal_subsidy=None, + yearly_subsidies=None, + weights=None, +): + """A flat file with one household per state and family. ``yearly_subsidies`` + maps a year to each household's child care subsidy, and ``weights`` gives + each household's weight.""" columns = {} def add(name, parent, child): @@ -109,9 +129,12 @@ def add(name, parent, child): add(f"childcare_attending_days_per_month__{YEAR}", 0, 21) add(f"spm_unit_pre_subsidy_childcare_expenses__{YEAR}", expenses, expenses) add(f"state_fips__{YEAR}", fips, fips) - add(f"household_weight__{YEAR}", 1, 1) + weight = 1 if weights is None else weights[unit] + add(f"household_weight__{YEAR}", weight, weight) if eternal_subsidy is not None: add("child_care_subsidies__eternity", eternal_subsidy, eternal_subsidy) + for year, subsidies in (yearly_subsidies or {}).items(): + add(f"child_care_subsidies__{year}", subsidies[unit], subsidies[unit]) return Dataset.from_dataframe(pd.DataFrame(columns), time_period=YEAR) @@ -157,10 +180,13 @@ def situation(): } +def value(simulation, variable, year=YEAR): + return np.asarray(simulation.calculate(variable, year), dtype=float) + + def values(simulation): return { - variable: np.asarray(simulation.calculate(variable, YEAR), dtype=float) - for variable in PRE_RESPONSE + OUTPUTS + variable: value(simulation, variable) for variable in PRE_RESPONSE + OUTPUTS } @@ -230,11 +256,12 @@ def test_situation_arms_match_a_simulation_with_no_reform(): def test_the_arm_calculates_what_the_reform_stores_for_all_time(): - """New York's first family enters with a $500 subsidy that the reform - stores for all time. The baseline's yearly ``child_care_subsidies`` cannot - use that storage, so the arm drops the input and pays what a simulation - with no reform pays. Keeping it gave the arm $500 as S0 where baseline - policy pays $13,916.40, and left the reform's expense $13,416.40 low.""" + """New York's first family enters with a $500 subsidy for all time, which + the reform stores for all time. The baseline's yearly + ``child_care_subsidies`` can hold no input for all time, so the arm drops + the input and pays what a simulation with no reform pays. Keeping it gave + the arm $500 as S0 where baseline policy pays $13,916.40, and left the + reform's expense $13,416.40 low.""" plain = Microsimulation(dataset=dataset((NEW_YORK,), FAMILIES[:1])) reformed = Microsimulation( dataset=dataset((NEW_YORK,), FAMILIES[:1], eternal_subsidy=500), @@ -244,9 +271,6 @@ def test_the_arm_calculates_what_the_reform_stores_for_all_time(): for simulation in (reformed, arm): assert_holders_suit_their_variables(simulation) - def value(simulation, variable): - return np.asarray(simulation.calculate(variable, YEAR), dtype=float) - baseline_subsidy = value(plain, "child_care_subsidies") assert baseline_subsidy[0] > 500 np.testing.assert_allclose( @@ -268,3 +292,85 @@ def value(simulation, variable): value(reformed, "spm_unit_head_spouse_earned_cap"), ) np.testing.assert_allclose(value(reformed, expense), expected, atol=TOLERANCE) + + +def test_the_arm_sets_again_the_yearly_subsidies_the_reform_stores_for_all_time(): + """Both runs read the same dataset, which gives New York's first family a + $400 child care subsidy in 2025 and $500 in 2026. The reform stores + ``child_care_subsidies`` for all time, so it keeps one of them, and the + arm drops that holder. The arm then sets both yearly inputs again and + reads each year's as a simulation with no reform does. Before, it + calculated the 2026 subsidy, and S0 rose to $13,916.40 though the subsidy + paid had not changed.""" + subsidies = {2025: [400], YEAR: [500]} + plain = Microsimulation( + dataset=dataset((NEW_YORK,), FAMILIES[:1], yearly_subsidies=subsidies) + ) + reformed = Microsimulation( + dataset=dataset((NEW_YORK,), FAMILIES[:1], yearly_subsidies=subsidies), + reform=StoreSubsidiesForAllTime, + ) + arm = reformed.baseline + for simulation in (reformed, arm): + assert_holders_suit_their_variables(simulation) + for year, subsidy in subsidies.items(): + for simulation in (plain, arm): + np.testing.assert_allclose( + value(simulation, "child_care_subsidies", year), subsidy + ) + # The reform's holder keeps the input it received last, for all time. + np.testing.assert_allclose(value(reformed, "child_care_subsidies", year), 500) + # S1 equals S0, so the reform reports the expense baseline policy reports. + expense = "spm_unit_capped_work_childcare_expenses" + for simulation in (reformed, arm): + np.testing.assert_allclose( + value(simulation, expense), value(plain, expense), atol=TOLERANCE + ) + + +def test_the_baseline_measurement_sets_again_the_yearly_subsidies(): + """The behavioural-response measurement branches the reform under baseline + policy and drops the same holder, so it too sets each yearly input + again.""" + subsidies = {2025: [400], YEAR: [500]} + reformed = Microsimulation( + dataset=dataset((NEW_YORK,), FAMILIES[:1], yearly_subsidies=subsidies), + reform=StoreSubsidiesForAllTime, + ) + try: + branch = _baseline_measurement_branch(reformed) + assert_holders_suit_their_variables(branch) + for year, subsidy in subsidies.items(): + np.testing.assert_allclose( + value(branch, "child_care_subsidies", year), subsidy + ) + finally: + reformed.branches.pop(BASELINE_BEHAVIORAL_RESPONSE_MEASUREMENT_BRANCH, None) + + +def test_subsampling_keeps_each_yearly_subsidy_for_the_arm(): + """Core subsamples by rebuilding the simulation from what its holders + record, and the reform's holder for all time records neither year. The + sample keeps only the second household, whose inputs the arm then reads + for each year, as before subsampling. A subsample that fails before core + rebuilds anything leaves the simulation's inputs, and those it kept, in + place.""" + subsidies = {2025: [400, 600], YEAR: [500, 700]} + reformed = Microsimulation( + dataset=dataset( + (NEW_YORK,), FAMILIES, yearly_subsidies=subsidies, weights=(0, 1) + ), + reform=StoreSubsidiesForAllTime, + ) + with pytest.raises(ValueError, match="Either n or frac"): + reformed.subsample() + reformed.subsample(n=1) + arm = reformed.baseline + assert reformed.calculate("household_id", YEAR).values.tolist() == [1] + for simulation in (reformed, arm): + assert_holders_suit_their_variables(simulation) + for year, subsidy in subsidies.items(): + np.testing.assert_allclose( + value(arm, "child_care_subsidies", year), subsidy[1:] + ) + np.testing.assert_allclose(value(reformed, "child_care_subsidies", year), 700) diff --git a/policyengine_us/tests/test_child_care_subsidies_household_benefits.py b/policyengine_us/tests/test_child_care_subsidies_household_benefits.py index e2742f0a3e6..77d7fab991d 100644 --- a/policyengine_us/tests/test_child_care_subsidies_household_benefits.py +++ b/policyengine_us/tests/test_child_care_subsidies_household_benefits.py @@ -56,9 +56,16 @@ def test_latest_blocks_list_every_state_program(): ) } assert len(defined) == 51 - for start, programs in blocks(PROGRAMS).items(): - if start >= "2025": - assert set(programs) == defined, start + # Every block from 2024 on lists all 51 programs. With no such block the + # loop would check nothing and pass. + latest = { + start: programs + for start, programs in blocks(PROGRAMS).items() + if start >= "2024" + } + assert latest + for start, programs in latest.items(): + assert set(programs) == defined, start def net_income_and_benefits(state, year, program, amount): diff --git a/policyengine_us/tests/test_spm_child_care_subsidy_invariants.py b/policyengine_us/tests/test_spm_child_care_subsidy_invariants.py index 478cbb0a855..05188f32603 100644 --- a/policyengine_us/tests/test_spm_child_care_subsidy_invariants.py +++ b/policyengine_us/tests/test_spm_child_care_subsidy_invariants.py @@ -68,11 +68,13 @@ without a child in the unit, and W and C come from the policy simulated. A policy that pays the same subsidy and leaves W and C alone leaves the expense where baseline policy put it. -9. Differential. Give a dataset the amount the household rule says a unit pays - at baseline policy. Then the two rules give the same expense under any - policy. With the same input and real programs, repealing a subsidy moves - SPM net income by the same amount under both rules, unless the earnings cap - binds under either. +9. Differential. Where the subsidy baseline policy pays does not exceed the + price, give a dataset the amount the household rule says a unit pays at + baseline policy. Then the two rules give the same expense under any + policy. A larger subsidy leaves the unit paying nothing, which hides the + price from the dataset rule. With the same input and real programs, + repealing a subsidy moves SPM net income by the same amount under both + rules, unless the earnings cap binds under either. """ from functools import cache diff --git a/policyengine_us/variables/gov/simulation/behavioral_response_measurements.py b/policyengine_us/variables/gov/simulation/behavioral_response_measurements.py index 328d88cf0a3..99b7e4f5d80 100644 --- a/policyengine_us/variables/gov/simulation/behavioral_response_measurements.py +++ b/policyengine_us/variables/gov/simulation/behavioral_response_measurements.py @@ -95,8 +95,10 @@ def _baseline_measurement_branch(simulation): branch.baseline = None # The copied holders were built for reform policy; its entities or # ETERNITY storage may differ from the baseline's, as after subsampling. + # Dropping one drops its inputs, so set again those baseline policy holds. branch._drop_holders_built_for_another_policy() branch._rebind_holders() + branch._set_inputs_kept_for_baseline_policy(simulation) drop_inherited_values(branch) branch._isolate_parameter_tracing() # The policy copy's receipts list the counties the baseline read; record From 7da8e231899c429f4ea803e17cd3b029359da538 Mon Sep 17 00:00:00 2001 From: Max Ghenis Date: Tue, 24 Nov 2026 01:09:41 +0100 Subject: [PATCH 13/42] Replay to the baseline arm only the inputs the reform still holds The record of inputs a reform stores apart from baseline policy now keeps what core stored, drops inputs core deleted or replaced, and reaches a subsample through core's own export, so core samples and reweights them. The behavioural-response measurement branch no longer sets them, as on main, which fixes main's test_baseline_measurement_drops_incompatible_holders. Co-Authored-By: Claude Opus 5.5 --- changelog.d/spm-child-care-subsidies.fixed.md | 2 +- policyengine_us/spm.py | 277 +++++++++++------- policyengine_us/system.py | 4 +- .../core/test_reform_baseline_arm_inputs.py | 272 ++++++++++++++--- .../behavioral_response_measurements.py | 2 - 5 files changed, 409 insertions(+), 148 deletions(-) diff --git a/changelog.d/spm-child-care-subsidies.fixed.md b/changelog.d/spm-child-care-subsidies.fixed.md index 36eea7c754b..07e8d4ddd4a 100644 --- a/changelog.d/spm-child-care-subsidies.fixed.md +++ b/changelog.d/spm-child-care-subsidies.fixed.md @@ -1 +1 @@ -Count every state child care subsidy in the Supplemental Poverty Measure from 2024 by netting it from the SPM child care expense in household calculations, keep the ASEC's reported spending as that expense over a dataset while a reform moves it by the change in subsidy, and add the District of Columbia, Tennessee and Texas subsidies to the 2024 program list. Rebuild a reform's baseline arm without the holders the reform built for its own definition of a variable in another entity or with other ETERNITY storage, as core's own branch does, then set again each input a dataset or set_input gave the reform for such a variable, wherever the baseline's definition can hold it. +Count every state child care subsidy in the Supplemental Poverty Measure from 2024 by netting it from the SPM child care expense in household calculations, keep the ASEC's reported spending as that expense over a dataset while a reform moves it by the change in subsidy, and add the District of Columbia, Tennessee and Texas subsidies to the 2024 program list. Rebuild a reform's baseline arm without the holders the reform built for its own definition of a variable in another entity or with other ETERNITY storage, as core's own branch does, then set again each input the reform still holds for such a variable, wherever the baseline's definition can hold it, before and after subsampling. diff --git a/policyengine_us/spm.py b/policyengine_us/spm.py index 83024d05ec4..c371e0f812d 100644 --- a/policyengine_us/spm.py +++ b/policyengine_us/spm.py @@ -13,6 +13,7 @@ from inspect import ismethod, signature import numpy as np +import pandas as pd from policyengine_core import periods as periods_ from policyengine_core.errors import PeriodMismatchError from policyengine_core.parameters import Parameter, ParameterScale @@ -92,11 +93,14 @@ # branch and invalidation paths below handle them explicitly. BEHAVIORAL_RESPONSE_CACHE_ATTR = "_behavioral_response_measurements" -# Where a reform simulation keeps, as given, each input whose variable baseline -# policy stores apart from it, for its baseline arm to set again +# Where a reform simulation keeps, as core stored it, each input whose variable +# baseline policy stores apart from it, for its baseline arm to set again # (``SPMSimulationMixin._keep_input_for_baseline_policy``). Each simulation and # branch has its own list. KEPT_BASELINE_INPUTS_ATTR = "_inputs_kept_for_baseline_policy" +# The kept inputs a subsample exports, from the start of ``subsample`` until it +# rebuilds the simulation. +SAMPLED_BASELINE_INPUTS_ATTR = "_inputs_kept_for_baseline_policy_to_sample" COUNTY_INPUT_FIX = ( 'send county_fips as a five-digit string (for example "06037"), or select ' @@ -875,8 +879,10 @@ def _drop_holders_built_for_another_policy(self): ``ETERNITY`` variable, therefore cannot hold the baseline's definition. Drop it with its recorded inputs, as core 3.32.21 and later do in ``_bind_to_tax_benefit_system``; core 3.32.8 keeps it. - ``_set_inputs_kept_for_baseline_policy`` then sets again each input - the source gave that the baseline's definition can hold. + A baseline arm then sets again each input the source still holds that + the baseline's definition can hold + (``_set_inputs_kept_for_baseline_policy``); the behavioural-response + measurement branch sets none, and calculates such a variable. Only a baseline arm does this. ``apply_reform`` keeps a simulation's own inputs, as core's does. @@ -901,19 +907,43 @@ def _drop_holders_built_for_another_policy(self): name for name in self.input_variables if name not in dropped ] - def _keep_input_for_baseline_policy(self, variable_name, period, value): + def _baseline_policy_stores_apart(self, variable_name): + """Whether baseline policy stores ``variable_name`` apart from this + simulation, which has a baseline arm. + + Only a simulation built with ``reform=`` has a baseline arm. Its arm + drops each holder this simulation built with storage for (or not for) + ``ETERNITY`` that the baseline's variable lacks, and the holder's + inputs go with it. + """ + if getattr(self, "reform", None) is None: + return False + baseline_policy = getattr(self, "default_tax_benefit_system_instance", None) + return baseline_policy is not None and _stored_apart( + self.tax_benefit_system.variables.get(variable_name), + baseline_policy.variables.get(variable_name), + ) + + def _input_key(self, holder, period): + """The key core records an input under: the period its holder stores + the input for, which is ``ETERNITY`` for an ``ETERNITY`` holder.""" + if holder._memory_storage.is_eternal: + period = periods_.ETERNITY + return (holder.variable.name, self.branch_name, periods_.period(period)) + + def _keep_input_for_baseline_policy(self, variable_name, period, held): """Keep an input whose variable baseline policy stores apart from this one. - A reform's baseline arm drops each holder the reform built with storage - for (or not for) ``ETERNITY`` that the baseline's variable lacks, and - the holder's inputs go with it. An ``ETERNITY`` holder keeps no - period, so it cannot give back a yearly input: under a reform that - stores ``child_care_subsidies`` for all time, the arm calculated the - 2026 subsidy a dataset supplied, and S0 moved by thousands of dollars - with no change in the subsidy paid. So keep each such input as given, - for the arm to set under baseline policy. A holder in another entity - holds values the baseline's entity cannot take, so this keeps none of - those. + An ``ETERNITY`` holder keeps no period, so it cannot give back a yearly + input: under a reform that stores ``child_care_subsidies`` for all + time, the arm calculated the 2026 subsidy a dataset supplied, and S0 + moved by thousands of dollars with no change in the subsidy paid. So + keep, with the period it was set for, the value core stored, as core + stored it: a numeric expression evaluated, an enum encoded. ``held`` + says whether the holder held an input under the same key before this + one. If it held none, what was kept for that key was deleted, so it + goes. An input for all time is not kept, since a yearly definition + cannot hold it, and neither is one core did not store. Core's builder sets a situation's inputs on their holders directly, not through ``set_input``, so this keeps none of them, and the arm @@ -921,93 +951,135 @@ def _keep_input_for_baseline_policy(self, variable_name, period, value): for the SPM expense reads no baseline subsidy, so what the arm pays never reaches a situation's SPM expense. """ - if getattr(self, "reform", None) is None: - # Only a simulation built with ``reform=`` has a baseline arm. - return - baseline_policy = getattr(self, "default_tax_benefit_system_instance", None) - if baseline_policy is None or not _stored_apart( - self.tax_benefit_system.variables.get(variable_name), - baseline_policy.variables.get(variable_name), + holder = self.get_holder(variable_name) + key = self._input_key(holder, period) + kept = self.__dict__.get(KEPT_BASELINE_INPUTS_ATTR, []) + if not held: + kept = [ + entry + for entry in kept + if entry[0] != variable_name or self._input_key(holder, entry[1]) != key + ] + if periods_.period(period).unit != periods_.ETERNITY and key in getattr( + self, "_user_input_keys", () ): - return - count = self.get_variable_population(variable_name).count - # A copy, broadcast as a population takes a scalar input, so a later - # write to the caller's array cannot change what the arm sets. - kept = np.array(np.broadcast_to(value, count, subok=True), subok=True) - self.__dict__.setdefault(KEPT_BASELINE_INPUTS_ATTR, []).append( - (variable_name, period, kept) - ) + stored = self._get_recorded_input_array(variable_name, key[2]) + if stored is not None: + kept = [*kept, (variable_name, periods_.period(period), stored.copy())] + self.__dict__[KEPT_BASELINE_INPUTS_ATTR] = kept + + def _kept_inputs_still_held(self): + """The kept inputs this simulation still holds, oldest first. + + An input stays while baseline policy stores its variable apart from + this simulation and core records the input's key. Of the inputs kept + for one period, the latest stays. The last input kept under a key must + be the value the holder stores there now: one that differs came by a + path this record does not see, such as a write to the holder itself, + so the inputs kept under that key go. A subsample rebuilds what this + keeps (``build_from_dataset``). + """ + input_keys = getattr(self, "_user_input_keys", set()) + latest = {} + for variable_name, period, value in self.__dict__.get( + KEPT_BASELINE_INPUTS_ATTR, () + ): + if not self._baseline_policy_stores_apart(variable_name): + continue + population = self.get_variable_population(variable_name) + holder = population._holders.get(variable_name) + if holder is None: + continue + key = self._input_key(holder, period) + if key not in input_keys: + continue + # Order by the last time each period was set. + latest.pop((variable_name, period), None) + latest[(variable_name, period)] = (key, value) + last_under_key = {} + for (variable_name, period), (key, value) in latest.items(): + last_under_key[key] = value + current = { + key: np.array_equal( + np.asarray(value), + np.asarray(self._get_recorded_input_array(key[0], key[2])), + ) + for key, value in last_under_key.items() + } + return [ + (variable_name, period, key, value) + for (variable_name, period), (key, value) in latest.items() + if current[key] + ] def _set_inputs_kept_for_baseline_policy(self, source): """Set the inputs ``source`` kept for this simulation's policy. - ``source`` is the simulation this baseline arm, or baseline measurement - branch, was branched from. Each input it kept belongs to a variable it - stores apart from this policy, so this simulation dropped the holder. - Setting each input again, in the order ``source`` received them, gives - this simulation what a simulation with no reform loads from the same - inputs. This policy cannot hold an ``ETERNITY`` input for a yearly - variable, so that input stays out and this simulation calculates the - variable. + ``source`` is the simulation this baseline arm was branched from. Each + input it still holds belongs to a variable it stores apart from this + policy, so this simulation dropped the holder. Setting each input + again, in the order ``source`` last set each period, gives this + simulation what a simulation with no reform loads from the same inputs. """ variables = self.tax_benefit_system.variables - source_variables = source.tax_benefit_system.variables - for variable_name, period, value in source.__dict__.get( - KEPT_BASELINE_INPUTS_ATTR, () - ): - if not _stored_apart( - source_variables.get(variable_name), variables.get(variable_name) - ): + for ( + variable_name, + period, + _, + value, + ) in source._kept_inputs_still_held(): + if variable_name not in variables: continue try: self.set_input(variable_name, period, value.copy()) except PeriodMismatchError: + # An ETERNITY definition takes a yearly input for all time; a + # yearly one takes none for all time, and none is kept. continue - def _kept_inputs_on_person_rows(self): - """Each kept input with its values on person rows. - - Core's subsampling exports a group's value on each member's row, so - this does the same. - """ + def build_from_dataset(self): + # Loading replaces every input, so what was kept for the old ones goes + # with them; the loader's own ``set_input`` calls keep the new ones. A + # subsample has exported its inputs by now. + self.__dict__.pop(KEPT_BASELINE_INPUTS_ATTR, None) + self.__dict__.pop(SAMPLED_BASELINE_INPUTS_ATTR, None) + return super().build_from_dataset() + + def _to_person_dataframe(self, get_periods, include_computed_variables=False): + frame = super()._to_person_dataframe(get_periods, include_computed_variables) + sampled = self.__dict__.get(SAMPLED_BASELINE_INPUTS_ATTR) + if not sampled: + return frame + # Core's export holds an ETERNITY holder's input as one column for all + # time. Put each kept input before its variable's own columns, in the + # order the inputs were set, so the rebuild sets them in that order, + # keeps them for the new arm, and ends with the input the holder + # stores now. person_key = self.persons.entity.key - rows = [] - for variable_name, period, value in self.__dict__.get( - KEPT_BASELINE_INPUTS_ATTR, () - ): + kept = {} + for variable_name, period, _, value in sampled: entity_key = self.tax_benefit_system.variables[variable_name].entity.key - if entity_key != person_key: - value = self.populations[entity_key].project(value) - rows.append((variable_name, period, entity_key, value)) - return rows - - def _keep_inputs_for_sampled_rows(self, rows, person_ids): - """Keep the inputs on ``rows`` for the people a subsample retained. - - Core retains people by their IDs, as ``_select_subsample_sources`` in - ``tools/social_security_inputs.py`` reads them, and its flat-file - loader gives a group its first member's value, so this does the same. - These replace what the rebuild kept for the same variables and join - what it kept for any other. - """ - positions = {person_id: index for index, person_id in enumerate(person_ids)} - retained = np.array( - [positions[person_id] for person_id in self.persons.ids], dtype=int - ) - person_key = self.persons.entity.key - kept = [] - for variable_name, period, entity_key, values in rows: - values = values[retained] - if entity_key != person_key: - values = self.populations[entity_key].value_from_first_person(values) - kept.append((variable_name, period, values)) - carried = {variable_name for variable_name, *_ in rows} - recorded = [ - entry - for entry in self.__dict__.get(KEPT_BASELINE_INPUTS_ATTR, ()) - if entry[0] not in carried - ] - self.__dict__[KEPT_BASELINE_INPUTS_ATTR] = kept + recorded + kept.setdefault(variable_name, {})[f"{variable_name}__{period}"] = ( + self.map_result(value, entity_key, person_key) + ) + columns = {} + for column in frame.columns: + columns.update(kept.pop(column.split("__")[0], {})) + if column not in columns: + columns[column] = frame[column].values + for added in kept.values(): + columns.update(added) + return pd.DataFrame(columns, index=frame.index) + + def _get_recorded_input_array(self, variable_name, period): + # Core reweights each weight column of a subsample by its recorded + # total, so it reads a kept input's total here. + for name, kept_period, _, value in self.__dict__.get( + SAMPLED_BASELINE_INPUTS_ATTR, () + ): + if name == variable_name and kept_period == period: + return value + return super()._get_recorded_input_array(variable_name, period) def apply_reform(self, reform): policy = self.tax_benefit_system @@ -1152,6 +1224,8 @@ def clone(self, debug=False, trace=False, clone_tax_benefit_system=True): kept = self.__dict__.get(KEPT_BASELINE_INPUTS_ATTR) if kept is not None: cloned.__dict__[KEPT_BASELINE_INPUTS_ATTR] = list(kept) + # What a subsample exports belongs to the simulation it rebuilds. + cloned.__dict__.pop(SAMPLED_BASELINE_INPUTS_ATTR, None) return cloned def _invalidate_all_caches(self): @@ -1239,23 +1313,14 @@ def subsample(self, *args, **kwargs): # Core rebuilds this simulation from the inputs its holders record, and # an ETERNITY holder records no year: a yearly input the reform stores # for all time comes back as one input for all time, which baseline - # policy cannot hold. So carry the kept inputs over to the sample as - # given, in place of what the rebuild keeps for their variables. - kept = self._kept_inputs_on_person_rows() - person_ids = tuple(self.persons.ids) if kept else () - dataset = self.dataset - previous = self.__dict__.pop(KEPT_BASELINE_INPUTS_ATTR, None) + # policy cannot hold. So hand core's export each kept input as a + # column of its own (``_to_person_dataframe``). Core then samples and + # reweights those columns with the rest, and the rebuild keeps them. + self.__dict__[SAMPLED_BASELINE_INPUTS_ATTR] = self._kept_inputs_still_held() try: result = super().subsample(*args, **kwargs) - except BaseException: - # Core checks its arguments and draws the sample before it sets - # the sample's dataset and rebuilds. A failure before then leaves - # this simulation as it was, so it keeps what it kept. - if previous is not None and self.dataset is dataset: - self.__dict__[KEPT_BASELINE_INPUTS_ATTR] = previous - raise - if kept: - self._keep_inputs_for_sampled_rows(kept, person_ids) + finally: + self.__dict__.pop(SAMPLED_BASELINE_INPUTS_ATTR, None) baseline = self.branches.get("baseline") if baseline is not None: # Core rebuilds the baseline arm by branching this simulation, so @@ -1294,8 +1359,14 @@ def set_input(self, variable_name, period, value): f"Dataset supplies formula-owned SPM output {variable_name}. " "Use primitive inputs and retain observed outputs under report-only names." ) + keep = self._baseline_policy_stores_apart(variable_name) + if keep: + held = self._input_key(self.get_holder(variable_name), period) in getattr( + self, "_user_input_keys", () + ) result = super().set_input(variable_name, period, value) - self._keep_input_for_baseline_policy(variable_name, period, value) + if keep: + self._keep_input_for_baseline_policy(variable_name, period, held) # Core snapshots input_variables during construction, but later # explicit inputs must also survive counterfactual branches. Keep # only stored inputs; neutralized and expired writes are ignored. diff --git a/policyengine_us/system.py b/policyengine_us/system.py index 333a204efa0..825ed6ff66d 100644 --- a/policyengine_us/system.py +++ b/policyengine_us/system.py @@ -278,8 +278,8 @@ def _rebuild_baseline_branch(simulation): except those the reform stored for its own definition of a variable in another entity or with other ``ETERNITY`` storage, which core's branch dropped too. Of those, the baseline then sets again each input the - reform received that the baseline's definition can hold, such as a yearly - subsidy the reform stores for all time. + reform still holds that the baseline's definition can hold, such as a + yearly subsidy the reform stores for all time. """ baseline = simulation.branches.pop("baseline", None) if baseline is None: diff --git a/policyengine_us/tests/core/test_reform_baseline_arm_inputs.py b/policyengine_us/tests/core/test_reform_baseline_arm_inputs.py index 344df4cba76..48e38501516 100644 --- a/policyengine_us/tests/core/test_reform_baseline_arm_inputs.py +++ b/policyengine_us/tests/core/test_reform_baseline_arm_inputs.py @@ -14,16 +14,18 @@ entity or with other ``ETERNITY`` storage than the baseline's variable has. A kept holder hands the arm the reform's input in place of its formula. A dropped holder takes its inputs with it, so the arm then sets again each input -the reform received for a variable it stores apart from baseline policy, +the reform still holds for a variable it stores apart from baseline policy, wherever the baseline's definition can hold that input. Without that step, a yearly subsidy the reform stores for all time left the arm calculating one. Invariants: under a reform that changes nothing, the reform and its baseline arm compute what a simulation with no reform computes, for every household, whether a situation or a dataset of raw columns supplies the inputs. Under any -reform, each holder in either arm suits that arm's definition of its variable, -and the arm reads each dataset input that baseline policy can hold as a -simulation with no reform reads it, before and after subsampling. +reform, each holder in either arm suits that arm's definition of its variable. +Under a reform that stores a variable for all time, the arm reads each yearly +input of it as a simulation with no reform given the same inputs, deletions +and subsample reads it, and subsampling leaves the reform's own value as it +was. """ from itertools import product @@ -37,10 +39,9 @@ from policyengine_core.variables import Variable from policyengine_us import Microsimulation, Simulation -from policyengine_us.entities import SPMUnit -from policyengine_us.variables.gov.simulation.behavioral_response_measurements import ( - BASELINE_BEHAVIORAL_RESPONSE_MEASUREMENT_BRANCH, - _baseline_measurement_branch, +from policyengine_us.entities import Household, Person, SPMUnit +from policyengine_us.variables.gov.hhs.ccdf.child_care_subsidies import ( + child_care_subsidies as yearly_child_care_subsidies, ) YEAR = 2026 @@ -328,49 +329,240 @@ def test_the_arm_sets_again_the_yearly_subsidies_the_reform_stores_for_all_time( ) -def test_the_baseline_measurement_sets_again_the_yearly_subsidies(): - """The behavioural-response measurement branches the reform under baseline - policy and drops the same holder, so it too sets each yearly input - again.""" - subsidies = {2025: [400], YEAR: [500]} - reformed = Microsimulation( - dataset=dataset((NEW_YORK,), FAMILIES[:1], yearly_subsidies=subsidies), - reform=StoreSubsidiesForAllTime, - ) - try: - branch = _baseline_measurement_branch(reformed) - assert_holders_suit_their_variables(branch) - for year, subsidy in subsidies.items(): - np.testing.assert_allclose( - value(branch, "child_care_subsidies", year), subsidy - ) - finally: - reformed.branches.pop(BASELINE_BEHAVIORAL_RESPONSE_MEASUREMENT_BRANCH, None) +SUBSIDY = "child_care_subsidies" +TWO_YEARS = {2025: [400, 600], YEAR: [500, 700]} + + +def delete_then_set(simulation): + simulation.delete_arrays(SUBSIDY) + simulation.set_input(SUBSIDY, YEAR, [800, 900]) -def test_subsampling_keeps_each_yearly_subsidy_for_the_arm(): +def delete_on_the_holder_then_set(simulation): + # PolicyEngine's input moves delete on the holder, not the simulation. + simulation.get_holder(SUBSIDY).delete_arrays() + simulation.set_input(SUBSIDY, YEAR, [800, 900]) + + +def set_the_first_year_again(simulation): + simulation.set_input(SUBSIDY, 2025, [450, 650]) + + +@pytest.mark.parametrize( + "change", + [ + None, + delete_then_set, + delete_on_the_holder_then_set, + set_the_first_year_again, + ], +) +def test_subsampling_gives_the_arm_each_yearly_subsidy_the_reform_holds(change): """Core subsamples by rebuilding the simulation from what its holders - record, and the reform's holder for all time records neither year. The - sample keeps only the second household, whose inputs the arm then reads - for each year, as before subsampling. A subsample that fails before core - rebuilds anything leaves the simulation's inputs, and those it kept, in - place.""" - subsidies = {2025: [400, 600], YEAR: [500, 700]} + record, and the reform's holder for all time records neither year. Both + runs read the same dataset and receive the same inputs and deletions, and + the sample keeps only the second household. The arm then reads each + year's subsidy as the simulation with no reform does, and the reform keeps + the subsidy it held. Before, a deleted input came back. A subsample that + fails before core rebuilds anything keeps the inputs in place.""" + simulations = [ + Microsimulation( + dataset=dataset( + (NEW_YORK,), FAMILIES, yearly_subsidies=TWO_YEARS, weights=(0, 1) + ), + reform=reform, + ) + for reform in (None, StoreSubsidiesForAllTime) + ] + plain, reformed = simulations + for simulation in simulations: + if change is not None: + change(simulation) + held = value(reformed, SUBSIDY)[1] + with pytest.raises(ValueError, match="Either n or frac"): + reformed.subsample() + for simulation in simulations: + simulation.subsample(n=1) + arm = reformed.baseline + for simulation in (reformed, arm): + assert_holders_suit_their_variables(simulation) + assert simulation.calculate("household_id", YEAR).values.tolist() == [1] + for year in TWO_YEARS: + np.testing.assert_allclose( + value(arm, SUBSIDY, year), value(plain, SUBSIDY, year), atol=TOLERANCE + ) + np.testing.assert_allclose(value(reformed, SUBSIDY, year), [held]) + expense = "spm_unit_capped_work_childcare_expenses" + np.testing.assert_allclose( + value(arm, expense), value(plain, expense), atol=TOLERANCE + ) + + +def test_the_arm_sets_a_numeric_expression_as_core_stored_it(): + """Core evaluates a numeric expression it is given for a numeric variable + and stores the result, $600. The arm sets that 2026 subsidy after a + subsample, beside the dataset's $400 for 2025. Before, the arm received + the expression as an array of text, and setting it raised a + ValueError.""" + subsidies = {2025: [400], YEAR: [500]} + simulations = [ + Microsimulation( + dataset=dataset((NEW_YORK,), FAMILIES[:1], yearly_subsidies=subsidies), + reform=reform, + ) + for reform in (None, StoreSubsidiesForAllTime) + ] + for simulation in simulations: + simulation.set_input(SUBSIDY, YEAR, "400 + 200") + simulation.subsample(n=1) + plain, reformed = simulations + arm = reformed.baseline + for year, subsidy in ((2025, 400), (YEAR, 600)): + np.testing.assert_allclose(value(plain, SUBSIDY, year), [subsidy]) + np.testing.assert_allclose(value(arm, SUBSIDY, year), [subsidy]) + np.testing.assert_allclose(value(reformed, SUBSIDY, year), [600]) + + +class RestoreYearlySubsidies(Reform): + def apply(self): + self.update_variable(yearly_child_care_subsidies) + + +def test_a_reform_that_restores_the_yearly_subsidy_leaves_none_to_set_again(): + """Applying a reform that restores baseline policy's yearly subsidy drops + the holder that stored it for all time, with its input, so the reform + calculates the subsidy. A later subsample then gives the arm no input the + reform no longer holds, and the two read the same subsidy each year.""" reformed = Microsimulation( dataset=dataset( - (NEW_YORK,), FAMILIES, yearly_subsidies=subsidies, weights=(0, 1) + (NEW_YORK,), FAMILIES, yearly_subsidies=TWO_YEARS, weights=(0, 1) ), reform=StoreSubsidiesForAllTime, ) - with pytest.raises(ValueError, match="Either n or frac"): - reformed.subsample() + reformed.apply_reform(RestoreYearlySubsidies) reformed.subsample(n=1) arm = reformed.baseline - assert reformed.calculate("household_id", YEAR).values.tolist() == [1] for simulation in (reformed, arm): assert_holders_suit_their_variables(simulation) - for year, subsidy in subsidies.items(): + for year in TWO_YEARS: + np.testing.assert_allclose( + value(arm, SUBSIDY, year), value(reformed, SUBSIDY, year), atol=TOLERANCE + ) + expense = "spm_unit_capped_work_childcare_expenses" + np.testing.assert_allclose( + value(reformed, expense), value(arm, expense), atol=TOLERANCE + ) + + +class household_weight(Variable): + # Stored for all time, where baseline policy stores a weight each year. + value_type = float + entity = Household + label = "Household weight" + definition_period = ETERNITY + + +class StoreWeightsForAllTime(Reform): + def apply(self): + self.update_variable(household_weight) + + +def test_subsampling_reweights_a_weight_the_reform_stores_for_all_time(): + """Two households weigh 1 each, and a sample of one keeps their total of + 2. The arm reads the sampled household's yearly weight as the simulation + with no reform does. Before, the arm set the weight the dataset gave, 1.""" + simulations = [ + Microsimulation(dataset=dataset((NEW_YORK,), FAMILIES), reform=reform) + for reform in (None, StoreWeightsForAllTime) + ] + for simulation in simulations: + simulation.subsample(n=1, seed=0) + plain, reformed = simulations + arm = reformed.baseline + for simulation in (reformed, arm): + assert_holders_suit_their_variables(simulation) + for simulation in (reformed, arm): + assert ( + simulation.calculate("household_id", YEAR).values.tolist() + == plain.calculate("household_id", YEAR).values.tolist() + ) + weight = np.asarray(plain.calculate("household_weight", YEAR, use_weights=False)) + np.testing.assert_allclose(weight, [2]) + for simulation in (reformed, arm): + np.testing.assert_allclose( + simulation.calculate("household_weight", YEAR, use_weights=False), weight + ) + + +def test_the_arm_sets_none_of_the_inputs_a_write_to_the_holder_replaced(): + """A write to the reform's holder itself, as core's situation builder + makes, replaces the subsidy kept for all time without telling the record. + The arm then sets none of the kept yearly inputs and calculates both + years, as a simulation with no subsidy input does, rather than the + replaced $600 and $700.""" + simulations = [ + Microsimulation( + dataset=dataset( + (NEW_YORK,), FAMILIES, yearly_subsidies=TWO_YEARS, weights=(0, 1) + ), + reform=reform, + ) + for reform in (None, StoreSubsidiesForAllTime) + ] + plain, reformed = simulations + plain.delete_arrays(SUBSIDY) + reformed.get_holder(SUBSIDY).set_input(YEAR, np.array([800.0, 900.0])) + for simulation in simulations: + simulation.subsample(n=1) + arm = reformed.baseline + for year in TWO_YEARS: + calculated = value(plain, SUBSIDY, year) + assert calculated[0] not in TWO_YEARS[year] np.testing.assert_allclose( - value(arm, "child_care_subsidies", year), subsidy[1:] + value(arm, SUBSIDY, year), calculated, atol=TOLERANCE ) - np.testing.assert_allclose(value(reformed, "child_care_subsidies", year), 700) + np.testing.assert_allclose(value(reformed, SUBSIDY, year), [900]) + + +class is_household_head(Variable): + # Stored each year, where baseline policy stores it for all time. + value_type = bool + entity = Person + label = "is head of this household" + definition_period = "year" + + +class StoreHeadsEachYear(Reform): + def apply(self): + self.update_variable(is_household_head) + + +def test_subsampling_keeps_the_order_of_inputs_baseline_policy_stores_for_all_time(): + """The dataset names each household's parent its head in 2026, and both + runs then name each child head in 2025. Baseline policy stores the role + for all time, so the input set last wins. The reform stores it each year, + and core exports its years in order, 2025 first; the arm sets them in the + order the reform received them, so it reads the child as head, as the + simulation with no reform does.""" + simulations = [ + Microsimulation( + dataset=dataset((NEW_YORK,), FAMILIES, weights=(0, 1)), reform=reform + ) + for reform in (None, StoreHeadsEachYear) + ] + for simulation in simulations: + simulation.set_input("is_household_head", 2025, [False, True, False, True]) + for simulation in simulations: + simulation.subsample(n=1) + plain, reformed = simulations + arm = reformed.baseline + for simulation in (reformed, arm): + assert_holders_suit_their_variables(simulation) + heads = plain.calculate("is_household_head", YEAR, use_weights=False) + assert np.asarray(heads).tolist() == [False, True] + assert np.asarray( + arm.calculate("is_household_head", YEAR, use_weights=False) + ).tolist() == [False, True] + assert np.asarray( + reformed.calculate("is_household_head", YEAR, use_weights=False) + ).tolist() == [True, False] diff --git a/policyengine_us/variables/gov/simulation/behavioral_response_measurements.py b/policyengine_us/variables/gov/simulation/behavioral_response_measurements.py index 99b7e4f5d80..328d88cf0a3 100644 --- a/policyengine_us/variables/gov/simulation/behavioral_response_measurements.py +++ b/policyengine_us/variables/gov/simulation/behavioral_response_measurements.py @@ -95,10 +95,8 @@ def _baseline_measurement_branch(simulation): branch.baseline = None # The copied holders were built for reform policy; its entities or # ETERNITY storage may differ from the baseline's, as after subsampling. - # Dropping one drops its inputs, so set again those baseline policy holds. branch._drop_holders_built_for_another_policy() branch._rebind_holders() - branch._set_inputs_kept_for_baseline_policy(simulation) drop_inherited_values(branch) branch._isolate_parameter_tracing() # The policy copy's receipts list the counties the baseline read; record From 279f65467846d76af523725ee932a620ec7f04e7 Mon Sep 17 00:00:00 2001 From: Max Ghenis Date: Tue, 24 Nov 2026 01:43:58 +0100 Subject: [PATCH 14/42] Update the New York and Colorado integration cases for main's changes Main's New York CCAP changes (#10817, #10827) count the Family Assistance grant a family takes up and waive the family share for it. TANF reads employment_income_before_lsr, which a household simulation fills from employment_income but the YAML runner leaves at zero, so the New York cases now give pre-response earnings, as a household run stores them. Colorado's single parent fee (#10721) sets that family's fee at $1,518. The microsimulation test imports the fixture under its Microcosm name (#10687). Co-Authored-By: Claude Opus 5.5 --- .../test_spm_child_care_reported_expense.py | 2 +- .../spm_child_care_subsidies_integration.yaml | 14 +++++++++----- 2 files changed, 10 insertions(+), 6 deletions(-) diff --git a/policyengine_us/tests/microsimulation/test_spm_child_care_reported_expense.py b/policyengine_us/tests/microsimulation/test_spm_child_care_reported_expense.py index 328c171fc6b..26bbe863841 100644 --- a/policyengine_us/tests/microsimulation/test_spm_child_care_reported_expense.py +++ b/policyengine_us/tests/microsimulation/test_spm_child_care_reported_expense.py @@ -11,7 +11,7 @@ import numpy as np -from policyengine_us.tests.microsimulation.populace_fixture import ( +from policyengine_us.tests.microsimulation.microcosm_fixture import ( default_population_sample, ) diff --git a/policyengine_us/tests/policy/baseline/household/expense/childcare/spm_child_care_subsidies_integration.yaml b/policyengine_us/tests/policy/baseline/household/expense/childcare/spm_child_care_subsidies_integration.yaml index 0a569868a10..c3ec98f18ec 100644 --- a/policyengine_us/tests/policy/baseline/household/expense/childcare/spm_child_care_subsidies_integration.yaml +++ b/policyengine_us/tests/policy/baseline/household/expense/childcare/spm_child_care_subsidies_integration.yaml @@ -7,6 +7,10 @@ # earn $30,000 and the 2024 cases earn $24,000. # Without weeks_worked, work expenses are zero, so the SPM expense is the # out-of-pocket amount. +# The New York cases give earnings before labor supply responses, as a +# household simulation stores them. TANF reads that variable, so a bare +# employment_income input leaves New York's Family Assistance seeing no +# earnings, and the grant it then pays waives the CCAP family share. - name: New York, Manhattan family with a subsidy just below the expense period: 2026 @@ -15,7 +19,7 @@ people: parent: age: 30 - employment_income: 30_000 + employment_income_before_lsr: 30_000 weekly_hours_worked_before_lsr: 40 is_tax_unit_head: true is_household_head: true @@ -51,7 +55,7 @@ people: parent: age: 30 - employment_income: 30_000 + employment_income_before_lsr: 30_000 weekly_hours_worked_before_lsr: 40 is_tax_unit_head: true is_household_head: true @@ -253,9 +257,9 @@ members: [parent, child] state_code: CO output: - child_care_subsidies: 12_613.16 - # 14,000 - 12,613.16. - spm_unit_capped_work_childcare_expenses: 1_386.84 + child_care_subsidies: 12_482 + # 14,000 - 12,482. + spm_unit_capped_work_childcare_expenses: 1_518 - name: District of Columbia, a program the 2024 list left out period: 2024 From 5b05e30fa0ab47d1d8199bb28abddcda5c114663 Mon Sep 17 00:00:00 2001 From: Max Ghenis Date: Tue, 24 Nov 2026 01:57:09 +0100 Subject: [PATCH 15/42] Say what apply_reform drops under current core Core's apply_reform binds holders through _bind_to_tax_benefit_system, which drops a holder the new definition cannot use, with its recorded inputs. The docstring said apply_reform keeps a simulation's own inputs. Co-Authored-By: Claude Opus 5.5 --- policyengine_us/spm.py | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/policyengine_us/spm.py b/policyengine_us/spm.py index c371e0f812d..69b89df872d 100644 --- a/policyengine_us/spm.py +++ b/policyengine_us/spm.py @@ -884,8 +884,9 @@ def _drop_holders_built_for_another_policy(self): (``_set_inputs_kept_for_baseline_policy``); the behavioural-response measurement branch sets none, and calculates such a variable. - Only a baseline arm does this. ``apply_reform`` keeps a simulation's - own inputs, as core's does. + Only a baseline arm calls this. Under ``apply_reform``, core's own + ``_bind_to_tax_benefit_system`` drops a holder the new definition + cannot use, with its recorded inputs, and keeps every other input. """ variables = self.tax_benefit_system.variables dropped = set() From 3ba8fc7182a52860aeba65c12275a4a5e5c565a8 Mon Sep 17 00:00:00 2001 From: Max Ghenis Date: Tue, 24 Nov 2026 03:21:32 +0100 Subject: [PATCH 16/42] Keep only stored inputs for the arm, and calculate what it can't place The in-session review of 5b05e30fa0 found three ways the baseline arm's record of stored-apart inputs went wrong, each reached only by a constructed harness: - An input core skipped, for a neutralized variable or a period after the variable's end, was kept with the value the holder stored for all time. set_input now keeps an input only when core's count of stored inputs rises. - A write the record didn't see, such as one on the holder itself, came back into play once a later input passed the current-value check. Before keeping an input, the record now checks that its last input under the key is what the holder stores there, and starts the key's record again if not. - Under a yearly reform of a variable baseline policy stores for all time, a holder write under another year was exported after the kept columns, so a subsample's arm ended with it. A variable whose holder holds an input the record doesn't account for is now calculated in the arm, and a subsample drops it from the record it rebuilds. _input_key now uses core's storage period. Four arm tests pin these and the removal of a failed subsample's export. Every case in the integration YAML now gives pre-response earnings, since TANF reads them and the YAML runner leaves them at zero; the asserted outputs don't change. Docstrings now say which callers drop holders, that a flat situation's inputs go through set_input, and why clone copies the list. Co-Authored-By: Claude Opus 5.5 --- policyengine_us/spm.py | 177 +++++++++++++----- .../core/test_reform_baseline_arm_inputs.py | 150 ++++++++++++++- .../spm_child_care_subsidies_integration.yaml | 26 +-- 3 files changed, 292 insertions(+), 61 deletions(-) diff --git a/policyengine_us/spm.py b/policyengine_us/spm.py index 69b89df872d..252bdfc3ae2 100644 --- a/policyengine_us/spm.py +++ b/policyengine_us/spm.py @@ -884,9 +884,10 @@ def _drop_holders_built_for_another_policy(self): (``_set_inputs_kept_for_baseline_policy``); the behavioural-response measurement branch sets none, and calculates such a variable. - Only a baseline arm calls this. Under ``apply_reform``, core's own - ``_bind_to_tax_benefit_system`` drops a holder the new definition - cannot use, with its recorded inputs, and keeps every other input. + A simulation given a reform by ``apply_reform`` does not call this: + core's own ``_bind_to_tax_benefit_system`` drops a holder the new + definition cannot use, with its recorded inputs, and keeps every + other input. """ variables = self.tax_benefit_system.variables dropped = set() @@ -927,12 +928,40 @@ def _baseline_policy_stores_apart(self, variable_name): def _input_key(self, holder, period): """The key core records an input under: the period its holder stores - the input for, which is ``ETERNITY`` for an ``ETERNITY`` holder.""" - if holder._memory_storage.is_eternal: - period = periods_.ETERNITY - return (holder.variable.name, self.branch_name, periods_.period(period)) + the input for, which is ``ETERNITY`` for an ``ETERNITY`` holder and + the year for twelve months from the first of a month.""" + return ( + holder.variable.name, + self.branch_name, + holder._storage_period(periods_.period(period)), + ) + + def _kept_record_is_whole(self, variable_name, period): + """Whether what this simulation kept under the key an input for + ``period`` goes to still accounts for what the holder stores there. - def _keep_input_for_baseline_policy(self, variable_name, period, held): + It does when core records an input under the key and the last input + kept under it is the value the holder stores there now. If core + records none, what was kept for the key was deleted. If none was kept, + or the last differs, a write this record does not see stored the + value, such as one made on the holder itself. + """ + holder = self.get_holder(variable_name) + key = self._input_key(holder, period) + if key not in getattr(self, "_user_input_keys", ()): + return False + last = None + for name, kept_period, value in self.__dict__.get( + KEPT_BASELINE_INPUTS_ATTR, () + ): + if name == variable_name and self._input_key(holder, kept_period) == key: + last = value + return last is not None and np.array_equal( + np.asarray(last), + np.asarray(self._get_recorded_input_array(variable_name, key[2])), + ) + + def _keep_input_for_baseline_policy(self, variable_name, period, whole, stored): """Keep an input whose variable baseline policy stores apart from this one. An ``ETERNITY`` holder keeps no period, so it cannot give back a yearly @@ -940,22 +969,30 @@ def _keep_input_for_baseline_policy(self, variable_name, period, held): time, the arm calculated the 2026 subsidy a dataset supplied, and S0 moved by thousands of dollars with no change in the subsidy paid. So keep, with the period it was set for, the value core stored, as core - stored it: a numeric expression evaluated, an enum encoded. ``held`` - says whether the holder held an input under the same key before this - one. If it held none, what was kept for that key was deleted, so it - goes. An input for all time is not kept, since a yearly definition - cannot hold it, and neither is one core did not store. - - Core's builder sets a situation's inputs on their holders directly, - not through ``set_input``, so this keeps none of them, and the arm - calculates such a variable as core's own arm does. The household rule - for the SPM expense reads no baseline subsidy, so what the arm pays - never reaches a situation's SPM expense. + stored it: a numeric expression evaluated, an enum encoded. + + ``stored`` says whether core stored the input. One it did not, for a + neutralized variable or a period after the variable's end, changes + nothing here. ``whole`` says whether, just before this input, the + record accounted for what the holder stored under its key + (``_kept_record_is_whole``). If not, what was kept for that key was + deleted or replaced by a write the record missed, so it goes, and the + key's record starts again with this input. An input for all time is + not kept, since a yearly definition cannot hold it. + + Core's builder sets an entity situation's inputs on their holders + directly, not through ``set_input``, so this keeps none of them, and + the arm calculates such a variable (``_kept_record``). A situation + that gives variables alone goes through ``set_input``, so its inputs + are kept. The household rule for the SPM expense reads no baseline + subsidy, so what the arm pays never reaches a situation's SPM expense. """ + if not stored: + return holder = self.get_holder(variable_name) key = self._input_key(holder, period) kept = self.__dict__.get(KEPT_BASELINE_INPUTS_ATTR, []) - if not held: + if not whole: kept = [ entry for entry in kept @@ -964,28 +1001,56 @@ def _keep_input_for_baseline_policy(self, variable_name, period, held): if periods_.period(period).unit != periods_.ETERNITY and key in getattr( self, "_user_input_keys", () ): - stored = self._get_recorded_input_array(variable_name, key[2]) - if stored is not None: - kept = [*kept, (variable_name, periods_.period(period), stored.copy())] + recorded = self._get_recorded_input_array(variable_name, key[2]) + if recorded is not None: + kept = [ + *kept, + (variable_name, periods_.period(period), recorded.copy()), + ] self.__dict__[KEPT_BASELINE_INPUTS_ATTR] = kept def _kept_inputs_still_held(self): - """The kept inputs this simulation still holds, oldest first. + """The kept inputs this simulation still holds, in the order last set.""" + return self._kept_record()[0] + + def _kept_record(self): + """The kept inputs this simulation still holds, and the variables + whose inputs the record missed. An input stays while baseline policy stores its variable apart from this simulation and core records the input's key. Of the inputs kept - for one period, the latest stays. The last input kept under a key must - be the value the holder stores there now: one that differs came by a - path this record does not see, such as a write to the holder itself, - so the inputs kept under that key go. A subsample rebuilds what this - keeps (``build_from_dataset``). + for one period, the latest stays, ordered by the last time each period + was set. + + A variable's inputs all go when core holds an input for it, on this + simulation's branch, that the record does not account for: a key core + records with no input kept under it, or one whose last kept input is + not the value the holder stores there now. That input came by a path + ``set_input`` does not see, such as a write to the holder itself or an + entity situation. The arm could not tell where it falls among the + variable's other inputs, so it calculates the variable. Under a reform + that stores the variable for all time, an input set later restarts + the key's record (``_kept_record_is_whole``), and the arm then sets + the inputs given since. ``subsample`` drops a missed variable's inputs + from the rebuilt record, so a subsample keeps calculating it. """ - input_keys = getattr(self, "_user_input_keys", set()) + apart = {} + + def stores_apart(variable_name): + if variable_name not in apart: + apart[variable_name] = self._baseline_policy_stores_apart(variable_name) + return apart[variable_name] + + input_keys = { + key + for key in getattr(self, "_user_input_keys", ()) + if key[1] == self.branch_name + } latest = {} for variable_name, period, value in self.__dict__.get( KEPT_BASELINE_INPUTS_ATTR, () ): - if not self._baseline_policy_stores_apart(variable_name): + if not stores_apart(variable_name): continue population = self.get_variable_population(variable_name) holder = population._holders.get(variable_name) @@ -994,24 +1059,30 @@ def _kept_inputs_still_held(self): key = self._input_key(holder, period) if key not in input_keys: continue - # Order by the last time each period was set. latest.pop((variable_name, period), None) latest[(variable_name, period)] = (key, value) last_under_key = {} - for (variable_name, period), (key, value) in latest.items(): + for key, value in latest.values(): last_under_key[key] = value - current = { - key: np.array_equal( + missed = { + key[0] + for key, value in last_under_key.items() + if not np.array_equal( np.asarray(value), np.asarray(self._get_recorded_input_array(key[0], key[2])), ) - for key, value in last_under_key.items() } - return [ + missed.update( + key[0] + for key in input_keys + if key not in last_under_key and stores_apart(key[0]) + ) + held = [ (variable_name, period, key, value) for (variable_name, period), (key, value) in latest.items() - if current[key] + if variable_name not in missed ] + return held, missed def _set_inputs_kept_for_baseline_policy(self, source): """Set the inputs ``source`` kept for this simulation's policy. @@ -1220,8 +1291,10 @@ def clone(self, debug=False, trace=False, clone_tax_benefit_system=True): # other inputs reused them, and what it measured reached this # simulation. A clone measures its own (``get_branch`` seeds a branch). cloned.__dict__.pop(BEHAVIORAL_RESPONSE_CACHE_ATTR, None) - # It shared the kept inputs the same way, so an input set on either - # would reach the other's baseline arm. Each keeps its own list. + # The clone starts with this simulation's kept inputs, as it starts + # with its inputs. Each list is replaced rather than changed in place, + # so an input set on one never reaches the other's; the copy keeps it + # so if that changes. kept = self.__dict__.get(KEPT_BASELINE_INPUTS_ATTR) if kept is not None: cloned.__dict__[KEPT_BASELINE_INPUTS_ATTR] = list(kept) @@ -1317,11 +1390,22 @@ def subsample(self, *args, **kwargs): # policy cannot hold. So hand core's export each kept input as a # column of its own (``_to_person_dataframe``). Core then samples and # reweights those columns with the rest, and the rebuild keeps them. - self.__dict__[SAMPLED_BASELINE_INPUTS_ATTR] = self._kept_inputs_still_held() + # A variable whose inputs the record missed stays out of the export's + # kept columns, so core exports it as it holds it, and the rebuild + # keeps those inputs as if given in that order. Drop them, so the new + # arm calculates that variable as the old one did (``_kept_record``). + held, missed = self._kept_record() + self.__dict__[SAMPLED_BASELINE_INPUTS_ATTR] = held try: result = super().subsample(*args, **kwargs) finally: self.__dict__.pop(SAMPLED_BASELINE_INPUTS_ATTR, None) + if missed: + self.__dict__[KEPT_BASELINE_INPUTS_ATTR] = [ + entry + for entry in self.__dict__.get(KEPT_BASELINE_INPUTS_ATTR, ()) + if entry[0] not in missed + ] baseline = self.branches.get("baseline") if baseline is not None: # Core rebuilds the baseline arm by branching this simulation, so @@ -1362,12 +1446,15 @@ def set_input(self, variable_name, period, value): ) keep = self._baseline_policy_stores_apart(variable_name) if keep: - held = self._input_key(self.get_holder(variable_name), period) in getattr( - self, "_user_input_keys", () - ) + whole = self._kept_record_is_whole(variable_name, period) + # Core counts each input its holders store, and skips one for a + # neutralized variable or a period after the variable's end. + inputs_set = self._inputs_set result = super().set_input(variable_name, period, value) if keep: - self._keep_input_for_baseline_policy(variable_name, period, held) + self._keep_input_for_baseline_policy( + variable_name, period, whole, stored=self._inputs_set != inputs_set + ) # Core snapshots input_variables during construction, but later # explicit inputs must also survive counterfactual branches. Keep # only stored inputs; neutralized and expired writes are ignored. diff --git a/policyengine_us/tests/core/test_reform_baseline_arm_inputs.py b/policyengine_us/tests/core/test_reform_baseline_arm_inputs.py index 48e38501516..29d6f16223c 100644 --- a/policyengine_us/tests/core/test_reform_baseline_arm_inputs.py +++ b/policyengine_us/tests/core/test_reform_baseline_arm_inputs.py @@ -22,10 +22,14 @@ arm compute what a simulation with no reform computes, for every household, whether a situation or a dataset of raw columns supplies the inputs. Under any reform, each holder in either arm suits that arm's definition of its variable. -Under a reform that stores a variable for all time, the arm reads each yearly -input of it as a simulation with no reform given the same inputs, deletions -and subsample reads it, and subsampling leaves the reform's own value as it -was. +Under a reform that stores a variable apart from baseline policy, the arm reads +each input of it that the reform still holds as a simulation with no reform +given the same inputs, deletions and subsample reads it, and subsampling +leaves the reform's own value as it was. A deletion on a holder for all time +deletes every year's input, so the reform then holds none. Where the reform's +holder took an input its ``set_input`` never saw, such as a write to the +holder itself, the arm calculates what it can't place: under a reform for all +time, each year given no input since; under a yearly reform, the variable. """ from itertools import product @@ -566,3 +570,141 @@ def test_subsampling_keeps_the_order_of_inputs_baseline_policy_stores_for_all_ti assert np.asarray( reformed.calculate("is_household_head", YEAR, use_weights=False) ).tolist() == [True, False] + + +def test_after_a_write_to_the_holder_the_arm_sets_only_the_inputs_given_since(): + """A write to the reform's holder itself stores $900 for all time where the + record kept the dataset's $700, and both runs then set $650 for 2025. The + record can't tell which year the write was for, so it starts again from + the 2025 input: the arm sets it and calculates 2026, as a simulation with + no reform does once its 2026 input is gone. Before, the record took the + 2025 input as following the kept ones, and the arm set the replaced $700 + for 2026.""" + simulations = [ + Microsimulation( + dataset=dataset( + (NEW_YORK,), FAMILIES, yearly_subsidies=TWO_YEARS, weights=(0, 1) + ), + reform=reform, + ) + for reform in (None, StoreSubsidiesForAllTime) + ] + for simulation in simulations: + simulation.get_holder(SUBSIDY).set_input(YEAR, np.array([800.0, 900.0])) + simulation.set_input(SUBSIDY, 2025, [450, 650]) + simulation.subsample(n=1) + plain, reformed = simulations + arm = reformed.baseline + for simulation in (plain, arm): + np.testing.assert_allclose(value(simulation, SUBSIDY, 2025), [650]) + np.testing.assert_allclose(value(plain, SUBSIDY, YEAR), [900]) + np.testing.assert_allclose(value(reformed, SUBSIDY, YEAR), [650]) + plain.delete_arrays(SUBSIDY, YEAR) + calculated = value(plain, SUBSIDY, YEAR) + assert calculated[0] not in (700, 900) + np.testing.assert_allclose(value(arm, SUBSIDY, YEAR), calculated, atol=TOLERANCE) + + +# Stored for all time, and defined only through 2025. Core names a variable +# after its class. +subsidies_for_all_time_until_2025 = type( + "child_care_subsidies", + (Variable,), + dict( + value_type=float, + entity=SPMUnit, + label="Child care subsidies", + definition_period=ETERNITY, + end="2025-12-31", + ), +) + + +class StoreSubsidiesForAllTimeUntil2025(Reform): + def apply(self): + self.update_variable(subsidies_for_all_time_until_2025) + + +def test_the_arm_sets_no_input_the_reform_did_not_store(): + """The reform's subsidy ends with 2025, so core stores the dataset's 2026 + subsidy nowhere. The arm sets the $400 for 2025 and calculates 2026, as a + simulation with no reform does without a 2026 input. Before, the record + kept what the holder stored, the 2025 subsidy, for 2026 as well, and the + arm set $400 there.""" + subsidies = {2025: [400], YEAR: [500]} + plain, reformed = [ + Microsimulation( + dataset=dataset((NEW_YORK,), FAMILIES[:1], yearly_subsidies=subsidies), + reform=reform, + ) + for reform in (None, StoreSubsidiesForAllTimeUntil2025) + ] + arm = reformed.baseline + np.testing.assert_allclose(value(arm, SUBSIDY, 2025), [400]) + plain.delete_arrays(SUBSIDY, YEAR) + calculated = value(plain, SUBSIDY, YEAR) + assert calculated[0] not in (400, 500) + np.testing.assert_allclose(value(arm, SUBSIDY, YEAR), calculated, atol=TOLERANCE) + + +HEAD = "is_household_head" + + +def heads(simulation, year=YEAR): + return np.asarray(simulation.calculate(HEAD, year, use_weights=False)).tolist() + + +def test_the_arm_calculates_a_role_written_to_the_reform_holder(): + """Under the yearly reform, a write to the holder itself names the child + head in 2027, and both runs then name the parent head in 2025. The record + never saw the 2027 input, and baseline policy keeps only the role set + last, so the arm can't tell which input it would end with. It calculates + the role, through two subsamples, as a simulation with no reform does + with no role input. Before, the first subsample exported the 2027 input + after the kept ones, and the arm named the child head.""" + simulations = [ + Microsimulation(dataset=dataset((NEW_YORK,), FAMILIES[:1]), reform=reform) + for reform in (None, StoreHeadsEachYear) + ] + for simulation in simulations: + simulation.get_holder(HEAD).set_input(2027, np.array([False, True])) + simulation.set_input(HEAD, 2025, [True, False]) + plain, reformed = simulations + for _ in range(2): + for simulation in simulations: + simulation.subsample(n=1) + arm = reformed.baseline + assert_holders_suit_their_variables(arm) + assert heads(plain) == [True, False] + assert heads(arm) == [False, False] + assert heads(reformed, 2025) == [True, False] + assert heads(reformed, 2027) == [False, True] + plain.delete_arrays(HEAD) + assert heads(plain) == heads(arm) + + +def test_a_failed_subsample_leaves_no_export_behind(): + """Under the yearly reform, both runs name each child head in 2025, a + subsample fails before core rebuilds anything, and both then name each + parent head in 2025. A sample then reads the parent as head in the arm + and in 2025's reform, as in the simulation with no reform. Had the failed + subsample left its export in place, the reform would have kept the + child's 2025 role from it.""" + simulations = [ + Microsimulation( + dataset=dataset((NEW_YORK,), FAMILIES, weights=(0, 1)), reform=reform + ) + for reform in (None, StoreHeadsEachYear) + ] + for simulation in simulations: + simulation.set_input(HEAD, 2025, [False, True, False, True]) + plain, reformed = simulations + with pytest.raises(ValueError, match="Either n or frac"): + reformed.subsample() + for simulation in simulations: + simulation.set_input(HEAD, 2025, [True, False, True, False]) + simulation.subsample(n=1) + arm = reformed.baseline + assert heads(plain) == [True, False] + assert heads(arm) == [True, False] + assert heads(reformed, 2025) == [True, False] diff --git a/policyengine_us/tests/policy/baseline/household/expense/childcare/spm_child_care_subsidies_integration.yaml b/policyengine_us/tests/policy/baseline/household/expense/childcare/spm_child_care_subsidies_integration.yaml index c3ec98f18ec..63b008130c9 100644 --- a/policyengine_us/tests/policy/baseline/household/expense/childcare/spm_child_care_subsidies_integration.yaml +++ b/policyengine_us/tests/policy/baseline/household/expense/childcare/spm_child_care_subsidies_integration.yaml @@ -7,10 +7,12 @@ # earn $30,000 and the 2024 cases earn $24,000. # Without weeks_worked, work expenses are zero, so the SPM expense is the # out-of-pocket amount. -# The New York cases give earnings before labor supply responses, as a -# household simulation stores them. TANF reads that variable, so a bare -# employment_income input leaves New York's Family Assistance seeing no -# earnings, and the grant it then pays waives the CCAP family share. +# Each case gives earnings before labor supply responses, as a household +# simulation stores them. TANF reads that variable, and the YAML runner leaves +# it at zero when a case gives employment_income. TANF would then see no +# earnings: New York's Family Assistance would pay a grant that waives the CCAP +# family share, and Alaska, Washington, West Virginia and Tennessee would pay +# grants that a household simulation, which sees the earnings, does not. - name: New York, Manhattan family with a subsidy just below the expense period: 2026 @@ -88,7 +90,7 @@ people: parent: age: 30 - employment_income: 30_000 + employment_income_before_lsr: 30_000 weekly_hours_worked_before_lsr: 40 is_tax_unit_head: true is_household_head: true @@ -124,7 +126,7 @@ people: parent: age: 30 - employment_income: 30_000 + employment_income_before_lsr: 30_000 weekly_hours_worked_before_lsr: 40 is_tax_unit_head: true is_household_head: true @@ -160,7 +162,7 @@ people: parent: age: 30 - employment_income: 30_000 + employment_income_before_lsr: 30_000 weekly_hours_worked_before_lsr: 40 is_tax_unit_head: true is_household_head: true @@ -196,7 +198,7 @@ people: parent: age: 30 - employment_income: 30_000 + employment_income_before_lsr: 30_000 weekly_hours_worked_before_lsr: 40 is_tax_unit_head: true is_household_head: true @@ -232,7 +234,7 @@ people: parent: age: 30 - employment_income: 30_000 + employment_income_before_lsr: 30_000 weekly_hours_worked_before_lsr: 40 is_tax_unit_head: true is_household_head: true @@ -268,7 +270,7 @@ people: parent: age: 30 - employment_income: 24_000 + employment_income_before_lsr: 24_000 weekly_hours_worked_before_lsr: 40 is_tax_unit_head: true is_household_head: true @@ -304,7 +306,7 @@ people: parent: age: 30 - employment_income: 24_000 + employment_income_before_lsr: 24_000 weekly_hours_worked_before_lsr: 40 is_tax_unit_head: true is_household_head: true @@ -340,7 +342,7 @@ people: parent: age: 30 - employment_income: 24_000 + employment_income_before_lsr: 24_000 weekly_hours_worked_before_lsr: 40 is_tax_unit_head: true is_household_head: true From a109f69f8b256282283e6010a63d35bd3b8d4b35 Mon Sep 17 00:00:00 2001 From: Max Ghenis Date: Tue, 24 Nov 2026 04:55:18 +0100 Subject: [PATCH 17/42] Keep an input under each key core stored it under The in-session review of 3ba8fc7182 found that the record keyed an input by the period it was set for. A yearly holder can store one input under several years, or under fewer than the period spans: given 24 months from January 2025 while 2026 already held an input, core stored 2025 alone. The record then held no input under 2025 and marked the variable missed, so the arm calculated a role the plain run reads. Core's count of stored inputs also rose for an input whose years the holder's handler skipped. Core stamps every value it stores with a sequence number. set_input now draws the next number before the input and keeps it under each key stamped since, for its year on a yearly holder and with the period set for on a holder for all time. The value checks between calls stay as they were, since core's apply_reform stores preserved inputs again with new stamps. A write the record misses that stores the very array it kept last still goes unnoticed; the docstrings now say so. The role-order test now covers 12 and 24 months from January, and the holder-write test covers an edit to the stored array in place. The review's dispatch harnesses (one month, two years, 12 and 24 months, a month before 2026, and dataset month columns) now give the arm the plain run's role. Co-Authored-By: Claude Opus 5.5 --- policyengine_us/spm.py | 141 ++++++++++-------- .../core/test_reform_baseline_arm_inputs.py | 48 ++++-- 2 files changed, 120 insertions(+), 69 deletions(-) diff --git a/policyengine_us/spm.py b/policyengine_us/spm.py index 252bdfc3ae2..fe2e1bf95a3 100644 --- a/policyengine_us/spm.py +++ b/policyengine_us/spm.py @@ -15,6 +15,7 @@ import numpy as np import pandas as pd from policyengine_core import periods as periods_ +from policyengine_core.data_storage.store_history import next_sequence_number from policyengine_core.errors import PeriodMismatchError from policyengine_core.parameters import Parameter, ParameterScale from policyengine_core.simulations import Simulation as CoreSimulation @@ -936,49 +937,65 @@ def _input_key(self, holder, period): holder._storage_period(periods_.period(period)), ) - def _kept_record_is_whole(self, variable_name, period): - """Whether what this simulation kept under the key an input for - ``period`` goes to still accounts for what the holder stores there. + def _recorded_keys(self, variable_name): + """The keys core records an input of ``variable_name`` under, on this + simulation's branch.""" + return [ + key + for key in getattr(self, "_user_input_keys", ()) + if key[0] == variable_name and key[1] == self.branch_name + ] - It does when core records an input under the key and the last input - kept under it is the value the holder stores there now. If core - records none, what was kept for the key was deleted. If none was kept, - or the last differs, a write this record does not see stored the - value, such as one made on the holder itself. + def _keys_the_record_accounts_for(self, variable_name): + """The keys core records for ``variable_name`` on this branch whose + last kept input is the value the holder stores there now. + + A key core records but this leaves out holds an input the record did + not keep, or a different one: a write this record does not see stored + it, such as one made on the holder itself. A key core no longer + records lost its input, and what was kept under it, to a deletion. """ holder = self.get_holder(variable_name) - key = self._input_key(holder, period) - if key not in getattr(self, "_user_input_keys", ()): - return False - last = None - for name, kept_period, value in self.__dict__.get( - KEPT_BASELINE_INPUTS_ATTR, () - ): - if name == variable_name and self._input_key(holder, kept_period) == key: - last = value - return last is not None and np.array_equal( - np.asarray(last), - np.asarray(self._get_recorded_input_array(variable_name, key[2])), - ) + last = {} + for name, period, value in self.__dict__.get(KEPT_BASELINE_INPUTS_ATTR, ()): + if name == variable_name: + last[self._input_key(holder, period)] = value + return { + key + for key in self._recorded_keys(variable_name) + if key in last + and np.array_equal( + np.asarray(last[key]), + np.asarray(self._get_recorded_input_array(variable_name, key[2])), + ) + } - def _keep_input_for_baseline_policy(self, variable_name, period, whole, stored): + def _keep_input_for_baseline_policy(self, variable_name, period, accounted, since): """Keep an input whose variable baseline policy stores apart from this one. An ``ETERNITY`` holder keeps no period, so it cannot give back a yearly input: under a reform that stores ``child_care_subsidies`` for all time, the arm calculated the 2026 subsidy a dataset supplied, and S0 moved by thousands of dollars with no change in the subsidy paid. So - keep, with the period it was set for, the value core stored, as core - stored it: a numeric expression evaluated, an enum encoded. - - ``stored`` says whether core stored the input. One it did not, for a - neutralized variable or a period after the variable's end, changes - nothing here. ``whole`` says whether, just before this input, the - record accounted for what the holder stored under its key - (``_kept_record_is_whole``). If not, what was kept for that key was - deleted or replaced by a write the record missed, so it goes, and the - key's record starts again with this input. An input for all time is - not kept, since a yearly definition cannot hold it. + keep what core stored, as core stored it: a numeric expression + evaluated, an enum encoded. + + Core stamps each value it stores with a sequence number, and ``since`` + was drawn just before this input, so the keys stamped ``since`` or + later are the ones core stored this input under. There are none for + an input core skipped: a neutralized variable, a period after the + variable's end, or a year that a yearly holder's default handler + leaves as it was because it already holds an input. A yearly holder + can store one input under several years, and each is kept for its + year. An ``ETERNITY`` holder stores it under one key, and it is kept + with the period it was set for. An input for all time is not kept, + since a yearly definition cannot hold it. + + ``accounted`` holds the keys the record accounted for just before this + input (``_keys_the_record_accounts_for``). Under any other key this + input reaches, what was kept was deleted or replaced by a write the + record missed, so it goes, and the key's record starts again with + this input. Core's builder sets an entity situation's inputs on their holders directly, not through ``set_input``, so this keeps none of them, and @@ -987,26 +1004,30 @@ def _keep_input_for_baseline_policy(self, variable_name, period, whole, stored): are kept. The household rule for the SPM expense reads no baseline subsidy, so what the arm pays never reaches a situation's SPM expense. """ + holder = self.get_holder(variable_name) + stored = [] + for key in self._recorded_keys(variable_name): + stamp = holder._stored_sequence_number(key[2], key[1]) + if stamp is not None and stamp >= since: + stored.append((stamp, key)) if not stored: return - holder = self.get_holder(variable_name) - key = self._input_key(holder, period) - kept = self.__dict__.get(KEPT_BASELINE_INPUTS_ATTR, []) - if not whole: - kept = [ - entry - for entry in kept - if entry[0] != variable_name or self._input_key(holder, entry[1]) != key - ] - if periods_.period(period).unit != periods_.ETERNITY and key in getattr( - self, "_user_input_keys", () - ): + stored.sort() + restarted = {key for _, key in stored if key not in accounted} + kept = [ + entry + for entry in self.__dict__.get(KEPT_BASELINE_INPUTS_ATTR, ()) + if entry[0] != variable_name + or self._input_key(holder, entry[1]) not in restarted + ] + eternal = holder._memory_storage.is_eternal + for _, key in stored: + kept_period = periods_.period(period) if eternal else key[2] + if kept_period.unit == periods_.ETERNITY: + continue recorded = self._get_recorded_input_array(variable_name, key[2]) if recorded is not None: - kept = [ - *kept, - (variable_name, periods_.period(period), recorded.copy()), - ] + kept.append((variable_name, kept_period, recorded.copy())) self.__dict__[KEPT_BASELINE_INPUTS_ATTR] = kept def _kept_inputs_still_held(self): @@ -1028,11 +1049,14 @@ def _kept_record(self): not the value the holder stores there now. That input came by a path ``set_input`` does not see, such as a write to the holder itself or an entity situation. The arm could not tell where it falls among the - variable's other inputs, so it calculates the variable. Under a reform - that stores the variable for all time, an input set later restarts - the key's record (``_kept_record_is_whole``), and the arm then sets - the inputs given since. ``subsample`` drops a missed variable's inputs - from the rebuilt record, so a subsample keeps calculating it. + variable's other inputs, so it calculates the variable. An input set + later through ``set_input`` restarts the record of each key it reaches + (``_keep_input_for_baseline_policy``), and under a reform that stores + the variable for all time the arm then sets the inputs given since. A + write that stores the very array the record kept last under its key + goes unnoticed, and the arm then sets what was kept, in the order + kept. ``subsample`` drops a missed variable's inputs from the rebuilt + record, so a subsample keeps calculating it. """ apart = {} @@ -1446,14 +1470,13 @@ def set_input(self, variable_name, period, value): ) keep = self._baseline_policy_stores_apart(variable_name) if keep: - whole = self._kept_record_is_whole(variable_name, period) - # Core counts each input its holders store, and skips one for a - # neutralized variable or a period after the variable's end. - inputs_set = self._inputs_set + accounted = self._keys_the_record_accounts_for(variable_name) + # Each value core stores from here on gets this number or a later one. + since = next_sequence_number() result = super().set_input(variable_name, period, value) if keep: self._keep_input_for_baseline_policy( - variable_name, period, whole, stored=self._inputs_set != inputs_set + variable_name, period, accounted, since ) # Core snapshots input_variables during construction, but later # explicit inputs must also survive counterfactual branches. Keep diff --git a/policyengine_us/tests/core/test_reform_baseline_arm_inputs.py b/policyengine_us/tests/core/test_reform_baseline_arm_inputs.py index 29d6f16223c..38f37eb6ac2 100644 --- a/policyengine_us/tests/core/test_reform_baseline_arm_inputs.py +++ b/policyengine_us/tests/core/test_reform_baseline_arm_inputs.py @@ -30,6 +30,13 @@ holder took an input its ``set_input`` never saw, such as a write to the holder itself, the arm calculates what it can't place: under a reform for all time, each year given no input since; under a yearly reform, the variable. + +Two cases fall outside these invariants, and no test pins them. A write the +record never saw that stores the very array it kept last under that key goes +unnoticed, so the arm sets what was kept, in the order kept. And under a yearly +reform of a variable baseline policy stores for all time, deleting one year's +input leaves the reform its other years, which the arm sets again, while a +simulation with no reform loses every year's input. """ from itertools import product @@ -498,12 +505,27 @@ def test_subsampling_reweights_a_weight_the_reform_stores_for_all_time(): ) -def test_the_arm_sets_none_of_the_inputs_a_write_to_the_holder_replaced(): +def write_on_the_holder(simulation): + simulation.get_holder(SUBSIDY).set_input(YEAR, np.array([800.0, 900.0])) + + +def edit_the_stored_array(simulation): + simulation.get_holder(SUBSIDY).get_array(YEAR)[:] = [800.0, 900.0] + + +@pytest.mark.parametrize( + "write, held", + [ + (write_on_the_holder, 900), + (edit_the_stored_array, 900), + ], +) +def test_the_arm_sets_none_of_the_inputs_a_write_to_the_holder_replaced(write, held): """A write to the reform's holder itself, as core's situation builder - makes, replaces the subsidy kept for all time without telling the record. - The arm then sets none of the kept yearly inputs and calculates both - years, as a simulation with no subsidy input does, rather than the - replaced $600 and $700.""" + makes, or an edit in place to the array it stores, replaces the subsidy + kept for all time without telling the record. The arm then sets none of + the kept yearly inputs and calculates both years, as a simulation with no + subsidy input does, rather than the replaced $600 and $700.""" simulations = [ Microsimulation( dataset=dataset( @@ -515,7 +537,7 @@ def test_the_arm_sets_none_of_the_inputs_a_write_to_the_holder_replaced(): ] plain, reformed = simulations plain.delete_arrays(SUBSIDY) - reformed.get_holder(SUBSIDY).set_input(YEAR, np.array([800.0, 900.0])) + write(reformed) for simulation in simulations: simulation.subsample(n=1) arm = reformed.baseline @@ -525,7 +547,7 @@ def test_the_arm_sets_none_of_the_inputs_a_write_to_the_holder_replaced(): np.testing.assert_allclose( value(arm, SUBSIDY, year), calculated, atol=TOLERANCE ) - np.testing.assert_allclose(value(reformed, SUBSIDY, year), [900]) + np.testing.assert_allclose(value(reformed, SUBSIDY, year), [held]) class is_household_head(Variable): @@ -541,13 +563,19 @@ def apply(self): self.update_variable(is_household_head) -def test_subsampling_keeps_the_order_of_inputs_baseline_policy_stores_for_all_time(): +@pytest.mark.parametrize("period", [2025, "month:2025-01:12", "month:2025-01:24"]) +def test_subsampling_keeps_the_order_of_inputs_baseline_policy_stores_for_all_time( + period, +): """The dataset names each household's parent its head in 2026, and both runs then name each child head in 2025. Baseline policy stores the role for all time, so the input set last wins. The reform stores it each year, and core exports its years in order, 2025 first; the arm sets them in the order the reform received them, so it reads the child as head, as the - simulation with no reform does.""" + simulation with no reform does. Core stores twelve months from January + as the year, and so does the record. Over 24 months, the reform's holder + stores the input for 2025 alone, since 2026 already holds one, and the + record keeps what it stored.""" simulations = [ Microsimulation( dataset=dataset((NEW_YORK,), FAMILIES, weights=(0, 1)), reform=reform @@ -555,7 +583,7 @@ def test_subsampling_keeps_the_order_of_inputs_baseline_policy_stores_for_all_ti for reform in (None, StoreHeadsEachYear) ] for simulation in simulations: - simulation.set_input("is_household_head", 2025, [False, True, False, True]) + simulation.set_input("is_household_head", period, [False, True, False, True]) for simulation in simulations: simulation.subsample(n=1) plain, reformed = simulations From 165fd41b3dda7b24aaff9885afe09af3b61b9b24 Mon Sep 17 00:00:00 2001 From: Max Ghenis Date: Wed, 25 Nov 2026 00:36:28 +0100 Subject: [PATCH 18/42] Match kept weight periods by name, and keep no entity IDs for the arm Core reweights a subsample's weight columns by parsing each period back from its column name. Twelve months from January parse back as the year, and from February as a year from February, so neither equalled the period kept, and a reform storing weights for all time raised TypeError from subsample. Match the period's name instead. Core selects a subsample's households by the first household ID column of its export, and the arm's kept columns come first, so a reform storing an ID apart from baseline policy sampled by the IDs kept for the arm. The arm now sets again no entity ID, membership ID or role; it shares the reform's populations. State as a limit that core's handlers divide or dispatch an input over several periods around the inputs a holder already has, so overlapping inputs can leave the arm reading other values than a plain run. Co-Authored-By: Claude Opus 5.5 --- policyengine_us/spm.py | 36 +++++++- policyengine_us/system.py | 7 +- .../core/test_reform_baseline_arm_inputs.py | 83 +++++++++++++++++-- 3 files changed, 111 insertions(+), 15 deletions(-) diff --git a/policyengine_us/spm.py b/policyengine_us/spm.py index fe2e1bf95a3..03fcd88ed4a 100644 --- a/policyengine_us/spm.py +++ b/policyengine_us/spm.py @@ -790,6 +790,22 @@ def _stored_apart(variable, other): ) +def _structural_variables(policy): + """The variables core reads to build or rebuild populations: each entity's + ID, and each person's membership ID and role in each group entity.""" + person = policy.person_entity.key + names = {f"{person}_id"} + for entity in policy.group_entities: + names.update( + ( + f"{entity.key}_id", + f"{person}_{entity.key}_id", + f"{person}_{entity.key}_role", + ) + ) + return names + + class SPMSimulationMixin: """Keep forecast selection and receipts private to each simulation.""" @@ -918,9 +934,17 @@ def _baseline_policy_stores_apart(self, variable_name): drops each holder this simulation built with storage for (or not for) ``ETERNITY`` that the baseline's variable lacks, and the holder's inputs go with it. + + Entity IDs, membership IDs and roles never count. The arm shares this + simulation's populations, and ``subsample`` selects households and + rebuilds both from this simulation's own columns for them: core reads + the first household ID column it finds, so a kept column for one would + pick the sample. """ if getattr(self, "reform", None) is None: return False + if variable_name in _structural_variables(self.tax_benefit_system): + return False baseline_policy = getattr(self, "default_tax_benefit_system_instance", None) return baseline_policy is not None and _stored_apart( self.tax_benefit_system.variables.get(variable_name), @@ -1115,7 +1139,11 @@ def _set_inputs_kept_for_baseline_policy(self, source): input it still holds belongs to a variable it stores apart from this policy, so this simulation dropped the holder. Setting each input again, in the order ``source`` last set each period, gives this - simulation what a simulation with no reform loads from the same inputs. + simulation what a simulation with no reform loads from those inputs in + that order. Core's handlers divide or dispatch an input over several + periods around the inputs a holder already has, so where such inputs + overlap, or the reform's handler stored one around an earlier input, + that can differ from what it loads from the inputs first given. """ variables = self.tax_benefit_system.variables for ( @@ -1169,11 +1197,13 @@ def _to_person_dataframe(self, get_periods, include_computed_variables=False): def _get_recorded_input_array(self, variable_name, period): # Core reweights each weight column of a subsample by its recorded - # total, so it reads a kept input's total here. + # total, so it reads a kept input's total here. Core parses the period + # back from the column name, and the parsed period need not equal the + # kept one: twelve months from January name the year, so match names. for name, kept_period, _, value in self.__dict__.get( SAMPLED_BASELINE_INPUTS_ATTR, () ): - if name == variable_name and kept_period == period: + if name == variable_name and str(kept_period) == str(period): return value return super()._get_recorded_input_array(variable_name, period) diff --git a/policyengine_us/system.py b/policyengine_us/system.py index 825ed6ff66d..7a528f85358 100644 --- a/policyengine_us/system.py +++ b/policyengine_us/system.py @@ -277,9 +277,10 @@ def _rebuild_baseline_branch(simulation): ``subsample`` does, gives the baseline the same inputs as the reform, except those the reform stored for its own definition of a variable in another entity or with other ``ETERNITY`` storage, which core's branch - dropped too. Of those, the baseline then sets again each input the - reform still holds that the baseline's definition can hold, such as a - yearly subsidy the reform stores for all time. + dropped too. Of those, other than entity IDs, membership IDs and roles, + the baseline then sets again each input the reform still holds that the + baseline's definition can hold, such as a yearly subsidy the reform + stores for all time. """ baseline = simulation.branches.pop("baseline", None) if baseline is None: diff --git a/policyengine_us/tests/core/test_reform_baseline_arm_inputs.py b/policyengine_us/tests/core/test_reform_baseline_arm_inputs.py index 38f37eb6ac2..d25fab17379 100644 --- a/policyengine_us/tests/core/test_reform_baseline_arm_inputs.py +++ b/policyengine_us/tests/core/test_reform_baseline_arm_inputs.py @@ -22,21 +22,28 @@ arm compute what a simulation with no reform computes, for every household, whether a situation or a dataset of raw columns supplies the inputs. Under any reform, each holder in either arm suits that arm's definition of its variable. -Under a reform that stores a variable apart from baseline policy, the arm reads -each input of it that the reform still holds as a simulation with no reform -given the same inputs, deletions and subsample reads it, and subsampling -leaves the reform's own value as it was. A deletion on a holder for all time +Under a reform that stores a variable apart from baseline policy, other than an +entity ID, membership ID or role, the arm sets again the last array the reform +stored for each period it still holds, in the order those periods were last +set, through deletions and subsamples, and reads them as a simulation with no +reform given them in that order reads them. Subsampling leaves the reform's +own value, and the households it samples, as they were. A deletion on a holder for all time deletes every year's input, so the reform then holds none. Where the reform's holder took an input its ``set_input`` never saw, such as a write to the holder itself, the arm calculates what it can't place: under a reform for all time, each year given no input since; under a yearly reform, the variable. -Two cases fall outside these invariants, and no test pins them. A write the +Three cases fall outside these invariants, and no test pins them. A write the record never saw that stores the very array it kept last under that key goes -unnoticed, so the arm sets what was kept, in the order kept. And under a yearly +unnoticed, so the arm sets what was kept, in the order kept. Under a yearly reform of a variable baseline policy stores for all time, deleting one year's input leaves the reform its other years, which the arm sets again, while a -simulation with no reform loses every year's input. +simulation with no reform loses every year's input. And core's handlers divide +or dispatch an input over several periods around the inputs a holder already +has, so the arrays the reform stored, and the last of them for each period, +can tell another story than the inputs first given: where such inputs overlap, +or the reform's handler stored one around an earlier input, the arm can read +other values than a simulation with no reform given those inputs. """ from itertools import product @@ -478,15 +485,24 @@ def apply(self): self.update_variable(household_weight) -def test_subsampling_reweights_a_weight_the_reform_stores_for_all_time(): +@pytest.mark.parametrize("period", [None, "month:2025-01:12", "month:2026-02:12"]) +def test_subsampling_reweights_a_weight_the_reform_stores_for_all_time(period): """Two households weigh 1 each, and a sample of one keeps their total of 2. The arm reads the sampled household's yearly weight as the simulation - with no reform does. Before, the arm set the weight the dataset gave, 1.""" + with no reform does. Before, the arm set the weight the dataset gave, 1. + + A weight given for twelve months reaches the arm as a column named for + its period, which core parses back to reweight it. Twelve months from + January parse back as the year, and from February as a year from + February, so neither equals the period kept; matching on the period + raised ``TypeError`` from the subsample.""" simulations = [ Microsimulation(dataset=dataset((NEW_YORK,), FAMILIES), reform=reform) for reform in (None, StoreWeightsForAllTime) ] for simulation in simulations: + if period is not None: + simulation.set_input("household_weight", period, [1.0, 1.0]) simulation.subsample(n=1, seed=0) plain, reformed = simulations arm = reformed.baseline @@ -505,6 +521,55 @@ def test_subsampling_reweights_a_weight_the_reform_stores_for_all_time(): ) +class household_id(Variable): + # Stored for all time, where baseline policy stores an ID each year. + value_type = int + entity = Household + label = "Unique reference for this household" + definition_period = ETERNITY + + +class person_household_id(Variable): + value_type = int + entity = Person + label = "Unique reference for the household of this person" + definition_period = ETERNITY + + +class StoreHouseholdIdsForAllTime(Reform): + def apply(self): + self.update_variable(household_id) + self.update_variable(person_household_id) + + +def test_subsampling_selects_households_by_the_reforms_own_ids(): + """The reform gives the two households each other's ID for the year + before, which it holds for all time, and a sample of one picks the family + that a simulation with no reform, given those IDs for this year, picks. + Core selects households by the first household ID column of its export, + so the arm sets again no entity ID, membership ID or role. Before, the + arm kept the dataset's IDs, their column came first, and the reform + sampled the other family.""" + simulations = [ + Microsimulation(dataset=dataset((NEW_YORK,), FAMILIES), reform=reform) + for reform in (None, StoreHouseholdIdsForAllTime) + ] + plain, reformed = simulations + plain.set_input("household_id", YEAR, [1, 0]) + reformed.set_input("household_id", YEAR - 1, [1, 0]) + for simulation in simulations: + simulation.subsample(n=1, seed=0) + arm = reformed.baseline + for simulation in (reformed, arm): + assert_holders_suit_their_variables(simulation) + income = value(plain, "employment_income_before_lsr") + assert income.tolist() in ([30_000, 0], [15_000, 0]) + for simulation in (reformed, arm): + np.testing.assert_allclose( + value(simulation, "employment_income_before_lsr"), income + ) + + def write_on_the_holder(simulation): simulation.get_holder(SUBSIDY).set_input(YEAR, np.array([800.0, 900.0])) From 87aec7436dc8905b57001028be68bc5e766c9a02 Mon Sep 17 00:00:00 2001 From: Max Ghenis Date: Wed, 25 Nov 2026 21:37:28 +0100 Subject: [PATCH 19/42] Cut the input replay from the baseline arm; refuse a dropped input by name Remove the record and replay of inputs that baseline policy stores apart from a reform: the constants, the record and replay methods, the build_from_dataset and _to_person_dataframe overrides, the kept-input lines in clone, the record steps in subsample, the keep wrapper around set_input, and the replay call in system.py. set_input is main's again. Keep the drop at its three arm sites (the constructor, subsample and the country rebuild) and in the behavioural-response measurement branch. At the three arm sites, call a guard first that raises a ValueError naming each variable whose recorded input the arm would drop. The measurement branch keeps main's drop-and-calculate. A branch that shares its parent's baseline arm now hands core a copy of that arm under branches["baseline"] before it subsamples, so core's own rebuild gives the branch an arm on its sample. Before, the expense rule read the parent's arm and raised on the size mismatch. Co-Authored-By: Claude Opus 5.5 --- policyengine_us/spm.py | 419 +++++--------------------------------- policyengine_us/system.py | 12 +- 2 files changed, 56 insertions(+), 375 deletions(-) diff --git a/policyengine_us/spm.py b/policyengine_us/spm.py index 03fcd88ed4a..b7d52fcc263 100644 --- a/policyengine_us/spm.py +++ b/policyengine_us/spm.py @@ -12,11 +12,7 @@ from functools import lru_cache from inspect import ismethod, signature -import numpy as np -import pandas as pd from policyengine_core import periods as periods_ -from policyengine_core.data_storage.store_history import next_sequence_number -from policyengine_core.errors import PeriodMismatchError from policyengine_core.parameters import Parameter, ParameterScale from policyengine_core.simulations import Simulation as CoreSimulation from policyengine_core.taxbenefitsystems import TaxBenefitSystem @@ -94,15 +90,6 @@ # branch and invalidation paths below handle them explicitly. BEHAVIORAL_RESPONSE_CACHE_ATTR = "_behavioral_response_measurements" -# Where a reform simulation keeps, as core stored it, each input whose variable -# baseline policy stores apart from it, for its baseline arm to set again -# (``SPMSimulationMixin._keep_input_for_baseline_policy``). Each simulation and -# branch has its own list. -KEPT_BASELINE_INPUTS_ATTR = "_inputs_kept_for_baseline_policy" -# The kept inputs a subsample exports, from the start of ``subsample`` until it -# rebuilds the simulation. -SAMPLED_BASELINE_INPUTS_ATTR = "_inputs_kept_for_baseline_policy_to_sample" - COUNTY_INPUT_FIX = ( 'send county_fips as a five-digit string (for example "06037"), or select ' 'geography_kind="national" in the spm configuration' @@ -778,34 +765,17 @@ def pin_spm_policy(system): ) -def _stored_apart(variable, other): - """Whether two definitions of a variable share an entity but only one of - them is stored for ``ETERNITY``.""" - return ( - variable is not None - and other is not None - and variable.entity.key == other.entity.key - and (variable.definition_period == periods_.ETERNITY) - != (other.definition_period == periods_.ETERNITY) +def _built_for_another_policy(variable, population, holder): + """Whether ``variable`` cannot use ``holder``, which sits in ``population``: + the holder is in another entity's population, or has storage for (or not + for) an ``ETERNITY`` variable.""" + return variable is not None and ( + variable.entity.key != population.entity.key + or (variable.definition_period == periods_.ETERNITY) + != holder._memory_storage.is_eternal ) -def _structural_variables(policy): - """The variables core reads to build or rebuild populations: each entity's - ID, and each person's membership ID and role in each group entity.""" - person = policy.person_entity.key - names = {f"{person}_id"} - for entity in policy.group_entities: - names.update( - ( - f"{entity.key}_id", - f"{person}_{entity.key}_id", - f"{person}_{entity.key}_role", - ) - ) - return names - - class SPMSimulationMixin: """Keep forecast selection and receipts private to each simulation.""" @@ -814,10 +784,9 @@ def __init__(self, *args, **kwargs): # Core switches the baseline system after cloning its populations. baseline = self.branches.get("baseline") if baseline is not None: + baseline._refuse_inputs_baseline_policy_drops(self) baseline._drop_holders_built_for_another_policy() self._rebind_holders() - if baseline is not None: - baseline._set_inputs_kept_for_baseline_policy(self) # Core sets ``trace`` before this simulation owns its policy state. self._isolate_parameter_tracing() # Every input path - situation builder, dataset loader, direct @@ -896,10 +865,10 @@ def _drop_holders_built_for_another_policy(self): ``ETERNITY`` variable, therefore cannot hold the baseline's definition. Drop it with its recorded inputs, as core 3.32.21 and later do in ``_bind_to_tax_benefit_system``; core 3.32.8 keeps it. - A baseline arm then sets again each input the source still holds that - the baseline's definition can hold - (``_set_inputs_kept_for_baseline_policy``); the behavioural-response - measurement branch sets none, and calculates such a variable. + The arm then calculates such a variable. Where it would drop an input, + a baseline arm first refuses it + (``_refuse_inputs_baseline_policy_drops``); the behavioural-response + measurement branch drops it and calculates the variable. A simulation given a reform by ``apply_reform`` does not call this: core's own ``_bind_to_tax_benefit_system`` drops a holder the new @@ -910,12 +879,7 @@ def _drop_holders_built_for_another_policy(self): dropped = set() for population in self.populations.values(): for name, holder in list(population._holders.items()): - variable = variables.get(name) - if variable is not None and ( - variable.entity.key != population.entity.key - or (variable.definition_period == periods_.ETERNITY) - != holder._memory_storage.is_eternal - ): + if _built_for_another_policy(variables.get(name), population, holder): del population._holders[name] dropped.add(name) if dropped: @@ -926,286 +890,37 @@ def _drop_holders_built_for_another_policy(self): name for name in self.input_variables if name not in dropped ] - def _baseline_policy_stores_apart(self, variable_name): - """Whether baseline policy stores ``variable_name`` apart from this - simulation, which has a baseline arm. - - Only a simulation built with ``reform=`` has a baseline arm. Its arm - drops each holder this simulation built with storage for (or not for) - ``ETERNITY`` that the baseline's variable lacks, and the holder's - inputs go with it. - - Entity IDs, membership IDs and roles never count. The arm shares this - simulation's populations, and ``subsample`` selects households and - rebuilds both from this simulation's own columns for them: core reads - the first household ID column it finds, so a kept column for one would - pick the sample. - """ - if getattr(self, "reform", None) is None: - return False - if variable_name in _structural_variables(self.tax_benefit_system): - return False - baseline_policy = getattr(self, "default_tax_benefit_system_instance", None) - return baseline_policy is not None and _stored_apart( - self.tax_benefit_system.variables.get(variable_name), - baseline_policy.variables.get(variable_name), - ) - - def _input_key(self, holder, period): - """The key core records an input under: the period its holder stores - the input for, which is ``ETERNITY`` for an ``ETERNITY`` holder and - the year for twelve months from the first of a month.""" - return ( - holder.variable.name, - self.branch_name, - holder._storage_period(periods_.period(period)), - ) - - def _recorded_keys(self, variable_name): - """The keys core records an input of ``variable_name`` under, on this - simulation's branch.""" - return [ - key - for key in getattr(self, "_user_input_keys", ()) - if key[0] == variable_name and key[1] == self.branch_name - ] - - def _keys_the_record_accounts_for(self, variable_name): - """The keys core records for ``variable_name`` on this branch whose - last kept input is the value the holder stores there now. - - A key core records but this leaves out holds an input the record did - not keep, or a different one: a write this record does not see stored - it, such as one made on the holder itself. A key core no longer - records lost its input, and what was kept under it, to a deletion. - """ - holder = self.get_holder(variable_name) - last = {} - for name, period, value in self.__dict__.get(KEPT_BASELINE_INPUTS_ATTR, ()): - if name == variable_name: - last[self._input_key(holder, period)] = value - return { - key - for key in self._recorded_keys(variable_name) - if key in last - and np.array_equal( - np.asarray(last[key]), - np.asarray(self._get_recorded_input_array(variable_name, key[2])), - ) - } - - def _keep_input_for_baseline_policy(self, variable_name, period, accounted, since): - """Keep an input whose variable baseline policy stores apart from this one. - - An ``ETERNITY`` holder keeps no period, so it cannot give back a yearly - input: under a reform that stores ``child_care_subsidies`` for all - time, the arm calculated the 2026 subsidy a dataset supplied, and S0 - moved by thousands of dollars with no change in the subsidy paid. So - keep what core stored, as core stored it: a numeric expression - evaluated, an enum encoded. - - Core stamps each value it stores with a sequence number, and ``since`` - was drawn just before this input, so the keys stamped ``since`` or - later are the ones core stored this input under. There are none for - an input core skipped: a neutralized variable, a period after the - variable's end, or a year that a yearly holder's default handler - leaves as it was because it already holds an input. A yearly holder - can store one input under several years, and each is kept for its - year. An ``ETERNITY`` holder stores it under one key, and it is kept - with the period it was set for. An input for all time is not kept, - since a yearly definition cannot hold it. - - ``accounted`` holds the keys the record accounted for just before this - input (``_keys_the_record_accounts_for``). Under any other key this - input reaches, what was kept was deleted or replaced by a write the - record missed, so it goes, and the key's record starts again with - this input. - - Core's builder sets an entity situation's inputs on their holders - directly, not through ``set_input``, so this keeps none of them, and - the arm calculates such a variable (``_kept_record``). A situation - that gives variables alone goes through ``set_input``, so its inputs - are kept. The household rule for the SPM expense reads no baseline - subsidy, so what the arm pays never reaches a situation's SPM expense. - """ - holder = self.get_holder(variable_name) - stored = [] - for key in self._recorded_keys(variable_name): - stamp = holder._stored_sequence_number(key[2], key[1]) - if stamp is not None and stamp >= since: - stored.append((stamp, key)) - if not stored: - return - stored.sort() - restarted = {key for _, key in stored if key not in accounted} - kept = [ - entry - for entry in self.__dict__.get(KEPT_BASELINE_INPUTS_ATTR, ()) - if entry[0] != variable_name - or self._input_key(holder, entry[1]) not in restarted - ] - eternal = holder._memory_storage.is_eternal - for _, key in stored: - kept_period = periods_.period(period) if eternal else key[2] - if kept_period.unit == periods_.ETERNITY: - continue - recorded = self._get_recorded_input_array(variable_name, key[2]) - if recorded is not None: - kept.append((variable_name, kept_period, recorded.copy())) - self.__dict__[KEPT_BASELINE_INPUTS_ATTR] = kept - - def _kept_inputs_still_held(self): - """The kept inputs this simulation still holds, in the order last set.""" - return self._kept_record()[0] - - def _kept_record(self): - """The kept inputs this simulation still holds, and the variables - whose inputs the record missed. - - An input stays while baseline policy stores its variable apart from - this simulation and core records the input's key. Of the inputs kept - for one period, the latest stays, ordered by the last time each period - was set. - - A variable's inputs all go when core holds an input for it, on this - simulation's branch, that the record does not account for: a key core - records with no input kept under it, or one whose last kept input is - not the value the holder stores there now. That input came by a path - ``set_input`` does not see, such as a write to the holder itself or an - entity situation. The arm could not tell where it falls among the - variable's other inputs, so it calculates the variable. An input set - later through ``set_input`` restarts the record of each key it reaches - (``_keep_input_for_baseline_policy``), and under a reform that stores - the variable for all time the arm then sets the inputs given since. A - write that stores the very array the record kept last under its key - goes unnoticed, and the arm then sets what was kept, in the order - kept. ``subsample`` drops a missed variable's inputs from the rebuilt - record, so a subsample keeps calculating it. - """ - apart = {} - - def stores_apart(variable_name): - if variable_name not in apart: - apart[variable_name] = self._baseline_policy_stores_apart(variable_name) - return apart[variable_name] - - input_keys = { - key - for key in getattr(self, "_user_input_keys", ()) - if key[1] == self.branch_name - } - latest = {} - for variable_name, period, value in self.__dict__.get( - KEPT_BASELINE_INPUTS_ATTR, () - ): - if not stores_apart(variable_name): - continue - population = self.get_variable_population(variable_name) - holder = population._holders.get(variable_name) - if holder is None: - continue - key = self._input_key(holder, period) - if key not in input_keys: - continue - latest.pop((variable_name, period), None) - latest[(variable_name, period)] = (key, value) - last_under_key = {} - for key, value in latest.values(): - last_under_key[key] = value - missed = { - key[0] - for key, value in last_under_key.items() - if not np.array_equal( - np.asarray(value), - np.asarray(self._get_recorded_input_array(key[0], key[2])), - ) - } - missed.update( - key[0] - for key in input_keys - if key not in last_under_key and stores_apart(key[0]) - ) - held = [ - (variable_name, period, key, value) - for (variable_name, period), (key, value) in latest.items() - if variable_name not in missed - ] - return held, missed - - def _set_inputs_kept_for_baseline_policy(self, source): - """Set the inputs ``source`` kept for this simulation's policy. - - ``source`` is the simulation this baseline arm was branched from. Each - input it still holds belongs to a variable it stores apart from this - policy, so this simulation dropped the holder. Setting each input - again, in the order ``source`` last set each period, gives this - simulation what a simulation with no reform loads from those inputs in - that order. Core's handlers divide or dispatch an input over several - periods around the inputs a holder already has, so where such inputs - overlap, or the reform's handler stored one around an earlier input, - that can differ from what it loads from the inputs first given. + def _refuse_inputs_baseline_policy_drops(self, source): + """Raise, naming each variable, if this baseline arm drops an input. + + ``source`` is the reform simulation this arm was branched from. The + arm drops each holder ``source`` built for the reform's definition of + a variable that baseline policy's definition cannot use, with its + inputs, and calculates the variable + (``_drop_holders_built_for_another_policy``). + Where the caller gave that variable an input, the arm, and the S0 the + dataset rule reads from it, would rest on a value the caller never + gave, so refuse it. Core's ``_bind_to_tax_benefit_system`` drops such + holders, with their keys, before construction or ``subsample`` reaches + this, so read ``source``'s holders and core's record of its inputs, + ``_user_input_keys``. """ variables = self.tax_benefit_system.variables - for ( - variable_name, - period, - _, - value, - ) in source._kept_inputs_still_held(): - if variable_name not in variables: - continue - try: - self.set_input(variable_name, period, value.copy()) - except PeriodMismatchError: - # An ETERNITY definition takes a yearly input for all time; a - # yearly one takes none for all time, and none is kept. - continue - - def build_from_dataset(self): - # Loading replaces every input, so what was kept for the old ones goes - # with them; the loader's own ``set_input`` calls keep the new ones. A - # subsample has exported its inputs by now. - self.__dict__.pop(KEPT_BASELINE_INPUTS_ATTR, None) - self.__dict__.pop(SAMPLED_BASELINE_INPUTS_ATTR, None) - return super().build_from_dataset() - - def _to_person_dataframe(self, get_periods, include_computed_variables=False): - frame = super()._to_person_dataframe(get_periods, include_computed_variables) - sampled = self.__dict__.get(SAMPLED_BASELINE_INPUTS_ATTR) - if not sampled: - return frame - # Core's export holds an ETERNITY holder's input as one column for all - # time. Put each kept input before its variable's own columns, in the - # order the inputs were set, so the rebuild sets them in that order, - # keeps them for the new arm, and ends with the input the holder - # stores now. - person_key = self.persons.entity.key - kept = {} - for variable_name, period, _, value in sampled: - entity_key = self.tax_benefit_system.variables[variable_name].entity.key - kept.setdefault(variable_name, {})[f"{variable_name}__{period}"] = ( - self.map_result(value, entity_key, person_key) + recorded = {key[0] for key in getattr(source, "_user_input_keys", ())} + names = sorted( + name + for population in source.populations.values() + for name, holder in population._holders.items() + if name in recorded + and _built_for_another_policy(variables.get(name), population, holder) + ) + if names: + raise ValueError( + f"Baseline policy cannot hold the input given for {', '.join(names)}: " + "the reform defines it in another entity or with other ETERNITY " + "storage than baseline policy, so the reform's baseline arm would " + "calculate it in place of the input." ) - columns = {} - for column in frame.columns: - columns.update(kept.pop(column.split("__")[0], {})) - if column not in columns: - columns[column] = frame[column].values - for added in kept.values(): - columns.update(added) - return pd.DataFrame(columns, index=frame.index) - - def _get_recorded_input_array(self, variable_name, period): - # Core reweights each weight column of a subsample by its recorded - # total, so it reads a kept input's total here. Core parses the period - # back from the column name, and the parsed period need not equal the - # kept one: twelve months from January name the year, so match names. - for name, kept_period, _, value in self.__dict__.get( - SAMPLED_BASELINE_INPUTS_ATTR, () - ): - if name == variable_name and str(kept_period) == str(period): - return value - return super()._get_recorded_input_array(variable_name, period) def apply_reform(self, reform): policy = self.tax_benefit_system @@ -1345,15 +1060,6 @@ def clone(self, debug=False, trace=False, clone_tax_benefit_system=True): # other inputs reused them, and what it measured reached this # simulation. A clone measures its own (``get_branch`` seeds a branch). cloned.__dict__.pop(BEHAVIORAL_RESPONSE_CACHE_ATTR, None) - # The clone starts with this simulation's kept inputs, as it starts - # with its inputs. Each list is replaced rather than changed in place, - # so an input set on one never reaches the other's; the copy keeps it - # so if that changes. - kept = self.__dict__.get(KEPT_BASELINE_INPUTS_ATTR) - if kept is not None: - cloned.__dict__[KEPT_BASELINE_INPUTS_ATTR] = list(kept) - # What a subsample exports belongs to the simulation it rebuilds. - cloned.__dict__.pop(SAMPLED_BASELINE_INPUTS_ATTR, None) return cloned def _invalidate_all_caches(self): @@ -1438,28 +1144,14 @@ def _simulation_family(self): yield from branch._simulation_family() def subsample(self, *args, **kwargs): - # Core rebuilds this simulation from the inputs its holders record, and - # an ETERNITY holder records no year: a yearly input the reform stores - # for all time comes back as one input for all time, which baseline - # policy cannot hold. So hand core's export each kept input as a - # column of its own (``_to_person_dataframe``). Core then samples and - # reweights those columns with the rest, and the rebuild keeps them. - # A variable whose inputs the record missed stays out of the export's - # kept columns, so core exports it as it holds it, and the rebuild - # keeps those inputs as if given in that order. Drop them, so the new - # arm calculates that variable as the old one did (``_kept_record``). - held, missed = self._kept_record() - self.__dict__[SAMPLED_BASELINE_INPUTS_ATTR] = held - try: - result = super().subsample(*args, **kwargs) - finally: - self.__dict__.pop(SAMPLED_BASELINE_INPUTS_ATTR, None) - if missed: - self.__dict__[KEPT_BASELINE_INPUTS_ATTR] = [ - entry - for entry in self.__dict__.get(KEPT_BASELINE_INPUTS_ATTR, ()) - if entry[0] not in missed - ] + inherited = getattr(self, "baseline", None) + if inherited is not None and "baseline" not in self.branches: + # A branch shares its parent's baseline arm, on the parent's + # population, and core rebuilds an arm only from + # ``branches["baseline"]``. Hand core a copy of the arm, whose + # policy it gives the arm it builds on this branch's sample. + self.branches["baseline"] = inherited.clone(clone_tax_benefit_system=False) + result = super().subsample(*args, **kwargs) baseline = self.branches.get("baseline") if baseline is not None: # Core rebuilds the baseline arm by branching this simulation, so @@ -1475,9 +1167,9 @@ def subsample(self, *args, **kwargs): # behavioural responses, holders bound to its own policy, and that # policy's tracing primed for this arm. baseline.baseline = None + baseline._refuse_inputs_baseline_policy_drops(self) baseline._drop_holders_built_for_another_policy() baseline._rebind_holders() - baseline._set_inputs_kept_for_baseline_policy(self) baseline._isolate_parameter_tracing() # Core hands the rebuilt baseline arm the previous arm's policy and so # its provider, which recorded the counties the previous arm read. @@ -1498,16 +1190,7 @@ def set_input(self, variable_name, period, value): f"Dataset supplies formula-owned SPM output {variable_name}. " "Use primitive inputs and retain observed outputs under report-only names." ) - keep = self._baseline_policy_stores_apart(variable_name) - if keep: - accounted = self._keys_the_record_accounts_for(variable_name) - # Each value core stores from here on gets this number or a later one. - since = next_sequence_number() result = super().set_input(variable_name, period, value) - if keep: - self._keep_input_for_baseline_policy( - variable_name, period, accounted, since - ) # Core snapshots input_variables during construction, but later # explicit inputs must also survive counterfactual branches. Keep # only stored inputs; neutralized and expired writes are ignored. diff --git a/policyengine_us/system.py b/policyengine_us/system.py index 7a528f85358..53264196e30 100644 --- a/policyengine_us/system.py +++ b/policyengine_us/system.py @@ -277,10 +277,8 @@ def _rebuild_baseline_branch(simulation): ``subsample`` does, gives the baseline the same inputs as the reform, except those the reform stored for its own definition of a variable in another entity or with other ``ETERNITY`` storage, which core's branch - dropped too. Of those, other than entity IDs, membership IDs and roles, - the baseline then sets again each input the reform still holds that the - baseline's definition can hold, such as a yearly subsidy the reform - stores for all time. + dropped too. Where it would drop such an input, it raises instead, + naming the variable (``_refuse_inputs_baseline_policy_drops``). """ baseline = simulation.branches.pop("baseline", None) if baseline is None: @@ -298,11 +296,11 @@ def _rebuild_baseline_branch(simulation): # the reform. A kept holder would hand the baseline the reform's input: # under a reform that stores ``child_care_subsidies`` for all time, the # baseline read that input in place of its own formula. A dropped holder - # takes its inputs with it, so the baseline sets again each one it can - # hold: dropping a yearly 2026 subsidy left the baseline calculating one. + # takes its inputs with it, and the baseline would calculate one the + # caller gave, so it refuses such an input first. + rebuilt._refuse_inputs_baseline_policy_drops(simulation) rebuilt._drop_holders_built_for_another_policy() rebuilt._rebind_holders() - rebuilt._set_inputs_kept_for_baseline_policy(simulation) rebuilt._isolate_parameter_tracing() simulation.baseline = rebuilt From c71aad67f2db276d1fc7fd9f10c7885d3baf45ed Mon Sep 17 00:00:00 2001 From: Max Ghenis Date: Wed, 25 Nov 2026 21:37:35 +0100 Subject: [PATCH 20/42] Read the guard from the baseline arm's own record The guard read the reform simulation's holders and recorded inputs. That refused an input main's subsampling test gives the reform's own yearly is_household_head, which the arm drops and calculates on main. Read the arm's own holders and _user_input_keys instead, so the guard refuses only an input the arm itself holds and would drop. Co-Authored-By: Claude Opus 5.5 --- policyengine_us/spm.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/policyengine_us/spm.py b/policyengine_us/spm.py index b7d52fcc263..40b83418935 100644 --- a/policyengine_us/spm.py +++ b/policyengine_us/spm.py @@ -906,10 +906,10 @@ def _refuse_inputs_baseline_policy_drops(self, source): ``_user_input_keys``. """ variables = self.tax_benefit_system.variables - recorded = {key[0] for key in getattr(source, "_user_input_keys", ())} + recorded = {key[0] for key in getattr(self, "_user_input_keys", ())} names = sorted( name - for population in source.populations.values() + for population in self.populations.values() for name, holder in population._holders.items() if name in recorded and _built_for_another_policy(variables.get(name), population, holder) From 70bffb050cfe1295ddd42918fff20096974a0dc2 Mon Sep 17 00:00:00 2001 From: Max Ghenis Date: Wed, 25 Nov 2026 21:38:19 +0100 Subject: [PATCH 21/42] Drop the guard's unused source parameter; say where it fires The guard reads only the arm it is called on, so its source parameter went unused: drop it from the guard and its three call sites. Its docstring now says what it reads, that keys match by variable name alone (the arm's copied keys keep the reform's branch name), and where it fires: only the rebuild at the end of construction still holds the holder and its keys, since core's _bind_to_tax_benefit_system drops both wherever core builds the arm. The changelog fragment described the input replay; it now describes the guard and the subsampled branch's own arm. Co-Authored-By: Claude Opus 5.5 --- changelog.d/spm-child-care-subsidies.fixed.md | 2 +- policyengine_us/spm.py | 38 +++++++++++-------- policyengine_us/system.py | 2 +- 3 files changed, 24 insertions(+), 18 deletions(-) diff --git a/changelog.d/spm-child-care-subsidies.fixed.md b/changelog.d/spm-child-care-subsidies.fixed.md index 07e8d4ddd4a..ccd15c94e8c 100644 --- a/changelog.d/spm-child-care-subsidies.fixed.md +++ b/changelog.d/spm-child-care-subsidies.fixed.md @@ -1 +1 @@ -Count every state child care subsidy in the Supplemental Poverty Measure from 2024 by netting it from the SPM child care expense in household calculations, keep the ASEC's reported spending as that expense over a dataset while a reform moves it by the change in subsidy, and add the District of Columbia, Tennessee and Texas subsidies to the 2024 program list. Rebuild a reform's baseline arm without the holders the reform built for its own definition of a variable in another entity or with other ETERNITY storage, as core's own branch does, then set again each input the reform still holds for such a variable, wherever the baseline's definition can hold it, before and after subsampling. +Count every state child care subsidy in the Supplemental Poverty Measure from 2024 by netting it from the SPM child care expense in household calculations, keep the ASEC's reported spending as that expense over a dataset while a reform moves it by the change in subsidy, and add the District of Columbia, Tennessee and Texas subsidies to the 2024 program list. Rebuild a reform's baseline arm without the holders the reform built for its own definition of a variable in another entity or with other ETERNITY storage, as core's own branch does, and raise an error naming the variable when that rebuild would drop an input the caller gave. Give a subsampled branch of a reform simulation its own baseline arm on its sample. diff --git a/policyengine_us/spm.py b/policyengine_us/spm.py index 40b83418935..52019b9451e 100644 --- a/policyengine_us/spm.py +++ b/policyengine_us/spm.py @@ -784,7 +784,7 @@ def __init__(self, *args, **kwargs): # Core switches the baseline system after cloning its populations. baseline = self.branches.get("baseline") if baseline is not None: - baseline._refuse_inputs_baseline_policy_drops(self) + baseline._refuse_inputs_baseline_policy_drops() baseline._drop_holders_built_for_another_policy() self._rebind_holders() # Core sets ``trace`` before this simulation owns its policy state. @@ -865,10 +865,10 @@ def _drop_holders_built_for_another_policy(self): ``ETERNITY`` variable, therefore cannot hold the baseline's definition. Drop it with its recorded inputs, as core 3.32.21 and later do in ``_bind_to_tax_benefit_system``; core 3.32.8 keeps it. - The arm then calculates such a variable. Where it would drop an input, - a baseline arm first refuses it + The arm then calculates such a variable. Where it would drop an input + it holds a key for, a baseline arm first refuses it (``_refuse_inputs_baseline_policy_drops``); the behavioural-response - measurement branch drops it and calculates the variable. + measurement branch drops it and calculates the variable, as on main. A simulation given a reform by ``apply_reform`` does not call this: core's own ``_bind_to_tax_benefit_system`` drops a holder the new @@ -890,20 +890,26 @@ def _drop_holders_built_for_another_policy(self): name for name in self.input_variables if name not in dropped ] - def _refuse_inputs_baseline_policy_drops(self, source): + def _refuse_inputs_baseline_policy_drops(self): """Raise, naming each variable, if this baseline arm drops an input. - ``source`` is the reform simulation this arm was branched from. The - arm drops each holder ``source`` built for the reform's definition of - a variable that baseline policy's definition cannot use, with its + The arm drops each holder built for the reform's definition of a + variable that baseline policy's definition cannot use, with its inputs, and calculates the variable - (``_drop_holders_built_for_another_policy``). - Where the caller gave that variable an input, the arm, and the S0 the - dataset rule reads from it, would rest on a value the caller never - gave, so refuse it. Core's ``_bind_to_tax_benefit_system`` drops such - holders, with their keys, before construction or ``subsample`` reaches - this, so read ``source``'s holders and core's record of its inputs, - ``_user_input_keys``. + (``_drop_holders_built_for_another_policy``). Where the caller gave + that variable an input, the arm, and the S0 the dataset rule reads + from it, would rest on a value the caller never gave, so refuse it. + + This reads the arm's own holders and core's record of the arm's + inputs, ``_user_input_keys``, and matches a recorded input by + variable name alone: the keys the arm copied from the reform keep the + reform's branch name. Only the country simulations' rebuild of the arm + at the end of construction (``system._rebuild_baseline_branch``) + hands this an arm that still holds such a holder with its keys. Where + core builds the arm, in construction and in ``subsample``, its + ``_bind_to_tax_benefit_system`` has already dropped both, so an input + set after construction and then subsampled is dropped and calculated, + as on main. """ variables = self.tax_benefit_system.variables recorded = {key[0] for key in getattr(self, "_user_input_keys", ())} @@ -1167,7 +1173,7 @@ def subsample(self, *args, **kwargs): # behavioural responses, holders bound to its own policy, and that # policy's tracing primed for this arm. baseline.baseline = None - baseline._refuse_inputs_baseline_policy_drops(self) + baseline._refuse_inputs_baseline_policy_drops() baseline._drop_holders_built_for_another_policy() baseline._rebind_holders() baseline._isolate_parameter_tracing() diff --git a/policyengine_us/system.py b/policyengine_us/system.py index 53264196e30..1b368156cb2 100644 --- a/policyengine_us/system.py +++ b/policyengine_us/system.py @@ -298,7 +298,7 @@ def _rebuild_baseline_branch(simulation): # baseline read that input in place of its own formula. A dropped holder # takes its inputs with it, and the baseline would calculate one the # caller gave, so it refuses such an input first. - rebuilt._refuse_inputs_baseline_policy_drops(simulation) + rebuilt._refuse_inputs_baseline_policy_drops() rebuilt._drop_holders_built_for_another_policy() rebuilt._rebind_holders() rebuilt._isolate_parameter_tracing() From dcce719192cfe1c25320eae4addd84b093dcfa75 Mon Sep 17 00:00:00 2001 From: Max Ghenis Date: Wed, 25 Nov 2026 21:41:23 +0100 Subject: [PATCH 22/42] Test the guard, its limit and a subsampled branch's arm; drop replay tests The arm file's replay tests tested code this branch removed. It keeps the two tests that a no-change reform's arms match a simulation with no reform, and adds: - four cases, a dataset or a situation giving a $500 subsidy for all time or for 2026 under a reform that stores the subsidy for all time, each refused at construction with a ValueError naming child_care_subsidies, raised from _rebuild_baseline_branch; - the stated limit: an input set after construction and then subsampled raises nothing, and the new arm calculates the subsidy as a plain run does. Its first assertion, that construction leaves the arm no holder stored for all time, reaches the rebuild's drop in system.py; - F1: a branch of a reform simulation that subsamples reads an arm on its own sample and gets the $500 expense a subsample of the reform gets, where before the expense raised on a size mismatch. Co-Authored-By: Claude Opus 5.5 --- .../core/test_reform_baseline_arm_inputs.py | 648 ++++-------------- 1 file changed, 126 insertions(+), 522 deletions(-) diff --git a/policyengine_us/tests/core/test_reform_baseline_arm_inputs.py b/policyengine_us/tests/core/test_reform_baseline_arm_inputs.py index d25fab17379..46b9757fc75 100644 --- a/policyengine_us/tests/core/test_reform_baseline_arm_inputs.py +++ b/policyengine_us/tests/core/test_reform_baseline_arm_inputs.py @@ -11,39 +11,24 @@ subsidy it reads from that arm, so the gap became a double count. ``system._rebuild_baseline_branch`` now branches the arm again after the moves. Like core's branch, it drops each holder the reform built in another -entity or with other ``ETERNITY`` storage than the baseline's variable has. -A kept holder hands the arm the reform's input in place of its formula. A -dropped holder takes its inputs with it, so the arm then sets again each input -the reform still holds for a variable it stores apart from baseline policy, -wherever the baseline's definition can hold that input. Without that step, a -yearly subsidy the reform stores for all time left the arm calculating one. +entity or with other ``ETERNITY`` storage than the baseline's variable has: a +kept holder hands the arm the reform's input in place of its formula. A +dropped holder takes its inputs with it, so where the caller gave such a +variable an input, the rebuild raises a ``ValueError`` naming the variable +rather than calculate it in place of the input. Invariants: under a reform that changes nothing, the reform and its baseline arm compute what a simulation with no reform computes, for every household, whether a situation or a dataset of raw columns supplies the inputs. Under any reform, each holder in either arm suits that arm's definition of its variable. -Under a reform that stores a variable apart from baseline policy, other than an -entity ID, membership ID or role, the arm sets again the last array the reform -stored for each period it still holds, in the order those periods were last -set, through deletions and subsamples, and reads them as a simulation with no -reform given them in that order reads them. Subsampling leaves the reform's -own value, and the households it samples, as they were. A deletion on a holder for all time -deletes every year's input, so the reform then holds none. Where the reform's -holder took an input its ``set_input`` never saw, such as a write to the -holder itself, the arm calculates what it can't place: under a reform for all -time, each year given no input since; under a yearly reform, the variable. - -Three cases fall outside these invariants, and no test pins them. A write the -record never saw that stores the very array it kept last under that key goes -unnoticed, so the arm sets what was kept, in the order kept. Under a yearly -reform of a variable baseline policy stores for all time, deleting one year's -input leaves the reform its other years, which the arm sets again, while a -simulation with no reform loses every year's input. And core's handlers divide -or dispatch an input over several periods around the inputs a holder already -has, so the arrays the reform stored, and the last of them for each period, -can tell another story than the inputs first given: where such inputs overlap, -or the reform's handler stored one around an earlier input, the arm can read -other values than a simulation with no reform given those inputs. +Under a reform that stores a variable apart from baseline policy, an input +given for it at construction, through a dataset or a situation, raises by +name. A branch that subsamples reads an arm built on its own sample. + +One limit is pinned here too. Where core builds the arm, in ``subsample``, it +has already dropped such a holder and its recorded inputs, so an input set +after construction and then subsampled raises nothing: the new arm calculates +the variable, as on main. """ from itertools import product @@ -57,10 +42,7 @@ from policyengine_core.variables import Variable from policyengine_us import Microsimulation, Simulation -from policyengine_us.entities import Household, Person, SPMUnit -from policyengine_us.variables.gov.hhs.ccdf.child_care_subsidies import ( - child_care_subsidies as yearly_child_care_subsidies, -) +from policyengine_us.entities import SPMUnit YEAR = 2026 TOLERANCE = 0.01 @@ -274,530 +256,152 @@ def test_situation_arms_match_a_simulation_with_no_reform(): assert state.tolist() == ["NY"] -def test_the_arm_calculates_what_the_reform_stores_for_all_time(): - """New York's first family enters with a $500 subsidy for all time, which - the reform stores for all time. The baseline's yearly - ``child_care_subsidies`` can hold no input for all time, so the arm drops - the input and pays what a simulation with no reform pays. Keeping it gave - the arm $500 as S0 where baseline policy pays $13,916.40, and left the - reform's expense $13,416.40 low.""" - plain = Microsimulation(dataset=dataset((NEW_YORK,), FAMILIES[:1])) - reformed = Microsimulation( - dataset=dataset((NEW_YORK,), FAMILIES[:1], eternal_subsidy=500), - reform=StoreSubsidiesForAllTime, - ) - arm = reformed.baseline - for simulation in (reformed, arm): - assert_holders_suit_their_variables(simulation) - - baseline_subsidy = value(plain, "child_care_subsidies") - assert baseline_subsidy[0] > 500 - np.testing.assert_allclose( - value(arm, "child_care_subsidies"), baseline_subsidy, atol=TOLERANCE - ) - np.testing.assert_allclose(value(reformed, "child_care_subsidies"), 500) - expense = "spm_unit_capped_work_childcare_expenses" - np.testing.assert_allclose( - value(arm, expense), value(plain, expense), atol=TOLERANCE - ) - # The dataset rule moves the reported amount by the change in subsidy. - expected = np.minimum( - value(reformed, "spm_unit_work_expenses") - + np.maximum( - value(reformed, "spm_unit_pre_subsidy_childcare_expenses") - - (500 - baseline_subsidy), - 0, - ), - value(reformed, "spm_unit_head_spouse_earned_cap"), - ) - np.testing.assert_allclose(value(reformed, expense), expected, atol=TOLERANCE) - - -def test_the_arm_sets_again_the_yearly_subsidies_the_reform_stores_for_all_time(): - """Both runs read the same dataset, which gives New York's first family a - $400 child care subsidy in 2025 and $500 in 2026. The reform stores - ``child_care_subsidies`` for all time, so it keeps one of them, and the - arm drops that holder. The arm then sets both yearly inputs again and - reads each year's as a simulation with no reform does. Before, it - calculated the 2026 subsidy, and S0 rose to $13,916.40 though the subsidy - paid had not changed.""" - subsidies = {2025: [400], YEAR: [500]} - plain = Microsimulation( - dataset=dataset((NEW_YORK,), FAMILIES[:1], yearly_subsidies=subsidies) - ) - reformed = Microsimulation( - dataset=dataset((NEW_YORK,), FAMILIES[:1], yearly_subsidies=subsidies), - reform=StoreSubsidiesForAllTime, - ) - arm = reformed.baseline - for simulation in (reformed, arm): - assert_holders_suit_their_variables(simulation) - for year, subsidy in subsidies.items(): - for simulation in (plain, arm): - np.testing.assert_allclose( - value(simulation, "child_care_subsidies", year), subsidy - ) - # The reform's holder keeps the input it received last, for all time. - np.testing.assert_allclose(value(reformed, "child_care_subsidies", year), 500) - # S1 equals S0, so the reform reports the expense baseline policy reports. - expense = "spm_unit_capped_work_childcare_expenses" - for simulation in (reformed, arm): - np.testing.assert_allclose( - value(simulation, expense), value(plain, expense), atol=TOLERANCE - ) - - SUBSIDY = "child_care_subsidies" -TWO_YEARS = {2025: [400, 600], YEAR: [500, 700]} - - -def delete_then_set(simulation): - simulation.delete_arrays(SUBSIDY) - simulation.set_input(SUBSIDY, YEAR, [800, 900]) - +EXPENSE = "spm_unit_capped_work_childcare_expenses" +REFUSAL = f"Baseline policy cannot hold the input given for {SUBSIDY}" -def delete_on_the_holder_then_set(simulation): - # PolicyEngine's input moves delete on the holder, not the simulation. - simulation.get_holder(SUBSIDY).delete_arrays() - simulation.set_input(SUBSIDY, YEAR, [800, 900]) +def with_subsidy(subsidy): + """The situation, with a child care subsidy given on the SPM unit.""" + given = situation() + given["spm_units"]["spm_unit"][SUBSIDY] = subsidy + return given -def set_the_first_year_again(simulation): - simulation.set_input(SUBSIDY, 2025, [450, 650]) - -@pytest.mark.parametrize( - "change", - [ - None, - delete_then_set, - delete_on_the_holder_then_set, - set_the_first_year_again, - ], -) -def test_subsampling_gives_the_arm_each_yearly_subsidy_the_reform_holds(change): - """Core subsamples by rebuilding the simulation from what its holders - record, and the reform's holder for all time records neither year. Both - runs read the same dataset and receive the same inputs and deletions, and - the sample keeps only the second household. The arm then reads each - year's subsidy as the simulation with no reform does, and the reform keeps - the subsidy it held. Before, a deleted input came back. A subsample that - fails before core rebuilds anything keeps the inputs in place.""" - simulations = [ - Microsimulation( - dataset=dataset( - (NEW_YORK,), FAMILIES, yearly_subsidies=TWO_YEARS, weights=(0, 1) - ), - reform=reform, - ) - for reform in (None, StoreSubsidiesForAllTime) - ] - plain, reformed = simulations - for simulation in simulations: - if change is not None: - change(simulation) - held = value(reformed, SUBSIDY)[1] - with pytest.raises(ValueError, match="Either n or frac"): - reformed.subsample() - for simulation in simulations: - simulation.subsample(n=1) - arm = reformed.baseline - for simulation in (reformed, arm): - assert_holders_suit_their_variables(simulation) - assert simulation.calculate("household_id", YEAR).values.tolist() == [1] - for year in TWO_YEARS: - np.testing.assert_allclose( - value(arm, SUBSIDY, year), value(plain, SUBSIDY, year), atol=TOLERANCE - ) - np.testing.assert_allclose(value(reformed, SUBSIDY, year), [held]) - expense = "spm_unit_capped_work_childcare_expenses" - np.testing.assert_allclose( - value(arm, expense), value(plain, expense), atol=TOLERANCE +def subsidy_for_all_time_from_a_dataset(): + return Microsimulation( + dataset=dataset((NEW_YORK,), FAMILIES[:1], eternal_subsidy=500), + reform=StoreSubsidiesForAllTime, ) -def test_the_arm_sets_a_numeric_expression_as_core_stored_it(): - """Core evaluates a numeric expression it is given for a numeric variable - and stores the result, $600. The arm sets that 2026 subsidy after a - subsample, beside the dataset's $400 for 2025. Before, the arm received - the expression as an array of text, and setting it raised a - ValueError.""" - subsidies = {2025: [400], YEAR: [500]} - simulations = [ - Microsimulation( - dataset=dataset((NEW_YORK,), FAMILIES[:1], yearly_subsidies=subsidies), - reform=reform, - ) - for reform in (None, StoreSubsidiesForAllTime) - ] - for simulation in simulations: - simulation.set_input(SUBSIDY, YEAR, "400 + 200") - simulation.subsample(n=1) - plain, reformed = simulations - arm = reformed.baseline - for year, subsidy in ((2025, 400), (YEAR, 600)): - np.testing.assert_allclose(value(plain, SUBSIDY, year), [subsidy]) - np.testing.assert_allclose(value(arm, SUBSIDY, year), [subsidy]) - np.testing.assert_allclose(value(reformed, SUBSIDY, year), [600]) - - -class RestoreYearlySubsidies(Reform): - def apply(self): - self.update_variable(yearly_child_care_subsidies) - - -def test_a_reform_that_restores_the_yearly_subsidy_leaves_none_to_set_again(): - """Applying a reform that restores baseline policy's yearly subsidy drops - the holder that stored it for all time, with its input, so the reform - calculates the subsidy. A later subsample then gives the arm no input the - reform no longer holds, and the two read the same subsidy each year.""" - reformed = Microsimulation( - dataset=dataset( - (NEW_YORK,), FAMILIES, yearly_subsidies=TWO_YEARS, weights=(0, 1) - ), +def subsidy_for_the_year_from_a_dataset(): + return Microsimulation( + dataset=dataset((NEW_YORK,), FAMILIES[:1], yearly_subsidies={YEAR: [500]}), reform=StoreSubsidiesForAllTime, ) - reformed.apply_reform(RestoreYearlySubsidies) - reformed.subsample(n=1) - arm = reformed.baseline - for simulation in (reformed, arm): - assert_holders_suit_their_variables(simulation) - for year in TWO_YEARS: - np.testing.assert_allclose( - value(arm, SUBSIDY, year), value(reformed, SUBSIDY, year), atol=TOLERANCE - ) - expense = "spm_unit_capped_work_childcare_expenses" - np.testing.assert_allclose( - value(reformed, expense), value(arm, expense), atol=TOLERANCE - ) - - -class household_weight(Variable): - # Stored for all time, where baseline policy stores a weight each year. - value_type = float - entity = Household - label = "Household weight" - definition_period = ETERNITY - - -class StoreWeightsForAllTime(Reform): - def apply(self): - self.update_variable(household_weight) - - -@pytest.mark.parametrize("period", [None, "month:2025-01:12", "month:2026-02:12"]) -def test_subsampling_reweights_a_weight_the_reform_stores_for_all_time(period): - """Two households weigh 1 each, and a sample of one keeps their total of - 2. The arm reads the sampled household's yearly weight as the simulation - with no reform does. Before, the arm set the weight the dataset gave, 1. - - A weight given for twelve months reaches the arm as a column named for - its period, which core parses back to reweight it. Twelve months from - January parse back as the year, and from February as a year from - February, so neither equals the period kept; matching on the period - raised ``TypeError`` from the subsample.""" - simulations = [ - Microsimulation(dataset=dataset((NEW_YORK,), FAMILIES), reform=reform) - for reform in (None, StoreWeightsForAllTime) - ] - for simulation in simulations: - if period is not None: - simulation.set_input("household_weight", period, [1.0, 1.0]) - simulation.subsample(n=1, seed=0) - plain, reformed = simulations - arm = reformed.baseline - for simulation in (reformed, arm): - assert_holders_suit_their_variables(simulation) - for simulation in (reformed, arm): - assert ( - simulation.calculate("household_id", YEAR).values.tolist() - == plain.calculate("household_id", YEAR).values.tolist() - ) - weight = np.asarray(plain.calculate("household_weight", YEAR, use_weights=False)) - np.testing.assert_allclose(weight, [2]) - for simulation in (reformed, arm): - np.testing.assert_allclose( - simulation.calculate("household_weight", YEAR, use_weights=False), weight - ) - - -class household_id(Variable): - # Stored for all time, where baseline policy stores an ID each year. - value_type = int - entity = Household - label = "Unique reference for this household" - definition_period = ETERNITY - - -class person_household_id(Variable): - value_type = int - entity = Person - label = "Unique reference for the household of this person" - definition_period = ETERNITY - -class StoreHouseholdIdsForAllTime(Reform): - def apply(self): - self.update_variable(household_id) - self.update_variable(person_household_id) - - -def test_subsampling_selects_households_by_the_reforms_own_ids(): - """The reform gives the two households each other's ID for the year - before, which it holds for all time, and a sample of one picks the family - that a simulation with no reform, given those IDs for this year, picks. - Core selects households by the first household ID column of its export, - so the arm sets again no entity ID, membership ID or role. Before, the - arm kept the dataset's IDs, their column came first, and the reform - sampled the other family.""" - simulations = [ - Microsimulation(dataset=dataset((NEW_YORK,), FAMILIES), reform=reform) - for reform in (None, StoreHouseholdIdsForAllTime) - ] - plain, reformed = simulations - plain.set_input("household_id", YEAR, [1, 0]) - reformed.set_input("household_id", YEAR - 1, [1, 0]) - for simulation in simulations: - simulation.subsample(n=1, seed=0) - arm = reformed.baseline - for simulation in (reformed, arm): - assert_holders_suit_their_variables(simulation) - income = value(plain, "employment_income_before_lsr") - assert income.tolist() in ([30_000, 0], [15_000, 0]) - for simulation in (reformed, arm): - np.testing.assert_allclose( - value(simulation, "employment_income_before_lsr"), income - ) - -def write_on_the_holder(simulation): - simulation.get_holder(SUBSIDY).set_input(YEAR, np.array([800.0, 900.0])) +def subsidy_for_all_time_in_a_situation(): + return Simulation( + situation=with_subsidy({"ETERNITY": 500}), reform=StoreSubsidiesForAllTime + ) -def edit_the_stored_array(simulation): - simulation.get_holder(SUBSIDY).get_array(YEAR)[:] = [800.0, 900.0] +def subsidy_for_the_year_in_a_situation(): + return Simulation( + situation=with_subsidy({YEAR: 500}), reform=StoreSubsidiesForAllTime + ) @pytest.mark.parametrize( - "write, held", + "build", [ - (write_on_the_holder, 900), - (edit_the_stored_array, 900), + subsidy_for_all_time_from_a_dataset, + subsidy_for_the_year_from_a_dataset, + subsidy_for_all_time_in_a_situation, + subsidy_for_the_year_in_a_situation, ], ) -def test_the_arm_sets_none_of_the_inputs_a_write_to_the_holder_replaced(write, held): - """A write to the reform's holder itself, as core's situation builder - makes, or an edit in place to the array it stores, replaces the subsidy - kept for all time without telling the record. The arm then sets none of - the kept yearly inputs and calculates both years, as a simulation with no - subsidy input does, rather than the replaced $600 and $700.""" +def test_the_arm_refuses_a_subsidy_the_reform_stores_for_all_time(build): + """New York's first family enters with a $500 subsidy, for all time or for + 2026, under a reform that stores ``child_care_subsidies`` for all time. + Baseline policy's yearly variable can't use the reform's holder, so the + arm would drop the input and calculate a subsidy in its place: given for + 2026, S0 would move from the $500 given to what baseline policy pays, + though the subsidy paid hadn't changed. So construction refuses either + input, naming the variable. The rebuild at the end of construction + raises: where core builds the arm, it has already dropped the holder and + its recorded input.""" + with pytest.raises(ValueError, match=REFUSAL) as refused: + build() + assert "_rebuild_baseline_branch" in [entry.name for entry in refused.traceback] + + +def test_an_input_set_after_construction_is_calculated_after_a_subsample(): + """The stated limit. Both runs read two New York families, and the sample + keeps the second, the family a plain run pays more than $500. After + construction the reform gets a $500 subsidy, which it stores for all + time. Its arm never sees an input set after construction, and the + subsample raises nothing: core drops the reform's holder from the arm it + builds, so that arm calculates the subsidy, as on main. Construction's + rebuild first drops the reform's empty holder for all time from the + arm.""" + families = (FAMILIES[1], FAMILIES[0]) simulations = [ Microsimulation( - dataset=dataset( - (NEW_YORK,), FAMILIES, yearly_subsidies=TWO_YEARS, weights=(0, 1) - ), - reform=reform, + dataset=dataset((NEW_YORK,), families, weights=(0, 1)), reform=reform ) for reform in (None, StoreSubsidiesForAllTime) ] plain, reformed = simulations - plain.delete_arrays(SUBSIDY) - write(reformed) - for simulation in simulations: - simulation.subsample(n=1) - arm = reformed.baseline - for year in TWO_YEARS: - calculated = value(plain, SUBSIDY, year) - assert calculated[0] not in TWO_YEARS[year] - np.testing.assert_allclose( - value(arm, SUBSIDY, year), calculated, atol=TOLERANCE - ) - np.testing.assert_allclose(value(reformed, SUBSIDY, year), [held]) - - -class is_household_head(Variable): - # Stored each year, where baseline policy stores it for all time. - value_type = bool - entity = Person - label = "is head of this household" - definition_period = "year" - - -class StoreHeadsEachYear(Reform): - def apply(self): - self.update_variable(is_household_head) - - -@pytest.mark.parametrize("period", [2025, "month:2025-01:12", "month:2025-01:24"]) -def test_subsampling_keeps_the_order_of_inputs_baseline_policy_stores_for_all_time( - period, -): - """The dataset names each household's parent its head in 2026, and both - runs then name each child head in 2025. Baseline policy stores the role - for all time, so the input set last wins. The reform stores it each year, - and core exports its years in order, 2025 first; the arm sets them in the - order the reform received them, so it reads the child as head, as the - simulation with no reform does. Core stores twelve months from January - as the year, and so does the record. Over 24 months, the reform's holder - stores the input for 2025 alone, since 2026 already holds one, and the - record keeps what it stored.""" - simulations = [ - Microsimulation( - dataset=dataset((NEW_YORK,), FAMILIES, weights=(0, 1)), reform=reform - ) - for reform in (None, StoreHeadsEachYear) - ] - for simulation in simulations: - simulation.set_input("is_household_head", period, [False, True, False, True]) + for simulation in (reformed, reformed.baseline): + assert_holders_suit_their_variables(simulation) + reformed.set_input(SUBSIDY, YEAR, [500, 500]) for simulation in simulations: simulation.subsample(n=1) - plain, reformed = simulations arm = reformed.baseline for simulation in (reformed, arm): assert_holders_suit_their_variables(simulation) - heads = plain.calculate("is_household_head", YEAR, use_weights=False) - assert np.asarray(heads).tolist() == [False, True] - assert np.asarray( - arm.calculate("is_household_head", YEAR, use_weights=False) - ).tolist() == [False, True] - assert np.asarray( - reformed.calculate("is_household_head", YEAR, use_weights=False) - ).tolist() == [True, False] - - -def test_after_a_write_to_the_holder_the_arm_sets_only_the_inputs_given_since(): - """A write to the reform's holder itself stores $900 for all time where the - record kept the dataset's $700, and both runs then set $650 for 2025. The - record can't tell which year the write was for, so it starts again from - the 2025 input: the arm sets it and calculates 2026, as a simulation with - no reform does once its 2026 input is gone. Before, the record took the - 2025 input as following the kept ones, and the arm set the replaced $700 - for 2026.""" - simulations = [ - Microsimulation( - dataset=dataset( - (NEW_YORK,), FAMILIES, yearly_subsidies=TWO_YEARS, weights=(0, 1) - ), - reform=reform, - ) - for reform in (None, StoreSubsidiesForAllTime) - ] - for simulation in simulations: - simulation.get_holder(SUBSIDY).set_input(YEAR, np.array([800.0, 900.0])) - simulation.set_input(SUBSIDY, 2025, [450, 650]) - simulation.subsample(n=1) - plain, reformed = simulations - arm = reformed.baseline - for simulation in (plain, arm): - np.testing.assert_allclose(value(simulation, SUBSIDY, 2025), [650]) - np.testing.assert_allclose(value(plain, SUBSIDY, YEAR), [900]) - np.testing.assert_allclose(value(reformed, SUBSIDY, YEAR), [650]) - plain.delete_arrays(SUBSIDY, YEAR) - calculated = value(plain, SUBSIDY, YEAR) - assert calculated[0] not in (700, 900) - np.testing.assert_allclose(value(arm, SUBSIDY, YEAR), calculated, atol=TOLERANCE) - - -# Stored for all time, and defined only through 2025. Core names a variable -# after its class. -subsidies_for_all_time_until_2025 = type( - "child_care_subsidies", - (Variable,), - dict( - value_type=float, - entity=SPMUnit, - label="Child care subsidies", - definition_period=ETERNITY, - end="2025-12-31", - ), -) - - -class StoreSubsidiesForAllTimeUntil2025(Reform): - def apply(self): - self.update_variable(subsidies_for_all_time_until_2025) - - -def test_the_arm_sets_no_input_the_reform_did_not_store(): - """The reform's subsidy ends with 2025, so core stores the dataset's 2026 - subsidy nowhere. The arm sets the $400 for 2025 and calculates 2026, as a - simulation with no reform does without a 2026 input. Before, the record - kept what the holder stored, the 2025 subsidy, for 2026 as well, and the - arm set $400 there.""" - subsidies = {2025: [400], YEAR: [500]} - plain, reformed = [ - Microsimulation( - dataset=dataset((NEW_YORK,), FAMILIES[:1], yearly_subsidies=subsidies), - reform=reform, - ) - for reform in (None, StoreSubsidiesForAllTimeUntil2025) - ] - arm = reformed.baseline - np.testing.assert_allclose(value(arm, SUBSIDY, 2025), [400]) - plain.delete_arrays(SUBSIDY, YEAR) - calculated = value(plain, SUBSIDY, YEAR) - assert calculated[0] not in (400, 500) - np.testing.assert_allclose(value(arm, SUBSIDY, YEAR), calculated, atol=TOLERANCE) + assert simulation.calculate("household_id", YEAR).values.tolist() == [1] + calculated = value(plain, SUBSIDY) + assert calculated[0] > 500 + np.testing.assert_allclose(value(arm, SUBSIDY), calculated, atol=TOLERANCE) + np.testing.assert_allclose(value(reformed, SUBSIDY), [500]) -HEAD = "is_household_head" +STANDARD_DEDUCTION = Reform.from_dict( + {"gov.irs.deductions.standard.amount.SINGLE": {"2026-01-01.2100-12-31": 20_000}}, + country_id="us", +) -def heads(simulation, year=YEAR): - return np.asarray(simulation.calculate(HEAD, year, use_weights=False)).tolist() +def two_new_york_earners(): + """Two single earners in New York who each paid $500 for care. Only the + second weighs anything, and each has its own subsidy.""" + columns = { + "person_id": [0, 1], + **{f"{entity}_id": [0, 1] for entity in ("household", "tax_unit")}, + **{f"{entity}_id": [0, 1] for entity in ("spm_unit", "family")}, + "marital_unit_id": [0, 1], + f"age__{YEAR}": [40, 40], + f"employment_income__{YEAR}": [80_000, 80_000], + f"is_tax_unit_head__{YEAR}": [True, True], + f"is_household_head__{YEAR}": [True, True], + f"state_fips__{YEAR}": [NEW_YORK, NEW_YORK], + f"household_weight__{YEAR}": [0.0, 1.0], + f"{SUBSIDY}__{YEAR}": [100.0, 200.0], + f"spm_unit_pre_subsidy_childcare_expenses__{YEAR}": [500.0, 500.0], + } + return Dataset.from_dataframe(pd.DataFrame(columns), time_period=YEAR) -def test_the_arm_calculates_a_role_written_to_the_reform_holder(): - """Under the yearly reform, a write to the holder itself names the child - head in 2027, and both runs then name the parent head in 2025. The record - never saw the 2027 input, and baseline policy keeps only the role set - last, so the arm can't tell which input it would end with. It calculates - the role, through two subsamples, as a simulation with no reform does - with no role input. Before, the first subsample exported the 2027 input - after the kept ones, and the arm named the child head.""" - simulations = [ - Microsimulation(dataset=dataset((NEW_YORK,), FAMILIES[:1]), reform=reform) - for reform in (None, StoreHeadsEachYear) - ] - for simulation in simulations: - simulation.get_holder(HEAD).set_input(2027, np.array([False, True])) - simulation.set_input(HEAD, 2025, [True, False]) - plain, reformed = simulations - for _ in range(2): - for simulation in simulations: - simulation.subsample(n=1) - arm = reformed.baseline - assert_holders_suit_their_variables(arm) - assert heads(plain) == [True, False] - assert heads(arm) == [False, False] - assert heads(reformed, 2025) == [True, False] - assert heads(reformed, 2027) == [False, True] - plain.delete_arrays(HEAD) - assert heads(plain) == heads(arm) - - -def test_a_failed_subsample_leaves_no_export_behind(): - """Under the yearly reform, both runs name each child head in 2025, a - subsample fails before core rebuilds anything, and both then name each - parent head in 2025. A sample then reads the parent as head in the arm - and in 2025's reform, as in the simulation with no reform. Had the failed - subsample left its export in place, the reform would have kept the - child's 2025 role from it.""" - simulations = [ - Microsimulation( - dataset=dataset((NEW_YORK,), FAMILIES, weights=(0, 1)), reform=reform - ) - for reform in (None, StoreHeadsEachYear) - ] - for simulation in simulations: - simulation.set_input(HEAD, 2025, [False, True, False, True]) - plain, reformed = simulations - with pytest.raises(ValueError, match="Either n or frac"): - reformed.subsample() - for simulation in simulations: - simulation.set_input(HEAD, 2025, [True, False, True, False]) - simulation.subsample(n=1) - arm = reformed.baseline - assert heads(plain) == [True, False] - assert heads(arm) == [True, False] - assert heads(reformed, 2025) == [True, False] +def test_a_subsampled_branch_reads_an_arm_on_its_own_sample(): + """A branch shares its parent's arm, and core rebuilds only the arm a + simulation holds in ``branches["baseline"]``. So a branch that + subsampled kept the parent's arm, on both households, and the dataset + rule, which reads S0 from that arm, raised on the size mismatch. Now the + branch reads an arm on its own sample and gets the expense a subsample + of the reform itself gets, $500, while the parent keeps its arm.""" + top = Microsimulation(dataset=two_new_york_earners(), reform=STANDARD_DEDUCTION) + top.subsample(n=1, seed=0) + expected = value(top, EXPENSE) + np.testing.assert_allclose(expected, [500]) + + parent = Microsimulation(dataset=two_new_york_earners(), reform=STANDARD_DEDUCTION) + arm = parent.baseline + branch = parent.get_branch("trial") + assert branch.baseline is arm + branch.subsample(n=1, seed=0) + own_arm = branch.baseline + assert own_arm is not arm + assert own_arm is branch.branches["baseline"] + assert own_arm.baseline is None + assert own_arm.tax_benefit_system.simulation is own_arm + np.testing.assert_allclose(value(own_arm, SUBSIDY), [200]) + np.testing.assert_allclose(value(branch, EXPENSE), expected) + + assert parent.baseline is arm + assert arm.tax_benefit_system.simulation is arm + np.testing.assert_allclose(value(arm, SUBSIDY), [100, 200]) + np.testing.assert_allclose(value(parent, EXPENSE), [500, 500]) From da87caeb3e809f2eadd67e965313d9cf247bc891 Mon Sep 17 00:00:00 2001 From: Max Ghenis Date: Wed, 25 Nov 2026 21:41:23 +0100 Subject: [PATCH 23/42] Test that no shipped reform stores a variable apart from baseline policy The arm's drop, and the guard that refuses an input it drops, matter only under a reform that redefines a variable in another entity or with other ETERNITY storage. A static scan of policyengine_us/reforms, which imports nothing, finds no such reform, and fails on any variable change it can't resolve to a class in the same file. A second test checks that the scan flags the reforms the tests build for that purpose. Co-Authored-By: Claude Opus 5.5 --- ...shipped_reforms_store_no_variable_apart.py | 149 ++++++++++++++++++ 1 file changed, 149 insertions(+) create mode 100644 policyengine_us/tests/core/test_shipped_reforms_store_no_variable_apart.py diff --git a/policyengine_us/tests/core/test_shipped_reforms_store_no_variable_apart.py b/policyengine_us/tests/core/test_shipped_reforms_store_no_variable_apart.py new file mode 100644 index 00000000000..c7535309a02 --- /dev/null +++ b/policyengine_us/tests/core/test_shipped_reforms_store_no_variable_apart.py @@ -0,0 +1,149 @@ +"""No shipped reform stores a variable apart from baseline policy. + +A reform's baseline arm drops each holder the reform built for its own +definition of a variable in another entity or with other ``ETERNITY`` +storage, and refuses an input the caller gave that variable +(``SPMSimulationMixin._refuse_inputs_baseline_policy_drops``). Only a reform +that redefines a variable that way reaches either path. This scan reads the +source of every reform under ``policyengine_us/reforms``, without importing +the package, and finds none that does. A new reform that changes a variable's +entity or all-time storage fails it, and so does one that passes +``update_variable``, ``add_variable`` or ``replace_variable`` anything other +than a class defined in its own file. + +A reform's class that leaves out ``entity`` or ``definition_period`` keeps +the baseline variable's, so a missing attribute counts as unchanged. The +second test checks that the scan flags the reforms this package's tests build +to store a variable apart. +""" + +import ast +import re +from functools import cache +from pathlib import Path + +PACKAGE = Path(__file__).resolve().parents[2] +ATTRIBUTES = ("entity", "definition_period") +CHANGES = re.compile( + r"\.(update_variable|add_variable|replace_variable)\(\s*([A-Za-z_][A-Za-z0-9_]*)" +) + + +def named(node): + """An entity or period expression as a name, or None if it isn't one.""" + if isinstance(node, ast.Constant) and isinstance(node.value, str): + # Core accepts "year" and "eternity" as well as YEAR and ETERNITY. + return node.value.upper() + if isinstance(node, ast.Name): + return node.id + if isinstance(node, ast.Attribute): + return node.attr + return None + + +def variable_classes(path): + """Each Variable class in ``path``, with the attributes its body sets. + + A class counts if it subclasses ``Variable`` or a baseline variable the + file imports from ``policyengine_us.variables``.""" + tree = ast.parse(path.read_text(), filename=str(path)) + baseline_names = { + alias.asname or alias.name + for node in ast.walk(tree) + if isinstance(node, ast.ImportFrom) + and (node.module or "").startswith("policyengine_us.variables") + for alias in node.names + } + for node in ast.walk(tree): + if not isinstance(node, ast.ClassDef): + continue + bases = { + base.id if isinstance(base, ast.Name) else getattr(base, "attr", None) + for base in node.bases + } + if "Variable" not in bases and not bases & baseline_names: + continue + attributes = {} + for statement in node.body: + if isinstance(statement, ast.Assign): + for target in statement.targets: + if isinstance(target, ast.Name) and target.id in ATTRIBUTES: + attributes[target.id] = statement.value + yield node.name, attributes, node.lineno + + +@cache +def baseline_variables(): + found = {} + for path in sorted((PACKAGE / "variables").rglob("*.py")): + for name, attributes, _ in variable_classes(path): + found[name] = {key: named(value) for key, value in attributes.items()} + return found + + +def stored_apart(files): + """The classes in ``files`` that redefine a baseline variable in another + entity or with other all-time storage, and the comparisons the scan + can't make.""" + baseline = baseline_variables() + apart, unresolved = [], [] + for path in files: + for name, attributes, line in variable_classes(path): + if name not in baseline: + continue + where = f"{name} ({path.relative_to(PACKAGE.parent)}:{line})" + for key, value in attributes.items(): + mine, theirs = named(value), baseline[name].get(key) + if mine is None or theirs is None: + unresolved.append(f"{where}: {key}") + elif key == "entity" and mine != theirs: + apart.append((name, where)) + elif key == "definition_period" and (mine == "ETERNITY") != ( + theirs == "ETERNITY" + ): + apart.append((name, where)) + return apart, unresolved + + +def changes_the_scan_cannot_see(files): + """Variable changes whose argument isn't a class defined in the same file, + or a loop variable over such classes.""" + found = [] + for path in files: + text = path.read_text() + defined = {name for name, _, _ in variable_classes(path)} + for node in ast.walk(ast.parse(text)): + if ( + isinstance(node, ast.For) + and isinstance(node.target, ast.Name) + and isinstance(node.iter, (ast.Tuple, ast.List)) + and all( + isinstance(element, ast.Name) and element.id in defined + for element in node.iter.elts + ) + ): + defined.add(node.target.id) + for match in CHANGES.finditer(text): + if match.group(2) not in defined: + found.append( + f"{match.group(1)}({match.group(2)}) in " + f"{path.relative_to(PACKAGE.parent)}" + ) + return found + + +def test_no_shipped_reform_stores_a_variable_apart_from_baseline_policy(): + reforms = sorted((PACKAGE / "reforms").rglob("*.py")) + assert len(reforms) > 100 + apart, unresolved = stored_apart(reforms) + assert apart == [] + assert unresolved == [] + assert changes_the_scan_cannot_see(reforms) == [] + + +def test_the_scan_flags_reforms_built_to_store_a_variable_apart(): + tests = PACKAGE / "tests" / "core" + apart, _ = stored_apart( + [tests / "test_reform_baseline_arm_inputs.py", tests / "test_spm_system.py"] + ) + assert {"child_care_subsidies", "is_household_head"} <= {name for name, _ in apart} From 61baf5dcf46da20cd0f66b40bf3cc07e7d9a6f91 Mon Sep 17 00:00:00 2001 From: Max Ghenis Date: Wed, 25 Nov 2026 21:41:23 +0100 Subject: [PATCH 24/42] Pin the household rule's childcare_expenses precedence in YAML For a unit with a child the household rule reads childcare_expenses, so a caller who gives only that amount, $6,000, gets it as the expense; main's formula read only the pre-subsidy amount and gave $0. A unit with no child ignores childcare_expenses and nets its subsidy from its own pre-subsidy amount. Co-Authored-By: Claude Opus 5.5 --- ...m_unit_capped_work_childcare_expenses.yaml | 50 +++++++++++++++++++ 1 file changed, 50 insertions(+) diff --git a/policyengine_us/tests/policy/baseline/household/expense/childcare/spm_unit_capped_work_childcare_expenses.yaml b/policyengine_us/tests/policy/baseline/household/expense/childcare/spm_unit_capped_work_childcare_expenses.yaml index 0c7d4b1ce85..3559d463999 100644 --- a/policyengine_us/tests/policy/baseline/household/expense/childcare/spm_unit_capped_work_childcare_expenses.yaml +++ b/policyengine_us/tests/policy/baseline/household/expense/childcare/spm_unit_capped_work_childcare_expenses.yaml @@ -225,6 +225,56 @@ output: spm_unit_capped_work_childcare_expenses: 6_000 +- name: A unit with a child that gives only an out-of-pocket amount counts it + period: 2026 + absolute_error_margin: 0.001 + input: + people: + head: + age: 30 + employment_income: 30_000 + is_household_head: true + is_tax_unit_head: true + child: + age: 3 + is_tax_unit_dependent: true + tax_units: + tax_unit: + members: [head, child] + spm_units: + spm_unit: + members: [head, child] + spm_unit_work_expenses: 0 + childcare_expenses: 6_000 + output: + # The pre-subsidy amount is left at 0. Main's formula read only that + # amount, so it gave 0 here. + spm_unit_capped_work_childcare_expenses: 6_000 + +- name: A unit with no child ignores an out-of-pocket amount + period: 2026 + absolute_error_margin: 0.001 + input: + people: + head: + age: 46 + employment_income: 9_000 + is_household_head: true + is_tax_unit_head: true + tax_units: + tax_unit: + members: [head] + spm_units: + spm_unit: + members: [head] + spm_unit_work_expenses: 0 + spm_unit_pre_subsidy_childcare_expenses: 4_000 + child_care_subsidies: 1_500 + childcare_expenses: 6_000 + output: + # 4,000 - 1,500; the 6,000 is ignored. + spm_unit_capped_work_childcare_expenses: 2_500 + - name: A subsidy lowers the expense in 2024, the formula's first year period: 2024 absolute_error_margin: 0.001 From 94a0cb665f9db148047b6494dda0b5f1c76518f7 Mon Sep 17 00:00:00 2001 From: Max Ghenis Date: Wed, 25 Nov 2026 21:42:15 +0100 Subject: [PATCH 25/42] Pin the household rule's floor for a unit with no child A unit with no child nets its subsidy from its own pre-subsidy amount, and no case had a subsidy above that amount. Add one: $1,500 against $1,000 leaves only the $500 of work expenses. Co-Authored-By: Claude Opus 5.5 --- ...m_unit_capped_work_childcare_expenses.yaml | 24 +++++++++++++++++++ 1 file changed, 24 insertions(+) diff --git a/policyengine_us/tests/policy/baseline/household/expense/childcare/spm_unit_capped_work_childcare_expenses.yaml b/policyengine_us/tests/policy/baseline/household/expense/childcare/spm_unit_capped_work_childcare_expenses.yaml index 3559d463999..5ec5478e40e 100644 --- a/policyengine_us/tests/policy/baseline/household/expense/childcare/spm_unit_capped_work_childcare_expenses.yaml +++ b/policyengine_us/tests/policy/baseline/household/expense/childcare/spm_unit_capped_work_childcare_expenses.yaml @@ -199,6 +199,30 @@ output: spm_unit_capped_work_childcare_expenses: 2_500 +- name: A subsidy above the expense of a unit with no child leaves only work expenses + period: 2026 + absolute_error_margin: 0.001 + input: + people: + head: + age: 46 + employment_income: 9_000 + is_household_head: true + is_tax_unit_head: true + tax_units: + tax_unit: + members: [head] + spm_units: + spm_unit: + members: [head] + spm_unit_work_expenses: 500 + spm_unit_pre_subsidy_childcare_expenses: 1_000 + child_care_subsidies: 1_500 + output: + # The floor keeps the 500 of subsidy above the expense from offsetting + # work expenses. + spm_unit_capped_work_childcare_expenses: 500 + - name: A direct out-of-pocket amount replaces the amount net of subsidies period: 2026 absolute_error_margin: 0.001 From 2611629985c4c53bbcd69670ded34331bb39471f Mon Sep 17 00:00:00 2001 From: Max Ghenis Date: Wed, 25 Nov 2026 22:41:30 +0100 Subject: [PATCH 26/42] Test that the rebuild drops a reform's empty holder from the arm With the guard in place, the rebuild's drop matters only for a holder the reform built for its own definition of a variable that holds no recorded input. No test reached it: with the drop removed, the guard's-limit test and main's subsampling test stayed green. The guard's-limit test's docstring, and the message of the commit that added it, said its first assertion reached the drop; under that reform construction leaves no subsidy holder at all, so it doesn't. Construction's input move asks the reform for the holder of sstb_self_employment_income even where the caller gave none. Under a reform that stores that variable for all time, the reform then holds an empty holder for all time, which the arm copies when it branches after the moves. The new test checks that the rebuild's drop keeps that holder out of the arm. The guard's-limit docstring loses its wrong sentence. Co-Authored-By: Claude Opus 5.5 --- .../core/test_reform_baseline_arm_inputs.py | 41 +++++++++++++++++-- 1 file changed, 37 insertions(+), 4 deletions(-) diff --git a/policyengine_us/tests/core/test_reform_baseline_arm_inputs.py b/policyengine_us/tests/core/test_reform_baseline_arm_inputs.py index 46b9757fc75..60dbad3876f 100644 --- a/policyengine_us/tests/core/test_reform_baseline_arm_inputs.py +++ b/policyengine_us/tests/core/test_reform_baseline_arm_inputs.py @@ -42,7 +42,7 @@ from policyengine_core.variables import Variable from policyengine_us import Microsimulation, Simulation -from policyengine_us.entities import SPMUnit +from policyengine_us.entities import Person, SPMUnit YEAR = 2026 TOLERANCE = 0.01 @@ -324,9 +324,7 @@ def test_an_input_set_after_construction_is_calculated_after_a_subsample(): construction the reform gets a $500 subsidy, which it stores for all time. Its arm never sees an input set after construction, and the subsample raises nothing: core drops the reform's holder from the arm it - builds, so that arm calculates the subsidy, as on main. Construction's - rebuild first drops the reform's empty holder for all time from the - arm.""" + builds, so that arm calculates the subsidy, as on main.""" families = (FAMILIES[1], FAMILIES[0]) simulations = [ Microsimulation( @@ -350,6 +348,41 @@ def test_an_input_set_after_construction_is_calculated_after_a_subsample(): np.testing.assert_allclose(value(reformed, SUBSIDY), [500]) +SSTB_INCOME = "sstb_self_employment_income" + + +class sstb_self_employment_income(Variable): + # Stored for all time, where baseline policy stores it each year. + value_type = float + entity = Person + label = "SSTB self-employment income" + definition_period = ETERNITY + + +class StoreSSTBIncomeForAllTime(Reform): + def apply(self): + self.update_variable(sstb_self_employment_income) + + +def test_the_rebuild_drops_a_holder_the_reform_built_with_no_input(): + """Construction moves ``sstb_self_employment_income`` to its pre-response + variable, so it asks the reform for that variable's holder even where the + caller gave no input. Under a reform that stores the variable for all + time, the reform then holds an empty holder for all time, and the arm + branched after the moves copies it. With no input recorded, the guard has + nothing to refuse, so the rebuild's own drop keeps that holder out of the + arm.""" + reformed = Microsimulation( + dataset=dataset((NEW_YORK,), FAMILIES[:1]), reform=StoreSSTBIncomeForAllTime + ) + holder = reformed.populations["person"]._holders.get(SSTB_INCOME) + assert holder is not None and holder._memory_storage.is_eternal + assert SSTB_INCOME not in {key[0] for key in reformed._user_input_keys} + arm = reformed.baseline + assert SSTB_INCOME not in arm.populations["person"]._holders + assert_holders_suit_their_variables(arm) + + STANDARD_DEDUCTION = Reform.from_dict( {"gov.irs.deductions.standard.amount.SINGLE": {"2026-01-01.2100-12-31": 20_000}}, country_id="us", From ef189c4deaf04d5177a5cb77e4578a550f07add3 Mon Sep 17 00:00:00 2001 From: Max Ghenis Date: Thu, 26 Nov 2026 00:17:34 +0100 Subject: [PATCH 27/42] Pin that members' pre-subsidy amounts replace the unit's in the household rule For a unit with a child, the household rule reads childcare_expenses, which sums the members' pre_subsidy_childcare_expenses less the subsidy. A caller who gives a member's amount directly therefore replaces the unit's spm_unit_pre_subsidy_childcare_expenses with the members' sum. The new case gives the unit $10,000, the child $6,000, no subsidy, $1,000 of work expenses and a $20,000 cap, and expects $7,000. Main's formula read only the unit's amount and gave $11,000. No code change. Co-Authored-By: Claude Opus 5.5 --- ...m_unit_capped_work_childcare_expenses.yaml | 30 +++++++++++++++++++ 1 file changed, 30 insertions(+) diff --git a/policyengine_us/tests/policy/baseline/household/expense/childcare/spm_unit_capped_work_childcare_expenses.yaml b/policyengine_us/tests/policy/baseline/household/expense/childcare/spm_unit_capped_work_childcare_expenses.yaml index 5ec5478e40e..4bfc9ff74c9 100644 --- a/policyengine_us/tests/policy/baseline/household/expense/childcare/spm_unit_capped_work_childcare_expenses.yaml +++ b/policyengine_us/tests/policy/baseline/household/expense/childcare/spm_unit_capped_work_childcare_expenses.yaml @@ -299,6 +299,36 @@ # 4,000 - 1,500; the 6,000 is ignored. spm_unit_capped_work_childcare_expenses: 2_500 +- name: A member's pre-subsidy amount replaces the unit's for a unit with a child + period: 2026 + absolute_error_margin: 0.001 + input: + people: + head: + age: 30 + employment_income: 30_000 + is_household_head: true + is_tax_unit_head: true + child: + age: 3 + is_tax_unit_dependent: true + pre_subsidy_childcare_expenses: 6_000 + tax_units: + tax_unit: + members: [head, child] + spm_units: + spm_unit: + members: [head, child] + spm_unit_work_expenses: 1_000 + spm_unit_head_spouse_earned_cap: 20_000 + spm_unit_pre_subsidy_childcare_expenses: 10_000 + child_care_subsidies: 0 + output: + # childcare_expenses sums the members' pre-subsidy amounts, so the child's + # 6,000 replaces the unit's 10,000: 1,000 + 6,000. Main's formula read the + # unit's amount and gave 1,000 + 10,000 = 11,000. + spm_unit_capped_work_childcare_expenses: 7_000 + - name: A subsidy lowers the expense in 2024, the formula's first year period: 2024 absolute_error_margin: 0.001 From 7da15aca0fc01e2773bfe434e97f8b3ccdc629ac Mon Sep 17 00:00:00 2001 From: Max Ghenis Date: Thu, 26 Nov 2026 00:17:34 +0100 Subject: [PATCH 28/42] Read annotated assignments in the static reach test The scan read only plain assignments, so a reform class that declared `definition_period: str = ETERNITY` escaped it. It now also reads an annotated assignment with a value and a plain name target. The module docstring lists the forms it still doesn't read. A new positive control writes such a class to a temporary file and checks the scan flags it; the path label now falls back to the full path for a file outside the package. No class under policyengine_us/variables, reforms or tests uses the annotated form, so the shipped-reform result doesn't change. Co-Authored-By: Claude Opus 5.5 --- ...shipped_reforms_store_no_variable_apart.py | 54 ++++++++++++++++--- 1 file changed, 46 insertions(+), 8 deletions(-) diff --git a/policyengine_us/tests/core/test_shipped_reforms_store_no_variable_apart.py b/policyengine_us/tests/core/test_shipped_reforms_store_no_variable_apart.py index c7535309a02..d8cf59cf3ec 100644 --- a/policyengine_us/tests/core/test_shipped_reforms_store_no_variable_apart.py +++ b/policyengine_us/tests/core/test_shipped_reforms_store_no_variable_apart.py @@ -12,9 +12,18 @@ than a class defined in its own file. A reform's class that leaves out ``entity`` or ``definition_period`` keeps -the baseline variable's, so a missing attribute counts as unchanged. The -second test checks that the scan flags the reforms this package's tests build -to store a variable apart. +the baseline variable's, so a missing attribute counts as unchanged. The scan +reads two forms at the top level of a class body: a plain assignment +(``definition_period = ETERNITY``) and an annotated one with a value +(``definition_period: str = ETERNITY``). It doesn't read a tuple target +(``entity, definition_period = ...``), an augmented assignment, an assignment +inside an ``if`` or a loop in the class body, an attribute set on the class +after its ``class`` statement or through ``setattr``, or an attribute the +class inherits from a base other than ``Variable`` or a baseline variable. + +The second test checks that the scan flags the reforms this package's tests +build to store a variable apart, and the third that it reads the annotated +form. """ import ast @@ -69,9 +78,23 @@ def variable_classes(path): for target in statement.targets: if isinstance(target, ast.Name) and target.id in ATTRIBUTES: attributes[target.id] = statement.value + elif ( + isinstance(statement, ast.AnnAssign) + and statement.value is not None + and isinstance(statement.target, ast.Name) + and statement.target.id in ATTRIBUTES + ): + attributes[statement.target.id] = statement.value yield node.name, attributes, node.lineno +def label(path): + """``path`` from the repository root, or in full outside it.""" + if path.is_relative_to(PACKAGE.parent): + return path.relative_to(PACKAGE.parent) + return path + + @cache def baseline_variables(): found = {} @@ -91,7 +114,7 @@ def stored_apart(files): for name, attributes, line in variable_classes(path): if name not in baseline: continue - where = f"{name} ({path.relative_to(PACKAGE.parent)}:{line})" + where = f"{name} ({label(path)}:{line})" for key, value in attributes.items(): mine, theirs = named(value), baseline[name].get(key) if mine is None or theirs is None: @@ -125,10 +148,7 @@ def changes_the_scan_cannot_see(files): defined.add(node.target.id) for match in CHANGES.finditer(text): if match.group(2) not in defined: - found.append( - f"{match.group(1)}({match.group(2)}) in " - f"{path.relative_to(PACKAGE.parent)}" - ) + found.append(f"{match.group(1)}({match.group(2)}) in {label(path)}") return found @@ -147,3 +167,21 @@ def test_the_scan_flags_reforms_built_to_store_a_variable_apart(): [tests / "test_reform_baseline_arm_inputs.py", tests / "test_spm_system.py"] ) assert {"child_care_subsidies", "is_household_head"} <= {name for name, _ in apart} + + +def test_the_scan_reads_an_annotated_assignment(tmp_path): + """``definition_period: str = ETERNITY`` sets the class attribute as the + plain assignment does, so the scan flags a reform that stores + ``child_care_subsidies`` for all time that way.""" + reform = tmp_path / "annotated_reform.py" + reform.write_text( + "from policyengine_core.periods import ETERNITY\n" + "from policyengine_core.variables import Variable\n" + "\n" + "\n" + "class child_care_subsidies(Variable):\n" + " definition_period: str = ETERNITY\n" + ) + apart, unresolved = stored_apart([reform]) + assert [name for name, _ in apart] == ["child_care_subsidies"] + assert unresolved == [] From 30660daff615865ee85104eb319e47169248f895 Mon Sep 17 00:00:00 2001 From: Max Ghenis Date: Thu, 26 Nov 2026 00:17:35 +0100 Subject: [PATCH 29/42] Correct the empty-holder comment in the subsampling test The comment said the redefining reform gets an empty yearly is_household_head holder that the rebuilt arm must drop. On this test's own path, after construction neither the reform nor its arm holds a holder for is_household_head, with or without the rebuild's drop, so the check before subsampling passes either way. The comment now says so and names the arm test that pins the rebuild's drop. No assertion changes. Co-Authored-By: Claude Opus 5.5 --- policyengine_us/tests/core/test_spm_system.py | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/policyengine_us/tests/core/test_spm_system.py b/policyengine_us/tests/core/test_spm_system.py index 9f863865e12..e95a9e14521 100644 --- a/policyengine_us/tests/core/test_spm_system.py +++ b/policyengine_us/tests/core/test_spm_system.py @@ -874,9 +874,11 @@ def test_subsampling_never_changes_which_policy_a_holder_belongs_to( reform=SUBSAMPLED_REFORMS[reform], spm={"geography_kind": "national"}, ) - # Core lists input variables by asking for every variable's holder, so the - # redefining reform gets an empty yearly holder for is_household_head. The - # arm branched after the moves copies it and must drop it. + # The dataset gives no is_household_head, and after construction neither + # the reform nor its arm holds a holder for it, with or without the + # rebuild's drop. So this checks that both arms start bound to their own + # policy; test_the_rebuild_drops_a_holder_the_reform_built_with_no_input, + # in tests/core/test_reform_baseline_arm_inputs.py, pins that drop. for simulation in (changed, changed.baseline): assert_bound_to_own_policy(simulation) policies = { From 23b81c588fd367e20352e418f515efdfb9d4924b Mon Sep 17 00:00:00 2001 From: Max Ghenis Date: Thu, 26 Nov 2026 10:43:42 +0100 Subject: [PATCH 30/42] Give a branch's subsample the arm wherever its baseline entry is another branch Core rebuilds a subsample's baseline arm from branches["baseline"]. A branch shares its parent's arm and usually holds nothing under that name, so subsample put a copy of the arm there. Where the caller had named one of the branch's calculation branches "baseline", subsample skipped the copy, and core rebuilt the arm from that branch under the reform's policy. subsample now puts the copy in place wherever self.baseline is set and branches["baseline"] is anything other than that arm. If core's subsample raises while the copy is still in place, subsample puts back what the branch held before (nothing, or the same calculation branch) and re-raises. Tests: under a repeal of child care subsidies, a branch that named a calculation branch "baseline" reads S0 of $6,000 and an expense of $12,000 after a subsample, as a subsample of the reform itself does, and the parent keeps its arm on both households. A subsample given neither n nor frac leaves each branch as it found it, sharing the parent's arm, and a retry reads the same S0 and expense. Co-Authored-By: Claude Opus 5.5 --- policyengine_us/spm.py | 31 +++++-- .../core/test_reform_baseline_arm_inputs.py | 91 ++++++++++++++++++- 2 files changed, 114 insertions(+), 8 deletions(-) diff --git a/policyengine_us/spm.py b/policyengine_us/spm.py index c9dd455dfe6..129e36c5795 100644 --- a/policyengine_us/spm.py +++ b/policyengine_us/spm.py @@ -1175,13 +1175,30 @@ def _simulation_family(self): def subsample(self, *args, **kwargs): inherited = getattr(self, "baseline", None) - if inherited is not None and "baseline" not in self.branches: - # A branch shares its parent's baseline arm, on the parent's - # population, and core rebuilds an arm only from - # ``branches["baseline"]``. Hand core a copy of the arm, whose - # policy it gives the arm it builds on this branch's sample. - self.branches["baseline"] = inherited.clone(clone_tax_benefit_system=False) - result = super().subsample(*args, **kwargs) + had_entry = "baseline" in self.branches + previous = self.branches.get("baseline") + arm_copy = None + if inherited is not None and previous is not inherited: + # Core rebuilds an arm only from ``branches["baseline"]``. A branch + # shares its parent's arm, on the parent's population, and holds + # nothing there or something other than its arm, such as a + # calculation branch the caller named "baseline". Hand core a copy + # of the arm, whose policy it gives the arm it builds on this + # branch's sample. Core's subsample drops every other calculation + # branch, and this drops whatever the copy replaces. + arm_copy = inherited.clone(clone_tax_benefit_system=False) + self.branches["baseline"] = arm_copy + try: + result = super().subsample(*args, **kwargs) + except BaseException: + # Where core raises with the copy still in place, put back what + # the branch held before, and leave the rest as core left it. + if arm_copy is not None and self.branches.get("baseline") is arm_copy: + if had_entry: + self.branches["baseline"] = previous + else: + del self.branches["baseline"] + raise baseline = self.branches.get("baseline") if baseline is not None: # Core rebuilds the baseline arm by branching this simulation, so diff --git a/policyengine_us/tests/core/test_reform_baseline_arm_inputs.py b/policyengine_us/tests/core/test_reform_baseline_arm_inputs.py index 60dbad3876f..5c44cc79649 100644 --- a/policyengine_us/tests/core/test_reform_baseline_arm_inputs.py +++ b/policyengine_us/tests/core/test_reform_baseline_arm_inputs.py @@ -23,7 +23,10 @@ reform, each holder in either arm suits that arm's definition of its variable. Under a reform that stores a variable apart from baseline policy, an input given for it at construction, through a dataset or a situation, raises by -name. A branch that subsamples reads an arm built on its own sample. +name. A branch that subsamples reads an arm built on its own sample, under +baseline policy, even where the caller named one of its calculation branches +"baseline". A subsample that raises before core rebuilds the arm leaves what +the branch held under that name as it was. One limit is pinned here too. Where core builds the arm, in ``subsample``, it has already dropped such a holder and its recorded inputs, so an input set @@ -438,3 +441,89 @@ def test_a_subsampled_branch_reads_an_arm_on_its_own_sample(): assert arm.tax_benefit_system.simulation is arm np.testing.assert_allclose(value(arm, SUBSIDY), [100, 200]) np.testing.assert_allclose(value(parent, EXPENSE), [500, 500]) + + +REPEAL = Reform.from_dict( + {"gov.abolitions.child_care_subsidies": {"2026-01-01.2026-12-31": True}}, + country_id="us", +) +# What a subsample of the reform itself reads under REPEAL, keeping the second +# New York family: S0, and the expense, $6,000 reported plus the $6,000 lost. +SAMPLED_S0 = [6_000] +SAMPLED_EXPENSE = [12_000] + + +def new_york_families(): + """Both New York families. Only the second weighs anything.""" + return dataset((NEW_YORK,), FAMILIES, weights=(0, 1)) + + +def repeals_the_subsidy(simulation): + parameters = simulation.tax_benefit_system.parameters(f"{YEAR}-01-01") + return bool(parameters.gov.abolitions.child_care_subsidies) + + +def households(simulation): + return simulation.calculate("household_id", YEAR).values.tolist() + + +def test_a_branch_named_baseline_gives_way_to_the_arm_in_a_subsample(): + """Core rebuilds the arm from ``branches["baseline"]``. So where the + caller had named one of a branch's calculation branches "baseline", the + branch's subsample built its new arm from that one, under the reform: + with the subsidy repealed, S0 read $0 and the expense $6,000. Now the + subsample hands core a copy of the arm in its place, and the branch + reads what a subsample of the reform itself reads. The parent keeps its + arm, on both households.""" + top = Microsimulation(dataset=new_york_families(), reform=REPEAL) + top.subsample(n=1, seed=0) + assert households(top) == [1] + np.testing.assert_allclose(value(top, SUBSIDY), [0]) + np.testing.assert_allclose(value(top.baseline, SUBSIDY), SAMPLED_S0) + np.testing.assert_allclose(value(top, EXPENSE), SAMPLED_EXPENSE) + + parent = Microsimulation(dataset=new_york_families(), reform=REPEAL) + arm = parent.baseline + trial = parent.get_branch("trial") + named = trial.get_branch("baseline") + assert trial.baseline is arm and named is not arm + trial.subsample(n=1, seed=0) + own_arm = trial.baseline + assert own_arm is trial.branches["baseline"] + assert own_arm is not arm and own_arm is not named + assert repeals_the_subsidy(trial) and not repeals_the_subsidy(own_arm) + assert households(trial) == households(own_arm) == [1] + np.testing.assert_allclose(value(own_arm, SUBSIDY), SAMPLED_S0) + np.testing.assert_allclose(value(trial, EXPENSE), SAMPLED_EXPENSE) + + assert parent.baseline is arm + assert households(arm) == [0, 1] + + +def test_a_failed_branch_subsample_leaves_the_branch_as_it_found_it(): + """Core's subsample raises before it samples anything when given neither + ``n`` nor ``frac``. The branch then keeps what it held under "baseline": + nothing, for a branch that shares its parent's arm, or the calculation + branch the caller named "baseline", the same object. Each branch still + shares the parent's arm, and a retry reads what a subsample of the + reform itself reads.""" + parent = Microsimulation(dataset=new_york_families(), reform=REPEAL) + arm = parent.baseline + plain = parent.get_branch("plain") + trial = parent.get_branch("trial") + named = trial.get_branch("baseline") + for branch in (plain, trial): + with pytest.raises(ValueError, match="Either n or frac must be provided"): + branch.subsample() + assert branch.baseline is arm + assert "baseline" not in plain.branches + assert trial.branches["baseline"] is named + + for branch in (plain, trial): + branch.subsample(n=1, seed=0) + assert branch.baseline is not arm + assert households(branch) == households(branch.baseline) == [1] + np.testing.assert_allclose(value(branch.baseline, SUBSIDY), SAMPLED_S0) + np.testing.assert_allclose(value(branch, EXPENSE), SAMPLED_EXPENSE) + assert parent.baseline is arm + assert households(arm) == [0, 1] From c9e7e1484f7a4de31945bf9da0db10864a373725 Mon Sep 17 00:00:00 2001 From: Max Ghenis Date: Thu, 26 Nov 2026 10:43:42 +0100 Subject: [PATCH 31/42] Align #10975's subsampled-branch tests with a branch's own baseline A subsampled branch now gets a baseline of its own on the same sample. So test_a_subsampled_branch_matches_its_baseline_by_person and test_a_subsampled_branch_finds_its_person_among_repeated_axis_ids check that the branch's baseline holds the same people as the branch, by count and by ID, in place of the parent's unsampled count. Their value assertions are unchanged. The axes test drops its NotImplementedError arm for a kept ID the parent repeats: identical ID lists align by position, so that arm no longer describes the code, and the test's seed keeps an ID the parent has once. for_each_person's docstring now says a subsampled branch aligns by position, and that the ID lookup serves a baseline that lists other people, as after a branch subsample that raised once core had resampled the branch. Its code is unchanged. Co-Authored-By: Claude Opus 5.5 --- .../test_employer_payroll_tax_incidence.py | 49 +++++++++---------- ..._payroll_tax_fixed_employer_cost_change.py | 17 ++++--- 2 files changed, 34 insertions(+), 32 deletions(-) diff --git a/policyengine_us/tests/core/test_employer_payroll_tax_incidence.py b/policyengine_us/tests/core/test_employer_payroll_tax_incidence.py index 48403dc9a4d..d54503858b0 100644 --- a/policyengine_us/tests/core/test_employer_payroll_tax_incidence.py +++ b/policyengine_us/tests/core/test_employer_payroll_tax_incidence.py @@ -29,10 +29,10 @@ fica_pre_tax_contributions, so a supplied total counts in both, and neutralizing or abolishing it moves pay with the components unchanged, as do reforms that keep the list but limit the total to children or give - a listed contribution a formula. A branch that was subsampled matches its - ancestor's baseline by person ID, among the IDs the baseline has once, so - a person whose ID axes repeated raises by name, and a formula for the - total that reads employment income is refused with core's CycleError. + a listed contribution a formula. A branch that was subsampled gets a + baseline of its own on the same sample, so its people align by position, + and a formula for the total that reads employment income is refused with + core's CycleError. Abolishing a variable a federal employer tax is calculated from zeroes the rate of exactly the taxes calculated from it. Neutralizing one changes no rate, so it moves no wages, and an employer tax formula the @@ -1151,13 +1151,14 @@ def numbered_situation(year, people, states): @pytest.mark.parametrize("removal", ["employee_rate", "neutralized"]) def test_a_subsampled_branch_matches_its_baseline_by_person(removal): - """A branch keeps its ancestor's baseline, with all of its people. - - Subsampling the branch to one of two households leaves that baseline at - two people, so the baseline's FICA pre-tax total is read for the person - the sample kept, matched by ID. Under an employee-only reform the two - totals are equal and the change is zero; with the total neutralized, - pay falls by the employer tax on the kept worker's premiums. + """A subsampled branch gets a baseline of its own, with the same people. + + Subsampling the branch to one of two households builds its baseline on + the same sample, so the baseline holds the one person the sample kept, + under the same ID, and its FICA pre-tax total lines up with that person. + Under an employee-only reform the two totals are equal and the change is + zero; with the total neutralized, pay falls by the employer tax on the + kept worker's premiums. """ if removal == "employee_rate": reform = Reform.from_dict( @@ -1180,7 +1181,8 @@ def test_a_subsampled_branch_matches_its_baseline_by_person(removal): branch = simulation.get_branch("sampled") branch.subsample(n=1, seed="sampled", time_period=YEAR) assert branch.persons.count == 1 - assert branch.baseline.persons.count == 2 + assert branch.baseline.persons.count == 1 + np.testing.assert_array_equal(branch.baseline.persons.ids, branch.persons.ids) kept = str(branch.persons.ids[0]) pay = branch.calculate("employment_income", YEAR) if removal == "employee_rate": @@ -1238,17 +1240,19 @@ def axes_situation(person_ids): def test_a_subsampled_branch_finds_its_person_among_repeated_axis_ids(): - """Axes can give two people one ID; a subsampled branch matches by ID. + """Axes can give two people one ID; a subsampled branch lines up by position. With the FICA pre-tax total neutralized, each worker's pay falls by the employer tax on their premiums: (pay * 1.0765 - 0.0765 * premiums) / 1.0765. Before the subsample both simulations list the same IDs, so the repeated "110" aligns by position. A branch subsampled to one household - reads the baseline's total for the person it kept, by an ID the baseline - has once, or raises naming an ID the baseline repeats. The test accepts - either outcome, whichever household the seed keeps; + gets a baseline of its own on the same sample, with the same IDs, so its + people align by position too. Where the kept person's ID is one the + parent has once, their pay is checked against the parent's; an ID the + parent repeats can't say which person was kept, so the test then checks + only the baseline's people. test_people_match_by_position_or_by_an_id_the_baseline_has_once covers - each path directly. + the lookup by ID directly. """ simulation = Simulation( situation=axes_situation(["1", "11"]), reform=NeutralizeFicaTotal @@ -1271,16 +1275,11 @@ def test_a_subsampled_branch_finds_its_person_among_repeated_axis_ids(): ) branch = simulation.get_branch("sampled") branch.subsample(n=1, seed="axes-collision", time_period=YEAR) - assert branch.baseline.persons.count == len(ids) kept = [str(pid) for pid in branch.persons.ids] + assert branch.baseline.persons.count == len(kept) + assert [str(pid) for pid in branch.baseline.persons.ids] == kept repeated = [pid for pid in kept if ids.count(pid) > 1] - if repeated: - with pytest.raises( - NotImplementedError, - match=f"more than one person with ID '{repeated[0]}'", - ): - branch.calculate("employment_income", YEAR) - else: + if not repeated: np.testing.assert_allclose( branch.calculate("employment_income", YEAR), [pay[ids.index(pid)] for pid in kept], diff --git a/policyengine_us/variables/gov/simulation/employer_payroll_tax_incidence/employer_payroll_tax_fixed_employer_cost_change.py b/policyengine_us/variables/gov/simulation/employer_payroll_tax_incidence/employer_payroll_tax_fixed_employer_cost_change.py index 672a93c41d3..bc6db7092e0 100644 --- a/policyengine_us/variables/gov/simulation/employer_payroll_tax_incidence/employer_payroll_tax_fixed_employer_cost_change.py +++ b/policyengine_us/variables/gov/simulation/employer_payroll_tax_incidence/employer_payroll_tax_fixed_employer_cost_change.py @@ -340,13 +340,16 @@ def for_each_person(person, baseline_person, values): When both simulations list the same person IDs in the same order, they hold the same people, so values align by position, even where axes have - given two people one ID. Otherwise ``person`` belongs to a branch that - was subsampled: a branch shares its ancestor's baseline, and subsampling - the branch leaves that baseline's people in place. Core's ``subsample`` - keeps the rows of the chosen households (it selects them with ``isin``), - so each kept person appears once, with their ID, in their original - order, and a kept person's ID is unique in the baseline whenever the - ancestor's person IDs are. Axes can repeat a person ID, since they append + given two people one ID. A subsampled branch gets a baseline of its own + on the same sample, so it aligns by position too. Otherwise the baseline + lists other people than ``person``'s simulation, as where a branch's + subsample raised after core had resampled the branch but before it + rebuilt the baseline, and each person is looked up by ID. Where the + baseline stayed unsampled, core's ``subsample`` kept the rows of the + chosen households (it selects them with ``isin``), so each kept person + appears once, with their ID, in their original order, and a kept + person's ID is unique in the baseline whenever the ancestor's person IDs + are. Axes can repeat a person ID, since they append each cell's index to it (people "1" and "11" both get "110", in cells 10 and 0), so people are looked up only among the IDs the baseline has once. A person whose ID the baseline lacks or repeats raises From 1b9dec83169aef03d0f424e753f00248a7f1a309 Mon Sep 17 00:00:00 2001 From: Max Ghenis Date: Thu, 26 Nov 2026 10:43:42 +0100 Subject: [PATCH 32/42] Pin that one child's pre-subsidy amount replaces the unit's amount In a household situation, a person variable given for one member is an input for every member, and the members given none hold 0. So with the unit's $10,000, $6,000 given for one of two children, no subsidy, W of $1,000 and C of $20,000, the second child's pre-subsidy amount is 0, childcare_expenses is $6,000 and the expense $7,000, where main's formula gives $11,000. No code change. Co-Authored-By: Claude Opus 5.5 --- ...m_unit_capped_work_childcare_expenses.yaml | 37 +++++++++++++++++++ 1 file changed, 37 insertions(+) diff --git a/policyengine_us/tests/policy/baseline/household/expense/childcare/spm_unit_capped_work_childcare_expenses.yaml b/policyengine_us/tests/policy/baseline/household/expense/childcare/spm_unit_capped_work_childcare_expenses.yaml index 4bfc9ff74c9..48ee9b3ad5f 100644 --- a/policyengine_us/tests/policy/baseline/household/expense/childcare/spm_unit_capped_work_childcare_expenses.yaml +++ b/policyengine_us/tests/policy/baseline/household/expense/childcare/spm_unit_capped_work_childcare_expenses.yaml @@ -329,6 +329,43 @@ # unit's amount and gave 1,000 + 10,000 = 11,000. spm_unit_capped_work_childcare_expenses: 7_000 +- name: A pre-subsidy amount given for one of two children replaces the unit's amount + period: 2026 + absolute_error_margin: 0.001 + input: + people: + head: + age: 30 + employment_income: 30_000 + is_household_head: true + is_tax_unit_head: true + first_child: + age: 3 + is_tax_unit_dependent: true + pre_subsidy_childcare_expenses: 6_000 + second_child: + age: 5 + is_tax_unit_dependent: true + tax_units: + tax_unit: + members: [head, first_child, second_child] + spm_units: + spm_unit: + members: [head, first_child, second_child] + spm_unit_work_expenses: 1_000 + spm_unit_head_spouse_earned_cap: 20_000 + spm_unit_pre_subsidy_childcare_expenses: 10_000 + child_care_subsidies: 0 + output: + # Given for one member, pre_subsidy_childcare_expenses is an input for + # every member, so the second child counts 0 rather than a share of the + # unit's 10,000. So childcare_expenses is 6,000, and the expense is + # 1,000 + 6,000 = 7,000, under the 20,000 cap. Main's formula read the + # unit's amount and gave 1,000 + 10,000 = 11,000. + pre_subsidy_childcare_expenses: [0, 6_000, 0] + childcare_expenses: 6_000 + spm_unit_capped_work_childcare_expenses: 7_000 + - name: A subsidy lowers the expense in 2024, the formula's first year period: 2024 absolute_error_margin: 0.001 From 4f52713fe449ffd075d07176d6ed0472f05518bb Mon Sep 17 00:00:00 2001 From: Max Ghenis Date: Thu, 26 Nov 2026 12:47:56 +0100 Subject: [PATCH 33/42] Say what a subsample does to the baseline's people and inputs The variable's documentation and fica_pre_tax_totals' docstring said a branch keeps its ancestor's baseline, and that a subsampled branch raises for a person whose ID the baseline lacks or repeats. A branch now shares its ancestor's baseline until its own subsample rebuilds one on the same people from the inputs the branch then holds, as a reform simulation's subsample does. So an input set on the branch counts as a change to payroll wages until that subsample, and the ID lookup serves a baseline that lists other people, as after a subsample that raised once core had resampled the simulation. Text only: no code, label, unit or reference changes. Co-Authored-By: Claude Opus 5.5 --- ..._payroll_tax_fixed_employer_cost_change.py | 31 ++++++++++++------- 1 file changed, 20 insertions(+), 11 deletions(-) diff --git a/policyengine_us/variables/gov/simulation/employer_payroll_tax_incidence/employer_payroll_tax_fixed_employer_cost_change.py b/policyengine_us/variables/gov/simulation/employer_payroll_tax_incidence/employer_payroll_tax_fixed_employer_cost_change.py index bc6db7092e0..4d536ed699e 100644 --- a/policyengine_us/variables/gov/simulation/employer_payroll_tax_incidence/employer_payroll_tax_fixed_employer_cost_change.py +++ b/policyengine_us/variables/gov/simulation/employer_payroll_tax_incidence/employer_payroll_tax_fixed_employer_cost_change.py @@ -397,11 +397,14 @@ def fica_pre_tax_totals(person, period, baseline): each apply to the side they belong to. Equal lists don't make equal totals, so the baseline's total always comes from the baseline simulation, matched to this simulation's people (``for_each_person``). - The baseline simulation holds the inputs this one was built with, or - rebuilt with by its own ``subsample``, and a branch keeps its ancestor's - baseline. So an input to the total or to a listed contribution, set on - this simulation after its baseline was built, counts as a change to - payroll wages. A formula for the total that reads employment_income is + The baseline simulation holds the inputs this one was built with, and a + branch shares its ancestor's baseline until its own ``subsample`` gives + it one. A ``subsample``, of a branch or of a reform simulation, rebuilds + the baseline on the same people from the inputs the simulation then + holds. So an input to the total or to a listed contribution, set on this + simulation after its baseline was built, counts as a change to payroll + wages until this simulation's own ``subsample`` rebuilds the baseline + with it. A formula for the total that reads employment_income is not supported: this variable is part of employment_income, so core raises a CycleError. """ @@ -507,12 +510,18 @@ class employer_payroll_tax_fixed_employer_cost_change(Variable): "simulation's, matched by person ID, so a reform to the total or to " "a listed contribution applies to the reform side alone, even when " "it keeps the list. The baseline simulation holds the inputs the " - "simulation was built with, or rebuilt with by its own subsample, " - "and a branch keeps its ancestor's baseline: an input to the total " - "or to a listed contribution, set on a reform simulation after its " - "baseline was built, counts as a change to payroll wages. A " - "subsampled branch raises for a person whose ID the baseline lacks " - "or repeats, as axes can. A formula for the total that reads " + "simulation was built with, and a branch shares its ancestor's " + "baseline until its own subsample gives it one. A subsample, of a " + "branch or of a reform simulation, rebuilds the baseline on the same " + "people from the inputs the simulation then holds. So an input to " + "the total or to a listed contribution, set on a reform simulation " + "after its baseline was built, counts as a change to payroll wages " + "until that simulation's own subsample rebuilds the baseline with " + "it. Where the baseline lists other people than the simulation, as " + "after a subsample that raised once core had resampled the " + "simulation, the variable matches each person by ID. It raises " + "NotImplementedError for a person whose ID the baseline lacks or " + "repeats, as axes can. A formula for the total that reads " "employment_income is not supported: core raises a CycleError. A " "simulation that supplies " "payroll_tax_gross_wages itself fixes payroll wages, so employer " From a92315ef96a567163d7cedc7291c2c0c83d07c4e Mon Sep 17 00:00:00 2001 From: Max Ghenis Date: Thu, 26 Nov 2026 12:49:53 +0100 Subject: [PATCH 34/42] Pin that a failed subsample with no arm raises core's error A simulation with no reform has no arm and no "baseline" entry, so subsample makes no copy and must put nothing back when core raises. The test checks that core's ValueError for a call with neither n nor frac reaches the caller and that the simulation still has no arm. Without the restore's arm_copy check, the restore deletes a missing "baseline" key and raises KeyError while handling core's ValueError. Co-Authored-By: Claude Opus 5.5 --- .../tests/core/test_reform_baseline_arm_inputs.py | 15 +++++++++++++++ 1 file changed, 15 insertions(+) diff --git a/policyengine_us/tests/core/test_reform_baseline_arm_inputs.py b/policyengine_us/tests/core/test_reform_baseline_arm_inputs.py index 5c44cc79649..8cee8fe43c8 100644 --- a/policyengine_us/tests/core/test_reform_baseline_arm_inputs.py +++ b/policyengine_us/tests/core/test_reform_baseline_arm_inputs.py @@ -527,3 +527,18 @@ def test_a_failed_branch_subsample_leaves_the_branch_as_it_found_it(): np.testing.assert_allclose(value(branch, EXPENSE), SAMPLED_EXPENSE) assert parent.baseline is arm assert households(arm) == [0, 1] + + +def test_a_failed_subsample_with_no_arm_raises_core_error(): + """A simulation with no reform has no arm and no "baseline" entry, so + ``subsample`` hands core no copy and has nothing to put back when core + raises. Core's own ``ValueError`` reaches the caller, rather than a + ``KeyError`` from removing an entry that was never there, and the + simulation still has no arm.""" + simulation = Microsimulation(dataset=new_york_families()) + assert simulation.baseline is None + assert "baseline" not in simulation.branches + with pytest.raises(ValueError, match="Either n or frac must be provided"): + simulation.subsample() + assert "baseline" not in simulation.branches + assert simulation.baseline is None From e9fc366e76794055b586059cb80d9889126a93da Mon Sep 17 00:00:00 2001 From: Max Ghenis Date: Thu, 26 Nov 2026 16:47:44 +0100 Subject: [PATCH 35/42] Refuse to subsample a simulation named "baseline" that has an arm Core rebuilds a subsample's arm with get_branch("baseline"), which returns the simulation itself when that is its own name. A branch named "baseline" under another branch shares its parent's arm, so its subsample gave it baseline policy and dropped its arm. subsample now raises before it changes anything and says to name the branch something else. Co-Authored-By: Claude Opus 5.5 --- policyengine_us/spm.py | 15 ++++++ .../core/test_reform_baseline_arm_inputs.py | 53 ++++++++++++++++++- 2 files changed, 67 insertions(+), 1 deletion(-) diff --git a/policyengine_us/spm.py b/policyengine_us/spm.py index 129e36c5795..1f2f0da61ea 100644 --- a/policyengine_us/spm.py +++ b/policyengine_us/spm.py @@ -1174,6 +1174,21 @@ def _simulation_family(self): yield from branch._simulation_family() def subsample(self, *args, **kwargs): + if ( + self.branch_name == "baseline" + and getattr(self, "baseline", None) is not None + ): + # Core rebuilds the arm with get_branch("baseline"), which returns + # the simulation itself when that is its own name. A branch named + # "baseline" with an arm would then take baseline policy and lose + # its arm, so refuse before anything changes. + raise ValueError( + 'A simulation named "baseline" with a baseline arm cannot ' + 'subsample. Core rebuilds the arm as the branch named "baseline", ' + "and that name returns this simulation, so it would take " + "baseline policy and lose its arm. Name the branch something " + 'else, such as get_branch("trial"), and subsample that.' + ) inherited = getattr(self, "baseline", None) had_entry = "baseline" in self.branches previous = self.branches.get("baseline") diff --git a/policyengine_us/tests/core/test_reform_baseline_arm_inputs.py b/policyengine_us/tests/core/test_reform_baseline_arm_inputs.py index 8cee8fe43c8..656d8ba2589 100644 --- a/policyengine_us/tests/core/test_reform_baseline_arm_inputs.py +++ b/policyengine_us/tests/core/test_reform_baseline_arm_inputs.py @@ -26,7 +26,9 @@ name. A branch that subsamples reads an arm built on its own sample, under baseline policy, even where the caller named one of its calculation branches "baseline". A subsample that raises before core rebuilds the arm leaves what -the branch held under that name as it was. +the branch held under that name as it was. A simulation that is itself named +"baseline" and has an arm raises when asked to subsample, before it changes +anything. One limit is pinned here too. Where core builds the arm, in ``subsample``, it has already dropped such a holder and its recorded inputs, so an input set @@ -529,6 +531,55 @@ def test_a_failed_branch_subsample_leaves_the_branch_as_it_found_it(): assert households(arm) == [0, 1] +NAMED_REFUSAL = 'A simulation named "baseline" with a baseline arm cannot subsample' + + +def test_a_simulation_named_baseline_with_an_arm_refuses_to_subsample(): + """Core rebuilds the arm with ``get_branch("baseline")``, which returns a + simulation itself when that is its own name. A branch named "baseline" + under another branch shares the parent's arm, so its subsample put + baseline policy on the branch and dropped its arm: the repeal read False + and the expense $14,000 in place of $27,916.40. Now ``subsample`` raises + before it changes anything, on that branch, a clone of it, a deeper + branch of that name and a reform simulation renamed "baseline", and each + keeps its policy, arm, branches and name.""" + parent = Microsimulation(dataset=new_york_families(), reform=REPEAL) + arm = parent.baseline + trial = parent.get_branch("trial") + named = trial.get_branch("baseline") + renamed = parent.clone() + renamed.branch_name = "baseline" + cases = ( + named, + named.clone(), + trial.get_branch("deeper").get_branch("baseline"), + renamed, + ) + before = [ + (case.baseline, dict(case.branches), case.tax_benefit_system) for case in cases + ] + for case, (own_arm, branches, system) in zip(cases, before): + assert case.branch_name == "baseline" and own_arm is not None + with pytest.raises(ValueError, match=NAMED_REFUSAL): + case.subsample(n=1, seed=0) + assert case.branch_name == "baseline" + assert case.baseline is own_arm + assert case.tax_benefit_system is system + assert case.branches.keys() == branches.keys() + assert all(case.branches[key] is branches[key] for key in branches) + assert repeals_the_subsidy(case) + assert households(case) == [0, 1] + assert named.baseline is arm + np.testing.assert_allclose(value(named, SUBSIDY), [0, 0]) + np.testing.assert_allclose( + value(named, EXPENSE), [27_916.40, 12_000], atol=TOLERANCE + ) + np.testing.assert_allclose(value(arm, SUBSIDY), [13_916.40, 6_000], atol=TOLERANCE) + assert trial.branches["baseline"] is named + assert parent.baseline is arm + assert households(arm) == [0, 1] + + def test_a_failed_subsample_with_no_arm_raises_core_error(): """A simulation with no reform has no arm and no "baseline" entry, so ``subsample`` hands core no copy and has nothing to put back when core From 439c863eeac38cc57f9e2466b4ed3a4694a83d2b Mon Sep 17 00:00:00 2001 From: Max Ghenis Date: Thu, 26 Nov 2026 17:04:33 +0100 Subject: [PATCH 36/42] Keep the dataset reading of the SPM child care expense through snapshots Over a dataset, spm_unit_pre_subsidy_childcare_expenses reads as what parents paid after any subsidy; in a household, as the price before it. export_source_inputs and extract_person turn a dataset simulation into a situation, so its reload read the same inputs as a household's, and the Manhattan family's expense fell from $14,000 to $83.60. Both now write "_dataset_inputs": true for a simulation whose inputs came from a dataset. This package's builders strip the key and mark the simulation they build, inside core's __init__ and so before core clones it into a reform's baseline arm. The expense reads one predicate, holds_dataset_inputs; no other reader of is_over_dataset uses it. Snapshots stay at version 1, and one without the key reloads as a household. Co-Authored-By: Claude Opus 5.5 --- docs/social-security-benefit-levers.md | 13 +- .../core/test_reform_baseline_arm_inputs.py | 121 +++++++++++++++++- .../tools/social_security_inputs.py | 65 +++++++--- ...spm_unit_capped_work_childcare_expenses.py | 13 +- 4 files changed, 187 insertions(+), 25 deletions(-) diff --git a/docs/social-security-benefit-levers.md b/docs/social-security-benefit-levers.md index c09263434b6..3706b58ee22 100644 --- a/docs/social-security-benefit-levers.md +++ b/docs/social-security-benefit-levers.md @@ -57,12 +57,19 @@ factors once, and perform their earnings test on the resulting payable amount. exports all recorded pure-input periods and entity memberships as `sources`, with supplied formula-variable values in a separate `overrides` payload. Cached calculations are excluded. `reload_source_inputs(payload, ...)` restores sources -before final overrides. Core's legacy `extract_person` retains every recorded +before final overrides. A snapshot of a simulation over a dataset also carries +`"_dataset_inputs": true`, so the reloaded simulation, its baseline arm and its +later branches read `spm_unit_capped_work_childcare_expenses` as a dataset +simulation does; other dataset-only rules, such as county, read it as a +household. The payload stays at version 1, and a snapshot without the key +reloads as a household. Core's legacy `extract_person` retains every recorded input period for the four benefit components and their reported twins, excluding formula caches. This keeps later overrides final on reload and preserves their source histories and future uprating. Other variables keep Core's usual first -known period. Neither interface settles the separate API/application metadata -and field-exposure contract. +known period. A situation extracted from a dataset simulation carries the same +key, and like the provenance envelope it loads only through this package's +builders. Neither interface settles the separate API/application metadata and +field-exposure contract. Annual benefit inputs retain Core's period normalization. For example, supplying `social_security_retirement: {"2024-07": 500}` through a PE-US constructor stores diff --git a/policyengine_us/tests/core/test_reform_baseline_arm_inputs.py b/policyengine_us/tests/core/test_reform_baseline_arm_inputs.py index 656d8ba2589..a0a0b02fba1 100644 --- a/policyengine_us/tests/core/test_reform_baseline_arm_inputs.py +++ b/policyengine_us/tests/core/test_reform_baseline_arm_inputs.py @@ -28,7 +28,10 @@ "baseline". A subsample that raises before core rebuilds the arm leaves what the branch held under that name as it was. A simulation that is itself named "baseline" and has an arm raises when asked to subsample, before it changes -anything. +anything. A snapshot of a dataset simulation, from ``export_source_inputs`` or +``extract_person``, reloads with the dataset's rule for the SPM child care +expense, in the reform and in its arm; a snapshot without the dataset mark +reloads as a household. One limit is pinned here too. Where core builds the arm, in ``subsample``, it has already dropped such a holder and its recorded inputs, so an input set @@ -36,6 +39,7 @@ the variable, as on main. """ +import json from itertools import product import numpy as np @@ -48,6 +52,10 @@ from policyengine_us import Microsimulation, Simulation from policyengine_us.entities import Person, SPMUnit +from policyengine_us.tools.social_security_inputs import ( + export_source_inputs, + reload_source_inputs, +) YEAR = 2026 TOLERANCE = 0.01 @@ -593,3 +601,114 @@ def test_a_failed_subsample_with_no_arm_raises_core_error(): simulation.subsample() assert "baseline" not in simulation.branches assert simulation.baseline is None + + +# What both New York families reported paying for care, which baseline policy +# keeps over a dataset; under REPEAL, that plus the subsidy lost, S0, which the +# reform reads from its arm. +REPORTED_EXPENSE = [14_000, 6_000] +REPEALED_EXPENSE = [27_916.40, 12_000] +NEW_YORK_S0 = [13_916.40, 6_000] +DATASET_INPUTS = "_dataset_inputs" +PROVENANCE = "_social_security_input_provenance" + + +@pytest.fixture(scope="module") +def new_york_source(): + """Both New York families over a dataset, with no reform. The second + receives a Social Security benefit, so a snapshot carries the provenance + envelope beside the dataset mark.""" + return Simulation(dataset=dataset((NEW_YORK,), FAMILIES)) + + +def assert_dataset_reading(simulation, households=slice(None)): + """The expense a dataset simulation computes: the reported amount with no + reform, and under REPEAL that plus the subsidy lost, read from an arm + that keeps the reported amount.""" + reported = REPORTED_EXPENSE[households] + if simulation.baseline is None: + np.testing.assert_allclose(value(simulation, EXPENSE), reported, atol=TOLERANCE) + return + assert repeals_the_subsidy(simulation) + np.testing.assert_allclose(value(simulation, SUBSIDY), [0] * len(reported)) + np.testing.assert_allclose( + value(simulation, EXPENSE), REPEALED_EXPENSE[households], atol=TOLERANCE + ) + arm = simulation.baseline + assert not repeals_the_subsidy(arm) + np.testing.assert_allclose( + value(arm, SUBSIDY), NEW_YORK_S0[households], atol=TOLERANCE + ) + np.testing.assert_allclose(value(arm, EXPENSE), reported, atol=TOLERANCE) + + +def test_a_dataset_snapshot_reloads_with_the_dataset_reading(new_york_source): + """Over a dataset, the pre-subsidy input reads as what parents paid after + any subsidy; in a household, as the amount before it. A snapshot used to + reload as a household, so the first family's expense fell from $14,000 + to $83.60. Now the snapshot carries a mark, and the reload, a branch of + it and a second snapshot of it keep the dataset reading.""" + payload = export_source_inputs(new_york_source) + assert_dataset_reading(new_york_source) + reloaded = reload_source_inputs(payload) + assert not reloaded.is_over_dataset + np.testing.assert_allclose( + value(reloaded, EXPENSE), value(new_york_source, EXPENSE), atol=TOLERANCE + ) + assert_dataset_reading(reloaded) + assert_dataset_reading(reloaded.get_branch("trial")) + again = export_source_inputs(reloaded) + assert_dataset_reading(reload_source_inputs(again)) + for snapshot in (payload, again): + assert snapshot["version"] == 1 and snapshot[DATASET_INPUTS] is True + assert snapshot[PROVENANCE] is not None + + +def test_a_dataset_snapshot_reloaded_under_a_reform_keeps_the_reading_in_its_arm( + new_york_source, +): + """Core builds a reform's arm inside ``__init__``, by cloning the + simulation, so the mark must be on the simulation before then. The + reform reads S0 from the arm, and the arm keeps the reported amount.""" + payload = export_source_inputs(new_york_source) + assert_dataset_reading(reload_source_inputs(payload, reform=REPEAL)) + + +def test_a_reform_over_a_dataset_keeps_the_reading_through_a_snapshot(): + """A source built with the reform exports the mark too, from the reform + and from its arm, and each reloads with the dataset reading.""" + source = Simulation(dataset=dataset((NEW_YORK,), FAMILIES), reform=REPEAL) + assert_dataset_reading(source) + payload = export_source_inputs(source) + assert payload[DATASET_INPUTS] is True + assert_dataset_reading(reload_source_inputs(payload, reform=REPEAL)) + arm_payload = export_source_inputs(source.baseline) + assert arm_payload[DATASET_INPUTS] is True + assert_dataset_reading(reload_source_inputs(arm_payload)) + + +def test_a_person_extracted_from_a_dataset_keeps_the_reading(new_york_source): + """``extract_person`` marks the situation it extracts from a dataset + simulation, and a simulation built from it, with or without a reform, + reads the expense as the dataset does.""" + for person, households in ((0, slice(0, 1)), (2, slice(1, 2))): + extracted = json.loads(json.dumps(new_york_source.extract_person(person))) + built = Simulation(situation=extracted) + assert not built.is_over_dataset + assert_dataset_reading(built, households) + assert_dataset_reading( + Simulation(situation=extracted, reform=REPEAL), households + ) + assert extracted[DATASET_INPUTS] is True + + +def test_an_unmarked_snapshot_reloads_as_a_household(new_york_source): + """A version 1 snapshot without the mark, as export wrote before it + recorded one, reloads as a household: each family's expense nets its + subsidy, $14,000 less $13,916.40 and $6,000 less $6,000. A snapshot of + that reload carries no mark either.""" + payload = export_source_inputs(new_york_source) + del payload[DATASET_INPUTS] + reloaded = reload_source_inputs(payload) + np.testing.assert_allclose(value(reloaded, EXPENSE), [83.60, 0], atol=TOLERANCE) + assert DATASET_INPUTS not in export_source_inputs(reloaded) diff --git a/policyengine_us/tools/social_security_inputs.py b/policyengine_us/tools/social_security_inputs.py index 249a14a6a16..d1cb2be576b 100644 --- a/policyengine_us/tools/social_security_inputs.py +++ b/policyengine_us/tools/social_security_inputs.py @@ -41,6 +41,11 @@ # Keep the established envelope key so existing complete-snapshot callers # need not change; version two contains actual source values, never stamps. _PROVENANCE = "_social_security_input_provenance" +# A snapshot or extracted situation of a simulation over a dataset carries this +# key as true, and this package's builders turn it into the attribute below, +# so the simulation built from it still reads its inputs as a dataset's. +_DATASET_INPUTS = "_dataset_inputs" +_DATASET_INPUTS_ATTRIBUTE = "_inputs_from_dataset" _initial_social_security_ingress = ContextVar("initial_ss_ingress", default=False) _initial_social_security_writes = ContextVar("initial_ss_writes", default=None) @@ -67,6 +72,18 @@ class _Value: registered: bool +def holds_dataset_inputs(simulation): + """Whether a simulation's inputs came from a dataset: it runs over one, or + it was built from a snapshot (``export_source_inputs``) or an extracted + situation (``extract_person``) of a simulation that did. Core's ``clone`` + copies the attribute, so a branch, a clone and a reform's baseline arm + give the same answer as the simulation they copy.""" + return bool( + getattr(simulation, "is_over_dataset", False) + or getattr(simulation, _DATASET_INPUTS_ATTRIBUTE, False) + ) + + def _enabled(simulation): return getattr( getattr(simulation, "tax_benefit_system", None), @@ -1067,12 +1084,16 @@ def load(first, *args, **kwargs): if not getattr(system, "_social_security_input_compatibility", False): return original(first, *args, **kwargs) metadata = None + from_dataset = False if not dataset: input_dict = args[1] if len(args) > 1 else kwargs["input_dict"] metadata = input_dict.get(_PROVENANCE) - if _PROVENANCE in input_dict: + from_dataset = input_dict.get(_DATASET_INPUTS) is True + if _PROVENANCE in input_dict or _DATASET_INPUTS in input_dict: input_dict = { - k: v for k, v in input_dict.items() if k != _PROVENANCE + k: v + for k, v in input_dict.items() + if k not in (_PROVENANCE, _DATASET_INPUTS) } if len(args) > 1: args = (args[0], input_dict, *args[2:]) @@ -1095,6 +1116,11 @@ def load(first, *args, **kwargs): result = None try: result = original(first, *args, **kwargs) + if from_dataset: + # Inside core's __init__ the builder runs before core + # builds a reform's baseline arm, which clones this + # simulation and so keeps the mark too. + setattr(result, _DATASET_INPUTS_ATTRIBUTE, True) return result finally: _initial_social_security_writes.reset(writes_token) @@ -1190,6 +1216,8 @@ def extract_person(simulation, index=0, exclude_entities=("state",)): ) if metadata is not None: payload[_PROVENANCE] = metadata + if holds_dataset_inputs(simulation): + payload[_DATASET_INPUTS] = True return payload CoreSimulation.extract_person = extract_person @@ -1275,7 +1303,8 @@ def restore_holder( def export_source_inputs(simulation): - """Export all registered source periods and final overrides.""" + """Export all registered source periods and final overrides, and mark a + snapshot of a simulation whose inputs came from a dataset.""" names = { key: [str(name) for name in population.ids] for key, population in simulation.populations.items() @@ -1302,21 +1331,17 @@ def export_source_inputs(simulation): source.setdefault(name, {})[str(period)] = values[index] else: overrides.setdefault(name, {})[str(period)] = values - return json.loads( - json.dumps( - { - "version": 1, - "sources": sources, - "overrides": overrides, - _PROVENANCE: _automatic_reported_metadata(simulation), - "default_input_period": str(simulation.default_input_period), - "default_calculation_period": str( - simulation.default_calculation_period - ), - }, - cls=NpEncoder, - ) - ) + payload = { + "version": 1, + "sources": sources, + "overrides": overrides, + _PROVENANCE: _automatic_reported_metadata(simulation), + "default_input_period": str(simulation.default_input_period), + "default_calculation_period": str(simulation.default_calculation_period), + } + if holds_dataset_inputs(simulation): + payload[_DATASET_INPUTS] = True + return json.loads(json.dumps(payload, cls=NpEncoder)) def reload_source_inputs(payload, **simulation_kwargs): @@ -1331,6 +1356,10 @@ def reload_source_inputs(payload, **simulation_kwargs): sources = payload["sources"] if metadata is not None: sources = {**sources, _PROVENANCE: metadata} + if payload.get(_DATASET_INPUTS) is True: + # The builder marks the simulation before core builds a reform's + # baseline arm, so the arm reads the snapshot as a dataset too. + sources = {**sources, _DATASET_INPUTS: True} simulation = Simulation(situation=sources, **simulation_kwargs) for name, periods in payload["overrides"].items(): for period, values in periods.items(): diff --git a/policyengine_us/variables/household/expense/childcare/spm_unit_capped_work_childcare_expenses.py b/policyengine_us/variables/household/expense/childcare/spm_unit_capped_work_childcare_expenses.py index 49ee176948b..90b876810ed 100644 --- a/policyengine_us/variables/household/expense/childcare/spm_unit_capped_work_childcare_expenses.py +++ b/policyengine_us/variables/household/expense/childcare/spm_unit_capped_work_childcare_expenses.py @@ -1,4 +1,5 @@ from policyengine_us.model_api import * +from policyengine_us.tools.social_security_inputs import holds_dataset_inputs class spm_unit_capped_work_childcare_expenses(Variable): @@ -10,7 +11,11 @@ class spm_unit_capped_work_childcare_expenses(Variable): documentation = ( "Over a dataset, the child care part keeps the reported amount under " "baseline policy and moves by the change in subsidy under a reform, " - "which it reads from the reform's baseline arm. Core builds that arm " + "which it reads from the reform's baseline arm. export_source_inputs " + "and extract_person mark a snapshot of a dataset simulation, and a " + "simulation built from a marked snapshot follows the same rule, as " + "does its arm. An unmarked snapshot reloads as a household. " + "Core builds that arm " "only for a reform passed as reform=, and apply_reform builds none. A " "simulation built with reform= keeps its arm, under baseline policy, " "through any reform applied later. A reformed system passed as " @@ -28,10 +33,12 @@ def formula_2024(spm_unit, period, parameters): # is not among its noncash benefits, so a subsidy lowers this expense # rather than adding to resources. simulation = spm_unit.simulation - if simulation.is_over_dataset: + if holds_dataset_inputs(simulation): # Datasets fill the pre-subsidy input from the ASEC, which asks # parents how much they spent on child care, and this rule reads - # that as what they paid after any subsidy. Baseline policy keeps + # that as what they paid after any subsidy. A snapshot of a + # dataset simulation carries the same amounts, so a simulation + # rebuilt from one reads them the same way. Baseline policy keeps # that amount, and a reform moves it by the change in subsidy. A # baseline arm has no baseline of its own, so it keeps the amount. out_of_pocket_expenses = pre_subsidy_expenses From 202b79eb80bd021691a405ee66de3f9f76b54c29 Mon Sep 17 00:00:00 2001 From: Max Ghenis Date: Thu, 26 Nov 2026 19:20:51 +0100 Subject: [PATCH 37/42] Give a marked reload's arm the snapshot's overrides, and mark dumps Over a dataset, core gives a reform's baseline arm each value the dataset gives. export_source_inputs lists a value given for a formula variable among the overrides, and reload_source_inputs set those on the reform side only, so the reload's arm calculated them and the reform side read S0 from that arm. A marked reload now sets each override on its arm too. Export lists, under _baseline_arm_overrides, what the source's arm held for each override it doesn't share (null for nothing), so a value a caller set on the reform after construction stays off the reload's arm. A marked reload skips a variable baseline policy doesn't define, and refuses one the reform stores in another entity or with other ETERNITY storage, as construction over a dataset does. An unmarked snapshot reloads as before. The dump wrapper writes the dataset mark to __entities__/dataset_inputs.json, and the restore wrapper sets it, so a restored dump of a dataset simulation keeps the dataset rule. A mark other than true or false raises ValueError in the builder, the reload and the restore. The round-trip test now takes its branch before the reload calculates anything. Co-Authored-By: Claude Opus 5.5 --- .../core/test_reform_baseline_arm_inputs.py | 250 +++++++++++++++++- .../tools/social_security_inputs.py | 126 ++++++++- 2 files changed, 364 insertions(+), 12 deletions(-) diff --git a/policyengine_us/tests/core/test_reform_baseline_arm_inputs.py b/policyengine_us/tests/core/test_reform_baseline_arm_inputs.py index a0a0b02fba1..f303134ebc4 100644 --- a/policyengine_us/tests/core/test_reform_baseline_arm_inputs.py +++ b/policyengine_us/tests/core/test_reform_baseline_arm_inputs.py @@ -30,8 +30,11 @@ "baseline" and has an arm raises when asked to subsample, before it changes anything. A snapshot of a dataset simulation, from ``export_source_inputs`` or ``extract_person``, reloads with the dataset's rule for the SPM child care -expense, in the reform and in its arm; a snapshot without the dataset mark -reloads as a household. +expense, in the reform and in its arm, and a dump of one restores with it; a +snapshot or dump without the dataset mark reloads as a household, and a mark +other than true or false raises. A marked reload's arm holds what the +source's arm held for each override: the dataset's value, or, where a caller +set a value on the reform after construction, what the arm kept. One limit is pinned here too. Where core builds the arm, in ``subsample``, it has already dropped such a holder and its recorded inputs, so an input set @@ -48,6 +51,7 @@ from policyengine_core.data import Dataset from policyengine_core.periods import ETERNITY from policyengine_core.reforms import Reform +from policyengine_core.tools import simulation_dumper from policyengine_core.variables import Variable from policyengine_us import Microsimulation, Simulation @@ -114,10 +118,12 @@ def dataset( eternal_subsidy=None, yearly_subsidies=None, weights=None, + given=None, ): """A flat file with one household per state and family. ``yearly_subsidies`` - maps a year to each household's child care subsidy, and ``weights`` gives - each household's weight.""" + maps a year to each household's child care subsidy, ``weights`` gives + each household's weight, and ``given`` maps a variable to each household's + value of it in 2026.""" columns = {} def add(name, parent, child): @@ -149,6 +155,8 @@ def add(name, parent, child): add("child_care_subsidies__eternity", eternal_subsidy, eternal_subsidy) for year, subsidies in (yearly_subsidies or {}).items(): add(f"child_care_subsidies__{year}", subsidies[unit], subsidies[unit]) + for name, given_values in (given or {}).items(): + add(f"{name}__{YEAR}", given_values[unit], given_values[unit]) return Dataset.from_dataframe(pd.DataFrame(columns), time_period=YEAR) @@ -611,6 +619,9 @@ def test_a_failed_subsample_with_no_arm_raises_core_error(): NEW_YORK_S0 = [13_916.40, 6_000] DATASET_INPUTS = "_dataset_inputs" PROVENANCE = "_social_security_input_provenance" +BASELINE_ARM_OVERRIDES = "_baseline_arm_overrides" +DUMP_MARK_FILE = "dataset_inputs.json" +NOT_TRUE_OR_FALSE = "the mark must be true or false" @pytest.fixture(scope="module") @@ -647,16 +658,19 @@ def test_a_dataset_snapshot_reloads_with_the_dataset_reading(new_york_source): any subsidy; in a household, as the amount before it. A snapshot used to reload as a household, so the first family's expense fell from $14,000 to $83.60. Now the snapshot carries a mark, and the reload, a branch of - it and a second snapshot of it keep the dataset reading.""" + it and a second snapshot of it keep the dataset reading. The branch is + taken before the reload calculates anything, so it reads the expense + itself rather than copying the reload's.""" payload = export_source_inputs(new_york_source) assert_dataset_reading(new_york_source) reloaded = reload_source_inputs(payload) + branch = reloaded.get_branch("trial") assert not reloaded.is_over_dataset + assert_dataset_reading(branch) np.testing.assert_allclose( value(reloaded, EXPENSE), value(new_york_source, EXPENSE), atol=TOLERANCE ) assert_dataset_reading(reloaded) - assert_dataset_reading(reloaded.get_branch("trial")) again = export_source_inputs(reloaded) assert_dataset_reading(reload_source_inputs(again)) for snapshot in (payload, again): @@ -712,3 +726,227 @@ def test_an_unmarked_snapshot_reloads_as_a_household(new_york_source): reloaded = reload_source_inputs(payload) np.testing.assert_allclose(value(reloaded, EXPENSE), [83.60, 0], atol=TOLERANCE) assert DATASET_INPUTS not in export_source_inputs(reloaded) + + +def test_a_mark_other_than_true_or_false_raises(new_york_source): + """The builder and the reload take the mark as true or false. JSON false + reads as no mark, so the first family's expense nets its subsidy, and + any other value raises before anything is built.""" + extracted = json.loads(json.dumps(new_york_source.extract_person(0))) + payload = export_source_inputs(new_york_source) + for mark in ("true", 1): + with pytest.raises(ValueError, match=NOT_TRUE_OR_FALSE): + Simulation(situation={**extracted, DATASET_INPUTS: mark}) + with pytest.raises(ValueError, match=NOT_TRUE_OR_FALSE): + reload_source_inputs({**payload, DATASET_INPUTS: mark}) + unmarked = ( + Simulation( + situation=json.loads(json.dumps({**extracted, DATASET_INPUTS: False})) + ), + reload_source_inputs( + json.loads(json.dumps({**payload, DATASET_INPUTS: False})) + ), + ) + for simulation in unmarked: + np.testing.assert_allclose(value(simulation, EXPENSE)[0], 83.60, atol=TOLERANCE) + + +# The dataset counts $40,000 of the first New York family's income for its +# child care program, where the program's formula counts $30,000, so baseline +# policy pays that family $100 less, and gives it $2,000 of other work +# expenses, W, where the formula gives none. +GIVEN = {"ny_ccap_countable_income": (40_000, 0), "spm_unit_work_expenses": (2_000, 0)} +GIVEN_S0 = [13_816.40, 6_000] +GIVEN_ARM_EXPENSE = [16_000, 6_000] +GIVEN_EXPENSE = [29_816.40, 12_000] + + +def given_source(): + return Simulation( + dataset=dataset((NEW_YORK,), FAMILIES, given=GIVEN), reform=REPEAL + ) + + +@pytest.fixture(scope="module") +def given_snapshot(): + """``given_source`` and its snapshot, which the tests below only read.""" + source = given_source() + return source, export_source_inputs(source) + + +def test_a_marked_reload_sets_the_snapshots_overrides_on_its_arm(given_snapshot): + """Over a dataset, core gives the reform and its arm each value the + dataset gives. Export lists a value given for a variable with a formula, + such as New York's countable income, among the overrides, and the reload + set those on the reform side only. Its arm then calculated S0 at + $13,916.40 where the source's arm reads $13,816.40, and the reform's + expense read $100 more than the source's. Now a marked reload sets each + override on its arm too.""" + source, payload = given_snapshot + assert GIVEN.keys() <= payload["overrides"].keys() + assert BASELINE_ARM_OVERRIDES not in payload + reloaded = reload_source_inputs(payload, reform=REPEAL) + np.testing.assert_allclose( + value(reloaded, EXPENSE), value(source, EXPENSE), atol=TOLERANCE + ) + np.testing.assert_allclose(value(source, EXPENSE), GIVEN_EXPENSE, atol=TOLERANCE) + arm = reloaded.baseline + for name in (SUBSIDY, EXPENSE, "ny_ccap_countable_income"): + np.testing.assert_allclose( + value(arm, name), value(source.baseline, name), atol=TOLERANCE + ) + np.testing.assert_allclose(value(arm, SUBSIDY), GIVEN_S0, atol=TOLERANCE) + + +def test_a_marked_reload_arm_keeps_the_datasets_work_expense(given_snapshot): + """The source's arm holds the $2,000 of work expenses the dataset gives, + so it reads $16,000 for the first family's expense. The reload's arm + calculated W at $0 and read $14,000.""" + source, payload = given_snapshot + arm = reload_source_inputs(payload, reform=REPEAL).baseline + np.testing.assert_allclose(value(arm, "spm_unit_work_expenses"), [2_000, 0]) + for simulation in (arm, source.baseline): + np.testing.assert_allclose( + value(simulation, EXPENSE), GIVEN_ARM_EXPENSE, atol=TOLERANCE + ) + + +def test_an_unmarked_reload_sets_overrides_on_the_reform_side_only(given_snapshot): + """Without the mark, the reload sets the overrides on the reform side + alone, as on main, and its arm calculates both variables.""" + _, payload = given_snapshot + unmarked = {key: item for key, item in payload.items() if key != DATASET_INPUTS} + reloaded = reload_source_inputs(unmarked, reform=REPEAL) + np.testing.assert_allclose(value(reloaded, "ny_ccap_countable_income"), [40_000, 0]) + np.testing.assert_allclose(value(reloaded, "spm_unit_work_expenses"), [2_000, 0]) + arm = reloaded.baseline + np.testing.assert_allclose(value(arm, "ny_ccap_countable_income"), [30_000, 19_200]) + np.testing.assert_allclose(value(arm, "spm_unit_work_expenses"), [0, 0]) + + +def test_a_marked_reload_keeps_values_set_on_the_reform_side_off_its_arm(): + """A caller who sets a value on the reform after construction sets it + there alone. The source's arm keeps the $2,000 of work expenses the + dataset gave under the $3,000 set, and calculates the earned cap set to + $20,000. Export lists what the arm holds for each override it doesn't + share, null where it holds nothing, and the reload's arm takes that, so + both sides match the source's, through a second snapshot too.""" + source = given_source() + source.set_input("spm_unit_work_expenses", YEAR, [3_000, 0]) + source.set_input("spm_unit_head_spouse_earned_cap", YEAR, [20_000, 20_000]) + payload = export_source_inputs(source) + reloaded = reload_source_inputs(payload, reform=REPEAL) + names = ("spm_unit_work_expenses", "spm_unit_head_spouse_earned_cap", EXPENSE) + for name in names: + for side, source_side in ( + (reloaded, source), + (reloaded.baseline, source.baseline), + ): + np.testing.assert_allclose( + value(side, name), value(source_side, name), atol=TOLERANCE + ) + np.testing.assert_allclose( + value(reloaded.baseline, "spm_unit_head_spouse_earned_cap"), [30_000, 18_000] + ) + assert payload[BASELINE_ARM_OVERRIDES] == { + "spm_unit_work_expenses": {str(YEAR): [2_000, 0]}, + "spm_unit_head_spouse_earned_cap": {str(YEAR): None}, + } + again = export_source_inputs(reloaded) + assert again[BASELINE_ARM_OVERRIDES] == payload[BASELINE_ARM_OVERRIDES] + + +def test_a_marked_reload_refuses_an_override_the_reform_stores_for_all_time(): + """A dataset with no reform gives New York's first family a $500 subsidy + for 2026, and export lists it among the overrides. Under a reform that + stores the subsidy for all time, baseline policy's yearly variable can't + use the reform's holder, so a reform built over that dataset refuses the + input. A marked reload refuses it the same way, by name, before it sets + anything on its arm. An unmarked reload builds, as on main, and its arm + calculates the subsidy.""" + source = Simulation( + dataset=dataset((NEW_YORK,), FAMILIES[:1], yearly_subsidies={YEAR: [500]}) + ) + payload = export_source_inputs(source) + assert SUBSIDY in payload["overrides"] + with pytest.raises(ValueError, match=REFUSAL) as refused: + reload_source_inputs(payload, reform=StoreSubsidiesForAllTime) + names = [entry.name for entry in refused.traceback] + assert "_set_overrides_on_the_arm" in names + assert "_rebuild_baseline_branch" not in names + unmarked = {key: item for key, item in payload.items() if key != DATASET_INPUTS} + reloaded = reload_source_inputs(unmarked, reform=StoreSubsidiesForAllTime) + np.testing.assert_allclose(value(reloaded, SUBSIDY), [500]) + np.testing.assert_allclose( + value(reloaded.baseline, SUBSIDY), NEW_YORK_S0[:1], atol=TOLERANCE + ) + + +class spm_unit_reform_only_amount(Variable): + value_type = float + entity = SPMUnit + label = "An amount only the reform defines" + definition_period = "year" + + def formula(spm_unit, period, parameters): + return spm_unit("spm_unit_pre_subsidy_childcare_expenses", period) * 0 + + +class AddAVariable(Reform): + def apply(self): + self.update_variable(spm_unit_reform_only_amount) + + +def test_a_marked_reload_skips_an_override_baseline_policy_does_not_define(): + """A dataset under a reform that adds a variable gives it a value, which + export lists among the overrides. Baseline policy has no such variable, + so the source's arm has none, and a marked reload sets it on the reform + side alone and raises nothing.""" + name = "spm_unit_reform_only_amount" + source = Simulation( + dataset=dataset((NEW_YORK,), FAMILIES, given={name: (250, 0)}), + reform=AddAVariable, + ) + payload = export_source_inputs(source) + assert name in payload["overrides"] and BASELINE_ARM_OVERRIDES not in payload + reloaded = reload_source_inputs(payload, reform=AddAVariable) + np.testing.assert_allclose(value(reloaded, name), [250, 0]) + assert name not in reloaded.baseline.tax_benefit_system.variables + assert name not in reloaded.baseline.populations["spm_unit"]._holders + np.testing.assert_allclose( + value(reloaded.baseline, EXPENSE), REPORTED_EXPENSE, atol=TOLERANCE + ) + + +def test_a_dump_of_a_dataset_simulation_restores_with_the_dataset_reading(tmp_path): + """Core's ``restore_simulation`` builds a plain core simulation, which read + the pre-subsidy input as a household's: the first family's expense fell + from $14,000 to $83.60. Now the dump holds the mark in ``__entities__``, + and the restore sets it, so the restored simulation reads the expense, + and the second family's Social Security benefit, as its source does. A + dump without the mark file, as earlier dumps are, restores as a + household, a mark other than true or false raises, and a household + simulation's dump holds no mark.""" + source = Simulation(dataset=dataset((NEW_YORK,), FAMILIES)) + directory = tmp_path / "dataset" + simulation_dumper.dump_simulation(source, str(directory)) + system = source.tax_benefit_system + restored = simulation_dumper.restore_simulation(str(directory), system) + np.testing.assert_allclose( + value(restored, EXPENSE), REPORTED_EXPENSE, atol=TOLERANCE + ) + np.testing.assert_allclose(value(restored, "social_security"), [0, 0, 1_200, 0]) + np.testing.assert_allclose( + value(source, "social_security"), value(restored, "social_security") + ) + mark = directory / "__entities__" / DUMP_MARK_FILE + assert json.loads(mark.read_text()) is True + mark.unlink() + unmarked = simulation_dumper.restore_simulation(str(directory), system) + np.testing.assert_allclose(value(unmarked, EXPENSE), [83.60, 0], atol=TOLERANCE) + mark.write_text("1") + with pytest.raises(ValueError, match=NOT_TRUE_OR_FALSE): + simulation_dumper.restore_simulation(str(directory), system) + household = tmp_path / "household" + simulation_dumper.dump_simulation(Simulation(situation=situation()), str(household)) + assert not (household / "__entities__" / DUMP_MARK_FILE).exists() diff --git a/policyengine_us/tools/social_security_inputs.py b/policyengine_us/tools/social_security_inputs.py index d1cb2be576b..3eb677368ff 100644 --- a/policyengine_us/tools/social_security_inputs.py +++ b/policyengine_us/tools/social_security_inputs.py @@ -20,6 +20,7 @@ from pathlib import Path from weakref import WeakKeyDictionary, ref +import numpy as np from policyengine_core.data_storage.store_history import ( advance_sequence_past, next_sequence_number, @@ -46,6 +47,14 @@ # so the simulation built from it still reads its inputs as a dataset's. _DATASET_INPUTS = "_dataset_inputs" _DATASET_INPUTS_ATTRIBUTE = "_inputs_from_dataset" +# A marked snapshot of a reform simulation lists here each override its +# baseline arm doesn't share, with what the arm holds there (null for nothing), +# and a reload gives its arm that in place of the override. +_BASELINE_ARM_OVERRIDES = "_baseline_arm_overrides" +# A dump of a simulation whose inputs came from a dataset holds this file, with +# JSON true, in core's __entities__ directory, which core's restore reads only +# by the names it knows. +_DUMP_MARK_FILE = "dataset_inputs.json" _initial_social_security_ingress = ContextVar("initial_ss_ingress", default=False) _initial_social_security_writes = ContextVar("initial_ss_writes", default=None) @@ -75,7 +84,8 @@ class _Value: def holds_dataset_inputs(simulation): """Whether a simulation's inputs came from a dataset: it runs over one, or it was built from a snapshot (``export_source_inputs``) or an extracted - situation (``extract_person``) of a simulation that did. Core's ``clone`` + situation (``extract_person``) of a simulation that did, or core's + ``restore_simulation`` restored it from a dump of one. Core's ``clone`` copies the attribute, so a branch, a clone and a reform's baseline arm give the same answer as the simulation they copy.""" return bool( @@ -84,6 +94,28 @@ def holds_dataset_inputs(simulation): ) +def _dataset_mark(container, source): + """The dataset mark ``container`` carries: true or false, or false when it + has none. Any other value raises.""" + if _DATASET_INPUTS not in container: + return False + mark = container[_DATASET_INPUTS] + if not isinstance(mark, bool): + raise ValueError( + f"{source} holds {_DATASET_INPUTS} = {mark!r}: the mark must be true or " + "false." + ) + return mark + + +def _same_recorded_values(held, values): + try: + return np.array_equal(np.asarray(held), np.asarray(values), equal_nan=True) + except TypeError: + # Text has no NaN. + return np.array_equal(np.asarray(held), np.asarray(values)) + + def _enabled(simulation): return getattr( getattr(simulation, "tax_benefit_system", None), @@ -1088,7 +1120,7 @@ def load(first, *args, **kwargs): if not dataset: input_dict = args[1] if len(args) > 1 else kwargs["input_dict"] metadata = input_dict.get(_PROVENANCE) - from_dataset = input_dict.get(_DATASET_INPUTS) is True + from_dataset = _dataset_mark(input_dict, "The situation") if _PROVENANCE in input_dict or _DATASET_INPUTS in input_dict: input_dict = { k: v @@ -1229,6 +1261,10 @@ def dump_holder(holder, directory): result = original_dump(holder, directory) if not _enabled(holder.simulation): return result + mark_path = Path(directory) / "__entities__" / _DUMP_MARK_FILE + if holds_dataset_inputs(holder.simulation) and not mark_path.exists(): + # Core makes __entities__ before it dumps any holder. + mark_path.write_text(json.dumps(True)) if holder.variable.name in (*SOCIAL_SECURITY_COMPONENTS, *_REPORTED_COMPONENTS): # A virtual source need not have a physically visible array. # Core creates the directory before discovering that; leave no @@ -1258,6 +1294,11 @@ def restore_holder( return original_restore( simulation, variable, directory, inputs, calculated_number ) + mark_path = Path(directory) / "__entities__" / _DUMP_MARK_FILE + if mark_path.exists() and _dataset_mark( + {_DATASET_INPUTS: json.loads(mark_path.read_text())}, str(mark_path) + ): + setattr(simulation, _DATASET_INPUTS_ATTRIBUTE, True) if not inputs and not getattr( simulation, "_social_security_source_data_restored", False ): @@ -1304,7 +1345,12 @@ def restore_holder( def export_source_inputs(simulation): """Export all registered source periods and final overrides, and mark a - snapshot of a simulation whose inputs came from a dataset.""" + snapshot of a simulation whose inputs came from a dataset. For such a + simulation with a baseline arm, also list each override the arm doesn't + hold, with what it holds there, so a reload's arm can match it.""" + marked = holds_dataset_inputs(simulation) + arm = simulation.baseline if marked else None + arm_overrides = {} names = { key: [str(name) for name in population.ids] for key, population in simulation.populations.items() @@ -1323,6 +1369,7 @@ def export_source_inputs(simulation): values = simulation._get_recorded_input_array(name, period) if values is None: continue + recorded = values if hasattr(values, "decode_to_str"): values = values.decode_to_str() if variable.is_input_variable(): @@ -1331,6 +1378,18 @@ def export_source_inputs(simulation): source.setdefault(name, {})[str(period)] = values[index] else: overrides.setdefault(name, {})[str(period)] = values + if arm is None or name not in arm.tax_benefit_system.variables: + continue + # Core gives the arm each value the dataset gave, so the arm + # lacks or differs from only what a caller set on this + # simulation after construction. + held = arm._get_recorded_input_array(name, period) + if held is None: + arm_overrides.setdefault(name, {})[str(period)] = None + elif not _same_recorded_values(held, recorded): + if hasattr(held, "decode_to_str"): + held = held.decode_to_str() + arm_overrides.setdefault(name, {})[str(period)] = held payload = { "version": 1, "sources": sources, @@ -1339,24 +1398,30 @@ def export_source_inputs(simulation): "default_input_period": str(simulation.default_input_period), "default_calculation_period": str(simulation.default_calculation_period), } - if holds_dataset_inputs(simulation): + if marked: payload[_DATASET_INPUTS] = True + if arm_overrides: + payload[_BASELINE_ARM_OVERRIDES] = arm_overrides return json.loads(json.dumps(payload, cls=NpEncoder)) def reload_source_inputs(payload, **simulation_kwargs): - """Reload complete snapshots, including legacy automatic projections.""" + """Reload complete snapshots, including legacy automatic projections. + + The overrides of a snapshot marked as a dataset's reach a reform's + baseline arm too, as core gives a dataset's values to both.""" from policyengine_us import Simulation if payload.get("version") != 1: raise ValueError("Unsupported source-input snapshot version") + marked = _dataset_mark(payload, "The snapshot") for period_name in ("default_input_period", "default_calculation_period"): simulation_kwargs.setdefault(period_name, payload[period_name]) metadata = payload.get(_PROVENANCE) sources = payload["sources"] if metadata is not None: sources = {**sources, _PROVENANCE: metadata} - if payload.get(_DATASET_INPUTS) is True: + if marked: # The builder marks the simulation before core builds a reform's # baseline arm, so the arm reads the snapshot as a dataset too. sources = {**sources, _DATASET_INPUTS: True} @@ -1364,5 +1429,54 @@ def reload_source_inputs(payload, **simulation_kwargs): for name, periods in payload["overrides"].items(): for period, values in periods.items(): simulation.set_input(name, period, values) + if marked and simulation.baseline is not None: + _set_overrides_on_the_arm( + simulation, + payload["overrides"], + payload.get(_BASELINE_ARM_OVERRIDES) or {}, + ) _refresh_input_variables(simulation) return simulation + + +def _set_overrides_on_the_arm(simulation, overrides, arm_overrides): + """Set each override on ``simulation``'s baseline arm, or, where the + source's arm held something else, that. Skip a variable baseline policy + doesn't define. Raise, naming each variable, before setting anything, if + the reform holds one in another entity or with other ``ETERNITY`` storage + than baseline policy: a dataset giving it raises the same way.""" + from policyengine_us.spm import _built_for_another_policy + + arm = simulation.baseline + variables = arm.tax_benefit_system.variables + mirrored = {} + for name, periods in overrides.items(): + if name not in variables: + continue + held = arm_overrides.get(name, {}) + for period, values in periods.items(): + if period in held: + values = held[period] + if values is None: + continue + mirrored.setdefault(name, {})[period] = values + refused = sorted( + name + for name in mirrored + if _built_for_another_policy( + variables[name], + (holder := simulation.get_holder(name)).population, + holder, + ) + ) + if refused: + raise ValueError( + f"Baseline policy cannot hold the input given for {', '.join(refused)}: " + "the reform defines it in another entity or with other ETERNITY " + "storage than baseline policy, so the reform's baseline arm would " + "calculate it in place of the input." + ) + for name, periods in mirrored.items(): + for period, values in periods.items(): + arm.set_input(name, period, values) + _refresh_input_variables(arm) From a7c00425d38b62c5e34c84537c1d22c10a1ca84e Mon Sep 17 00:00:00 2001 From: Max Ghenis Date: Thu, 26 Nov 2026 19:27:12 +0100 Subject: [PATCH 38/42] Describe snapshots, situations and dumps in the docs and changelog Reorder the SPM child care expense's documentation so "that arm" follows the arm it names, and say that export_source_inputs marks a snapshot, extract_person a situation and dump_simulation a dump. A simulation restored from a marked dump has no arm, as core's restore_simulation builds none, so the documentation no longer gives it one. The Social Security levers page now says what a marked reload gives a reform's baseline arm and where a dump holds the mark, and the changelog fragment names the snapshot mark and the refusal to subsample a simulation named "baseline". Co-Authored-By: Claude Opus 5.5 --- changelog.d/spm-child-care-subsidies.fixed.md | 2 +- docs/social-security-benefit-levers.md | 30 +++++++++++++------ ...spm_unit_capped_work_childcare_expenses.py | 26 +++++++++------- 3 files changed, 37 insertions(+), 21 deletions(-) diff --git a/changelog.d/spm-child-care-subsidies.fixed.md b/changelog.d/spm-child-care-subsidies.fixed.md index ccd15c94e8c..e90c1c08ccb 100644 --- a/changelog.d/spm-child-care-subsidies.fixed.md +++ b/changelog.d/spm-child-care-subsidies.fixed.md @@ -1 +1 @@ -Count every state child care subsidy in the Supplemental Poverty Measure from 2024 by netting it from the SPM child care expense in household calculations, keep the ASEC's reported spending as that expense over a dataset while a reform moves it by the change in subsidy, and add the District of Columbia, Tennessee and Texas subsidies to the 2024 program list. Rebuild a reform's baseline arm without the holders the reform built for its own definition of a variable in another entity or with other ETERNITY storage, as core's own branch does, and raise an error naming the variable when that rebuild would drop an input the caller gave. Give a subsampled branch of a reform simulation its own baseline arm on its sample. +Count every state child care subsidy in the Supplemental Poverty Measure from 2024 by netting it from the SPM child care expense in household calculations, keep the ASEC's reported spending as that expense over a dataset while a reform moves it by the change in subsidy, and add the District of Columbia, Tennessee and Texas subsidies to the 2024 program list. Rebuild a reform's baseline arm without the holders the reform built for its own definition of a variable in another entity or with other ETERNITY storage, as core's own branch does, and raise an error naming the variable when that rebuild would drop an input the caller gave. Give a subsampled branch of a reform simulation its own baseline arm on its sample, and raise an error when a simulation named "baseline" with a baseline arm subsamples, as core would give it baseline policy and drop its arm. Keep the dataset reading of the expense in a simulation built from a snapshot or extracted situation of a dataset simulation and in its baseline arm, which also gets the snapshot's overrides, and in a simulation restored from a dump of one. diff --git a/docs/social-security-benefit-levers.md b/docs/social-security-benefit-levers.md index 3706b58ee22..d31d96837c4 100644 --- a/docs/social-security-benefit-levers.md +++ b/docs/social-security-benefit-levers.md @@ -61,15 +61,27 @@ before final overrides. A snapshot of a simulation over a dataset also carries `"_dataset_inputs": true`, so the reloaded simulation, its baseline arm and its later branches read `spm_unit_capped_work_childcare_expenses` as a dataset simulation does; other dataset-only rules, such as county, read it as a -household. The payload stays at version 1, and a snapshot without the key -reloads as a household. Core's legacy `extract_person` retains every recorded -input period for the four benefit components and their reported twins, excluding -formula caches. This keeps later overrides final on reload and preserves their -source histories and future uprating. Other variables keep Core's usual first -known period. A situation extracted from a dataset simulation carries the same -key, and like the provenance envelope it loads only through this package's -builders. Neither interface settles the separate API/application metadata and -field-exposure contract. +household. Core gives a dataset's values to a reform's baseline arm too, so a +marked reload sets each override on its arm as well. Where the source's arm +held something else for an override, as it does for a value a caller set on +the reform after construction, the snapshot lists what the arm held under +`"_baseline_arm_overrides"`, null for nothing, and the reload's arm gets that. +A marked reload skips a variable baseline policy doesn't define. For one the +reform stores in another entity or with other ETERNITY storage, it raises, +naming the variable, as a reform built over the dataset does. The key must be +true or false, and any other value raises. The payload stays at version 1, and +a snapshot without the key reloads as a household. Core's legacy +`extract_person` retains every recorded input period for the four benefit +components and their reported twins, excluding formula caches. This keeps later +overrides final on reload and preserves their source histories and future +uprating. Other variables keep Core's usual first known period. A situation +extracted from a dataset simulation carries the same key, and like the +provenance envelope it loads only through this package's builders. Neither +interface settles the separate API/application metadata and field-exposure +contract. A dump of a dataset simulation through Core's `dump_simulation` holds +the mark, as JSON true, in `__entities__/dataset_inputs.json`. Core's +`restore_simulation` builds no baseline arm, so a simulation it restores from +that dump reads the expense as a dataset simulation with no arm does. Annual benefit inputs retain Core's period normalization. For example, supplying `social_security_retirement: {"2024-07": 500}` through a PE-US constructor stores diff --git a/policyengine_us/variables/household/expense/childcare/spm_unit_capped_work_childcare_expenses.py b/policyengine_us/variables/household/expense/childcare/spm_unit_capped_work_childcare_expenses.py index 90b876810ed..353509a6ba7 100644 --- a/policyengine_us/variables/household/expense/childcare/spm_unit_capped_work_childcare_expenses.py +++ b/policyengine_us/variables/household/expense/childcare/spm_unit_capped_work_childcare_expenses.py @@ -11,16 +11,19 @@ class spm_unit_capped_work_childcare_expenses(Variable): documentation = ( "Over a dataset, the child care part keeps the reported amount under " "baseline policy and moves by the change in subsidy under a reform, " - "which it reads from the reform's baseline arm. export_source_inputs " - "and extract_person mark a snapshot of a dataset simulation, and a " - "simulation built from a marked snapshot follows the same rule, as " - "does its arm. An unmarked snapshot reloads as a household. " - "Core builds that arm " + "which it reads from the reform's baseline arm. Core builds that arm " "only for a reform passed as reform=, and apply_reform builds none. A " "simulation built with reform= keeps its arm, under baseline policy, " "through any reform applied later. A reformed system passed as " "tax_benefit_system=, or apply_reform on a simulation built without " - "reform=, leaves no arm, so the expense keeps the reported amount." + "reform=, leaves no arm, so the expense keeps the reported amount. " + "export_source_inputs marks a snapshot of a dataset simulation, " + "extract_person a situation extracted from one, and dump_simulation " + "a dump of one. A simulation built from a marked snapshot or " + "situation follows the same rule, as does its arm. One restored from " + "a marked dump follows it too, but core's restore_simulation builds " + "no arm, so where it calculates the expense it keeps the reported " + "amount. An unmarked snapshot, situation or dump reads as a household." ) reference = "https://www2.census.gov/programs-surveys/supplemental-poverty-measure/datasets/spm/spm_techdoc.pdf#page=17" @@ -36,11 +39,12 @@ def formula_2024(spm_unit, period, parameters): if holds_dataset_inputs(simulation): # Datasets fill the pre-subsidy input from the ASEC, which asks # parents how much they spent on child care, and this rule reads - # that as what they paid after any subsidy. A snapshot of a - # dataset simulation carries the same amounts, so a simulation - # rebuilt from one reads them the same way. Baseline policy keeps - # that amount, and a reform moves it by the change in subsidy. A - # baseline arm has no baseline of its own, so it keeps the amount. + # that as what they paid after any subsidy. A snapshot, extracted + # situation or dump of a dataset simulation carries the same + # amounts, so a simulation rebuilt from one reads them the same + # way. Baseline policy keeps that amount, and a reform moves it by + # the change in subsidy. A baseline arm has no baseline of its + # own, so it keeps the amount. out_of_pocket_expenses = pre_subsidy_expenses if simulation.baseline is not None: baseline_spm_unit = simulation.baseline.populations["spm_unit"] From cf7a43e027b0523bbb747e9a5c82b771bd002f70 Mon Sep 17 00:00:00 2001 From: Max Ghenis Date: Thu, 26 Nov 2026 23:15:31 +0100 Subject: [PATCH 39/42] Narrow the docs' arm-override sentence to formula overrides A Social Security component or pure input that a caller sets on a reform after construction reaches both sides of a reload through the snapshot's sources and provenance envelope, so the arm-override list doesn't cover it. Say so, name the `_dataset_inputs` key, limit the refusal to values the arm would get, and state what a reload with `reform=` gives the arm of a snapshot taken without one. Co-Authored-By: Claude Opus 5.5 --- docs/social-security-benefit-levers.md | 22 ++++++++++++++-------- 1 file changed, 14 insertions(+), 8 deletions(-) diff --git a/docs/social-security-benefit-levers.md b/docs/social-security-benefit-levers.md index d31d96837c4..e383aaf5837 100644 --- a/docs/social-security-benefit-levers.md +++ b/docs/social-security-benefit-levers.md @@ -63,14 +63,20 @@ later branches read `spm_unit_capped_work_childcare_expenses` as a dataset simulation does; other dataset-only rules, such as county, read it as a household. Core gives a dataset's values to a reform's baseline arm too, so a marked reload sets each override on its arm as well. Where the source's arm -held something else for an override, as it does for a value a caller set on -the reform after construction, the snapshot lists what the arm held under -`"_baseline_arm_overrides"`, null for nothing, and the reload's arm gets that. -A marked reload skips a variable baseline policy doesn't define. For one the -reform stores in another entity or with other ETERNITY storage, it raises, -naming the variable, as a reform built over the dataset does. The key must be -true or false, and any other value raises. The payload stays at version 1, and -a snapshot without the key reloads as a household. Core's legacy +records another input for a formula override, as it does for a value a caller +set on the reform after construction, the snapshot lists what the arm records +under `"_baseline_arm_overrides"`, null for none, and the reload's arm gets +that. A pure input that a caller sets on a reform simulation after +construction travels in `sources`, and a Social Security component travels in +the provenance envelope, so each reaches both sides of the reload, though the +source's arm lacks it. A marked snapshot of a simulation with no arm lists no +arm values, so a reload with `reform=` gives its arm every override. A marked +reload skips a variable baseline policy doesn't define. It raises, naming the +variable, when the arm would get a value that the reform stores in another +entity or with other ETERNITY storage, as a reform built over the dataset +does. The `_dataset_inputs` key must be true or false, and any other value +raises. The payload stays at version 1, and a snapshot without the key reloads +as a household. Core's legacy `extract_person` retains every recorded input period for the four benefit components and their reported twins, excluding formula caches. This keeps later overrides final on reload and preserves their source histories and future From d10cddb4106316f4ec8fb39690e58da3ccf45194 Mon Sep 17 00:00:00 2001 From: Max Ghenis Date: Thu, 26 Nov 2026 23:33:05 +0100 Subject: [PATCH 40/42] Say what a reload gives the arm for each kind of hand-set value A Social Security component that a caller sets on a reform after construction gets a null in the arm-override list, yet reaches the reload's arm through the provenance envelope, as a pure input does through the sources. Describe the comparison, the listing and the skip in their own sentences, then the two paths that bypass them, and say when a reload raises on the mark's value. Co-Authored-By: Claude Opus 5.5 --- docs/social-security-benefit-levers.md | 34 ++++++++++++++------------ 1 file changed, 19 insertions(+), 15 deletions(-) diff --git a/docs/social-security-benefit-levers.md b/docs/social-security-benefit-levers.md index e383aaf5837..7d490fed5db 100644 --- a/docs/social-security-benefit-levers.md +++ b/docs/social-security-benefit-levers.md @@ -62,21 +62,25 @@ before final overrides. A snapshot of a simulation over a dataset also carries later branches read `spm_unit_capped_work_childcare_expenses` as a dataset simulation does; other dataset-only rules, such as county, read it as a household. Core gives a dataset's values to a reform's baseline arm too, so a -marked reload sets each override on its arm as well. Where the source's arm -records another input for a formula override, as it does for a value a caller -set on the reform after construction, the snapshot lists what the arm records -under `"_baseline_arm_overrides"`, null for none, and the reload's arm gets -that. A pure input that a caller sets on a reform simulation after -construction travels in `sources`, and a Social Security component travels in -the provenance envelope, so each reaches both sides of the reload, though the -source's arm lacks it. A marked snapshot of a simulation with no arm lists no -arm values, so a reload with `reform=` gives its arm every override. A marked -reload skips a variable baseline policy doesn't define. It raises, naming the -variable, when the arm would get a value that the reform stores in another -entity or with other ETERNITY storage, as a reform built over the dataset -does. The `_dataset_inputs` key must be true or false, and any other value -raises. The payload stays at version 1, and a snapshot without the key reloads -as a household. Core's legacy +marked reload sets each override on its arm as well. For a reform simulation +whose inputs came from a dataset, `export_source_inputs` compares each +override with the input its arm records. Where they differ, as they do for a +value a caller set on the reform after construction, the snapshot lists the +arm's input under `"_baseline_arm_overrides"`, or null where the arm records +none. A marked reload gives its arm each listed input in place of the +override and skips a null one. A pure input or a Social Security component +that a caller sets on a reform simulation after construction reaches both +sides of the reload, though the source's arm lacks it. The pure input travels +in `sources`, and the component travels in the provenance envelope even where +the snapshot lists it as null. A marked snapshot of a simulation with no arm +carries no `"_baseline_arm_overrides"`, so a reload with `reform=` gives its +arm every override. A marked reload skips a variable that baseline policy +doesn't define. It raises, naming the variable, when the arm would get a value +that the reform stores in another entity or with other ETERNITY storage, as a +reform built over the dataset does. A reload raises `ValueError` when the +snapshot's `_dataset_inputs` key holds anything but true or false. The payload +stays at version 1, and a snapshot without the key reloads as a household. +Core's legacy `extract_person` retains every recorded input period for the four benefit components and their reported twins, excluding formula caches. This keeps later overrides final on reload and preserves their source histories and future From 688fc8d7af159951f7d0d95c97b40db0ddae1d93 Mon Sep 17 00:00:00 2001 From: Max Ghenis Date: Fri, 27 Nov 2026 00:23:45 +0100 Subject: [PATCH 41/42] Say how a situation's reform arm and a restored dump read the expense A reform rebuilt from an extract_person or sample_person situation of a reform simulation gives its arm the reform side's values, so its arm takes a formula value set on the reform after construction, where a marked snapshot's arm keeps the source arm's value. A restored dump returns an expense it already holds as dumped. Other dataset-only rules read the reload, not the expense, as a household. Co-Authored-By: Claude Opus 5.5 --- docs/social-security-benefit-levers.md | 21 +++++++++++++-------- 1 file changed, 13 insertions(+), 8 deletions(-) diff --git a/docs/social-security-benefit-levers.md b/docs/social-security-benefit-levers.md index 7d490fed5db..49aa5b9aa55 100644 --- a/docs/social-security-benefit-levers.md +++ b/docs/social-security-benefit-levers.md @@ -60,8 +60,8 @@ calculations are excluded. `reload_source_inputs(payload, ...)` restores sources before final overrides. A snapshot of a simulation over a dataset also carries `"_dataset_inputs": true`, so the reloaded simulation, its baseline arm and its later branches read `spm_unit_capped_work_childcare_expenses` as a dataset -simulation does; other dataset-only rules, such as county, read it as a -household. Core gives a dataset's values to a reform's baseline arm too, so a +simulation does; other dataset-only rules, such as county, read the reload as +a household. Core gives a dataset's values to a reform's baseline arm too, so a marked reload sets each override on its arm as well. For a reform simulation whose inputs came from a dataset, `export_source_inputs` compares each override with the input its arm records. Where they differ, as they do for a @@ -86,12 +86,17 @@ components and their reported twins, excluding formula caches. This keeps later overrides final on reload and preserves their source histories and future uprating. Other variables keep Core's usual first known period. A situation extracted from a dataset simulation carries the same key, and like the -provenance envelope it loads only through this package's builders. Neither -interface settles the separate API/application metadata and field-exposure -contract. A dump of a dataset simulation through Core's `dump_simulation` holds -the mark, as JSON true, in `__entities__/dataset_inputs.json`. Core's -`restore_simulation` builds no baseline arm, so a simulation it restores from -that dump reads the expense as a dataset simulation with no arm does. +provenance envelope it loads only through this package's builders. A reform +rebuilt from a situation that `extract_person` or `sample_person` took from a +reform simulation gives its arm the reform side's values. So its arm also takes +a formula value a caller set on the reform after construction, where a marked +snapshot's arm keeps the source arm's value. Neither interface settles the +separate API/application metadata and field-exposure contract. A dump of a +dataset simulation through Core's `dump_simulation` holds the mark, as JSON +true, in `__entities__/dataset_inputs.json`. Core's +`restore_simulation` builds no baseline arm, so where a simulation it restores +from that dump calculates the expense, it reads it as a dataset simulation with +no arm does. An expense the dump already holds comes back as dumped. Annual benefit inputs retain Core's period normalization. For example, supplying `social_security_retirement: {"2024-07": 500}` through a PE-US constructor stores From d367d8c1babb27d9dea1441b221f3ca53aa9ff88 Mon Sep 17 00:00:00 2001 From: Max Ghenis Date: Fri, 27 Nov 2026 00:26:09 +0100 Subject: [PATCH 42/42] Describe the baseline arm's listed inputs in the snapshot comments The comments on _baseline_arm_overrides, export_source_inputs and _set_overrides_on_the_arm now say the snapshot lists each formula override whose recorded input the arm lacks or records differently, with the arm's recorded input or null, and that a pure input or Social Security component set after construction reaches both sides of a reload. Comments and docstrings only. Co-Authored-By: Claude Opus 5.5 --- .../tools/social_security_inputs.py | 23 +++++++++++-------- 1 file changed, 14 insertions(+), 9 deletions(-) diff --git a/policyengine_us/tools/social_security_inputs.py b/policyengine_us/tools/social_security_inputs.py index 3eb677368ff..967d425dfb5 100644 --- a/policyengine_us/tools/social_security_inputs.py +++ b/policyengine_us/tools/social_security_inputs.py @@ -47,9 +47,10 @@ # so the simulation built from it still reads its inputs as a dataset's. _DATASET_INPUTS = "_dataset_inputs" _DATASET_INPUTS_ATTRIBUTE = "_inputs_from_dataset" -# A marked snapshot of a reform simulation lists here each override its -# baseline arm doesn't share, with what the arm holds there (null for nothing), -# and a reload gives its arm that in place of the override. +# A marked snapshot of a reform simulation lists here each formula override +# whose recorded input its baseline arm lacks or records differently, with the +# arm's recorded input (null for none). A reload gives its arm each listed +# input in place of the override and skips a null one. _BASELINE_ARM_OVERRIDES = "_baseline_arm_overrides" # A dump of a simulation whose inputs came from a dataset holds this file, with # JSON true, in core's __entities__ directory, which core's restore reads only @@ -1346,8 +1347,11 @@ def restore_holder( def export_source_inputs(simulation): """Export all registered source periods and final overrides, and mark a snapshot of a simulation whose inputs came from a dataset. For such a - simulation with a baseline arm, also list each override the arm doesn't - hold, with what it holds there, so a reload's arm can match it.""" + simulation with a baseline arm, also list each formula override whose + recorded input the arm lacks or records differently, with the arm's + recorded input (null for none). A pure input or Social Security component + set on the reform after construction travels in ``sources`` or the + provenance envelope, so it reaches both sides of a reload.""" marked = holds_dataset_inputs(simulation) arm = simulation.baseline if marked else None arm_overrides = {} @@ -1441,10 +1445,11 @@ def reload_source_inputs(payload, **simulation_kwargs): def _set_overrides_on_the_arm(simulation, overrides, arm_overrides): """Set each override on ``simulation``'s baseline arm, or, where the - source's arm held something else, that. Skip a variable baseline policy - doesn't define. Raise, naming each variable, before setting anything, if - the reform holds one in another entity or with other ``ETERNITY`` storage - than baseline policy: a dataset giving it raises the same way.""" + snapshot lists the source arm's recorded input, that input, and skip a + listed null. Skip a variable baseline policy doesn't define. Raise, naming + each variable, before setting anything, if the reform holds one in another + entity or with other ``ETERNITY`` storage than baseline policy: a dataset + giving it raises the same way.""" from policyengine_us.spm import _built_for_another_policy arm = simulation.baseline