From 964525d2e97ecb51dd66a82f25ce6ae489f2e363 Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Thu, 19 Nov 2026 00:32:31 +0400 Subject: [PATCH 1/4] Derive reform systems from the built default system Creating a Simulation or Microsimulation with a reform and no supplied tax-benefit system rebuilt CountryTaxBenefitSystem from every parameter and variable file. Copy the built default system instead, return it to its state before the reform-dependent steps, and run those steps on the copy. Fall back to a full build when the default system has changed in a way that would make the copy differ. Co-Authored-By: Claude Opus 5.5 --- policyengine_us/spm.py | 30 +- policyengine_us/system.py | 240 ++++++ .../tests/core/test_derived_reform_system.py | 748 ++++++++++++++++++ policyengine_us/tools/per_capita_uprating.py | 92 +++ 4 files changed, 1107 insertions(+), 3 deletions(-) create mode 100644 policyengine_us/tests/core/test_derived_reform_system.py diff --git a/policyengine_us/spm.py b/policyengine_us/spm.py index 94d547c331e..a1629a3f8ff 100644 --- a/policyengine_us/spm.py +++ b/policyengine_us/spm.py @@ -685,6 +685,10 @@ def clone_spm_system(system, *, copy_receipts=True, parameters=None): cloned.spm_forecast_provider = system.spm_forecast_provider.snapshot( copy_receipts=copy_receipts ) + # The record a default system keeps to derive reform systems holds its + # own variable objects, which the clone has replaced: keeping it would + # keep those objects alive for as long as the clone. + cloned.__dict__.pop("_unreformed_build", None) # A clone owns its tree outright, but it does not keep it to itself: a # branch copies the system, and another simulation can be built on it, at # which point a reform must clone before it writes. ``plain_policy_copy`` @@ -951,9 +955,7 @@ def _prepare_spm_system(self, args, kwargs, config, start_instant): if supplied is None: if reform is not None: chosen = with_parameter_barrier( - self.default_tax_benefit_system( - reform=reform, spm=config, start_instant=start_instant - ) + self._reform_system(reform, config, start_instant) ) else: # No reform and no supplied system: nothing distinguishes this @@ -990,6 +992,28 @@ def _prepare_spm_system(self, args, kwargs, config, start_instant): key: value for key, value in arguments.arguments.items() if key != "self" } + def _reform_system(self, reform, config, start_instant): + """The system ``default_tax_benefit_system(reform=...)`` would build. + + Derive it from the shared default system when that system can give + the same result (``CountryTaxBenefitSystem.can_derive_reform_systems``), + which skips loading and processing every parameter and variable file. + Otherwise build it. + """ + default = self.default_tax_benefit_system_instance + can_derive = getattr(default, "can_derive_reform_systems", None) + if ( + type(default) is self.default_tax_benefit_system + and can_derive is not None + and can_derive() + ): + return default.derive_reform_system( + reform, start_instant=start_instant, spm=config + ) + return self.default_tax_benefit_system( + reform=reform, spm=config, start_instant=start_instant + ) + def clone(self, debug=False, trace=False, clone_tax_benefit_system=True): """Retain cached-result receipts while isolating future calculations.""" cloned = super().clone(debug=debug, trace=trace, clone_tax_benefit_system=False) diff --git a/policyengine_us/system.py b/policyengine_us/system.py index 4460cc277fd..0285a73d734 100644 --- a/policyengine_us/system.py +++ b/policyengine_us/system.py @@ -1,4 +1,6 @@ import hashlib +from copy import deepcopy +from dataclasses import dataclass from functools import lru_cache from pathlib import Path from policyengine_core.taxbenefitsystems import TaxBenefitSystem @@ -50,6 +52,13 @@ from .tools.per_capita_uprating import ( add_per_capita_parameters_for_parameter_uprating, add_per_capita_uprating, + derived_per_capita_series, + detached_copy, + is_national_total_path, + per_capita_nodes_unchanged, + remove_per_capita_series, + restore_child_order, + restore_per_capita_series, ) from policyengine_us.data.dataset_schema import ( _DEFAULT_TIME_PERIOD, @@ -61,9 +70,12 @@ from typing import Annotated from spm_calculator.policyengine_adapter import build_policyengine_variables from policyengine_us.spm import ( + SHARED_TREE_MARK, SPMSimulationMixin, + bind_private_entities, clone_spm_system, create_spm_provider, + plain_policy_copy, ) install_social_security_input_compatibility() @@ -91,6 +103,34 @@ ) +@dataclass(frozen=True, eq=False) +class UnreformedBuild: + """What a system built without a reform records to derive reform systems. + + It holds no reference to the system, so a copy or clone that carries it + does not keep the original's parameter tree alive. + """ + + # The registry before the structural reforms and per-state variables. + variables_before_reforms: dict + # Copies, taken at the same point, of the variables in that registry that + # uprate by a national total. ``add_per_capita_uprating`` later points the + # registry's own objects at the per-capita series in place. + total_uprated_variables: dict + # The per-capita series ``add_per_capita_uprating`` added to the tree + # after that point, and copies, as they stood at that point, of those it + # replaced when it refreshed them. + per_capita_series_added: frozenset + per_capita_series_replaced: dict + # The order of the children of each node holding a replaced series, at + # that point: a refresh moves the series to the end of its parent. + per_capita_parent_child_order: dict + # The children of those nodes when construction finished. + per_capita_parent_children: dict + # The registry when construction finished. + variables: dict + + class CountryTaxBenefitSystem(TaxBenefitSystem): """ The tax-benefit system for the United States. @@ -169,6 +209,61 @@ def __init__( "current_law_cap", draw_cap ) + # Nothing above depends on the reform. A system built without one + # records its policy as it stands here, before the structural reforms, + # the per-state variables and the per-capita series, so that a reform + # system can be derived from it by running only the steps below. An + # empty reform counts as a reform here, as it does for a simulation, + # which derives its system whenever its reform is not None. + if reform is not None: + self._apply_reforms(reform, start_instant) + self._unreformed_build = None + return + variables_before_reforms = dict(self.variables) + total_uprated_variables = { + name: variable.clone() + for name, variable in variables_before_reforms.items() + if is_national_total_path(variable.uprating) + } + series_before = derived_per_capita_series(self.parameters) + series_copies = { + path: detached_copy(series) for path, series in series_before.items() + } + child_order_before = { + parent_path: tuple(self.parameters.get_child(parent_path).children) + for parent_path in {path.rpartition(".")[0] for path in series_before} + } + self._apply_reforms(reform, start_instant) + series_after = derived_per_capita_series(self.parameters) + series_replaced = { + path: series_copies[path] + for path, series in series_before.items() + if series_after.get(path) is not series + } + self._unreformed_build = UnreformedBuild( + variables_before_reforms=variables_before_reforms, + total_uprated_variables=total_uprated_variables, + per_capita_series_added=frozenset( + series_after.keys() - series_before.keys() + ), + per_capita_series_replaced=series_replaced, + per_capita_parent_child_order={ + parent_path: child_order_before[parent_path] + for parent_path in {path.rpartition(".")[0] for path in series_replaced} + }, + per_capita_parent_children={ + parent_path: frozenset(self.parameters.get_child(parent_path).children) + for parent_path in {path.rpartition(".")[0] for path in series_replaced} + }, + variables=dict(self.variables), + ) + + def _apply_reforms(self, reform, start_instant): + """Apply ``reform`` and the structural reforms to processed policy. + + These are the steps of construction that depend on the reform, so + ``derive_reform_system`` runs them on a copy of an unreformed system. + """ if reform: # Applied after the parameter processing pipeline so that values # a reform inserts at future dates cannot act as defined values @@ -206,6 +301,151 @@ def __init__( add_per_capita_uprating(self) self._per_capita_uprating_built = True + def can_derive_reform_systems(self) -> bool: + """Whether ``derive_reform_system`` gives what a full rebuild would. + + Only a system built without a reform, and changed in neither its + variable registry nor its parameters since, holds the policy that + construction reaches before it applies a reform. A clone drops the + record of the build (``clone_spm_system``); a shallow copy that still + reads the same registry objects and tree keeps it, and derives the + same system. A subclass with its own constructor may build more than + ``_apply_reforms`` gives a derived system, so it is rebuilt. + + The check sees every change to the variable registry, and every + parameter change made through ``Parameter.update``, which marks the + parameter and its ancestors modified; reform dictionaries and most + ``modify_parameters`` modifiers change parameters that way. It does + not see changes that mark nothing: nodes added or replaced with + ``add_child``, ``replace_child`` or ``merge`` (by a modifier, or by + ``load_extension`` for an extension's parameters), assignments to + ``values_list[i].value``, and edits to metadata or to a variable's + attributes. A reform system derived afterwards includes + such changes, as every simulation that shares this system's policy + already does; a full rebuild would not. Detecting them would need a + comparison of the whole tree on every derivation (measured at 0.7 to + 1.6 s, against about 2.75 s for the derivation). The exception is the + few nodes derivation itself undoes the per-capita step on: if a series + the build added or refreshed, or the set of children of a node holding + a refreshed one, has changed, the system is rebuilt. + """ + build = self.__dict__.get("_unreformed_build") + if build is None: + return False + if type(self).__init__ is not CountryTaxBenefitSystem.__init__: + return False + if self.variables.keys() != build.variables.keys() or any( + self.variables[name] is not variable + for name, variable in build.variables.items() + ): + return False + # Derivation removes the per-capita series the build added and + # restores those it refreshed, so those nodes must be as it left them. + if not per_capita_nodes_unchanged( + self.parameters, + build.per_capita_series_added | build.per_capita_series_replaced.keys(), + build.per_capita_parent_children, + ): + return False + # Construction leaves every parameter unmodified, and + # ``Parameter.update`` marks what it changes. A node added after + # construction has no flag at all: an unmarked change, like those + # the docstring lists. + return not any( + getattr(parameter, "modified", False) + for parameter in self.parameters.get_descendants() + ) + + def derive_reform_system( + self, + reform, + start_instant: Annotated[ + str, "ISO date format YYYY-MM-DD" + ] = DEFAULT_START_DATE, + spm: dict | None = None, + ) -> "CountryTaxBenefitSystem": + """The system ``CountryTaxBenefitSystem(reform, start_instant, spm)`` + builds, without loading or processing any parameter or variable file. + + Construction loads about 12,000 parameter files and 12,300 variable + files and then homogenizes, interpolates, uprates and backdates the + tree, none of which depends on the reform. So copy this system's + processed parameters and its variable registry from before the + structural reforms, and run only the steps that follow + (``_apply_reforms``): apply the reform, detect the structural reforms + from the reformed parameters at ``start_instant``, add the per-state + variables and rebuild the per-capita uprating series. + + Like core's ``Reform(baseline)``, this clones the parameter tree and + copies the variable dictionary, but the result is a + ``CountryTaxBenefitSystem``. A core ``Reform`` takes its class + attributes and methods from ``TaxBenefitSystem`` instead, which drops + ``auto_carry_over_input_variables`` and this class's ``clone`` and + ``modify_parameters``. + + Variable objects are shared with this system, as ``share_spm_policy`` + shares them with every ordinary simulation: each core operation a + reform performs on a variable binds a new object to the name. The + exceptions are the variables that uprate by a national total, which + the per-capita step changes in place: those are fresh copies of the + recorded ones. + + Edits written directly into this system's objects, bypassing the + methods that mark parameters modified, carry over into the derived + system (see ``can_derive_reform_systems``). + """ + if not self.can_derive_reform_systems(): + raise ValueError( + "Only a system built without a reform, and unchanged since, " + "can derive reform systems; build CountryTaxBenefitSystem(" + "reform=...) instead." + ) + derived = plain_policy_copy(self) + derived._unreformed_build = None + # A simulation may have bound this system as its own; the derived + # system is not bound to any simulation yet. + derived.__dict__.pop("simulation", None) + # Core's clone copies the root node's attributes, including the mark + # that another system reads this tree and any tracer a traced request + # wrote there. A tree loaded from files has no mark (which reads as + # unshared) and no tracer. + build = self._unreformed_build + parameters = self.parameters.clone() + parameters.__dict__.pop(SHARED_TREE_MARK, None) + parameters.trace = False + parameters.tracer = None + parameters.branch_name = None + # In the default build, the per-capita step that ends construction is + # the only step after the recorded point that changes the tree: it + # adds series and refreshes some that parameter uprating built. Undo + # both, so a reform sees the series a full rebuild has when it + # applies the reform. + for path in build.per_capita_series_added: + remove_per_capita_series(parameters, path) + for path, earlier in build.per_capita_series_replaced.items(): + restore_per_capita_series(parameters, path, detached_copy(earlier)) + for parent_path, order in build.per_capita_parent_child_order.items(): + restore_child_order(parameters, parent_path, order) + derived.parameters = parameters + derived._parameters_at_instant_cache = {} + derived.variables = dict(build.variables_before_reforms) + # Fresh copies each time: the per-capita step points them at the + # per-capita series in place, and a reform's ``update_variable`` + # inherits the national total from them as it does in a full rebuild. + derived.variables.update( + (name, variable.clone()) + for name, variable in build.total_uprated_variables.items() + ) + bind_private_entities(derived) + derived.spm_forecast_provider = create_spm_provider(spm) + derived.modelled_policies = deepcopy(self.modelled_policies) + derived.variable_module_metadata = dict(self.variable_module_metadata) + # Construction applies the reform before it builds the per-capita + # series, so ``modify_parameters`` must not rebuild them midway. + derived._per_capita_uprating_built = False + derived._apply_reforms(reform, start_instant) + return derived + def modify_parameters(self, modifier_function): result = super().modify_parameters(modifier_function) # Reforms applied after init (core's Simulation applies the reform diff --git a/policyengine_us/tests/core/test_derived_reform_system.py b/policyengine_us/tests/core/test_derived_reform_system.py new file mode 100644 index 00000000000..471b38b378e --- /dev/null +++ b/policyengine_us/tests/core/test_derived_reform_system.py @@ -0,0 +1,748 @@ +"""Reform simulations derive their policy from the built default system. + +``CountryTaxBenefitSystem(reform=...)`` loads every parameter and variable +file and runs the whole parameter pipeline again, although only the steps that +follow the pipeline depend on the reform. A reform simulation instead copies +the default system's processed parameters and variables and runs only those +steps (``CountryTaxBenefitSystem.derive_reform_system``). The system it gets +must be the one a full rebuild produces, and deriving it must leave the default +system unchanged. +""" + +import dataclasses +import json +import re +from copy import copy + +import pytest +from policyengine_core.parameters import ParameterNode +from policyengine_core.periods import YEAR +from policyengine_core.reforms import Reform +from policyengine_core.variables import Variable + +from policyengine_us import Simulation +from policyengine_us.entities import Person +from policyengine_us.spm import SHARED_TREE_MARK +from policyengine_us.system import CountryTaxBenefitSystem, system +from policyengine_us.tools.per_capita_uprating import ( + DERIVED_FROM, + detached_copy, + remove_per_capita_series, + restore_child_order, + restore_per_capita_series, +) + +SINGLE_STANDARD_DEDUCTION = "gov.irs.deductions.standard.amount.SINGLE" +# A single $50,000 earner in 2024, as in test_spm_simulation_isolation.py: +# a $20,000 single standard deduction leaves taxable income of 30,000, so +# 10% of 11,600 + 12% of 18,400 = 3,368. +BASELINE_INCOME_TAX = 4_016 +REFORMED_INCOME_TAX = 3_368 +REFORMED_STANDARD_DEDUCTION = 20_000 +BASELINE_SINGLE_STANDARD_DEDUCTION = 14_600 +# Structural reforms are detected from the reformed parameters: this switch +# makes the full rebuild replace ``refundable_ctc``. +CTC_SWITCH = "gov.contrib.ctc.minimum_refundable.in_effect" +# A structural switch whose first dated value is after 2019, detected from a +# start instant before 2024 (see test_reform_backdating.py). +LINEAR_PHASE_OUT_SWITCH = "gov.contrib.ctc.linear_phase_out.in_effect" +LINEAR_PHASE_OUT_START_YEAR = 2019 +# A national total that 391 variables uprate by through its per-capita series, +# and the population series that series divides by. +AGI_TOTAL = "calibration.gov.cbo.income_by_source.adjusted_gross_income" +# Built for parameter uprating, so a full rebuild holds it when it applies a +# reform; the default build's last step refreshes it, and a derived system +# restores the earlier version. +AGI_PER_CAPITA = f"{AGI_TOTAL}_per_capita" +POPULATION = "calibration.gov.census.populations.total" +# Fixed values, not scaled ones: the constructor applies a reform twice. +REFORMED_AGI_TOTAL = 3e13 +REFORMED_POPULATION = 4e8 +# The only variable that uprates by this national total is rental_income, so +# re-pointing it to CPI-U leaves the total's per-capita series unused, and a +# full rebuild never creates the series. +RENTAL_INCOME_TOTAL = "calibration.gov.irs.soi.rental_income" +RENTAL_INCOME_PER_CAPITA = f"{RENTAL_INCOME_TOTAL}_per_capita" +REFORMED_RENTAL_INCOME_TOTAL = 1e12 +CPI_U = "gov.bls.cpi.cpi_u" +SENIOR_DEDUCTION_EXTENSION_SWITCH = ( + "gov.contrib.crfb.senior_deduction_extension.applies" +) +# The structural reform adds the senior deduction to this list from 2029. +DEDUCTIONS_IF_ITEMIZING = "gov.irs.deductions.deductions_if_itemizing" + + +class derived_reform_test_income(Variable): + value_type = float + entity = Person + definition_period = YEAR + label = "Income input added only by the derived-reform test reform" + # A national total: the system must point it at the per-capita series. + uprating = AGI_TOTAL + + +class rental_income_uprated_by_prices(Variable): + # ``update_variable`` registers this under its ``__name__``. + uprating = CPI_U + + +rental_income_uprated_by_prices.__name__ = "rental_income" + + +class rental_income_with_a_formula(Variable): + # Inherits the national-total uprating that ``rental_income`` declares. + def formula(person, period, parameters): + return person("employment_income", period) * 0 + + +rental_income_with_a_formula.__name__ = "rental_income" + + +class RentalIncomeFormulaReform(Reform): + def apply(self): + self.update_variable(rental_income_with_a_formula) + + +def set_population_from_2031(parameters): + parameters.get_child(POPULATION).update( + start="2031-01-01", value=REFORMED_POPULATION + ) + return parameters + + +class VariableAndModifierReform(Reform): + """Reform steps a parameter dictionary does not exercise. + + ``update_variable`` rather than ``add_variable``, because the constructor + applies a reform twice. The modifier changes the population series, so + every per-capita series has to be rebuilt from the reformed values. + """ + + def apply(self): + self.neutralize_variable("snap") + self.update_variable(derived_reform_test_income) + self.update_variable(rental_income_uprated_by_prices) + self.modify_parameters(set_population_from_2031) + + +# A bracket of a parameter scale (corpus entry targeted-ctc-base-amount-bounded). +# Which ancestors an update to it marks modified depends on the brackets' +# parent links, which a tree loaded from files and its clone must share. +CTC_BASE_BRACKET_AMOUNT = "gov.irs.credits.ctc.amount.base[0].amount" +PARAMETER_REFORM = { + # Ends before the parameter's later scheduled values. + SINGLE_STANDARD_DEDUCTION: {"2026-01-01.2028-12-31": REFORMED_STANDARD_DEDUCTION}, + CTC_BASE_BRACKET_AMOUNT: {"2026-01-01.2100-12-31": 3_000}, + CTC_SWITCH: {"2026-01-01.2100-12-31": True}, + AGI_TOTAL: {"2030-01-01": REFORMED_AGI_TOTAL}, + AGI_PER_CAPITA: {"2026-01-01": 50_000.0}, + RENTAL_INCOME_TOTAL: {"2030-01-01": REFORMED_RENTAL_INCOME_TOTAL}, + # Detected within five years of the start instant; the structural reform + # it selects edits parameters, inside ``_apply_reforms``. + SENIOR_DEDUCTION_EXTENSION_SWITCH: {"2025-01-01.2100-12-31": True}, +} +COMBINED_REFORM = (PARAMETER_REFORM, VariableAndModifierReform) +# Detection looks five years ahead of the start instant, so a switch that ends +# in 2020 is found from 2019 but not from the default start in 2024. +EARLY_SWITCH_REFORM = { + LINEAR_PHASE_OUT_SWITCH: {f"{LINEAR_PHASE_OUT_START_YEAR}-01-01.2020-12-31": True} +} +EARLY_START_INSTANT = f"{LINEAR_PHASE_OUT_START_YEAR}-01-01" + + +def earner_situation(): + return { + "people": {"person": {"age": {2024: 40}, "employment_income": {2024: 50_000}}}, + "households": { + "household": {"members": ["person"], "county_fips": {2024: "06037"}} + }, + } + + +def parameter_state(policy): + """Every parameter node's type, dated values, metadata, modified flag + and child order, the root included. + + Values are compared by ``repr``, which is exact for floats and equal for + NaN. Metadata is serialized, so a later in-place edit of a metadata + dictionary shows up against a state recorded earlier. A node that was + never marked has no ``modified`` flag until ``_apply_reforms`` sets every + flag to False, and nothing reads the flag before then, so a missing flag + counts as False. + """ + state = {} + root = policy.parameters + for node in [root, *root.get_descendants()]: + values = getattr(node, "values_list", None) + children = getattr(node, "children", None) + state[node.name] = ( + type(node).__name__, + None + if values is None + else [(entry.instant_str, repr(entry.value)) for entry in values], + json.dumps(node.metadata, sort_keys=True, default=repr), + getattr(node, "modified", False), + None if children is None else list(children), + ) + return state + + +MODIFIED_FLAG = 3 + + +def without_modified_flags(state): + return { + name: node[:MODIFIED_FLAG] + node[MODIFIED_FLAG + 1 :] + for name, node in state.items() + } + + +def root_attributes(policy): + """The root node's attribute names, and the values of those a traced or + shared tree sets there.""" + root = policy.parameters + return ( + sorted(vars(root)), + getattr(root, SHARED_TREE_MARK, None), + root.trace, + root.tracer, + root.branch_name, + ) + + +def build_record_state(policy): + """What the build record holds, by value and by object identity.""" + build = policy._unreformed_build + return ( + { + name: id(variable) + for name, variable in build.variables_before_reforms.items() + }, + {name: id(variable) for name, variable in build.variables.items()}, + { + name: (variable.uprating, sorted(variable._explicit_attribute_names)) + for name, variable in build.total_uprated_variables.items() + }, + build.per_capita_series_added, + { + path: ( + [ + (entry.instant_str, repr(entry.value)) + for entry in series.values_list + ], + json.dumps(series.metadata, sort_keys=True, default=repr), + series.parent, + ) + for path, series in build.per_capita_series_replaced.items() + }, + dict(build.per_capita_parent_child_order), + ) + + +def has_parameter(policy, name): + node = policy.parameters + for part in name.split("."): + node = getattr(node, "children", {}).get(part) + if node is None: + return False + return True + + +def qualified_name(function): + """The formula's module and qualified name, without the loading system. + + Core names the module of each variable file it loads + ``{id(system)}_{hash(path)}_{file}``, so the same file loaded by two + systems gets two module names. + """ + module = re.sub(r"^\d+_", "", function.__module__) + return f"{module}.{function.__qualname__}" + + +def variable_state(policy): + """Each variable's formulas, by qualified name, and the attributes a + reform or the system's own build steps change.""" + return { + name: ( + { + str(start): qualified_name(formula) + for start, formula in variable.formulas.items() + }, + variable.uprating, + repr(variable.adds), + repr(variable.subtracts), + repr(variable.defined_for), + variable.is_neutralized, + variable.entity.key, + variable.definition_period, + variable.value_type, + repr(variable.default_value), + variable.label, + ) + for name, variable in policy.variables.items() + } + + +def test_derived_system_from_an_early_start_instant_matches_a_full_rebuild(): + rebuilt = CountryTaxBenefitSystem( + reform=EARLY_SWITCH_REFORM, start_instant=EARLY_START_INSTANT + ) + derived = system.derive_reform_system( + EARLY_SWITCH_REFORM, start_instant=EARLY_START_INSTANT + ) + derived_variables = variable_state(derived) + assert derived_variables == variable_state(rebuilt) + assert parameter_state(derived) == parameter_state(rebuilt) + # Guard: the switch replaced a formula. Detection from the default start + # instant would not find it, so detection ran from the early one. + assert derived_variables != variable_state(system) + + +@pytest.mark.parametrize( + "reform, error", + [ + # A full rebuild re-points the updated variable from the national + # total it inherits to the per-capita series, which declares + # ``uprating`` next to the formula. + (RentalIncomeFormulaReform, "mixes computation modes"), + # A full rebuild has no per-capita series yet when it applies the + # reform; the system builds them afterwards. + ( + {RENTAL_INCOME_PER_CAPITA: {"2026-01-01": 123.0}}, + f"Could not find the parameter {RENTAL_INCOME_PER_CAPITA}", + ), + ], + ids=["formula-on-a-total-uprated-input", "reform-to-a-per-capita-series"], +) +def test_a_reform_a_full_rebuild_rejects_is_rejected_when_derived(reform, error): + with pytest.raises(ValueError, match=re.escape(error)): + CountryTaxBenefitSystem(reform=reform) + with pytest.raises(ValueError, match=re.escape(error)): + system.derive_reform_system(reform) + assert system.can_derive_reform_systems() + + +def test_a_system_built_under_an_empty_reform_cannot_derive_like_a_derived_one(): + # ``Simulation(reform={})`` derives its system, because the reform is not + # None. A full rebuild under the same reform must match it, so it must not + # record a build to derive from either. + assert not system.derive_reform_system({}).can_derive_reform_systems() + assert not CountryTaxBenefitSystem(reform={}).can_derive_reform_systems() + + +def test_a_subclass_that_builds_differently_cannot_derive(): + """A subclass whose constructor does more than this class's would lose + those steps in a derived system, which runs only ``_apply_reforms``.""" + + class SystemWithItsOwnConstructor(CountryTaxBenefitSystem): + def __init__(self, *args, **kwargs): + super().__init__(*args, **kwargs) + + class SystemWithTheSameConstructor(CountryTaxBenefitSystem): + pass + + # Shallow copies read the default system's registry and tree, so only the + # class differs. Building either subclass would take seconds. + differently_built = copy(system) + differently_built.__class__ = SystemWithItsOwnConstructor + assert not differently_built.can_derive_reform_systems() + same_build = copy(system) + same_build.__class__ = SystemWithTheSameConstructor + assert same_build.can_derive_reform_systems() + + +def test_a_clone_does_not_keep_the_record_of_its_original_build(): + # The record holds the original's variable objects, which a clone + # replaces, so keeping it would keep them alive with the clone. + assert system.clone().__dict__.get("_unreformed_build") is None + + +def test_deriving_a_reform_system_leaves_the_default_system_unchanged(): + parameters_before = parameter_state(system) + variables_before = dict(system.variables) + # Derived systems share most variable objects with the default system, + # so their attributes must not change either. + variable_attributes_before = variable_state(system) + # Every later derivation starts from the build record. + build_record_before = build_record_state(system) + entities_before = list(system.entities) + provider_before = system.spm_forecast_provider + + derived = system.derive_reform_system(COMBINED_REFORM) + # A reform simulation applies the reform to its system again and adds a + # baseline arm that shares the default system's policy. + simulation = Simulation(situation=earner_situation(), reform=COMBINED_REFORM) + simulation.calculate("household_net_income", 2024) + simulation.baseline.calculate("household_net_income", 2024) + + assert parameter_state(system) == parameters_before + assert system.variables.keys() == variables_before.keys() + assert all( + system.variables[name] is variable + for name, variable in variables_before.items() + ) + assert variable_state(system) == variable_attributes_before + assert build_record_state(system) == build_record_before + assert system.entities == entities_before + assert all(entity._tax_benefit_system is system for entity in system.entities) + assert system.spm_forecast_provider is provider_before + assert derived.parameters is not system.parameters + # The default system stays derivable for the next reform simulation. + assert system.can_derive_reform_systems() + + +def test_reform_simulation_derives_its_system_instead_of_rebuilding(monkeypatch): + def refuse_to_rebuild(*args, **kwargs): + raise AssertionError("A reform simulation rebuilt the tax-benefit system.") + + # The default system's own cache of parameters at an instant, which a + # derived system must not read or fill. + default_at_2024 = system.get_parameters_at_instant("2024-01-01") + monkeypatch.setattr(CountryTaxBenefitSystem, "__init__", refuse_to_rebuild) + simulation = Simulation( + situation=earner_situation(), + reform={ + SINGLE_STANDARD_DEDUCTION: { + "2024-01-01.2100-12-31": REFORMED_STANDARD_DEDUCTION + } + }, + ) + + assert isinstance(simulation.tax_benefit_system, CountryTaxBenefitSystem) + assert simulation.tax_benefit_system.parameters is not system.parameters + assert simulation.calculate("income_tax", 2024)[0] == REFORMED_INCOME_TAX + assert simulation.baseline.calculate("income_tax", 2024)[0] == (BASELINE_INCOME_TAX) + derived_at_2024 = simulation.tax_benefit_system.get_parameters_at_instant( + "2024-01-01" + ) + assert derived_at_2024.gov.irs.deductions.standard.amount.SINGLE == ( + REFORMED_STANDARD_DEDUCTION + ) + assert system.get_parameters_at_instant("2024-01-01") is default_at_2024 + assert default_at_2024.gov.irs.deductions.standard.amount.SINGLE == ( + BASELINE_SINGLE_STANDARD_DEDUCTION + ) + + +def test_a_node_without_a_modified_flag_does_not_stop_the_check(monkeypatch): + # A scale added to the tree after construction (add_child, merge, + # load_extension) has no ``modified`` flag, since only ``_apply_reforms`` + # sets one on every node. Like other unmarked changes it is carried into + # derived systems (see ``can_derive_reform_systems``); it must not raise. + scale = system.parameters.get_child("gov.irs.credits.ctc.amount.base") + monkeypatch.delattr(scale, "modified") + assert system.can_derive_reform_systems() + + +def test_a_restored_series_returns_to_its_place_among_its_siblings(): + """Refreshing a series deletes it and adds it again, which moves it to + the end of its parent's children; a derived tree must put back the + order the parent had before the refresh. Removing and restoring series + must also keep the parent's attribute for each child in step, since + modifiers reach nodes by attribute.""" + series = { + name: { + "metadata": {DERIVED_FROM: f"totals.{name.removesuffix('_per_capita')}"}, + "values": {"2024-01-01": 1.0}, + } + for name in ("a_per_capita", "b_per_capita") + } + tree = ParameterNode("", data={"totals": series}) + totals = tree.get_child("totals") + order_before = list(totals.children) + earlier = detached_copy(totals.children["a_per_capita"]) + # What ``add_per_capita_uprating`` does when it refreshes a series. + refreshed = detached_copy(earlier) + del totals.children["a_per_capita"] + totals.add_child("a_per_capita", refreshed) + assert list(totals.children) != order_before + + restore_per_capita_series(tree, "totals.a_per_capita", earlier) + restore_child_order(tree, "totals", order_before) + + assert list(totals.children) == order_before + assert totals.children["a_per_capita"] is earlier + assert totals.a_per_capita is earlier + assert earlier.parent is totals + assert refreshed.parent is None + + removed = totals.children["b_per_capita"] + remove_per_capita_series(tree, "totals.b_per_capita") + assert "b_per_capita" not in totals.children + assert "b_per_capita" not in vars(totals) + assert removed.parent is None + + +def test_changed_nodes_holding_per_capita_series_are_rebuilt(monkeypatch): + """Derivation removes the series the build added and restores those it + refreshed, which needs those nodes as the build left them. If they have + changed, without anything marked modified, the system is rebuilt rather + than derivation failing.""" + refreshed_series = system.parameters.get_child(AGI_PER_CAPITA) + holder = refreshed_series.parent + added_series_name = RENTAL_INCOME_PER_CAPITA.rpartition(".")[2] + added_series_holder = system.parameters.get_child(RENTAL_INCOME_PER_CAPITA).parent + not_derived = detached_copy(refreshed_series) + not_derived.metadata = {} + changes = [ + lambda: monkeypatch.setitem( + holder.children, "added_after_construction", detached_copy(refreshed_series) + ), + lambda: monkeypatch.delitem( + holder.children, "adjusted_gross_income_per_capita" + ), + lambda: monkeypatch.setitem( + holder.children, "adjusted_gross_income_per_capita", not_derived + ), + lambda: monkeypatch.delitem(added_series_holder.children, added_series_name), + ] + for change in changes: + change() + assert not system.can_derive_reform_systems() + monkeypatch.undo() + assert system.can_derive_reform_systems() + + +def test_a_derived_tree_puts_back_the_recorded_order_of_refreshed_siblings( + monkeypatch, +): + """In the current tree each refreshed series is already the last of its + siblings, so the recorded and final orders agree. Reversing the recorded + order shows that derivation applies it before the reform steps start.""" + build = system._unreformed_build + reversed_orders = { + parent_path: tuple(reversed(order)) + for parent_path, order in build.per_capita_parent_child_order.items() + } + assert reversed_orders + monkeypatch.setattr( + system, + "_unreformed_build", + dataclasses.replace(build, per_capita_parent_child_order=reversed_orders), + ) + orders_at_start = {} + apply_reforms = CountryTaxBenefitSystem._apply_reforms + + def recording_apply_reforms(policy, reform, start_instant): + orders_at_start.update( + (path, tuple(policy.parameters.get_child(path).children)) + for path in reversed_orders + ) + apply_reforms(policy, reform, start_instant) + + monkeypatch.setattr( + CountryTaxBenefitSystem, "_apply_reforms", recording_apply_reforms + ) + system.derive_reform_system({}) + assert orders_at_start == reversed_orders + + +def test_a_default_system_of_another_class_is_rebuilt(monkeypatch): + """A simulation derives only from a default system of the class it would + build, since another class may build differently.""" + + class SystemWithTheSameConstructor(CountryTaxBenefitSystem): + pass + + other_class = copy(system) + other_class.__class__ = SystemWithTheSameConstructor + # Guard: the system itself could derive; only its class differs. + assert other_class.can_derive_reform_systems() + built = [] + + def record_rebuild(self, **kwargs): + built.append(kwargs) + + monkeypatch.setattr(CountryTaxBenefitSystem, "__init__", record_rebuild) + simulation = Simulation.__new__(Simulation) + simulation.default_tax_benefit_system_instance = other_class + + chosen = simulation._reform_system(PARAMETER_REFORM, None, "2024-01-01") + + assert type(chosen) is CountryTaxBenefitSystem + assert built == [ + {"reform": PARAMETER_REFORM, "spm": None, "start_instant": "2024-01-01"} + ] + + +def test_a_changed_default_system_is_rebuilt_rather_than_derived(monkeypatch): + """A default system changed after it was built is rebuilt from files. + + A full rebuild never saw the change, so a derived system would differ + from it. + """ + changed_variables = dict(system.variables) + changed_variables["snap"] = system.variables["income_tax"] + monkeypatch.setattr(system, "variables", changed_variables) + assert not system.can_derive_reform_systems() + monkeypatch.undo() + assert system.can_derive_reform_systems() + + # A variable added to the registry, as ``load_extension`` adds them. + monkeypatch.setitem( + system.variables, "added_after_construction", system.variables["income_tax"] + ) + assert not system.can_derive_reform_systems() + monkeypatch.undo() + assert system.can_derive_reform_systems() + + standard_deduction = system.parameters.get_child(SINGLE_STANDARD_DEDUCTION) + monkeypatch.setattr(standard_deduction, "modified", True) + assert not system.can_derive_reform_systems() + monkeypatch.undo() + assert system.can_derive_reform_systems() + + +def test_simulation_rebuilds_when_its_default_system_cannot_derive(monkeypatch): + built = [] + + def record_rebuild(self, **kwargs): + # Records the arguments instead of building, which takes seconds. + built.append(kwargs) + + monkeypatch.setattr(CountryTaxBenefitSystem, "__init__", record_rebuild) + monkeypatch.setattr( + CountryTaxBenefitSystem, "can_derive_reform_systems", lambda self: False + ) + config = {"geography_kind": "national"} + + chosen = Simulation.__new__(Simulation)._reform_system( + PARAMETER_REFORM, config, EARLY_START_INSTANT + ) + + assert type(chosen) is CountryTaxBenefitSystem + assert built == [ + { + "reform": PARAMETER_REFORM, + "spm": config, + "start_instant": EARLY_START_INSTANT, + } + ] + + +# The tests that share this fixture come last, so that its two systems are +# not kept alive while the tests above build their own. +@pytest.fixture(scope="module") +def combined_systems(): + """A full rebuild and a derived system under the same combined reform. + + Also records each system's policy as ``_apply_reforms`` starts, where + the steps that depend on the reform begin. + """ + policy_when_reforms_start = {} + apply_reforms = CountryTaxBenefitSystem._apply_reforms + + def recording_apply_reforms(policy, reform, start_instant): + policy_when_reforms_start[id(policy)] = ( + parameter_state(policy), + variable_state(policy), + ) + apply_reforms(policy, reform, start_instant) + + with pytest.MonkeyPatch.context() as patch: + patch.setattr( + CountryTaxBenefitSystem, "_apply_reforms", recording_apply_reforms + ) + rebuilt = CountryTaxBenefitSystem(reform=COMBINED_REFORM) + # What sharing and a traced request leave on the default tree's root, + # which a tree loaded from files does not have. + root = system.parameters + patch.setattr(root, SHARED_TREE_MARK, True, raising=False) + patch.setattr(root, "trace", True) + patch.setattr(root, "tracer", object()) + patch.setattr(root, "branch_name", "a branch") + derived = system.derive_reform_system(COMBINED_REFORM) + return ( + rebuilt, + derived, + policy_when_reforms_start[id(rebuilt)], + policy_when_reforms_start[id(derived)], + ) + + +def test_a_derived_system_starts_the_reform_steps_from_the_same_policy( + combined_systems, +): + """Everything construction does before ``_apply_reforms`` is independent + of the reform, so a derived system must reach that point holding what a + full rebuild holds there, not what the default system holds afterwards.""" + _, _, rebuilt_at_start, derived_at_start = combined_systems + # Without the ``modified`` flags: the parameter pipeline leaves many set, + # nothing reads them during construction, and ``_apply_reforms`` clears + # them all before it applies the reform that sets the final ones (which + # the other tests compare). + rebuilt_parameters, rebuilt_variables = rebuilt_at_start + derived_parameters, derived_variables = derived_at_start + for rebuilt_state, derived_state in ( + ( + without_modified_flags(rebuilt_parameters), + without_modified_flags(derived_parameters), + ), + (rebuilt_variables, derived_variables), + ): + differing_names = sorted( + name + for name in rebuilt_state.keys() | derived_state.keys() + if rebuilt_state.get(name) != derived_state.get(name) + ) + assert differing_names == [] + + +def test_derived_parameters_match_a_full_rebuild(combined_systems): + rebuilt, derived, *_ = combined_systems + rebuilt_parameters = parameter_state(rebuilt) + derived_parameters = parameter_state(derived) + assert derived_parameters == rebuilt_parameters + assert root_attributes(derived) == root_attributes(rebuilt) + # Guards: the default system builds the per-capita series that the + # re-pointed variable no longer uses; the full rebuild does not. The + # structural reform's parameter edit took effect. The bracket update + # marked the bracket modified. + assert has_parameter(system, RENTAL_INCOME_PER_CAPITA) + assert RENTAL_INCOME_PER_CAPITA not in rebuilt_parameters + deductions_in_2029 = [ + policy.parameters.get_child(DEDUCTIONS_IF_ITEMIZING)("2029-01-01") + for policy in (derived, system) + ] + assert deductions_in_2029[0] != deductions_in_2029[1] + assert derived_parameters[CTC_BASE_BRACKET_AMOUNT][MODIFIED_FLAG] + + +def test_derived_variables_match_a_full_rebuild(combined_systems): + rebuilt, derived, *_ = combined_systems + derived_variables = variable_state(derived) + assert derived_variables == variable_state(rebuilt) + # Guards: each reform step the comparison covers took effect. + assert derived_variables["snap"][5] + assert derived_variables["derived_reform_test_income"][1] == ( + f"{AGI_TOTAL}_per_capita" + ) + assert ( + variable_state(system)["refundable_ctc"][0] + != (derived_variables["refundable_ctc"][0]) + ) + + +def test_derived_system_is_a_country_system_like_a_full_rebuild(combined_systems): + rebuilt, derived, *_ = combined_systems + # Class attributes such as ``auto_carry_over_input_variables`` and methods + # such as ``clone`` come from the class, which core's ``Reform`` replaces. + assert type(derived) is type(rebuilt) is CountryTaxBenefitSystem + assert derived._per_capita_uprating_built + for entity in derived.entities: + assert entity._tax_benefit_system is derived + assert derived.person_entity in derived.entities + assert all(entity in derived.entities for entity in derived.group_entities) + assert derived.spm_forecast_provider is not system.spm_forecast_provider + assert derived.modelled_policies == rebuilt.modelled_policies + assert derived.modelled_policies is not system.modelled_policies + assert derived.variable_module_metadata == rebuilt.variable_module_metadata + assert derived.variable_module_metadata is not system.variable_module_metadata + + +def test_a_derived_system_cannot_derive_another(combined_systems): + rebuilt, derived, *_ = combined_systems + assert not rebuilt.can_derive_reform_systems() + assert not derived.can_derive_reform_systems() + with pytest.raises(ValueError, match="built without a reform"): + derived.derive_reform_system(EARLY_SWITCH_REFORM) diff --git a/policyengine_us/tools/per_capita_uprating.py b/policyengine_us/tools/per_capita_uprating.py index 21fb104d1ff..83d231d5788 100644 --- a/policyengine_us/tools/per_capita_uprating.py +++ b/policyengine_us/tools/per_capita_uprating.py @@ -223,6 +223,92 @@ def add_per_capita_uprating(system) -> None: variable.uprating = per_capita_path(variable.uprating) +def derived_per_capita_series(parameters) -> dict[str, Parameter]: + """The per-capita series this module has added to the tree, by path.""" + series = {} + for prefix in NATIONAL_TOTAL_PREFIXES: + family = _find(parameters, prefix.rstrip(".")) + if family is None: + continue + for node in family.get_descendants(): + if getattr(node, "metadata", {}).get(DERIVED_FROM): + series[node.name] = node + return series + + +def detached_copy(series: Parameter) -> Parameter: + """A copy of a series that belongs to no tree.""" + copied = series.clone() + copied.parent = None + return copied + + +def _derived_series_and_parent(parameters, path: str): + parent_path, _, name = path.rpartition(".") + parent = _find(parameters, parent_path) + series = parent.children[name] + if series.metadata.get(DERIVED_FROM) is None: + raise ValueError(f"{path} was not derived by this module.") + return parent, name, series + + +def remove_per_capita_series(parameters, path: str) -> None: + """Remove a series this module added, so that the tree is as it was + before ``add_per_capita_uprating`` added it.""" + parent, name, series = _derived_series_and_parent(parameters, path) + del parent.children[name] + if parent.__dict__.get(name) is series: + delattr(parent, name) + series.parent = None + parent.clear_parent_cache() + + +def restore_per_capita_series(parameters, path: str, earlier: Parameter) -> None: + """Put back, in place of the series at ``path``, an earlier version of it + that ``add_per_capita_uprating`` replaced when it refreshed the series. + + ``earlier`` must belong to no tree (``detached_copy``). + """ + parent, name, series = _derived_series_and_parent(parameters, path) + # Assigning to the same key keeps the child's position. + parent.children[name] = earlier + if parent.__dict__.get(name) is series: + setattr(parent, name, earlier) + series.parent = None + earlier.parent = parent + parent.clear_parent_cache() + + +def per_capita_nodes_unchanged(parameters, series_paths, children_by_parent) -> bool: + """Whether each of ``series_paths`` holds a series this module derived, + and each parent in ``children_by_parent`` holds exactly the children + named there: what removing and restoring series needs.""" + for path in series_paths: + series = _find(parameters, path) + if series is None or getattr(series, "metadata", {}).get(DERIVED_FROM) is None: + return False + for parent_path, names in children_by_parent.items(): + parent = _find(parameters, parent_path) + if parent is None or set(getattr(parent, "children", {})) != names: + return False + return True + + +def restore_child_order(parameters, parent_path: str, order) -> None: + """Put a node's children back in ``order``. + + Refreshing a series deletes it and adds it again, which moves it to the + end of its parent's children, so restoring the earlier version in its + key leaves it there. + """ + parent = _find(parameters, parent_path) + if set(parent.children) != set(order): + raise ValueError(f"{parent_path} no longer holds the children recorded for it.") + reordered = {name: parent.children[name] for name in order} + parent.children.clear() + parent.children.update(reordered) + + def check_per_capita_series_is_current(parameters, total_path: str, period: str): """Raise if a derived series no longer equals its total over population. @@ -255,6 +341,12 @@ def check_per_capita_series_is_current(parameters, total_path: str, period: str) "add_per_capita_parameters_for_parameter_uprating", "add_per_capita_uprating", "check_per_capita_series_is_current", + "derived_per_capita_series", + "detached_copy", "is_national_total_path", + "per_capita_nodes_unchanged", "per_capita_path", + "remove_per_capita_series", + "restore_child_order", + "restore_per_capita_series", ] From ea435d1d1c8ec1044091109e8d73318e029e13fc Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Thu, 19 Nov 2026 00:32:41 +0400 Subject: [PATCH 2/4] Add changelog fragment and name core's private child replacement Co-Authored-By: Claude Opus 5.5 --- changelog.d/derive-reform-systems-from-baseline.changed.md | 1 + policyengine_us/system.py | 2 +- 2 files changed, 2 insertions(+), 1 deletion(-) create mode 100644 changelog.d/derive-reform-systems-from-baseline.changed.md diff --git a/changelog.d/derive-reform-systems-from-baseline.changed.md b/changelog.d/derive-reform-systems-from-baseline.changed.md new file mode 100644 index 00000000000..448693d0df2 --- /dev/null +++ b/changelog.d/derive-reform-systems-from-baseline.changed.md @@ -0,0 +1 @@ +Build a reform's tax-benefit system from the already-built default system instead of reloading every parameter and variable file. diff --git a/policyengine_us/system.py b/policyengine_us/system.py index 0285a73d734..5a3213cb47e 100644 --- a/policyengine_us/system.py +++ b/policyengine_us/system.py @@ -317,7 +317,7 @@ def can_derive_reform_systems(self) -> bool: parameter and its ancestors modified; reform dictionaries and most ``modify_parameters`` modifiers change parameters that way. It does not see changes that mark nothing: nodes added or replaced with - ``add_child``, ``replace_child`` or ``merge`` (by a modifier, or by + ``add_child``, ``_replace_child`` or ``merge`` (by a modifier, or by ``load_extension`` for an extension's parameters), assignments to ``values_list[i].value``, and edits to metadata or to a variable's attributes. A reform system derived afterwards includes From b48192e3a2c4143f4475b3d37cfc3ef613db9712 Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Tue, 24 Nov 2026 23:26:35 +0400 Subject: [PATCH 3/4] Require policyengine-core 3.37.2 Derivation relies on core loading a parameter tree with every scale bracket and homogenized node linked to its parent (3.37.1), and 3.37.2 changes how a node's values at an instant read its children, so the derived-system tests and the reform comparison run on 3.37.2. Co-Authored-By: Claude Opus 5.5 --- pyproject.toml | 2 +- uv.lock | 8 ++++---- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/pyproject.toml b/pyproject.toml index a7beb2962bf..bd7712fc540 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -23,7 +23,7 @@ dependencies = [ # pandas 3 copy-on-write enables the shallow-copy fast path in dataset # extension and is available on every supported Python version. "pandas>=3.0", - "policyengine-core>=3.36.0", + "policyengine-core>=3.37.2", "spm-calculator>=1.1.0,<1.2", "tables>=3.9", "tqdm>=4.67.1", diff --git a/uv.lock b/uv.lock index 28425633856..76fa3d4a878 100644 --- a/uv.lock +++ b/uv.lock @@ -1786,7 +1786,7 @@ wheels = [ [[package]] name = "policyengine-core" -version = "3.36.0" +version = "3.37.2" source = { registry = "https://pypi.org/simple" } dependencies = [ { name = "dpath" }, @@ -1806,9 +1806,9 @@ dependencies = [ { name = "standard-imghdr" }, { name = "wheel" }, ] -sdist = { url = "https://files.pythonhosted.org/packages/16/0a/c897947bcc65d2529fd21fe55e5f06a3e4983547ab03ac1e3f443baa2751/policyengine_core-3.36.0.tar.gz", hash = "sha256:5cb39a1d32991d70dcd4afed53f2ec8cc1777ea54f218353dfe7d62d7de4d52d", size = 811544, upload-time = "2026-11-13T12:13:06.026Z" } +sdist = { url = "https://files.pythonhosted.org/packages/99/7b/3df46c7708285a22eb55c7f8a3f73214cf9644f48d736d1002724f1a5a39/policyengine_core-3.37.2.tar.gz", hash = "sha256:54aa9a3eb912e82c7859ca96e269217d2ca0f272784bdcf59abdc695ae161313", size = 853763, upload-time = "2026-11-24T13:55:58.395Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/d6/07/f0d649c065a12ca9ef35543ced8bb5b1b51bc1b2373c90c6f5c5ad39b69b/policyengine_core-3.36.0-py3-none-any.whl", hash = "sha256:eb7943fe5f1c63a3b70d60e673924a0703d5608dee330a4bcadb6911e0243b98", size = 317669, upload-time = "2026-11-13T12:13:04.33Z" }, + { url = "https://files.pythonhosted.org/packages/9d/8a/b1065dd1ef2f1f90a6a6dd73ac0c8fc4f88568eddd9b2a94a3d7cc66f27d/policyengine_core-3.37.2-py3-none-any.whl", hash = "sha256:fe95f96878e34e2a32a1b5ee3c9a9eef78fd5811d0ebe05c3bc60ab70f38df4c", size = 326029, upload-time = "2026-11-24T13:55:56.829Z" }, ] [[package]] @@ -1845,7 +1845,7 @@ requires-dist = [ { name = "jupyter-book", marker = "extra == 'dev'", specifier = ">=1.0.4.post1" }, { name = "microdf-python", specifier = ">=1.0.0" }, { name = "pandas", specifier = ">=3.0" }, - { name = "policyengine-core", specifier = ">=3.36.0" }, + { name = "policyengine-core", specifier = ">=3.37.2" }, { name = "ruff", marker = "extra == 'dev'", specifier = ">=0.9.0" }, { name = "setuptools", marker = "extra == 'dev'", specifier = ">=80.9.0" }, { name = "spm-calculator", specifier = ">=1.1.0,<1.2" }, From e12c9696be6ae849152ca33447a9ebba4ad222c4 Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Tue, 24 Nov 2026 23:26:35 +0400 Subject: [PATCH 4/4] Check that a formula on a total-uprated input derives like a rebuild Since PolicyEngine/policyengine-us#11121, the per-capita step re-points only input variables, so a full rebuild accepts a reform that gives rental_income a formula instead of raising "mixes computation modes". The test now requires the derived system to keep the inherited national total, as the rebuild does; the case that a full rebuild still rejects (a reform to a per-capita series) keeps its own test. Co-Authored-By: Claude Opus 5.5 --- .../tests/core/test_derived_reform_system.py | 39 +++++++++++-------- 1 file changed, 22 insertions(+), 17 deletions(-) diff --git a/policyengine_us/tests/core/test_derived_reform_system.py b/policyengine_us/tests/core/test_derived_reform_system.py index 471b38b378e..2a887f87f29 100644 --- a/policyengine_us/tests/core/test_derived_reform_system.py +++ b/policyengine_us/tests/core/test_derived_reform_system.py @@ -298,23 +298,11 @@ def test_derived_system_from_an_early_start_instant_matches_a_full_rebuild(): assert derived_variables != variable_state(system) -@pytest.mark.parametrize( - "reform, error", - [ - # A full rebuild re-points the updated variable from the national - # total it inherits to the per-capita series, which declares - # ``uprating`` next to the formula. - (RentalIncomeFormulaReform, "mixes computation modes"), - # A full rebuild has no per-capita series yet when it applies the - # reform; the system builds them afterwards. - ( - {RENTAL_INCOME_PER_CAPITA: {"2026-01-01": 123.0}}, - f"Could not find the parameter {RENTAL_INCOME_PER_CAPITA}", - ), - ], - ids=["formula-on-a-total-uprated-input", "reform-to-a-per-capita-series"], -) -def test_a_reform_a_full_rebuild_rejects_is_rejected_when_derived(reform, error): +def test_a_reform_a_full_rebuild_rejects_is_rejected_when_derived(): + # A full rebuild has no per-capita series yet when it applies the reform; + # the system builds them afterwards. + reform = {RENTAL_INCOME_PER_CAPITA: {"2026-01-01": 123.0}} + error = f"Could not find the parameter {RENTAL_INCOME_PER_CAPITA}" with pytest.raises(ValueError, match=re.escape(error)): CountryTaxBenefitSystem(reform=reform) with pytest.raises(ValueError, match=re.escape(error)): @@ -322,6 +310,23 @@ def test_a_reform_a_full_rebuild_rejects_is_rejected_when_derived(reform, error) assert system.can_derive_reform_systems() +def test_a_formula_on_a_total_uprated_input_derives_like_a_full_rebuild(): + # The default build re-points rental_income from the national total to + # its per-capita series. A full rebuild applies the formula reform before + # that step, which re-points only input variables, so the variable keeps + # the national total it inherits. A derived system must start the reform + # from that total too, not from the default system's per-capita series. + assert system.variables["rental_income"].uprating == RENTAL_INCOME_PER_CAPITA + rebuilt = CountryTaxBenefitSystem(reform=RentalIncomeFormulaReform) + derived = system.derive_reform_system(RentalIncomeFormulaReform) + assert variable_state(derived) == variable_state(rebuilt) + assert parameter_state(derived) == parameter_state(rebuilt) + rental_income = derived.variables["rental_income"] + assert rental_income.formulas + assert rental_income.uprating == RENTAL_INCOME_TOTAL + assert system.can_derive_reform_systems() + + def test_a_system_built_under_an_empty_reform_cannot_derive_like_a_derived_one(): # ``Simulation(reform={})`` derives its system, because the reform is not # None. A full rebuild under the same reform must match it, so it must not