From 001f201dfb2aa2da0b5f2c118b3d8b9715f1b983 Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Tue, 1 Dec 2026 22:31:43 +0400 Subject: [PATCH 01/11] Add tests for declared current-law reads and an on-demand copy Tests that fail before the change: Population.current_law reads a variable declared with current_law_read, an undeclared read raises, each declared call is reported to the tracer, a reform simulation builds no current-law copy while it is constructed, the copy is built from the inputs held when it is first needed and made read-only by the first declared call, and assigning baseline replaces the copy. Two existing tests read the baseline branch before anything built it; they now build it through simulation.baseline, or drop it only if it exists. Co-Authored-By: Claude Opus 5.5 --- tests/core/test_current_law_reads.py | 592 +++++++++++++++++++ tests/core/test_reform_baseline_system.py | 3 +- tests/core/test_subsample_baseline_branch.py | 3 +- 3 files changed, 596 insertions(+), 2 deletions(-) create mode 100644 tests/core/test_current_law_reads.py diff --git a/tests/core/test_current_law_reads.py b/tests/core/test_current_law_reads.py new file mode 100644 index 000000000..0592acdf2 --- /dev/null +++ b/tests/core/test_current_law_reads.py @@ -0,0 +1,592 @@ +"""Declared current-law reads, and the current-law copy built when one needs it. + +A reform simulation compares with current law. Formulas read current law +through declared calls: ``Population.current_law`` for a variable whose +``current_law_read`` attribute is true, ``Simulation.compares_with_current_law``, +``Simulation.current_law_system`` and ``Simulation.current_law_simulation``. +Each call is reported to the simulation's tracer. + +The simulation no longer branches a copy under current law while it is +constructed: the copy is built the first time something needs it, from the +inputs the simulation holds then, without the values it has calculated. The +first declared call that reaches the copy makes it read-only. A copy reached +only through the deprecated ``baseline`` alias stays writable, and so does a +simulation assigned to ``baseline``. +""" + +from __future__ import annotations + +import functools + +import numpy as np +import pytest + +from policyengine_core import errors, tracers +from policyengine_core.country_template import ( + CountryTaxBenefitSystem, + Microsimulation, + Simulation, +) +from policyengine_core.country_template.entities import Household, Person +from policyengine_core.periods import MONTH, YEAR +from policyengine_core.populations import Population +from policyengine_core.variables import Variable + +MONTH_PERIOD = "2022-01" +YEAR_PERIOD = "2022" +INSTANT = "2022-01-01" +BASELINE_RATE = 0.15 +REFORM_RATE = 0.42 +REFORM = {"taxes.income_tax_rate": {INSTANT: REFORM_RATE}} +YEARLY_SALARY = [48000.0, 30000.0] +MONTHLY_SALARY = [salary / 12 for salary in YEARLY_SALARY] +OTHER_MONTHLY_SALARY = [1000.0, 3000.0] +SITUATION = { + "persons": { + "a": {"salary": {YEAR_PERIOD: YEARLY_SALARY[0]}}, + "b": {"salary": {YEAR_PERIOD: YEARLY_SALARY[1]}}, + }, + "households": {"h": {"parents": ["a", "b"]}}, +} + + +# Variables whose current-law values formulas may read. + + +class declared_monthly_tax(Variable): + value_type = float + entity = Person + definition_period = MONTH + current_law_read = True + + def formula(person, period, parameters): + return person("income_tax", period) + + +class declared_yearly_tax(Variable): + value_type = float + entity = Person + definition_period = YEAR + current_law_read = True + + def formula(person, period, parameters): + return person("income_tax", period, options=["add"]) + + +class declared_household_monthly_tax(Variable): + value_type = float + entity = Household + definition_period = MONTH + current_law_read = True + + def formula(household, period, parameters): + return household.sum(household.members("income_tax", period)) + + +class declared_household_yearly_tax(Variable): + value_type = float + entity = Household + definition_period = YEAR + current_law_read = True + + def formula(household, period, parameters): + return household.sum(household.members("income_tax", period, options=["add"])) + + +# Variables whose formulas make declared calls. + + +class makes_every_declared_call(Variable): + value_type = float + entity = Person + definition_period = MONTH + + def formula(person, period, parameters): + simulation = person.simulation + compares = simulation.compares_with_current_law + rate = simulation.current_law_system.parameters(period).taxes.income_tax_rate + current_law_tax = person.current_law("declared_monthly_tax", period) + simulation.current_law_simulation() + return current_law_tax + 0 * rate + 0 * compares + + +class reads_the_baseline_alias(Variable): + value_type = float + entity = Person + definition_period = MONTH + + def formula(person, period, parameters): + baseline = person.simulation.baseline + return person.filled_array(0.0 if baseline is None else 1.0) + + +TEST_VARIABLES = ( + declared_monthly_tax, + declared_yearly_tax, + declared_household_monthly_tax, + declared_household_yearly_tax, + makes_every_declared_call, + reads_the_baseline_alias, +) + + +class DeclaredSystem(CountryTaxBenefitSystem): + def __init__(self, reform=None): + super().__init__(reform=reform) + for variable in TEST_VARIABLES: + self.add_variable(variable) + + +def _require_declared_current_law_reads() -> None: + """Fail on an assertion, not an error, where the declared calls are missing.""" + assert "current_law_read" in Variable.__dict__, "Variable.current_law_read" + assert hasattr(Population, "current_law"), "Population.current_law" + assert hasattr(Simulation, "current_law_simulation"), "current_law_simulation" + assert hasattr(Simulation, "compares_with_current_law") + assert hasattr(Simulation, "current_law_system") + assert hasattr(errors, "UndeclaredCurrentLawReadError") + assert hasattr(tracers.SimpleTracer, "record_current_law_call") + assert hasattr(tracers.FullTracer, "record_current_law_call") + + +@functools.lru_cache(maxsize=None) +def _simulation_classes(): + _require_declared_current_law_reads() + current_law_system = DeclaredSystem() + + class DeclaredSimulation(Simulation): + default_tax_benefit_system = DeclaredSystem + default_tax_benefit_system_instance = current_law_system + + class DeclaredMicrosimulation(Microsimulation): + default_tax_benefit_system = DeclaredSystem + default_tax_benefit_system_instance = current_law_system + + return DeclaredSimulation, DeclaredMicrosimulation + + +def _declared_simulation(reform=REFORM, **options): + simulation_class, _ = _simulation_classes() + return simulation_class(situation=SITUATION, reform=reform, **options) + + +def _current_law_values(entity_key, variable, period): + """What a simulation without a reform calculates.""" + plain = _declared_simulation(reform=None) + return plain.populations[entity_key](variable, period) + + +def _income_tax(salary, rate): + return np.array(salary) * rate + + +DECLARED_READS = [ + pytest.param("person", "declared_monthly_tax", MONTH_PERIOD, id="person-month"), + pytest.param("person", "declared_yearly_tax", YEAR_PERIOD, id="person-year"), + pytest.param( + "household", + "declared_household_monthly_tax", + MONTH_PERIOD, + id="household-month", + ), + pytest.param( + "household", + "declared_household_yearly_tax", + YEAR_PERIOD, + id="household-year", + ), +] + + +@pytest.mark.parametrize("entity_key, variable, period", DECLARED_READS) +def test_a_declared_read_returns_the_value_the_baseline_alias_returns( + entity_key, variable, period +): + simulation = _declared_simulation() + population = simulation.populations[entity_key] + + current_law_values = population.current_law(variable, period) + + np.testing.assert_array_equal( + current_law_values, _current_law_values(entity_key, variable, period) + ) + alias_values = _declared_simulation().baseline.populations[entity_key]( + variable, period + ) + np.testing.assert_array_equal(current_law_values, alias_values) + # The reform's own values differ, so the read did not return them. + assert not np.array_equal(population(variable, period), current_law_values) + + +@pytest.mark.parametrize( + "entity_key, variable", + [("person", "disposable_income"), ("household", "total_taxes")], +) +def test_an_undeclared_read_raises(entity_key, variable): + simulation = _declared_simulation() + + with pytest.raises(errors.UndeclaredCurrentLawReadError, match=variable): + simulation.populations[entity_key].current_law(variable, MONTH_PERIOD) + # Without a reform the check is the same. + with pytest.raises(errors.UndeclaredCurrentLawReadError, match=variable): + _declared_simulation(reform=None).populations[entity_key].current_law( + variable, MONTH_PERIOD + ) + + +def test_current_law_read_is_false_unless_a_variable_declares_it(): + _require_declared_current_law_reads() + system = CountryTaxBenefitSystem() + assert system.variables["income_tax"].current_law_read is False + assert DeclaredSystem().variables["declared_monthly_tax"].current_law_read is True + + +def test_a_reform_simulation_has_no_copy_after_construction(): + simulation = Simulation(situation=SITUATION, reform=REFORM) + + assert "baseline" not in simulation.branches + + +def test_the_first_declared_read_builds_the_copy_once(): + simulation = _declared_simulation() + assert "baseline" not in simulation.branches + + simulation.persons.current_law("declared_monthly_tax", MONTH_PERIOD) + + copy = simulation.branches["baseline"] + assert simulation.current_law_simulation() is copy + simulation.household.current_law("declared_household_yearly_tax", YEAR_PERIOD) + assert simulation.branches["baseline"] is copy + assert copy.parent_branch is simulation + assert copy.branch_name == "baseline" + assert ( + copy.tax_benefit_system + is _simulation_classes()[0].default_tax_benefit_system_instance + ) + # The copy is current law itself: it compares with nothing. + assert copy.compares_with_current_law is False + assert copy.current_law_simulation() is copy + assert copy.baseline is None + + +def test_compares_with_current_law_never_builds_a_copy(): + simulation = _declared_simulation() + + assert simulation.compares_with_current_law is True + assert "baseline" not in simulation.branches + assert _declared_simulation(reform=None).compares_with_current_law is False + + +def test_current_law_system_never_builds_a_copy(): + simulation = _declared_simulation() + current_law_system = _simulation_classes()[0].default_tax_benefit_system_instance + + assert simulation.current_law_system is current_law_system + assert "baseline" not in simulation.branches + assert ( + simulation.current_law_system.parameters(INSTANT).taxes.income_tax_rate + == BASELINE_RATE + ) + plain = _declared_simulation(reform=None) + assert plain.current_law_system is plain.tax_benefit_system + + +def test_without_a_reform_a_declared_read_returns_the_simulations_own_values(): + simulation = _declared_simulation(reform=None) + + np.testing.assert_array_equal( + simulation.persons.current_law("declared_monthly_tax", MONTH_PERIOD), + _income_tax(MONTHLY_SALARY, BASELINE_RATE), + ) + assert simulation.current_law_simulation() is simulation + assert simulation.baseline is None + assert simulation.branches == {} + assert not simulation.read_only + + +def test_the_copy_refuses_set_input_after_a_declared_call(): + simulation = _declared_simulation() + + simulation.persons.current_law("declared_monthly_tax", MONTH_PERIOD) + + copy = simulation.current_law_simulation() + assert copy.read_only + with pytest.raises(errors.ReadOnlySimulationError): + copy.set_input("salary", MONTH_PERIOD, OTHER_MONTHLY_SALARY) + # The simulation itself still takes inputs. + simulation.set_input("salary", MONTH_PERIOD, OTHER_MONTHLY_SALARY) + + +def test_current_law_simulation_makes_the_copy_read_only(): + simulation = _declared_simulation() + + copy = simulation.current_law_simulation() + + assert copy is simulation.branches["baseline"] + assert copy.read_only + + +def test_a_copy_reached_only_through_the_alias_stays_writable_until_a_declared_call(): + simulation = _declared_simulation() + + copy = simulation.baseline + assert not copy.read_only + copy.set_input("salary", MONTH_PERIOD, OTHER_MONTHLY_SALARY) + + # The declared call reads the copy as it was given its input. + np.testing.assert_array_equal( + simulation.persons.current_law("declared_monthly_tax", MONTH_PERIOD), + _income_tax(OTHER_MONTHLY_SALARY, BASELINE_RATE), + ) + assert simulation.baseline is copy + assert copy.read_only + + +def test_get_branch_baseline_returns_the_copy(): + simulation = Simulation(situation=SITUATION, reform=REFORM) + + copy = simulation.get_branch("baseline") + + assert simulation.baseline is copy + np.testing.assert_array_equal( + copy.calculate("income_tax", MONTH_PERIOD), + _income_tax(MONTHLY_SALARY, BASELINE_RATE), + ) + + +def test_a_copy_built_after_reform_calculations_holds_no_reform_values(): + simulation = _declared_simulation() + np.testing.assert_array_equal( + simulation.calculate("income_tax", MONTH_PERIOD), + _income_tax(MONTHLY_SALARY, REFORM_RATE), + ) + simulation.calculate("declared_yearly_tax", YEAR_PERIOD) + + np.testing.assert_array_equal( + simulation.persons.current_law("declared_monthly_tax", MONTH_PERIOD), + _income_tax(MONTHLY_SALARY, BASELINE_RATE), + ) + np.testing.assert_array_equal( + simulation.persons.current_law("declared_yearly_tax", YEAR_PERIOD), + _income_tax(YEARLY_SALARY, BASELINE_RATE), + ) + + +def test_an_input_set_after_construction_reaches_a_copy_built_later(): + simulation = Simulation(situation=SITUATION, reform=REFORM) + + simulation.set_input("salary", MONTH_PERIOD, OTHER_MONTHLY_SALARY) + + np.testing.assert_array_equal( + simulation.baseline.calculate("income_tax", MONTH_PERIOD), + _income_tax(OTHER_MONTHLY_SALARY, BASELINE_RATE), + ) + + +def test_an_input_set_after_the_copy_is_built_does_not_reach_it(): + simulation = _declared_simulation() + simulation.persons.current_law("declared_monthly_tax", MONTH_PERIOD) + + simulation.set_input("salary", MONTH_PERIOD, OTHER_MONTHLY_SALARY) + + copy = simulation.current_law_simulation() + np.testing.assert_array_equal( + copy.calculate("salary", MONTH_PERIOD), MONTHLY_SALARY + ) + np.testing.assert_array_equal( + simulation.calculate("salary", MONTH_PERIOD), OTHER_MONTHLY_SALARY + ) + + +def test_a_branch_made_before_the_copy_reads_its_parents_copy(): + simulation = _declared_simulation() + branch = simulation.get_branch("temporary") + branch.set_input("salary", MONTH_PERIOD, OTHER_MONTHLY_SALARY) + + branch_values = branch.persons.current_law("declared_monthly_tax", MONTH_PERIOD) + + # As the branch's ``baseline`` was its parent's, the branch reads the copy + # built from its parent's inputs. + assert branch.current_law_simulation() is simulation.current_law_simulation() + np.testing.assert_array_equal( + branch_values, _income_tax(MONTHLY_SALARY, BASELINE_RATE) + ) + assert branch.compares_with_current_law is True + assert "baseline" not in branch.branches + + +def test_assigning_a_simulation_to_baseline_makes_it_the_copy(): + simulation = _declared_simulation() + separate = _declared_simulation(reform=None) + separate.set_input("salary", MONTH_PERIOD, OTHER_MONTHLY_SALARY) + + simulation.baseline = separate + + assert simulation.baseline is separate + assert simulation.current_law_simulation() is separate + assert simulation.compares_with_current_law is True + np.testing.assert_array_equal( + simulation.persons.current_law("declared_monthly_tax", MONTH_PERIOD), + _income_tax(OTHER_MONTHLY_SALARY, BASELINE_RATE), + ) + # Kept as it was given: core does not make it read-only. + assert not separate.read_only + assert simulation.current_law_system is separate.tax_benefit_system + + +def test_assigning_none_to_baseline_stops_comparing_with_current_law(): + simulation = _declared_simulation() + + simulation.baseline = None + + assert simulation.baseline is None + assert simulation.compares_with_current_law is False + assert simulation.current_law_simulation() is simulation + np.testing.assert_array_equal( + simulation.persons.current_law("declared_monthly_tax", MONTH_PERIOD), + _income_tax(MONTHLY_SALARY, REFORM_RATE), + ) + assert "baseline" not in simulation.branches + + +def test_assigning_none_on_a_branch_leaves_its_parent_comparing(): + simulation = _declared_simulation() + branch = simulation.get_branch("measurement") + + branch.baseline = None + + assert branch.compares_with_current_law is False + assert simulation.compares_with_current_law is True + assert simulation.baseline is not None + + +def test_a_simulation_not_built_by_cores_constructor_compares_once_assigned(): + """A country package's simulation may skip core's ``__init__``.""" + simulation_class, _ = _simulation_classes() + simulation = simulation_class.__new__(simulation_class) + + assert simulation.baseline is None + assert simulation.compares_with_current_law is False + + separate = _declared_simulation(reform=None) + simulation.baseline = separate + + assert simulation.compares_with_current_law is True + assert simulation.current_law_simulation() is separate + + +def test_a_clone_of_a_simulation_without_a_copy_builds_its_own_from_its_inputs(): + simulation = _declared_simulation() + clone = simulation.clone() + + clone.set_input("salary", MONTH_PERIOD, OTHER_MONTHLY_SALARY) + + np.testing.assert_array_equal( + clone.persons.current_law("declared_monthly_tax", MONTH_PERIOD), + _income_tax(OTHER_MONTHLY_SALARY, BASELINE_RATE), + ) + assert clone.current_law_simulation().parent_branch is clone + assert "baseline" not in simulation.branches + np.testing.assert_array_equal( + simulation.persons.current_law("declared_monthly_tax", MONTH_PERIOD), + _income_tax(MONTHLY_SALARY, BASELINE_RATE), + ) + + +def test_subsample_keeps_no_copy_when_none_was_built(): + _, microsimulation_class = _simulation_classes() + simulation = microsimulation_class(reform=REFORM) + + simulation.subsample(n=3, seed="current-law", time_period="2022") + + assert "baseline" not in simulation.branches + values = simulation.persons.current_law("declared_monthly_tax", MONTH_PERIOD) + assert len(values) == simulation.persons.count + assert simulation.current_law_simulation().persons.count == simulation.persons.count + + +def _node_named(nodes, name): + for node in nodes: + if node.name == name: + return node + found = _node_named(node.children, name) + if found is not None: + return found + return None + + +def _reported_calls(node): + return [ + ( + call.call, + call.variable, + None if call.period is None else str(call.period), + call.branch_name, + ) + for call in node.current_law_calls + ] + + +@pytest.mark.parametrize("reform", [REFORM, None], ids=["reform", "current-law"]) +def test_each_declared_call_is_reported_to_the_tracer(reform): + simulation = _declared_simulation(reform=reform, trace=True) + + simulation.calculate("makes_every_declared_call", MONTH_PERIOD) + + node = _node_named(simulation.tracer.trees, "makes_every_declared_call") + assert _reported_calls(node) == [ + ("compares_with_current_law", None, None, "default"), + ("current_law_system", None, None, "default"), + ("current_law", "declared_monthly_tax", MONTH_PERIOD, "default"), + ("current_law_simulation", None, None, "default"), + ] + # The value read is calculated as before: on the copy under a reform, in + # the simulation itself without one. + read = _node_named(node.children, "declared_monthly_tax") + assert read.branch_name == ("baseline" if reform else "default") + + +def test_reading_the_baseline_alias_is_reported_to_the_tracer(): + simulation = _declared_simulation(trace=True) + + simulation.calculate("reads_the_baseline_alias", MONTH_PERIOD) + + node = _node_named(simulation.tracer.trees, "reads_the_baseline_alias") + assert _reported_calls(node) == [("baseline", None, None, "default")] + + +def test_a_tracer_without_the_new_method_still_calculates(): + class TracerWithoutCurrentLawCalls: + """A tracer written before core reported current-law calls.""" + + def __init__(self): + self._stack = [] + + def record_calculation_start(self, variable, period, branch_name="default"): + self._stack.append( + {"name": variable, "period": period, "branch_name": branch_name} + ) + + def record_calculation_result(self, value): + pass + + def record_parameter_access(self, parameter, period, branch_name, value): + pass + + def record_formula_run(self): + pass + + def record_calculation_end(self): + self._stack.pop() + + @property + def stack(self): + return self._stack + + simulation = _declared_simulation() + simulation.tracer = TracerWithoutCurrentLawCalls() + + np.testing.assert_array_equal( + simulation.calculate("makes_every_declared_call", MONTH_PERIOD), + _income_tax(MONTHLY_SALARY, BASELINE_RATE), + ) diff --git a/tests/core/test_reform_baseline_system.py b/tests/core/test_reform_baseline_system.py index c1c337280..f093a3108 100644 --- a/tests/core/test_reform_baseline_system.py +++ b/tests/core/test_reform_baseline_system.py @@ -196,7 +196,8 @@ def test_the_baseline_drops_a_holder_built_for_another_entity(): # Create the reform's household holder before cloning the baseline branch so # ``_bind_to_tax_benefit_system`` must drop the cross-entity holder. reform.calculate("salary", PERIOD) - del reform.branches["baseline"] + # Construction no longer builds the baseline branch; drop one if built. + reform.branches.pop("baseline", None) baseline = reform.get_branch("baseline") baseline.tax_benefit_system = reform.default_tax_benefit_system_instance baseline._bind_to_tax_benefit_system() diff --git a/tests/core/test_subsample_baseline_branch.py b/tests/core/test_subsample_baseline_branch.py index bcc3d59e1..634688071 100644 --- a/tests/core/test_subsample_baseline_branch.py +++ b/tests/core/test_subsample_baseline_branch.py @@ -16,7 +16,8 @@ def test_subsample_restores_baseline_system_and_branch_wiring(): simulation = Microsimulation( reform={"taxes.income_tax_rate": {INSTANT: REFORM_RATE}} ) - baseline_system_before = simulation.branches["baseline"].tax_benefit_system + # The baseline branch is built when first needed; reading it builds it. + baseline_system_before = simulation.baseline.tax_benefit_system simulation.subsample(n=3, seed="fix-522", time_period="2022") From e1a2d7dd063cd5023a11f0fc6acf0ea42761aa8c Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Tue, 1 Dec 2026 22:35:55 +0400 Subject: [PATCH 02/11] Label the test variables and compare float32 tax with a tolerance Core requires a label on every variable, and income tax is calculated in float32, so the tests compare it with the expected amounts to one part in a million. Co-Authored-By: Claude Opus 5.5 --- tests/core/test_current_law_reads.py | 75 ++++++++++++++++------------ 1 file changed, 44 insertions(+), 31 deletions(-) diff --git a/tests/core/test_current_law_reads.py b/tests/core/test_current_law_reads.py index 0592acdf2..92bd1b926 100644 --- a/tests/core/test_current_law_reads.py +++ b/tests/core/test_current_law_reads.py @@ -54,6 +54,7 @@ class declared_monthly_tax(Variable): + label = "Income tax in the month" value_type = float entity = Person definition_period = MONTH @@ -64,6 +65,7 @@ def formula(person, period, parameters): class declared_yearly_tax(Variable): + label = "Income tax in the year" value_type = float entity = Person definition_period = YEAR @@ -74,6 +76,7 @@ def formula(person, period, parameters): class declared_household_monthly_tax(Variable): + label = "Household income tax in the month" value_type = float entity = Household definition_period = MONTH @@ -84,6 +87,7 @@ def formula(household, period, parameters): class declared_household_yearly_tax(Variable): + label = "Household income tax in the year" value_type = float entity = Household definition_period = YEAR @@ -97,6 +101,7 @@ def formula(household, period, parameters): class makes_every_declared_call(Variable): + label = "Current-law income tax, read with every declared call" value_type = float entity = Person definition_period = MONTH @@ -111,6 +116,7 @@ def formula(person, period, parameters): class reads_the_baseline_alias(Variable): + label = "Whether the baseline alias returns a simulation" value_type = float entity = Person definition_period = MONTH @@ -176,8 +182,9 @@ def _current_law_values(entity_key, variable, period): return plain.populations[entity_key](variable, period) -def _income_tax(salary, rate): - return np.array(salary) * rate +def _assert_income_tax(values, salary, rate): + """Income tax is calculated in float32, so compare to one part in a million.""" + np.testing.assert_allclose(values, np.array(salary) * rate, rtol=1e-6) DECLARED_READS = [ @@ -294,9 +301,10 @@ def test_current_law_system_never_builds_a_copy(): def test_without_a_reform_a_declared_read_returns_the_simulations_own_values(): simulation = _declared_simulation(reform=None) - np.testing.assert_array_equal( + _assert_income_tax( simulation.persons.current_law("declared_monthly_tax", MONTH_PERIOD), - _income_tax(MONTHLY_SALARY, BASELINE_RATE), + MONTHLY_SALARY, + BASELINE_RATE, ) assert simulation.current_law_simulation() is simulation assert simulation.baseline is None @@ -334,9 +342,10 @@ def test_a_copy_reached_only_through_the_alias_stays_writable_until_a_declared_c copy.set_input("salary", MONTH_PERIOD, OTHER_MONTHLY_SALARY) # The declared call reads the copy as it was given its input. - np.testing.assert_array_equal( + _assert_income_tax( simulation.persons.current_law("declared_monthly_tax", MONTH_PERIOD), - _income_tax(OTHER_MONTHLY_SALARY, BASELINE_RATE), + OTHER_MONTHLY_SALARY, + BASELINE_RATE, ) assert simulation.baseline is copy assert copy.read_only @@ -348,27 +357,27 @@ def test_get_branch_baseline_returns_the_copy(): copy = simulation.get_branch("baseline") assert simulation.baseline is copy - np.testing.assert_array_equal( - copy.calculate("income_tax", MONTH_PERIOD), - _income_tax(MONTHLY_SALARY, BASELINE_RATE), + _assert_income_tax( + copy.calculate("income_tax", MONTH_PERIOD), MONTHLY_SALARY, BASELINE_RATE ) def test_a_copy_built_after_reform_calculations_holds_no_reform_values(): simulation = _declared_simulation() - np.testing.assert_array_equal( - simulation.calculate("income_tax", MONTH_PERIOD), - _income_tax(MONTHLY_SALARY, REFORM_RATE), + _assert_income_tax( + simulation.calculate("income_tax", MONTH_PERIOD), MONTHLY_SALARY, REFORM_RATE ) simulation.calculate("declared_yearly_tax", YEAR_PERIOD) - np.testing.assert_array_equal( + _assert_income_tax( simulation.persons.current_law("declared_monthly_tax", MONTH_PERIOD), - _income_tax(MONTHLY_SALARY, BASELINE_RATE), + MONTHLY_SALARY, + BASELINE_RATE, ) - np.testing.assert_array_equal( + _assert_income_tax( simulation.persons.current_law("declared_yearly_tax", YEAR_PERIOD), - _income_tax(YEARLY_SALARY, BASELINE_RATE), + YEARLY_SALARY, + BASELINE_RATE, ) @@ -377,9 +386,10 @@ def test_an_input_set_after_construction_reaches_a_copy_built_later(): simulation.set_input("salary", MONTH_PERIOD, OTHER_MONTHLY_SALARY) - np.testing.assert_array_equal( + _assert_income_tax( simulation.baseline.calculate("income_tax", MONTH_PERIOD), - _income_tax(OTHER_MONTHLY_SALARY, BASELINE_RATE), + OTHER_MONTHLY_SALARY, + BASELINE_RATE, ) @@ -408,9 +418,7 @@ def test_a_branch_made_before_the_copy_reads_its_parents_copy(): # As the branch's ``baseline`` was its parent's, the branch reads the copy # built from its parent's inputs. assert branch.current_law_simulation() is simulation.current_law_simulation() - np.testing.assert_array_equal( - branch_values, _income_tax(MONTHLY_SALARY, BASELINE_RATE) - ) + _assert_income_tax(branch_values, MONTHLY_SALARY, BASELINE_RATE) assert branch.compares_with_current_law is True assert "baseline" not in branch.branches @@ -425,9 +433,10 @@ def test_assigning_a_simulation_to_baseline_makes_it_the_copy(): assert simulation.baseline is separate assert simulation.current_law_simulation() is separate assert simulation.compares_with_current_law is True - np.testing.assert_array_equal( + _assert_income_tax( simulation.persons.current_law("declared_monthly_tax", MONTH_PERIOD), - _income_tax(OTHER_MONTHLY_SALARY, BASELINE_RATE), + OTHER_MONTHLY_SALARY, + BASELINE_RATE, ) # Kept as it was given: core does not make it read-only. assert not separate.read_only @@ -442,9 +451,10 @@ def test_assigning_none_to_baseline_stops_comparing_with_current_law(): assert simulation.baseline is None assert simulation.compares_with_current_law is False assert simulation.current_law_simulation() is simulation - np.testing.assert_array_equal( + _assert_income_tax( simulation.persons.current_law("declared_monthly_tax", MONTH_PERIOD), - _income_tax(MONTHLY_SALARY, REFORM_RATE), + MONTHLY_SALARY, + REFORM_RATE, ) assert "baseline" not in simulation.branches @@ -481,15 +491,17 @@ def test_a_clone_of_a_simulation_without_a_copy_builds_its_own_from_its_inputs() clone.set_input("salary", MONTH_PERIOD, OTHER_MONTHLY_SALARY) - np.testing.assert_array_equal( + _assert_income_tax( clone.persons.current_law("declared_monthly_tax", MONTH_PERIOD), - _income_tax(OTHER_MONTHLY_SALARY, BASELINE_RATE), + OTHER_MONTHLY_SALARY, + BASELINE_RATE, ) assert clone.current_law_simulation().parent_branch is clone assert "baseline" not in simulation.branches - np.testing.assert_array_equal( + _assert_income_tax( simulation.persons.current_law("declared_monthly_tax", MONTH_PERIOD), - _income_tax(MONTHLY_SALARY, BASELINE_RATE), + MONTHLY_SALARY, + BASELINE_RATE, ) @@ -586,7 +598,8 @@ def stack(self): simulation = _declared_simulation() simulation.tracer = TracerWithoutCurrentLawCalls() - np.testing.assert_array_equal( + _assert_income_tax( simulation.calculate("makes_every_declared_call", MONTH_PERIOD), - _income_tax(MONTHLY_SALARY, BASELINE_RATE), + MONTHLY_SALARY, + BASELINE_RATE, ) From 05485906e64c8fdbc98e21d5b081981c144f4e50 Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Tue, 1 Dec 2026 22:39:56 +0400 Subject: [PATCH 03/11] Add a test that a copy built later has requested nothing A variable that must be calculated after another raises in the current-law copy when the copy has not requested that other variable, as it did when construction built the copy, even if the reform simulation requested it. Co-Authored-By: Claude Opus 5.5 --- tests/core/test_current_law_reads.py | 28 ++++++++++++++++++++++++++++ 1 file changed, 28 insertions(+) diff --git a/tests/core/test_current_law_reads.py b/tests/core/test_current_law_reads.py index 92bd1b926..e5075d317 100644 --- a/tests/core/test_current_law_reads.py +++ b/tests/core/test_current_law_reads.py @@ -97,6 +97,18 @@ def formula(household, period, parameters): return household.sum(household.members("income_tax", period, options=["add"])) +class declared_tax_after_income_tax(Variable): + label = "Income tax, calculated only once income tax was requested" + value_type = float + entity = Person + definition_period = MONTH + current_law_read = True + requires_computation_after = "income_tax" + + def formula(person, period, parameters): + return person("income_tax", period) + + # Variables whose formulas make declared calls. @@ -131,6 +143,7 @@ def formula(person, period, parameters): declared_yearly_tax, declared_household_monthly_tax, declared_household_yearly_tax, + declared_tax_after_income_tax, makes_every_declared_call, reads_the_baseline_alias, ) @@ -381,6 +394,21 @@ def test_a_copy_built_after_reform_calculations_holds_no_reform_values(): ) +def test_a_copy_built_later_has_requested_nothing_its_simulation_requested(): + """``requires_computation_after`` holds in the copy as in one built at once. + + The reform simulation requested income tax; the copy has not, so a + variable that must be calculated after income tax raises there, as it did + when construction built the copy. + """ + simulation = _declared_simulation() + simulation.calculate("income_tax", MONTH_PERIOD) + simulation.calculate("declared_tax_after_income_tax", MONTH_PERIOD) + + with pytest.raises(ValueError, match="requires income_tax to be requested first"): + simulation.persons.current_law("declared_tax_after_income_tax", MONTH_PERIOD) + + def test_an_input_set_after_construction_reaches_a_copy_built_later(): simulation = Simulation(situation=SITUATION, reform=REFORM) From 8f0a3781f0fe26ec2a099b8c19c052f8bde772bd Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Tue, 1 Dec 2026 22:40:08 +0400 Subject: [PATCH 04/11] Declare current-law reads and build the current-law copy on demand Formulas read current law through declared calls, each reported to the simulation's tracer (record_current_law_call; the full tracer keeps them on TraceNode.current_law_calls): - Population.current_law(variable, period) reads a variable declaring current_law_read = True, and raises UndeclaredCurrentLawReadError for any other; without a reform it returns the simulation's own value. - Simulation.compares_with_current_law and Simulation.current_law_system, which never build a copy. - Simulation.current_law_simulation(), the simulation that calculates current-law values. A reform simulation no longer branches its current-law copy while it is constructed. The overridable _build_current_law_simulation() builds it the first time it is needed: a branch named baseline under the default system instance, keeping the inputs held then and dropping calculated values. The first declared call that reaches it makes it read-only. Branches read their parent's copy, and clone() and subsample() keep a copy only if one was built. Simulation.baseline is now a deprecated property: reading it returns the copy, left writable, and is reported to the tracer; assigning a simulation makes it the copy, kept as given, and assigning None stops the comparison. get_branch("baseline") still returns the copy. Co-Authored-By: Claude Opus 5.5 --- .../declared-current-law-reads.added.md | 1 + .../declared-current-law-reads.changed.md | 1 + docs/python_api/errors.md | 12 + docs/python_api/simulations.md | 32 ++ policyengine_core/errors/__init__.py | 1 + .../undeclared_current_law_read_error.py | 8 + policyengine_core/populations/population.py | 47 +++ policyengine_core/simulations/simulation.py | 362 +++++++++++++++--- policyengine_core/tracers/__init__.py | 2 +- policyengine_core/tracers/full_tracer.py | 20 + policyengine_core/tracers/simple_tracer.py | 11 +- policyengine_core/tracers/trace_node.py | 22 ++ policyengine_core/variables/variable.py | 6 + 13 files changed, 468 insertions(+), 57 deletions(-) create mode 100644 changelog.d/declared-current-law-reads.added.md create mode 100644 changelog.d/declared-current-law-reads.changed.md create mode 100644 policyengine_core/errors/undeclared_current_law_read_error.py diff --git a/changelog.d/declared-current-law-reads.added.md b/changelog.d/declared-current-law-reads.added.md new file mode 100644 index 000000000..996b5cac5 --- /dev/null +++ b/changelog.d/declared-current-law-reads.added.md @@ -0,0 +1 @@ +Added declared current-law reads: `Population.current_law` for variables that set `current_law_read = True`, `Simulation.compares_with_current_law`, `Simulation.current_law_system` and `Simulation.current_law_simulation()`, each reported to the tracer through `record_current_law_call`. diff --git a/changelog.d/declared-current-law-reads.changed.md b/changelog.d/declared-current-law-reads.changed.md new file mode 100644 index 000000000..7de4cccfa --- /dev/null +++ b/changelog.d/declared-current-law-reads.changed.md @@ -0,0 +1 @@ +A reform simulation no longer branches its current-law copy while it is constructed: the copy is built from the inputs held when first needed, without calculated values, and the first declared current-law call makes it read-only; `Simulation.baseline` is deprecated and assigning it replaces the copy. diff --git a/docs/python_api/errors.md b/docs/python_api/errors.md index 34c73c594..8b9963358 100644 --- a/docs/python_api/errors.md +++ b/docs/python_api/errors.md @@ -69,6 +69,18 @@ have changed. :show-inheritance: ``` +## UndeclaredCurrentLawReadError + +Raised by `Population.current_law` for a variable that does not declare +`current_law_read = True` in the current-law tax-benefit system. + +```{eval-rst} +.. autoclass:: policyengine_core.errors.undeclared_current_law_read_error.UndeclaredCurrentLawReadError + :members: + :undoc-members: + :show-inheritance: +``` + ## VariableNameConflictError ```{eval-rst} diff --git a/docs/python_api/simulations.md b/docs/python_api/simulations.md index ade143bd8..e138b3428 100644 --- a/docs/python_api/simulations.md +++ b/docs/python_api/simulations.md @@ -26,6 +26,38 @@ parameter change after `make_read_only()` makes its next calculation raise not kept in `branches` and is not read-only itself. The method's docstring lists what is not detected. +### Current-law reads + +A simulation built with a reform compares with current law. Formulas read +current law through declared calls, each reported to the simulation's tracer +(`record_current_law_call`, kept as `TraceNode.current_law_calls` by the full +tracer): + +- `population.current_law(variable, period)` returns the variable's value under + current law, for a variable that declares `current_law_read = True` in the + current-law tax-benefit system; any other variable raises + `UndeclaredCurrentLawReadError`. Without a reform it returns the + simulation's own value. +- `simulation.compares_with_current_law` says whether the simulation compares + with current law. +- `simulation.current_law_system` is the current-law tax-benefit system. +- `simulation.current_law_simulation()` is the simulation that calculates + current-law values: the simulation itself without a reform. + +Construction no longer branches a copy under current law. The copy is built the +first time something needs it, by the overridable +`_build_current_law_simulation()`: a branch named `baseline`, under +`default_tax_benefit_system_instance`, holding the inputs the simulation holds +then and none of its calculated values. `compares_with_current_law` and +`current_law_system` never build it. The first declared call that reaches it +makes it read-only (see above). Branches read their parent's copy; `clone()` +and `subsample()` keep a copy only if one was built. + +`simulation.baseline` is deprecated. It returns the copy (built if needed, and +left writable) or `None`, and each read is reported to the tracer. Assigning a +simulation to it makes that simulation the copy, kept as it is given; +assigning `None` stops the comparison. + ## Microsimulation ```{eval-rst} diff --git a/policyengine_core/errors/__init__.py b/policyengine_core/errors/__init__.py index 4c80bc797..74e5370c7 100644 --- a/policyengine_core/errors/__init__.py +++ b/policyengine_core/errors/__init__.py @@ -8,5 +8,6 @@ from .read_only_simulation_error import ReadOnlySimulationError from .situation_parsing_error import SituationParsingError from .spiral_error import SpiralError +from .undeclared_current_law_read_error import UndeclaredCurrentLawReadError from .variable_name_conflict_error import VariableNameConflictError from .variable_not_found_error import VariableNotFoundError diff --git a/policyengine_core/errors/undeclared_current_law_read_error.py b/policyengine_core/errors/undeclared_current_law_read_error.py new file mode 100644 index 000000000..ab2580386 --- /dev/null +++ b/policyengine_core/errors/undeclared_current_law_read_error.py @@ -0,0 +1,8 @@ +class UndeclaredCurrentLawReadError(ValueError): + """A formula read the current-law value of a variable not declared for it. + + Raised by ``Population.current_law`` when the variable's + ``current_law_read`` attribute, in the current-law tax-benefit system, is + not true. Declaring the reads lets core know in advance which current-law + values a simulation may need. + """ diff --git a/policyengine_core/populations/population.py b/policyengine_core/populations/population.py index 4e459117b..8a70907ed 100644 --- a/policyengine_core/populations/population.py +++ b/policyengine_core/populations/population.py @@ -179,6 +179,53 @@ def __call__( # Helpers + def current_law( + self, + variable_name: str, + period: Period = None, + options: Optional[Container[str]] = None, + ): + """Calculate ``variable_name`` under current law, for this entity. + + In a simulation that compares with current law (one built with a + reform, or one of its branches), the value its current-law copy + calculates (see ``Simulation.current_law_simulation``), which this + builds if there is none yet and makes read-only. Otherwise the + simulation is current law itself, and this is the same as calling + the population. ``period`` and ``options`` are as for a call. + + The variable must declare ``current_law_read = True`` in the + current-law tax-benefit system; otherwise this raises + ``UndeclaredCurrentLawReadError``. Each call is reported to the + simulation's tracer, with the variable and period. + + Example: + + >>> person.current_law('income_tax', '2017-04') + >>> array([45.]) + """ + from policyengine_core.errors import UndeclaredCurrentLawReadError + + simulation = self.simulation + variable = simulation._current_law_system().get_variable( + variable_name, check_existence=True + ) + if not variable.current_law_read: + raise UndeclaredCurrentLawReadError( + f'The variable "{variable_name}" does not declare ' + "current_law_read = True, so formulas may not read its " + "current-law value with current_law(). Declare it on the " + "variable." + ) + simulation._report_current_law_call("current_law", variable_name, period) + source = simulation._current_law_source() + if not source.compares: + return self(variable_name, period, options) + current_law_simulation = source.get(make_read_only=True) + return current_law_simulation.populations[self.entity.key]( + variable_name, period, options + ) + def get_holder(self, variable_name: str) -> Holder: self.entity.check_variable_defined_for_entity(variable_name) variable = self.entity.get_variable(variable_name) diff --git a/policyengine_core/simulations/simulation.py b/policyengine_core/simulations/simulation.py index ac5dcaffd..48d584d20 100644 --- a/policyengine_core/simulations/simulation.py +++ b/policyengine_core/simulations/simulation.py @@ -678,6 +678,95 @@ def _taint_waiting_frames(simulation: "Simulation") -> None: simulation = getattr(simulation, "parent_branch", None) +class _CurrentLawSource: + """Where a simulation's current-law values come from. + + ``compares`` says whether the simulation compares with current law (it + was built with a reform, or a simulation was assigned to its + ``baseline``). ``simulation`` is the simulation that calculates + current-law values for it, once built or assigned, and ``owner`` the one + it is built from. A simulation shares this record with the branches + ``get_branch`` makes of it, as it shared its ``baseline`` before: a + branch reads its parent's copy, built once from the parent's inputs. + Assigning ``baseline`` gives the simulation a new record, so branches + made before keep the old one. ``assigned`` marks a simulation assigned to + ``baseline``, which core keeps as it was given and never makes read-only. + """ + + def __init__( + self, + owner: "Simulation", + compares: bool, + simulation: Optional["Simulation"] = None, + assigned: bool = False, + ): + self.owner = owner + self.compares = compares + self.simulation = simulation + self.assigned = assigned + self.building = False + + def get(self, make_read_only: bool) -> "Simulation": + """The current-law copy, built first if there is none yet. + + With ``make_read_only``, as for a declared call, a copy core built is + made read-only (see ``Simulation.make_read_only``). + """ + copy = self.simulation + if copy is None: + if self.building: + raise RuntimeError( + "The current-law copy of this simulation was requested while " + "it was being built. _build_current_law_simulation must not " + "read current-law values or the baseline alias." + ) + self.building = True + try: + copy = self.owner._build_current_law_simulation() + finally: + self.building = False + # The copy is current law: it compares with nothing. + copy.__dict__["_current_law"] = _CurrentLawSource(copy, compares=False) + self.simulation = copy + if make_read_only and not self.assigned: + copy.make_read_only() + return copy + + def for_clone( + self, + source: "Simulation", + clone: "Simulation", + debug: bool, + trace: bool, + ) -> "_CurrentLawSource": + """The record for a clone of ``source``, whose record this is. + + A copy not built yet is not shared: the clone builds its own from its + own inputs when it needs one. A built copy that is a branch of + ``source`` is copied for the clone, as a branch of the clone; any + other (a simulation a country package built and assigned) is shared. + """ + copy = self.simulation + if copy is None or getattr(copy, "parent_branch", None) is not source: + return _CurrentLawSource( + clone, self.compares, simulation=copy, assigned=self.assigned + ) + # A copy of the copy, not a new branch of the clone: the clone's + # cached arrays include values calculated under ``source``'s policy, + # which a new branch would read as its own. + new_copy = copy.clone(debug=debug, trace=trace, clone_tax_benefit_system=False) + new_copy.parent_branch = clone + # A copy traced in its simulation (as the builder makes it) is traced + # in the clone. + if copy.tracer is source.tracer: + new_copy.tracer = clone.tracer + if source.branches.get(copy.branch_name) is copy: + clone.branches[copy.branch_name] = new_copy + return _CurrentLawSource( + clone, self.compares, simulation=new_copy, assigned=self.assigned + ) + + @dataclass(frozen=True) class PreservedUserInput: variable_name: str @@ -739,9 +828,6 @@ class Simulation: datasets: List[Dataset] = [] """The list of datasets available for this simulation.""" - baseline: "Simulation" = None - """The baseline simulation, if this simulation is a reform.""" - is_over_dataset: bool = False """Whether this simulation is built over a dataset.""" @@ -983,22 +1069,10 @@ def __init__( ) np.random.seed(hashed_input) - if reform is not None: - self.baseline = self.get_branch("baseline") - self.baseline.trace = self.trace - self.baseline.tracer = self.tracer - self.baseline.tax_benefit_system = self.default_tax_benefit_system_instance - # The branch was built under the reform's system: its populations - # looked variables up there, and its holders kept the reform's - # variables, so a variable the reform neutralized read as the - # default in the baseline too. - self.baseline._bind_to_tax_benefit_system() - # The branch shares this simulation's list of input variables, - # and the binding keeps a list it drops nothing from. The - # baseline runs under another system, so it keeps its own list. - self.baseline.input_variables = list(self.baseline.input_variables) - else: - self.baseline = None + # A reform simulation compares with current law. The simulation that + # calculates its current-law values is built when first needed (see + # ``current_law_simulation``), from the inputs held then. + self._current_law = _CurrentLawSource(self, compares=reform is not None) self.parent_branch = None @@ -1112,6 +1186,165 @@ def _refuse_if_parameters_changed(self) -> None: "no longer match its parameters." ) + def _current_law_source(self) -> _CurrentLawSource: + """This simulation's record of where its current-law values come from. + + A simulation that core's ``__init__`` did not build (a country + package may build its own) gets one when first asked: it compares + with current law only once a simulation is assigned to ``baseline``. + """ + source = self.__dict__.get("_current_law") + if source is None: + source = _CurrentLawSource(self, compares=False) + self.__dict__["_current_law"] = source + return source + + def _report_current_law_call( + self, + call: str, + variable: Optional[str] = None, + period: Optional[Period] = None, + ) -> None: + """Report a declared current-law call to this simulation's tracer. + + A tracer without ``record_current_law_call`` (one written before core + reported these calls) is not told. + """ + record = getattr(getattr(self, "tracer", None), "record_current_law_call", None) + if record is None: + return + if period is not None and not isinstance(period, Period): + period = periods.period(period) + record(call, variable, period, getattr(self, "branch_name", "default")) + + @property + def compares_with_current_law(self) -> bool: + """Whether this simulation compares with current law. + + True for a simulation built with a reform, and for its branches; + False without a reform, and for the current-law copy itself. + Assigning ``baseline`` changes it: a simulation makes it true, and + ``None`` false. A declared call: it is reported to the simulation's + tracer, and it never builds the current-law copy. + """ + self._report_current_law_call("compares_with_current_law") + return self._current_law_source().compares + + @property + def current_law_system(self) -> "TaxBenefitSystem": + """The tax-benefit system of current law, without building a copy. + + For a simulation that compares with current law, the system its + current-law copy calculates with (the class's + ``default_tax_benefit_system_instance`` unless a simulation was + assigned to ``baseline``); otherwise this simulation's own system. A + declared call, reported to the simulation's tracer. + """ + self._report_current_law_call("current_law_system") + return self._current_law_system() + + def _current_law_system(self) -> "TaxBenefitSystem": + source = self._current_law_source() + if not source.compares: + return self.tax_benefit_system + if source.simulation is not None: + return source.simulation.tax_benefit_system + return source.owner.default_tax_benefit_system_instance + + def current_law_simulation(self) -> "Simulation": + """The simulation that calculates this simulation's current-law values. + + For a simulation that compares with current law, the current-law + copy, built on the first call (by :meth:`_build_current_law_simulation`) + from the inputs the simulation holds then. A branch gets its parent's. + A copy core built is made read-only (see :meth:`make_read_only`); a + simulation assigned to ``baseline`` is returned as it was given. + Without a comparison, this simulation itself. A declared call, + reported to the simulation's tracer. + """ + self._report_current_law_call("current_law_simulation") + source = self._current_law_source() + if not source.compares: + return self + return source.get(make_read_only=True) + + @property + def baseline(self) -> Optional["Simulation"]: + """Deprecated alias: use the declared current-law calls instead. + + The current-law copy for a simulation that compares with current law + (see :meth:`current_law_simulation`), otherwise ``None``. Reading it + builds the copy if there is none, and does not make it read-only, so + code that sets inputs on the baseline keeps working; the first + declared call makes it read-only. Assigning a simulation makes it the + copy, kept as it is given, and the simulation then compares with + current law; assigning ``None`` stops the comparison. Each read is + reported to the tracer as a ``baseline`` call. Formulas should use + ``Population.current_law``, ``compares_with_current_law``, + ``current_law_system`` and ``current_law_simulation``; the alias is + due to be removed once country packages read current law only through + them. + """ + self._report_current_law_call("baseline") + source = self._current_law_source() + if not source.compares: + return None + return source.get(make_read_only=False) + + @baseline.setter + def baseline(self, simulation: Optional["Simulation"]) -> None: + self.__dict__["_current_law"] = _CurrentLawSource( + self, + compares=simulation is not None, + simulation=simulation, + assigned=simulation is not None, + ) + + def _build_current_law_simulation(self) -> "Simulation": + """Build the simulation that calculates this one's current-law values. + + Called once, the first time a simulation that compares with current + law needs current-law values (see :meth:`current_law_simulation`), + which may be in the middle of a calculation. Country packages may + override it to give the copy their own state; an override must not + read current-law values or ``baseline`` itself. + + The copy is a branch of this simulation named ``baseline``, traced in + this simulation, under the class's + ``default_tax_benefit_system_instance``. It keeps the inputs this + simulation holds now and none of the values it has calculated, which + were calculated under the reform: so an input set on this simulation + before the copy is built reaches the copy, and one set afterwards + does not. + """ + # A branch registered under the name, by code that ran before the copy + # was needed, may hold the reform's values; the copy replaces it. + self.branches.pop("baseline", None) + copy = self.get_branch("baseline") + copy.__dict__["_current_law"] = _CurrentLawSource(copy, compares=False) + copy.trace = self.trace + copy.tracer = self.tracer + copy.tax_benefit_system = self.default_tax_benefit_system_instance + # The branch was built under the reform's system: its populations + # looked variables up there, and its holders kept the reform's + # variables, so a variable the reform neutralized read as the + # default in the copy too. + copy._bind_to_tax_benefit_system() + # The branch shares this simulation's list of input variables, and + # the binding keeps a list it drops nothing from. The copy runs under + # another system, so it keeps its own list. + copy.input_variables = list(copy.input_variables) + # The branch started from everything this simulation holds, including + # what it calculated under the reform. Keep only the inputs, and read + # macro-cache files as this simulation does. + macro_cache_read = self.macro_cache_read + copy.drop_computed_arrays() + copy.macro_cache_read = macro_cache_read + # Nor has the copy requested what this simulation requested, which + # ``requires_computation_after`` reads. + copy._requested_variables = set() + return copy + def apply_reform(self, reform: Union[tuple, Reform]): refuse_on_read_only(self, "apply_reform") if isinstance(reform, tuple): @@ -3323,40 +3556,24 @@ def clone( # A ``set_input`` running on this simulation is not running on the copy. new._user_input_contexts = [] - # A branch shares its parent's baseline: formulas that run in a - # branch read the parent's baseline values through it. That holds for - # every clone of this simulation made while ``get_branch`` is making - # a branch of it, not only the one that shares its arrays (a subclass - # ``clone`` may clone it directly first; see ``_BranchClone``). + # A branch shares its parent's record of where its current-law + # values come from: formulas that run in a branch read the parent's + # current-law copy. That holds for every clone of this simulation + # made while ``get_branch`` is making a branch of it, not only the + # one that shares its arrays (a subclass ``clone`` may clone it + # directly first; see ``_BranchClone``). branching = request is not None and request.simulation is self - baseline = getattr(self, "baseline", None) - if ( - not branching - and baseline is not None - and getattr(baseline, "parent_branch", None) is self - ): - # This simulation's own baseline branch (``__init__`` makes one - # for a reform). A shared one filled this simulation's caches - # with the copy's baseline calculations and took inputs set - # through either, ``get_branch("baseline")`` on the copy made a - # branch under the copy's (reform) policy, ``subsample`` of the - # copy left its baseline at the old size, and the copy kept this - # simulation alive through the branch's ``parent_branch``. The - # copy gets a copy of the branch, not a new branch of itself as in - # ``__init__``: its cached arrays include values calculated under - # this simulation's policy, which a new branch would read as its - # own. - new_baseline = baseline.clone( - debug=debug, trace=trace, clone_tax_benefit_system=False + current_law = self.__dict__.get("_current_law") + if not branching and current_law is not None and current_law.owner is self: + # This simulation's own record. A shared copy filled this + # simulation's caches with the clone's current-law calculations + # and took inputs set through either, ``subsample`` of the clone + # left the copy at the old size, and the clone kept this + # simulation alive through the copy's ``parent_branch``. A record + # this simulation shares with its parent stays shared. + new.__dict__["_current_law"] = current_law.for_clone( + self, new, debug, trace ) - new_baseline.parent_branch = new - # A baseline traced in its simulation (as ``__init__`` makes it) - # is traced in the copy. - if baseline.tracer is self.tracer: - new_baseline.tracer = new.tracer - if self.branches.get(baseline.branch_name) is baseline: - new.branches[baseline.branch_name] = new_baseline - new.baseline = new_baseline return new @@ -3409,6 +3626,23 @@ def get_branch( """ if name == self.branch_name: return self + if name == "baseline" and name not in self.branches: + current_law = self.__dict__.get("_current_law") + if ( + current_law is not None + and current_law.owner is self + and current_law.compares + and not current_law.building + and ( + current_law.simulation is None + or getattr(current_law.simulation, "parent_branch", None) is self + ) + ): + # Construction used to register the current-law copy under + # this name, and code reached it here. A copy built after + # ``make_read_only`` is not registered (see ``get_branch`` on a + # read-only simulation), so it is returned from the record. + return current_law.get(make_read_only=False) if name in self.branches: branch = self.branches[name] frames = _calculation_frames.get() @@ -4073,9 +4307,19 @@ def retain_structure(name, values): # rebuilt baseline branch kept the reform system and reform-vs-baseline # comparisons after ``subsample`` compared the reform against itself. if "baseline" in self.branches: + # A current-law copy that was built (or a baseline branch that was + # assigned). One not built yet is built from the new sample when + # needed. baseline_tax_benefit_system = self.branches["baseline"].tax_benefit_system del self.branches["baseline"] - baseline = self.get_branch("baseline") + # A new branch, not the copy this replaces (see ``get_branch``). + current_law = self._current_law_source() + building = current_law.building + current_law.building = True + try: + baseline = self.get_branch("baseline") + finally: + current_law.building = building # As in ``__init__``, the branch is traced in this simulation, # uses the baseline system's entities and variables, and has no # baseline of its own: ``get_branch`` gave it this simulation's, @@ -4086,9 +4330,17 @@ def retain_structure(name, values): baseline._bind_to_tax_benefit_system() # As in ``__init__``, the baseline keeps its own list. baseline.input_variables = list(baseline.input_variables) - baseline.baseline = None - if getattr(self, "baseline", None) is not None: - self.baseline = baseline + baseline.__dict__["_current_law"] = _CurrentLawSource( + baseline, compares=False + ) + current_law = self._current_law_source() + if current_law.compares: + self.__dict__["_current_law"] = _CurrentLawSource( + self, + compares=True, + simulation=baseline, + assigned=current_law.assigned, + ) self.default_calculation_period = default_calculation_period return self diff --git a/policyengine_core/tracers/__init__.py b/policyengine_core/tracers/__init__.py index f23c0bbcd..d4198c923 100644 --- a/policyengine_core/tracers/__init__.py +++ b/policyengine_core/tracers/__init__.py @@ -4,7 +4,7 @@ from .performance_log import PerformanceLog from .variable_graph import VariableGraph from .simple_tracer import SimpleTracer -from .trace_node import TraceNode +from .trace_node import CurrentLawCall, TraceNode from .tracing_parameter_node_at_instant import ( TracingChildren, TracingParameterNode, diff --git a/policyengine_core/tracers/full_tracer.py b/policyengine_core/tracers/full_tracer.py index f2d93e7f4..7df194eba 100644 --- a/policyengine_core/tracers/full_tracer.py +++ b/policyengine_core/tracers/full_tracer.py @@ -76,6 +76,26 @@ def record_formula_run(self) -> None: if self._current_node is not None: self._current_node.formula_ran = True + def record_current_law_call( + self, + call: str, + variable: Optional[str], + period: Optional[Period], + branch_name: str, + ) -> None: + """Note on the calculation running now a declared current-law call + its formula made (see ``tracers.CurrentLawCall``). A call made outside + any calculation is not recorded.""" + if self._current_node is not None: + self._current_node.current_law_calls.append( + tracers.CurrentLawCall( + call=call, + variable=variable, + period=period, + branch_name=branch_name, + ) + ) + def _record_start_time( self, time_in_s: Optional[float] = None, diff --git a/policyengine_core/tracers/simple_tracer.py b/policyengine_core/tracers/simple_tracer.py index 9838491be..babcc2b4f 100644 --- a/policyengine_core/tracers/simple_tracer.py +++ b/policyengine_core/tracers/simple_tracer.py @@ -1,7 +1,7 @@ from __future__ import annotations import typing -from typing import Dict, List, Union +from typing import Dict, List, Optional, Union if typing.TYPE_CHECKING: from numpy.typing import ArrayLike @@ -33,6 +33,15 @@ def record_parameter_access(self, parameter: str, period, branch_name: str, valu def record_formula_run(self) -> None: pass + def record_current_law_call( + self, + call: str, + variable: Optional[str], + period: Optional[Period], + branch_name: str, + ) -> None: + pass # ignore declared current-law calls + def record_calculation_end(self) -> None: self.stack.pop() diff --git a/policyengine_core/tracers/trace_node.py b/policyengine_core/tracers/trace_node.py index 53679efab..8e991d0d3 100644 --- a/policyengine_core/tracers/trace_node.py +++ b/policyengine_core/tracers/trace_node.py @@ -13,6 +13,23 @@ Time = typing.Union[float, int] +@dataclasses.dataclass(frozen=True) +class CurrentLawCall: + """A declared current-law call a formula made while it was calculated. + + ``call`` names it: ``current_law``, ``compares_with_current_law``, + ``current_law_system`` or ``current_law_simulation``, or ``baseline`` for + a read of the deprecated alias. ``variable`` and ``period`` are the value + a ``current_law`` call read, and ``None`` for the other calls. + ``branch_name`` is the branch of the simulation that made the call. + """ + + call: str + variable: typing.Optional[str] = None + period: typing.Optional[Period] = None + branch_name: str = "default" + + @dataclasses.dataclass class TraceNode: name: str @@ -28,6 +45,11 @@ class TraceNode: # ``subtracts``. It stays False for a value that was stored, cached or # defaulted, including one masked by ``defined_for``. formula_ran: bool = False + # The declared current-law calls the formula made (``CurrentLawCall``), + # in order. The values those calls read are children, as other reads are. + current_law_calls: typing.List[CurrentLawCall] = dataclasses.field( + default_factory=list + ) def calculation_time(self, round_: bool = True) -> Time: result = self.end - self.start diff --git a/policyengine_core/variables/variable.py b/policyengine_core/variables/variable.py index de9415c42..8071419a7 100644 --- a/policyengine_core/variables/variable.py +++ b/policyengine_core/variables/variable.py @@ -143,6 +143,9 @@ class Variable: hidden_input: bool = False """Whether the variable is hidden from the input screen entirely on PolicyEngine.""" + current_law_read: bool = False + """Whether formulas may read the variable's current-law value with ``Population.current_law``. In a simulation with a reform, that call returns the value calculated under current law; without a reform, the simulation's own value. Reading the current-law value of a variable that does not declare this raises ``UndeclaredCurrentLawReadError``. A reform's ``update_variable`` keeps it unless the new class sets it.""" + requires_computation_after: str = None """Name of a variable that must be computed before this variable.""" @@ -309,6 +312,9 @@ def __init__(self, baseline_variable=None): self.hidden_input = self.set( attr, "hidden_input", allowed_type=bool, default=False ) + self.current_law_read = self.set( + attr, "current_law_read", allowed_type=bool, default=False + ) self.requires_computation_after = self.set( attr, "requires_computation_after", allowed_type=str From 5d591dd6a002f845ef6c3ac2e787938434450a0c Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Tue, 1 Dec 2026 23:14:44 +0400 Subject: [PATCH 05/11] Add tests for review round 1's findings Tests that fail before the fixes: current_law is projected through entity projections like a population call; current_law without a period raises before building the copy and names the calling code; a derivative does not depend on whether the copy was built before it; removing the registered copy lets get_branch("baseline") make a new branch; a simulation saved with baseline in its instance dictionary keeps it; an AttributeError while building the copy is not read as "no baseline". Tests for behaviour that already holds: options pass through current_law; a copy built inside a calculation ignores that calculation's reform values; a clone of a simulation with a read-only copy gets its own copy; a branch of a branch reads the first simulation's copy; a deep copy keeps its own copy; the declaration check reads an assigned simulation's system. One edited test now builds the baseline by reading it, and two test modules no longer say construction builds the branch. Co-Authored-By: Claude Opus 5.5 --- tests/core/test_clone_reform_baseline.py | 6 +- tests/core/test_current_law_reads.py | 184 ++++++++++++++++++++++ tests/core/test_reform_baseline_system.py | 18 +-- 3 files changed, 196 insertions(+), 12 deletions(-) diff --git a/tests/core/test_clone_reform_baseline.py b/tests/core/test_clone_reform_baseline.py index a23ecb299..88d7eceab 100644 --- a/tests/core/test_clone_reform_baseline.py +++ b/tests/core/test_clone_reform_baseline.py @@ -1,7 +1,9 @@ """A clone of a reform simulation has a baseline of its own. -``Simulation.__init__`` gives a reform simulation a baseline branch, -``baseline``, under the baseline policy. ``Simulation.clone`` copies the +A reform simulation has a baseline branch, ``baseline``, under the baseline +policy (the current-law copy: ``Simulation.__init__`` built it, and +``_build_current_law_simulation`` now builds it when it is first needed, so +these tests read ``baseline`` to build it). ``Simulation.clone`` copies the instance dictionary, so a clone shared that branch with its source: calculations on the clone's baseline filled the source's, an input set on either one's baseline reached the other, ``clone.get_branch("baseline")`` diff --git a/tests/core/test_current_law_reads.py b/tests/core/test_current_law_reads.py index e5075d317..96ebf80e5 100644 --- a/tests/core/test_current_law_reads.py +++ b/tests/core/test_current_law_reads.py @@ -16,6 +16,7 @@ from __future__ import annotations +import copy as copy_module import functools import numpy as np @@ -112,6 +113,32 @@ def formula(person, period, parameters): # Variables whose formulas make declared calls. +class reform_then_current_law_tax(Variable): + label = "Current-law income tax, read after the reform's" + value_type = float + entity = Person + definition_period = MONTH + + def formula(person, period, parameters): + # The reform simulation calculates these first, in this calculation. + reform_tax = person("income_tax", period) + reform_declared_tax = person("declared_monthly_tax", period) + current_law_tax = person.current_law("declared_monthly_tax", period) + return current_law_tax + 0 * reform_tax + 0 * reform_declared_tax + + +class income_tax_change(Variable): + label = "Income tax change from current law" + value_type = float + entity = Person + definition_period = MONTH + + def formula(person, period, parameters): + return person("income_tax", period) - person.current_law( + "declared_monthly_tax", period + ) + + class makes_every_declared_call(Variable): label = "Current-law income tax, read with every declared call" value_type = float @@ -144,6 +171,8 @@ def formula(person, period, parameters): declared_household_monthly_tax, declared_household_yearly_tax, declared_tax_after_income_tax, + reform_then_current_law_tax, + income_tax_change, makes_every_declared_call, reads_the_baseline_alias, ) @@ -545,6 +574,161 @@ def test_subsample_keeps_no_copy_when_none_was_built(): assert simulation.current_law_simulation().persons.count == simulation.persons.count +def test_current_law_is_projected_like_a_population_call(): + simulation = _declared_simulation() + + per_person = simulation.persons.household.current_law( + "declared_household_monthly_tax", MONTH_PERIOD + ) + + household_total = sum(MONTHLY_SALARY) * BASELINE_RATE + _assert_income_tax(per_person, [household_total, household_total], 1.0) + first_person = simulation.household.first_person.current_law( + "declared_monthly_tax", MONTH_PERIOD + ) + _assert_income_tax(first_person, [MONTHLY_SALARY[0]], BASELINE_RATE) + + +def test_current_law_passes_options_on(): + simulation = _declared_simulation() + + yearly = simulation.persons.current_law( + "declared_monthly_tax", YEAR_PERIOD, options=["add"] + ) + + _assert_income_tax(yearly, YEARLY_SALARY, BASELINE_RATE) + + +def test_current_law_without_a_period_raises_before_building_the_copy(): + simulation = _declared_simulation() + + with pytest.raises(ValueError, match="did not specify on which period") as error: + simulation.persons.current_law("declared_monthly_tax") + + assert "baseline" not in simulation.branches + # The message points at the code that left the period out. + assert "test_current_law_reads.py" in str(error.value) + + +def test_a_copy_built_in_a_calculation_ignores_what_that_calculation_calculated(): + simulation = _declared_simulation() + + values = simulation.calculate("reform_then_current_law_tax", MONTH_PERIOD) + + _assert_income_tax(values, MONTHLY_SALARY, BASELINE_RATE) + _assert_income_tax( + simulation.calculate("declared_monthly_tax", MONTH_PERIOD), + MONTHLY_SALARY, + REFORM_RATE, + ) + + +def test_a_derivative_does_not_depend_on_whether_the_copy_was_built(): + """``derivative`` changes an input on a clone; its current law does not.""" + fresh = _declared_simulation() + built = _declared_simulation() + built.current_law_simulation() + + fresh_derivative = fresh.derivative("income_tax_change", "salary", MONTH_PERIOD) + built_derivative = built.derivative("income_tax_change", "salary", MONTH_PERIOD) + + np.testing.assert_allclose(fresh_derivative, built_derivative, rtol=1e-3) + np.testing.assert_allclose(fresh_derivative, [REFORM_RATE] * 2, rtol=1e-3) + + +def test_removing_the_registered_copy_lets_get_branch_make_a_new_branch(): + """As before: code that rebuilds the baseline branch itself gets a new one.""" + simulation = _declared_simulation() + copy = simulation.baseline + + simulation.branches.pop("baseline") + new_branch = simulation.get_branch("baseline") + + assert new_branch is not copy + assert simulation.branches["baseline"] is new_branch + + +def test_a_clone_of_a_simulation_with_a_read_only_copy_gets_its_own_copy(): + simulation = _declared_simulation() + copy = simulation.current_law_simulation() + copy_values = copy.calculate("declared_monthly_tax", MONTH_PERIOD) + + clone = simulation.clone() + + clone_copy = clone.branches["baseline"] + assert clone_copy is not copy + assert clone_copy.parent_branch is clone + assert not clone_copy.read_only + assert clone.current_law_simulation() is clone_copy + assert clone_copy.read_only + np.testing.assert_array_equal( + clone_copy.calculate("declared_monthly_tax", MONTH_PERIOD), copy_values + ) + assert copy.read_only + assert simulation.current_law_simulation() is copy + + +def test_a_branch_of_a_branch_reads_the_first_simulations_copy(): + simulation = _declared_simulation() + inner = simulation.get_branch("outer").get_branch("inner") + + values = inner.persons.current_law("declared_monthly_tax", MONTH_PERIOD) + + assert inner.current_law_simulation() is simulation.current_law_simulation() + _assert_income_tax(values, MONTHLY_SALARY, BASELINE_RATE) + + +def test_a_deep_copy_keeps_its_own_copy(): + simulation = Simulation(situation=SITUATION, reform=REFORM) + copy = simulation.baseline + + duplicate = copy_module.deepcopy(simulation) + + assert duplicate.compares_with_current_law is True + assert duplicate.baseline is duplicate.branches["baseline"] + assert duplicate.baseline is not copy + assert duplicate.baseline.parent_branch is duplicate + _assert_income_tax( + duplicate.baseline.calculate("income_tax", MONTH_PERIOD), + MONTHLY_SALARY, + BASELINE_RATE, + ) + + +def test_a_simulation_saved_by_an_earlier_core_keeps_its_baseline(): + """An earlier core kept ``baseline`` in the instance dictionary.""" + simulation = Simulation(situation=SITUATION) + separate = Simulation(situation=SITUATION) + del simulation.__dict__["_current_law"] + simulation.__dict__["baseline"] = separate + + assert simulation.compares_with_current_law is True + assert simulation.current_law_simulation() is separate + assert simulation.baseline is separate + + +def test_the_declaration_check_reads_an_assigned_simulations_system(): + simulation = _declared_simulation() + # The template's own system has no ``declared_monthly_tax``. + simulation.baseline = Simulation(situation=SITUATION) + + with pytest.raises(errors.VariableNotFoundError): + simulation.persons.current_law("declared_monthly_tax", MONTH_PERIOD) + + +def test_an_attribute_error_while_building_is_not_read_as_no_baseline(): + simulation_class, _ = _simulation_classes() + + class FailingSimulation(simulation_class): + def _build_current_law_simulation(self): + raise AttributeError("a country package's builder failed") + + simulation = FailingSimulation(situation=SITUATION, reform=REFORM) + + with pytest.raises(RuntimeError, match="builder failed"): + getattr(simulation, "baseline", None) + + def _node_named(nodes, name): for node in nodes: if node.name == name: diff --git a/tests/core/test_reform_baseline_system.py b/tests/core/test_reform_baseline_system.py index f093a3108..1c1225e1d 100644 --- a/tests/core/test_reform_baseline_system.py +++ b/tests/core/test_reform_baseline_system.py @@ -1,7 +1,9 @@ """A reform simulation's baseline branch uses the baseline system throughout. -``Simulation.__init__`` builds the baseline branch with ``get_branch``, under -the reform's system, and then gives it the baseline's. The branch's +The baseline branch (the current-law copy, which ``Simulation.__init__`` +built and ``_build_current_law_simulation`` now builds when it is first +needed) is made with ``get_branch``, under the reform's system, and then given +the baseline's. The branch's populations kept the reform system's entities, so they looked variables up in the reform's system, and its holders kept the reform's ``Variable`` objects: a variable the reform neutralized read as its default in the baseline too, @@ -193,15 +195,11 @@ def test_the_baseline_drops_a_holder_built_for_another_entity(): "households": {"h": {"parents": ["a", "b"]}}, } reform = Simulation(situation=situation, reform=move_salary_to_households) - # Create the reform's household holder before cloning the baseline branch so - # ``_bind_to_tax_benefit_system`` must drop the cross-entity holder. + # Create the reform's household holder before the baseline branch is + # built, so ``_bind_to_tax_benefit_system`` must drop the cross-entity + # holder. Reading ``baseline`` builds the branch. reform.calculate("salary", PERIOD) - # Construction no longer builds the baseline branch; drop one if built. - reform.branches.pop("baseline", None) - baseline = reform.get_branch("baseline") - baseline.tax_benefit_system = reform.default_tax_benefit_system_instance - baseline._bind_to_tax_benefit_system() - baseline.input_variables = list(baseline.input_variables) + baseline = reform.baseline assert "salary" in reform.household._holders assert "salary" not in baseline.household._holders From 977323b6fdc9a8c4b649b719349859b645cab3fe Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Tue, 1 Dec 2026 23:16:25 +0400 Subject: [PATCH 06/11] Fix review round 1's findings on declared current-law reads - current_law is projectable, so person.household.current_law(...) returns one value per person, as person.household(...) does. - current_law checks the period before building the copy, so a missing period builds nothing and the error names the calling code. - derivative builds the current-law copy before cloning, so its result does not depend on whether an earlier call built the copy: the changed clone compares with the current law of the simulation's own inputs, as before. - get_branch("baseline") returns a built copy missing from branches only on a read-only simulation; elsewhere, code that removed the registered copy gets a new branch, as before. - subsample builds a copy core built again with _build_current_law_simulation, so an override applies and the copy starts with nothing requested; other baseline branches are rebuilt as before. - The builder also clears pending cache invalidations. - A simulation that kept baseline in its instance dictionary (saved by an earlier core) keeps it as its current-law copy. - An AttributeError while building the copy through the baseline property is raised as a RuntimeError, so getattr(simulation, "baseline", None) does not read it as "no baseline". - Docstrings no longer say construction builds the copy. Co-Authored-By: Claude Opus 5.5 --- policyengine_core/populations/population.py | 9 +- policyengine_core/simulations/simulation.py | 138 ++++++++++++++------ 2 files changed, 107 insertions(+), 40 deletions(-) diff --git a/policyengine_core/populations/population.py b/policyengine_core/populations/population.py index 8a70907ed..946808ec7 100644 --- a/policyengine_core/populations/population.py +++ b/policyengine_core/populations/population.py @@ -179,6 +179,7 @@ def __call__( # Helpers + @projectors.projectable def current_law( self, variable_name: str, @@ -199,13 +200,19 @@ def current_law( ``UndeclaredCurrentLawReadError``. Each call is reported to the simulation's tracer, with the variable and period. - Example: + Example, for a variable ``income_tax`` declaring + ``current_law_read = True``: >>> person.current_law('income_tax', '2017-04') >>> array([45.]) + + Called through a projection (``person.household.current_law(...)``), + the result is projected as a call's would be. """ from policyengine_core.errors import UndeclaredCurrentLawReadError + # Before anything is built, so a missing period names the caller. + self.check_period_validity(variable_name, period) simulation = self.simulation variable = simulation._current_law_system().get_variable( variable_name, check_existence=True diff --git a/policyengine_core/simulations/simulation.py b/policyengine_core/simulations/simulation.py index 48d584d20..3a908eb6c 100644 --- a/policyengine_core/simulations/simulation.py +++ b/policyengine_core/simulations/simulation.py @@ -1118,9 +1118,11 @@ def make_read_only(self) -> None: Calling it again changes nothing, and keeps the first record of the parameters. Nothing else is made read-only: not a clone, and not a - branch registered before this call (a reform simulation's - ``baseline``, or one a formula made in an earlier calculation), which - ``get_branch`` still returns as it is. A pickled or deep-copied + branch registered before this call (a reform simulation's current-law + copy built before it, or one a formula made in an earlier + calculation), which ``get_branch`` still returns as it is. A + current-law copy built after this call is not registered, and + ``get_branch("baseline")`` returns it. A pickled or deep-copied read-only simulation stays read-only, but a value it keeps only in its fast cache (a variable its memory configuration does not store) comes back writable. @@ -1195,7 +1197,15 @@ def _current_law_source(self) -> _CurrentLawSource: """ source = self.__dict__.get("_current_law") if source is None: - source = _CurrentLawSource(self, compares=False) + # A simulation saved by a core that kept ``baseline`` as an + # instance attribute, which the ``baseline`` property now hides. + saved_baseline = self.__dict__.pop("baseline", None) + source = _CurrentLawSource( + self, + compares=saved_baseline is not None, + simulation=saved_baseline, + assigned=saved_baseline is not None, + ) self.__dict__["_current_law"] = source return source @@ -1289,7 +1299,14 @@ def baseline(self) -> Optional["Simulation"]: source = self._current_law_source() if not source.compares: return None - return source.get(make_read_only=False) + try: + return source.get(make_read_only=False) + except AttributeError as error: + # Raised from a property, it would make ``getattr(simulation, + # "baseline", None)`` return ``None`` as if there were no copy. + raise RuntimeError( + f"Building the current-law copy of this simulation failed: {error}" + ) from error @baseline.setter def baseline(self, simulation: Optional["Simulation"]) -> None: @@ -1341,8 +1358,10 @@ def _build_current_law_simulation(self) -> "Simulation": copy.drop_computed_arrays() copy.macro_cache_read = macro_cache_read # Nor has the copy requested what this simulation requested, which - # ``requires_computation_after`` reads. + # ``requires_computation_after`` reads, or anything to delete once a + # calculation ends, as a spiral in this simulation queues. copy._requested_variables = set() + copy.invalidated_caches = set() return copy def apply_reform(self, reform: Union[tuple, Reform]): @@ -1743,8 +1762,9 @@ def _bind_to_tax_benefit_system(self) -> None: """Make this simulation's populations and holders use its own system. For a simulation given another system after its populations were - built: a reform simulation's baseline branch is a branch under the - reform's system that is then given the baseline's. Each population + built: a reform simulation's current-law copy is a branch under the + reform's system that is then given the baseline's + (see ``_build_current_law_simulation``). Each population takes that system's entity, so it looks variables up there, and each holder takes that system's variable, so a variable the reform neutralized or redefined is the baseline's again. Holders, recorded @@ -3420,14 +3440,18 @@ def clone( Copy the simulation just enough to be able to run the copy without modifying the original simulation. The copy records its own cache invalidations (``invalidated_caches``, - starting from this simulation's pending ones). If ``baseline`` is a - branch of this simulation, as a reform simulation's is, the copy gets - a copy of that branch as its own: a branch of the copy, under the same - name, with this baseline's tax-benefit system, traced in the copy if - this baseline is traced in this simulation. Any other ``baseline`` is - shared: a branch's is its parent's, and a country package that builds - a separate baseline simulation copies it, if it needs to, in its own - ``clone``. + starting from this simulation's pending ones). A simulation that + compares with current law gives the copy its own current-law copy + only if it has built one (see :meth:`current_law_simulation`): if + that is a branch of this simulation, the copy gets a copy of that + branch as its own, a branch of the copy under the same name, with the + same tax-benefit system, traced in the copy if it is traced in this + simulation, and not read-only until a declared call reaches it. A + copy not built yet is built by the copy from its own inputs when it + needs one, so an input set on the copy reaches it. Any other + current-law simulation is shared: a branch's is its parent's, and a + simulation a country package built and assigned to ``baseline`` is + shared unless the package copies it in its own ``clone``. Every cached array is copied, except in the first ``clone`` of this simulation made while ``get_branch`` is creating a branch of it: that @@ -3617,6 +3641,13 @@ def get_branch( branch is not read-only. A name registered before ``make_read_only`` gives that branch, as it is. + On a simulation that compares with current law, ``"baseline"`` gives + its current-law copy while that copy is not built yet (building it, + see :meth:`current_law_simulation`) and, on a read-only simulation, + while the copy is not registered. Once a built copy is registered, + the name gives it as any registered branch; code that removed it from + ``branches`` gets a new branch. + Args: name (str, optional): Name of the branch. Defaults to "branch". clone_system (bool, optional): Whether to clone the tax-benefit system. Use this if you're changing policy parameters. Defaults to False. @@ -3635,13 +3666,19 @@ def get_branch( and not current_law.building and ( current_law.simulation is None - or getattr(current_law.simulation, "parent_branch", None) is self + or ( + self.read_only + and getattr(current_law.simulation, "parent_branch", None) + is self + ) ) ): # Construction used to register the current-law copy under - # this name, and code reached it here. A copy built after - # ``make_read_only`` is not registered (see ``get_branch`` on a - # read-only simulation), so it is returned from the record. + # this name, and code reached it here. A read-only simulation + # does not register the copy it builds (see below), so it is + # returned from the record. On any other simulation, code + # that removed the registered copy gets a new branch, as + # before. return current_law.get(make_read_only=False) if name in self.branches: branch = self.branches[name] @@ -3686,6 +3723,11 @@ def derivative( period (Period): The period for which to compute the derivative. delta (float): The infinitesimal to use for the derivative. + A simulation that compares with current law compares the changed + copy with the current law of its own inputs: the current-law copy is + built first if there is none, so the copy of this simulation gets a + copy of it, without the change. + Returns: ArrayLike: The derivative. """ @@ -3695,6 +3737,11 @@ def derivative( elif period is None and self.default_calculation_period is not None: period = periods.period(self.default_calculation_period) + current_law = self._current_law_source() + if current_law.compares and current_law.owner is self: + # Otherwise the clone, which builds its own copy when it needs + # one, would build it from the changed input. + current_law.get(make_read_only=False) alt_sim = self.clone() alt_sim.drop_computed_arrays() alt_sim.set_input(wrt, period, self.calculate(wrt, period) + delta) @@ -4299,41 +4346,54 @@ def retain_structure(name, values): name: branch for name, branch in self.branches.items() if name == "baseline" } - # Ensure the baseline branch has the new data: rebuild it from the - # subsampled simulation through ``get_branch`` (the same wiring - # ``__init__`` uses), then restore the saved baseline tax-benefit - # system. Previously the saved system was assigned to - # ``self.branches["tax_benefit_system"]`` — a stray dict key — so the - # rebuilt baseline branch kept the reform system and reform-vs-baseline - # comparisons after ``subsample`` compared the reform against itself. - if "baseline" in self.branches: - # A current-law copy that was built (or a baseline branch that was - # assigned). One not built yet is built from the new sample when - # needed. - baseline_tax_benefit_system = self.branches["baseline"].tax_benefit_system + # Ensure a baseline branch that was built has the new data. A + # current-law copy not built yet is built from the new sample when it + # is first needed. + current_law = self._current_law_source() + replaced = self.branches.get("baseline") + if ( + replaced is not None + and current_law.owner is self + and current_law.simulation is replaced + and not current_law.assigned + ): + # The current-law copy core built: build it again from the new + # sample, with ``_build_current_law_simulation`` (which a country + # package may override). + del self.branches["baseline"] + current_law.simulation = None + current_law.get(make_read_only=False) + elif replaced is not None: + # A baseline branch assigned to ``baseline``, or registered under + # the name: rebuild it from the subsampled simulation through + # ``get_branch``, as the builder does, then restore its saved + # tax-benefit system. Previously the saved system was assigned to + # ``self.branches["tax_benefit_system"]`` (a stray dict key), so the + # rebuilt baseline branch kept the reform system and + # reform-vs-baseline comparisons after ``subsample`` compared the + # reform against itself. + baseline_tax_benefit_system = replaced.tax_benefit_system del self.branches["baseline"] # A new branch, not the copy this replaces (see ``get_branch``). - current_law = self._current_law_source() building = current_law.building current_law.building = True try: baseline = self.get_branch("baseline") finally: current_law.building = building - # As in ``__init__``, the branch is traced in this simulation, - # uses the baseline system's entities and variables, and has no - # baseline of its own: ``get_branch`` gave it this simulation's, - # the branch it replaces, which kept the old population alive. + # As the builder does, the branch is traced in this simulation, + # uses the baseline system's entities and variables, and compares + # with no current law of its own: ``get_branch`` gave it this + # simulation's record, whose copy kept the old population alive. baseline.trace = self.trace baseline.tracer = self.tracer baseline.tax_benefit_system = baseline_tax_benefit_system baseline._bind_to_tax_benefit_system() - # As in ``__init__``, the baseline keeps its own list. + # As the builder does, the baseline keeps its own list. baseline.input_variables = list(baseline.input_variables) baseline.__dict__["_current_law"] = _CurrentLawSource( baseline, compares=False ) - current_law = self._current_law_source() if current_law.compares: self.__dict__["_current_law"] = _CurrentLawSource( self, From be5b67cffa8f6ee075220eba522e7a5c81fefa28 Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Tue, 1 Dec 2026 23:39:02 +0400 Subject: [PATCH 07/11] Add tests for review round 2's findings Tests that fail before the fixes: a read-only simulation registers the current-law copy it builds, so a clone of it keeps its copy registered and get_branch("baseline") and subsample see it; a saved simulation's own baseline branch, kept in its instance dictionary by an earlier core, is copied by clone rather than shared; assigning baseline on a read-only simulation raises. Tests for behaviour that already holds: subsample builds a read-only copy again as a writable one, and does so with an overridden builder; a copy built in a calculation that runs again after an input change reads the new input. Co-Authored-By: Claude Opus 5.5 --- tests/core/test_current_law_reads.py | 115 +++++++++++++++++++++++++++ 1 file changed, 115 insertions(+) diff --git a/tests/core/test_current_law_reads.py b/tests/core/test_current_law_reads.py index 96ebf80e5..6c9c480b2 100644 --- a/tests/core/test_current_law_reads.py +++ b/tests/core/test_current_law_reads.py @@ -110,6 +110,19 @@ def formula(person, period, parameters): return person("income_tax", period) +class sets_salary_then_reads_current_law(Variable): + label = "Current-law income tax, read after the formula changes salary" + value_type = float + entity = Person + definition_period = MONTH + + def formula(person, period, parameters): + # An input set on the simulation while it calculates makes core run + # the calculation again. + person.simulation.set_input("salary", period, OTHER_MONTHLY_SALARY) + return person.current_law("declared_monthly_tax", period) + + # Variables whose formulas make declared calls. @@ -173,6 +186,7 @@ def formula(person, period, parameters): declared_tax_after_income_tax, reform_then_current_law_tax, income_tax_change, + sets_salary_then_reads_current_law, makes_every_declared_call, reads_the_baseline_alias, ) @@ -729,6 +743,107 @@ def _build_current_law_simulation(self): getattr(simulation, "baseline", None) +def test_a_read_only_simulation_registers_the_copy_it_builds(): + simulation = _declared_simulation() + simulation.make_read_only() + + copy = simulation.current_law_simulation() + + assert simulation.branches.get("baseline") is copy + assert simulation.get_branch("baseline") is copy + # Other branches of a read-only simulation stay unregistered. + assert "temporary" not in simulation.get_branch("temporary").branches + assert "temporary" not in simulation.branches + + +def test_a_clone_of_a_read_only_simulation_with_a_copy_keeps_it_registered(): + _, microsimulation_class = _simulation_classes() + simulation = microsimulation_class(reform=REFORM) + simulation.make_read_only() + simulation.current_law_simulation() + + clone = simulation.clone() + + clone_copy = clone.branches.get("baseline") + assert clone_copy is not None + assert clone.get_branch("baseline") is clone_copy + assert clone.current_law_simulation() is clone_copy + clone.subsample(n=3, seed="current-law", time_period="2022") + rebuilt = clone.current_law_simulation() + assert rebuilt is not clone_copy + assert rebuilt.persons.count == clone.persons.count + assert rebuilt.tax_benefit_system is clone_copy.tax_benefit_system + + +def test_subsample_builds_a_read_only_copy_again_as_a_writable_one(): + _, microsimulation_class = _simulation_classes() + simulation = microsimulation_class(reform=REFORM) + old_copy = simulation.current_law_simulation() + assert old_copy.read_only + + simulation.subsample(n=3, seed="current-law", time_period="2022") + + new_copy = simulation.branches["baseline"] + assert new_copy is not old_copy + assert not new_copy.read_only + assert old_copy.read_only + values = simulation.persons.current_law("declared_monthly_tax", MONTH_PERIOD) + assert len(values) == simulation.persons.count + assert simulation.current_law_simulation() is new_copy + assert new_copy.read_only + + +def test_subsample_builds_the_copy_again_with_an_overridden_builder(): + _, microsimulation_class = _simulation_classes() + + class MarkingMicrosimulation(microsimulation_class): + def _build_current_law_simulation(self): + copy = super()._build_current_law_simulation() + copy.built_by_override = True + return copy + + simulation = MarkingMicrosimulation(reform=REFORM) + simulation.current_law_simulation() + + simulation.subsample(n=3, seed="current-law", time_period="2022") + + assert simulation.current_law_simulation().built_by_override is True + + +def test_a_copy_built_in_a_calculation_that_runs_again_reads_the_new_input(): + simulation = _declared_simulation() + + values = simulation.calculate("sets_salary_then_reads_current_law", MONTH_PERIOD) + + # The formula set the input before the copy was built. + _assert_income_tax(values, OTHER_MONTHLY_SALARY, BASELINE_RATE) + + +def test_a_saved_simulations_own_baseline_branch_is_copied_by_clone(): + """An earlier core kept ``baseline``, a branch, in the instance dictionary.""" + simulation = Simulation(situation=SITUATION, reform=REFORM) + branch = simulation.baseline + del simulation.__dict__["_current_law"] + simulation.__dict__["baseline"] = branch + + clone = simulation.clone() + + assert clone.baseline is not branch + assert clone.baseline.parent_branch is clone + assert clone.branches.get("baseline") is clone.baseline + assert simulation.baseline is branch + + +def test_assigning_baseline_on_a_read_only_simulation_raises(): + simulation = _declared_simulation() + simulation.make_read_only() + + with pytest.raises(errors.ReadOnlySimulationError): + simulation.baseline = None + + assert simulation.compares_with_current_law is True + + def _node_named(nodes, name): for node in nodes: if node.name == name: From d0b42e78b9366a89ff89e0927961f8a008d23fe8 Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Tue, 1 Dec 2026 23:40:35 +0400 Subject: [PATCH 08/11] Fix review round 2's findings on declared current-law reads - A read-only simulation registers the current-law copy it builds, so a clone of it keeps its copy registered and get_branch("baseline") and subsample see it. get_branch("baseline") now returns the record's copy only while it is not built. - clone() and get_branch() turn a baseline kept in the instance dictionary by an earlier core into a record before deciding, so a clone copies a saved simulation's own baseline branch rather than sharing it. - Assigning baseline on a read-only simulation raises ReadOnlySimulationError, as assigning tax_benefit_system does. - The builder and subsample set up the baseline branch with one helper, _make_current_law_branch, and subsample gives the simulation a new record in both of its paths. - Docstrings: the builder is also called by subsample; get_branch's "baseline" case applies to a reform simulation, not its branches; a current_law result from a read-only copy is non-writable. Co-Authored-By: Claude Opus 5.5 --- docs/python_api/simulations.md | 8 +- policyengine_core/populations/population.py | 5 +- policyengine_core/simulations/simulation.py | 137 ++++++++++---------- 3 files changed, 78 insertions(+), 72 deletions(-) diff --git a/docs/python_api/simulations.md b/docs/python_api/simulations.md index e138b3428..7691a9037 100644 --- a/docs/python_api/simulations.md +++ b/docs/python_api/simulations.md @@ -50,13 +50,15 @@ first time something needs it, by the overridable `default_tax_benefit_system_instance`, holding the inputs the simulation holds then and none of its calculated values. `compares_with_current_law` and `current_law_system` never build it. The first declared call that reaches it -makes it read-only (see above). Branches read their parent's copy; `clone()` -and `subsample()` keep a copy only if one was built. +makes it read-only (see above). A read-only simulation registers the copy it +builds in `branches`, unlike its other branches. Branches read their parent's +copy; `clone()` and `subsample()` keep a copy only if one was built. `simulation.baseline` is deprecated. It returns the copy (built if needed, and left writable) or `None`, and each read is reported to the tracer. Assigning a simulation to it makes that simulation the copy, kept as it is given; -assigning `None` stops the comparison. +assigning `None` stops the comparison. Assigning it on a read-only simulation +raises `ReadOnlySimulationError`. ## Microsimulation diff --git a/policyengine_core/populations/population.py b/policyengine_core/populations/population.py index 946808ec7..5d5ef4567 100644 --- a/policyengine_core/populations/population.py +++ b/policyengine_core/populations/population.py @@ -207,7 +207,10 @@ def current_law( >>> array([45.]) Called through a projection (``person.household.current_law(...)``), - the result is projected as a call's would be. + the result is projected as a call's would be. Once the copy is + read-only, the array returned from it is non-writable, as every array + a read-only simulation stores: a formula that writes into what it + read must copy it first. """ from policyengine_core.errors import UndeclaredCurrentLawReadError diff --git a/policyengine_core/simulations/simulation.py b/policyengine_core/simulations/simulation.py index 3a908eb6c..4c637cd5c 100644 --- a/policyengine_core/simulations/simulation.py +++ b/policyengine_core/simulations/simulation.py @@ -1121,8 +1121,10 @@ def make_read_only(self) -> None: branch registered before this call (a reform simulation's current-law copy built before it, or one a formula made in an earlier calculation), which ``get_branch`` still returns as it is. A - current-law copy built after this call is not registered, and - ``get_branch("baseline")`` returns it. A pickled or deep-copied + current-law copy built after this call is registered as + ``baseline``, unlike the other branches it makes (see + :meth:`current_law_simulation`). Assigning ``baseline`` raises + ``ReadOnlySimulationError``. A pickled or deep-copied read-only simulation stays read-only, but a value it keeps only in its fast cache (a variable its memory configuration does not store) comes back writable. @@ -1288,7 +1290,8 @@ def baseline(self) -> Optional["Simulation"]: code that sets inputs on the baseline keeps working; the first declared call makes it read-only. Assigning a simulation makes it the copy, kept as it is given, and the simulation then compares with - current law; assigning ``None`` stops the comparison. Each read is + current law; assigning ``None`` stops the comparison. Assigning it on + a read-only simulation raises ``ReadOnlySimulationError``. Each read is reported to the tracer as a ``baseline`` call. Formulas should use ``Population.current_law``, ``compares_with_current_law``, ``current_law_system`` and ``current_law_simulation``; the alias is @@ -1310,6 +1313,8 @@ def baseline(self) -> Optional["Simulation"]: @baseline.setter def baseline(self, simulation: Optional["Simulation"]) -> None: + # It would change the values a read-only simulation's formulas read. + refuse_on_read_only(self, "Assigning baseline") self.__dict__["_current_law"] = _CurrentLawSource( self, compares=simulation is not None, @@ -1317,12 +1322,47 @@ def baseline(self, simulation: Optional["Simulation"]) -> None: assigned=simulation is not None, ) + def _make_current_law_branch(self, system: "TaxBenefitSystem") -> "Simulation": + """A new branch named ``baseline`` that calculates under ``system``. + + Registered in ``branches`` under the name, also on a read-only + simulation, whose other branches are not (see :meth:`make_read_only`): + the current-law copy is part of the simulation. Traced in this + simulation, with holders bound to ``system``, its own list of input + variables, and no comparison with current law of its own. + """ + current_law = self._current_law_source() + # A new branch, not the copy the record may hold (see ``get_branch``). + building = current_law.building + current_law.building = True + try: + branch = self.get_branch("baseline") + finally: + current_law.building = building + if self.read_only: + self.branches["baseline"] = branch + branch.__dict__["_current_law"] = _CurrentLawSource(branch, compares=False) + branch.trace = self.trace + branch.tracer = self.tracer + branch.tax_benefit_system = system + # The branch was built under this simulation's (reform) system: its + # populations looked variables up there, and its holders kept the + # reform's variables, so a variable the reform neutralized read as + # the default in the branch too. + branch._bind_to_tax_benefit_system() + # The branch shares this simulation's list of input variables, and + # the binding keeps a list it drops nothing from. The branch runs + # under another system, so it keeps its own list. + branch.input_variables = list(branch.input_variables) + return branch + def _build_current_law_simulation(self) -> "Simulation": """Build the simulation that calculates this one's current-law values. - Called once, the first time a simulation that compares with current - law needs current-law values (see :meth:`current_law_simulation`), - which may be in the middle of a calculation. Country packages may + Called the first time a simulation that compares with current law + needs current-law values (see :meth:`current_law_simulation`), which + may be in the middle of a calculation, and by :meth:`subsample` to + build a copy it built again from the new sample. Country packages may override it to give the copy their own state; an override must not read current-law values or ``baseline`` itself. @@ -1337,20 +1377,7 @@ def _build_current_law_simulation(self) -> "Simulation": # A branch registered under the name, by code that ran before the copy # was needed, may hold the reform's values; the copy replaces it. self.branches.pop("baseline", None) - copy = self.get_branch("baseline") - copy.__dict__["_current_law"] = _CurrentLawSource(copy, compares=False) - copy.trace = self.trace - copy.tracer = self.tracer - copy.tax_benefit_system = self.default_tax_benefit_system_instance - # The branch was built under the reform's system: its populations - # looked variables up there, and its holders kept the reform's - # variables, so a variable the reform neutralized read as the - # default in the copy too. - copy._bind_to_tax_benefit_system() - # The branch shares this simulation's list of input variables, and - # the binding keeps a list it drops nothing from. The copy runs under - # another system, so it keeps its own list. - copy.input_variables = list(copy.input_variables) + copy = self._make_current_law_branch(self.default_tax_benefit_system_instance) # The branch started from everything this simulation holds, including # what it calculated under the reform. Keep only the inputs, and read # macro-cache files as this simulation does. @@ -3469,6 +3496,10 @@ def clone( through them. Without it, the copy shares this simulation's system, which still names this simulation. """ + # A simulation saved by an earlier core keeps ``baseline`` in its + # instance dictionary; turn it into this simulation's record first, so + # the copy below does not carry the bare attribute. + current_law = self._current_law_source() request = _branch_clone.get() share_arrays = ( request is not None and request.pending and request.simulation is self @@ -3587,8 +3618,7 @@ def clone( # one that shares its arrays (a subclass ``clone`` may clone it # directly first; see ``_BranchClone``). branching = request is not None and request.simulation is self - current_law = self.__dict__.get("_current_law") - if not branching and current_law is not None and current_law.owner is self: + if not branching and current_law.owner is self: # This simulation's own record. A shared copy filled this # simulation's caches with the clone's current-law calculations # and took inputs set through either, ``subsample`` of the clone @@ -3641,12 +3671,13 @@ def get_branch( branch is not read-only. A name registered before ``make_read_only`` gives that branch, as it is. - On a simulation that compares with current law, ``"baseline"`` gives - its current-law copy while that copy is not built yet (building it, - see :meth:`current_law_simulation`) and, on a read-only simulation, - while the copy is not registered. Once a built copy is registered, - the name gives it as any registered branch; code that removed it from - ``branches`` gets a new branch. + On a simulation built with a reform (not on its branches, which get a + new branch under the name), ``"baseline"`` gives its current-law copy + while that copy is not built yet, building it (see + :meth:`current_law_simulation`). A built copy is registered under the + name, on a read-only simulation too, so the name gives it as any + registered branch; code that removed it from ``branches`` gets a new + branch. Args: name (str, optional): Name of the branch. Defaults to "branch". @@ -3658,27 +3689,16 @@ def get_branch( if name == self.branch_name: return self if name == "baseline" and name not in self.branches: - current_law = self.__dict__.get("_current_law") + current_law = self._current_law_source() if ( - current_law is not None - and current_law.owner is self + current_law.owner is self and current_law.compares + and current_law.simulation is None and not current_law.building - and ( - current_law.simulation is None - or ( - self.read_only - and getattr(current_law.simulation, "parent_branch", None) - is self - ) - ) ): # Construction used to register the current-law copy under - # this name, and code reached it here. A read-only simulation - # does not register the copy it builds (see below), so it is - # returned from the record. On any other simulation, code - # that removed the registered copy gets a new branch, as - # before. + # this name, and code reached it here. Code that removed a + # registered copy gets a new branch, as before. return current_law.get(make_read_only=False) if name in self.branches: branch = self.branches[name] @@ -4359,14 +4379,14 @@ def retain_structure(name, values): ): # The current-law copy core built: build it again from the new # sample, with ``_build_current_law_simulation`` (which a country - # package may override). + # package may override), in a new record, as the other path makes. del self.branches["baseline"] - current_law.simulation = None + current_law = _CurrentLawSource(self, compares=True) + self.__dict__["_current_law"] = current_law current_law.get(make_read_only=False) elif replaced is not None: # A baseline branch assigned to ``baseline``, or registered under - # the name: rebuild it from the subsampled simulation through - # ``get_branch``, as the builder does, then restore its saved + # the name: rebuild it from the subsampled simulation, keeping its # tax-benefit system. Previously the saved system was assigned to # ``self.branches["tax_benefit_system"]`` (a stray dict key), so the # rebuilt baseline branch kept the reform system and @@ -4374,26 +4394,7 @@ def retain_structure(name, values): # reform against itself. baseline_tax_benefit_system = replaced.tax_benefit_system del self.branches["baseline"] - # A new branch, not the copy this replaces (see ``get_branch``). - building = current_law.building - current_law.building = True - try: - baseline = self.get_branch("baseline") - finally: - current_law.building = building - # As the builder does, the branch is traced in this simulation, - # uses the baseline system's entities and variables, and compares - # with no current law of its own: ``get_branch`` gave it this - # simulation's record, whose copy kept the old population alive. - baseline.trace = self.trace - baseline.tracer = self.tracer - baseline.tax_benefit_system = baseline_tax_benefit_system - baseline._bind_to_tax_benefit_system() - # As the builder does, the baseline keeps its own list. - baseline.input_variables = list(baseline.input_variables) - baseline.__dict__["_current_law"] = _CurrentLawSource( - baseline, compares=False - ) + baseline = self._make_current_law_branch(baseline_tax_benefit_system) if current_law.compares: self.__dict__["_current_law"] = _CurrentLawSource( self, From 1a90495fe45ec133b8328a39658353263b7bedda Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Wed, 2 Dec 2026 00:11:41 +0400 Subject: [PATCH 09/11] Add tests for review round 3's findings Tests that fail before the fixes: a clone announced as a branch outside get_branch (as policyengine-uk's subsample makes one, to share arrays) builds its own current-law copy from its own inputs and does not keep its source alive through the current-law record; assigning baseline on a simulation saved by an earlier core drops the saved attribute, so its clones do not carry it. Test for behaviour that already holds: a traced clone of a simulation whose copy is built traces the clone's copy in the clone. The clone test module's docstring now says when a test's clone builds a copy of its own. Co-Authored-By: Claude Opus 5.5 --- tests/core/test_clone_reform_baseline.py | 5 +- tests/core/test_current_law_reads.py | 70 ++++++++++++++++++++++++ 2 files changed, 73 insertions(+), 2 deletions(-) diff --git a/tests/core/test_clone_reform_baseline.py b/tests/core/test_clone_reform_baseline.py index 88d7eceab..c39cbc54c 100644 --- a/tests/core/test_clone_reform_baseline.py +++ b/tests/core/test_clone_reform_baseline.py @@ -2,8 +2,9 @@ A reform simulation has a baseline branch, ``baseline``, under the baseline policy (the current-law copy: ``Simulation.__init__`` built it, and -``_build_current_law_simulation`` now builds it when it is first needed, so -these tests read ``baseline`` to build it). ``Simulation.clone`` copies the +``_build_current_law_simulation`` now builds it when it is first needed; +reading ``baseline`` builds it, so a test that clones before reading it gives +the clone a copy of its own built from the clone's inputs). ``Simulation.clone`` copies the instance dictionary, so a clone shared that branch with its source: calculations on the clone's baseline filled the source's, an input set on either one's baseline reached the other, ``clone.get_branch("baseline")`` diff --git a/tests/core/test_current_law_reads.py b/tests/core/test_current_law_reads.py index 6c9c480b2..c7ae40a7d 100644 --- a/tests/core/test_current_law_reads.py +++ b/tests/core/test_current_law_reads.py @@ -18,6 +18,8 @@ import copy as copy_module import functools +import gc +import weakref import numpy as np import pytest @@ -844,6 +846,74 @@ def test_assigning_baseline_on_a_read_only_simulation_raises(): assert simulation.compares_with_current_law is True +def _clone_announced_as_a_branch(simulation): + """Clone as policyengine-uk's subsample does, sharing arrays like a branch.""" + from policyengine_core.simulations.simulation import _BranchClone, _branch_clone + + request = _BranchClone(simulation) + token = _branch_clone.set(request) + try: + return simulation.clone() + finally: + request.pending = False + _branch_clone.reset(token) + + +def test_a_clone_announced_as_a_branch_builds_its_own_copy(): + simulation = _declared_simulation() + clone = _clone_announced_as_a_branch(simulation) + + clone.set_input("salary", MONTH_PERIOD, OTHER_MONTHLY_SALARY) + + _assert_income_tax( + clone.persons.current_law("declared_monthly_tax", MONTH_PERIOD), + OTHER_MONTHLY_SALARY, + BASELINE_RATE, + ) + assert clone.current_law_simulation().parent_branch is clone + assert "baseline" not in simulation.branches + + +def test_a_clone_announced_as_a_branch_does_not_keep_its_source_alive(): + simulation = _declared_simulation(reform=None) + clone = _clone_announced_as_a_branch(simulation) + source = weakref.ref(simulation) + + del simulation + gc.collect() + + assert source() is None + assert clone.compares_with_current_law is False + + +def test_assigning_baseline_on_a_saved_simulation_drops_the_saved_attribute(): + simulation = Simulation(situation=SITUATION, reform=REFORM) + branch = simulation.baseline + del simulation.__dict__["_current_law"] + simulation.__dict__["baseline"] = branch + separate = Simulation(situation=SITUATION) + + simulation.baseline = separate + + assert "baseline" not in simulation.__dict__ + clone = simulation.clone() + assert "baseline" not in clone.__dict__ + assert clone.baseline is separate + + +def test_a_traced_clone_of_a_built_copy_traces_its_copy_in_the_clone(): + simulation = _declared_simulation(trace=True) + copy = simulation.current_law_simulation() + assert copy.tracer is simulation.tracer + + clone = simulation.clone(trace=True) + + clone_copy = clone.branches["baseline"] + assert clone_copy is not copy + assert clone_copy.tracer is clone.tracer + assert clone_copy.trace + + def _node_named(nodes, name): for node in nodes: if node.name == name: From a6bc9250905e5592e8951a82101c52c7d4724423 Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Wed, 2 Dec 2026 00:12:33 +0400 Subject: [PATCH 10/11] Check the announced clone's record instead of its source's lifetime The template's module-level system names the last simulation built from it, which keeps that simulation alive whatever the clone holds, so the test now checks that the clone's current-law record refers to the clone and not to its source. It fails before the fix. Co-Authored-By: Claude Opus 5.5 --- tests/core/test_current_law_reads.py | 18 ++++++++++-------- 1 file changed, 10 insertions(+), 8 deletions(-) diff --git a/tests/core/test_current_law_reads.py b/tests/core/test_current_law_reads.py index c7ae40a7d..55ef0e58f 100644 --- a/tests/core/test_current_law_reads.py +++ b/tests/core/test_current_law_reads.py @@ -18,8 +18,6 @@ import copy as copy_module import functools -import gc -import weakref import numpy as np import pytest @@ -874,15 +872,19 @@ def test_a_clone_announced_as_a_branch_builds_its_own_copy(): assert "baseline" not in simulation.branches -def test_a_clone_announced_as_a_branch_does_not_keep_its_source_alive(): +def test_a_clone_announced_as_a_branch_does_not_refer_to_its_source(): + """Its current-law record must not keep the source alive. + + (A weak reference cannot show this: the template's module-level system + names the last simulation built from it, which keeps it alive anyway.) + """ simulation = _declared_simulation(reform=None) - clone = _clone_announced_as_a_branch(simulation) - source = weakref.ref(simulation) - del simulation - gc.collect() + clone = _clone_announced_as_a_branch(simulation) - assert source() is None + record = clone._current_law_source() + assert record.owner is clone + assert record.simulation is None assert clone.compares_with_current_law is False From 13aad57219df1f24c4cfa157ec7fb00b61f15a62 Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Wed, 2 Dec 2026 00:12:33 +0400 Subject: [PATCH 11/11] Fix review round 3's findings on declared current-law reads - A clone announced as a branch outside get_branch (policyengine-uk's subsample announces one to share arrays) gets a current-law record of its own that does not refer to its source, so it no longer keeps the source alive, and builds its own copy from its own inputs. get_branch gives the branch its parent's record once the clone is made. - Assigning baseline drops a baseline kept in the instance dictionary by an earlier core, so clones and pickles no longer carry it. - Docstrings: current_law_system names the default system of the simulation the copy is built from; current_law_simulation states that the copy is registered, also on a read-only simulation; current_law states the exception for an assigned simulation; TraceNode.current_law_calls says the values read are children only when the calculating simulation shares the tracer. Co-Authored-By: Claude Opus 5.5 --- policyengine_core/populations/population.py | 3 +- policyengine_core/simulations/simulation.py | 60 ++++++++++++++++----- policyengine_core/tracers/trace_node.py | 4 +- 3 files changed, 53 insertions(+), 14 deletions(-) diff --git a/policyengine_core/populations/population.py b/policyengine_core/populations/population.py index 5d5ef4567..0bbecbb8b 100644 --- a/policyengine_core/populations/population.py +++ b/policyengine_core/populations/population.py @@ -191,7 +191,8 @@ def current_law( In a simulation that compares with current law (one built with a reform, or one of its branches), the value its current-law copy calculates (see ``Simulation.current_law_simulation``), which this - builds if there is none yet and makes read-only. Otherwise the + builds if there is none yet and makes read-only (unless it is a + simulation assigned to ``baseline``, which is kept as it was given). Otherwise the simulation is current law itself, and this is the same as calling the population. ``period`` and ``options`` are as for a call. diff --git a/policyengine_core/simulations/simulation.py b/policyengine_core/simulations/simulation.py index fd8f6bcdd..5af87fd8d 100644 --- a/policyengine_core/simulations/simulation.py +++ b/policyengine_core/simulations/simulation.py @@ -732,6 +732,30 @@ def get(self, make_read_only: bool) -> "Simulation": copy.make_read_only() return copy + def for_announced_branch( + self, source: "Simulation", clone: "Simulation" + ) -> "_CurrentLawSource": + """The record for a clone of ``source`` announced as a branch. + + ``get_branch`` replaces it with ``source``'s own record once the + clone is made, so its branches read ``source``'s copy. A caller that + announces a clone as a branch only to share arrays (as + policyengine-uk's subsample does) keeps this one: it does not refer to + ``source``, and a copy that is a branch of ``source`` is not kept, so + the clone builds its own from its own inputs when it needs one. A + simulation assigned to ``baseline`` that is not a branch of + ``source`` is shared, as ``clone`` shares it. + """ + copy = self.simulation + if copy is not None and getattr(copy, "parent_branch", None) is source: + copy = None + return _CurrentLawSource( + clone, + self.compares, + simulation=copy, + assigned=self.assigned and copy is not None, + ) + def for_clone( self, source: "Simulation", @@ -1255,10 +1279,10 @@ def current_law_system(self) -> "TaxBenefitSystem": """The tax-benefit system of current law, without building a copy. For a simulation that compares with current law, the system its - current-law copy calculates with (the class's - ``default_tax_benefit_system_instance`` unless a simulation was - assigned to ``baseline``); otherwise this simulation's own system. A - declared call, reported to the simulation's tracer. + current-law copy calculates with: the copy's, once built or assigned, + and before that the ``default_tax_benefit_system_instance`` of the + simulation it will be built from. Otherwise this simulation's own + system. A declared call, reported to the simulation's tracer. """ self._report_current_law_call("current_law_system") return self._current_law_system() @@ -1276,9 +1300,11 @@ def current_law_simulation(self) -> "Simulation": For a simulation that compares with current law, the current-law copy, built on the first call (by :meth:`_build_current_law_simulation`) - from the inputs the simulation holds then. A branch gets its parent's. - A copy core built is made read-only (see :meth:`make_read_only`); a - simulation assigned to ``baseline`` is returned as it was given. + from the inputs the simulation holds then, and registered in + ``branches`` as ``baseline``, on a read-only simulation too (unlike + its other branches). A branch gets its parent's. A copy core built is + made read-only (see :meth:`make_read_only`); a simulation assigned to + ``baseline`` is returned as it was given. Without a comparison, this simulation itself. A declared call, reported to the simulation's tracer. """ @@ -1323,6 +1349,9 @@ def baseline(self) -> Optional["Simulation"]: def baseline(self, simulation: Optional["Simulation"]) -> None: # It would change the values a read-only simulation's formulas read. refuse_on_read_only(self, "Assigning baseline") + # A simulation saved by an earlier core keeps ``baseline`` in its + # instance dictionary, which clones and pickles would still carry. + self.__dict__.pop("baseline", None) self.__dict__["_current_law"] = _CurrentLawSource( self, compares=simulation is not None, @@ -3624,12 +3653,17 @@ def clone( # A branch shares its parent's record of where its current-law # values come from: formulas that run in a branch read the parent's - # current-law copy. That holds for every clone of this simulation - # made while ``get_branch`` is making a branch of it, not only the - # one that shares its arrays (a subclass ``clone`` may clone it - # directly first; see ``_BranchClone``). + # current-law copy. ``get_branch`` gives the branch that record once + # the clone is made. Until then, every clone of this simulation made + # while it is announced as a branch's (not only the one that shares + # its arrays; a subclass ``clone`` may clone it directly first, and a + # country package may announce a clone only to share arrays; see + # ``_BranchClone``) gets a record of its own that does not refer to + # this simulation. branching = request is not None and request.simulation is self - if not branching and current_law.owner is self: + if branching: + new.__dict__["_current_law"] = current_law.for_announced_branch(self, new) + elif current_law.owner is self: # This simulation's own record. A shared copy filled this # simulation's caches with the clone's current-law calculations # and took inputs set through either, ``subsample`` of the clone @@ -3726,6 +3760,8 @@ def get_branch( finally: request.pending = False _branch_clone.reset(token) + # The branch reads this simulation's current-law copy (see ``clone``). + branch.__dict__["_current_law"] = self._current_law_source() if not self.read_only: self.branches[name] = branch branch.branch_name = name diff --git a/policyengine_core/tracers/trace_node.py b/policyengine_core/tracers/trace_node.py index 8e991d0d3..2b59e2f94 100644 --- a/policyengine_core/tracers/trace_node.py +++ b/policyengine_core/tracers/trace_node.py @@ -46,7 +46,9 @@ class TraceNode: # defaulted, including one masked by ``defined_for``. formula_ran: bool = False # The declared current-law calls the formula made (``CurrentLawCall``), - # in order. The values those calls read are children, as other reads are. + # in order. The values those calls read are children, as other reads are, + # when the simulation that calculates them shares this tracer (core's + # current-law copy does; a simulation assigned to ``baseline`` may not). current_law_calls: typing.List[CurrentLawCall] = dataclasses.field( default_factory=list )