From 035d8b07ac62911cca3afced61a26feb65de04bc Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Sat, 28 Nov 2026 00:52:06 +0400 Subject: [PATCH 01/15] Add failing tests for read-only simulations A simulation made read-only with make_read_only() should refuse input, array, parameter and system changes, store only non-writable arrays, and make private branches that are never kept in its branches. Co-Authored-By: Claude Opus 5.5 --- tests/core/test_read_only_simulation.py | 578 ++++++++++++++++++++++++ 1 file changed, 578 insertions(+) create mode 100644 tests/core/test_read_only_simulation.py diff --git a/tests/core/test_read_only_simulation.py b/tests/core/test_read_only_simulation.py new file mode 100644 index 00000000..91aeecae --- /dev/null +++ b/tests/core/test_read_only_simulation.py @@ -0,0 +1,578 @@ +"""A simulation made read-only with ``make_read_only()``. + +A read-only simulation still calculates values it does not hold yet, and +keeps them. It refuses everything that would change its inputs, its stored +values or its tax-benefit system: + +- ``set_input`` (on the simulation or a holder), ``delete_arrays`` (on the + simulation or a holder), ``drop_computed_arrays``, ``apply_reform``, + ``subsample``, ``build_from_dataset``, ``build_from_populations`` and + assigning ``tax_benefit_system`` raise ``ReadOnlySimulationError`` and + change nothing; +- every array it stores is non-writable, in memory or on disk, so writing + into one in place raises numpy's ``ValueError``; +- a parameter change after ``make_read_only()`` (an update anywhere in its + parameter tree, or a new tree) makes its next calculation raise. + +A branch it makes with ``get_branch`` is part of it, but private: the branch +is not kept in its ``branches``, so nothing done through the branch stays in +the read-only simulation. The branch is not read-only itself. +""" + +from __future__ import annotations + +import warnings + +import numpy as np +import pytest + +from policyengine_core import errors, periods +from policyengine_core.country_template import ( + CountryTaxBenefitSystem, + Simulation, +) +from policyengine_core.country_template.entities import Person +from policyengine_core.country_template.reforms.removal_basic_income import ( + removal_basic_income, +) +from policyengine_core.experimental import MemoryConfig +from policyengine_core.variables import Variable + +PERIOD = "2022-01" +INSTANT = periods.instant("2022-01-01") +BASELINE_INCOME_TAX_RATE = 0.15 +REFORM_INCOME_TAX_RATE = 0.42 +SALARY = [4000.0, 2500.0] +OTHER_SALARY = [1000.0, 3000.0] +SITUATION = { + "persons": { + "a": {"salary": {PERIOD: SALARY[0]}, "age": {PERIOD: 40}}, + "b": {"salary": {PERIOD: SALARY[1]}, "age": {PERIOD: 30}}, + }, + "households": {"h": {"parents": ["a", "b"]}}, +} +OUTPUTS = ["income_tax", "disposable_income", "total_taxes", "household_income"] + + +@pytest.fixture(scope="module") +def shared_system(): + """A system the tests in this module read but never change.""" + return CountryTaxBenefitSystem() + + +def build_simulation(tax_benefit_system) -> Simulation: + return Simulation(tax_benefit_system=tax_benefit_system, situation=SITUATION) + + +def stored_values(simulation) -> dict: + """Copies of every array the simulation's holders store, memory and disk.""" + values = {} + for population in simulation.populations.values(): + for variable_name, holder in population._holders.items(): + for branch_name, period in holder.get_known_branch_periods(): + array = holder._get_array_from_storage(period, branch_name) + values[(variable_name, branch_name, str(period))] = np.array( + array, copy=True + ) + return values + + +def stored_arrays(simulation) -> dict: + """The array objects the simulation's in-memory storages hold.""" + return { + (variable_name, key): array + for population in simulation.populations.values() + for variable_name, holder in population._holders.items() + for key, array in holder._memory_storage._arrays.items() + } + + +def assert_same_values(before: dict, after: dict) -> None: + assert before.keys() == after.keys() + for key, array in after.items(): + assert np.array_equal(array, before[key]), key + + +# ----- The flag ----- # + + +def test_a_simulation_is_read_only_only_once_made_read_only(shared_system): + simulation = build_simulation(shared_system) + assert simulation.read_only is False + + simulation.make_read_only() + + assert simulation.read_only is True + + +def test_a_clone_of_a_read_only_simulation_is_not_read_only(shared_system): + simulation = build_simulation(shared_system) + simulation.make_read_only() + + clone = simulation.clone() + clone.set_input("salary", PERIOD, OTHER_SALARY) + + assert clone.read_only is False + assert clone.calculate("salary", PERIOD).tolist() == OTHER_SALARY + assert clone.calculate("salary", PERIOD).flags.writeable + assert simulation.calculate("salary", PERIOD).tolist() == SALARY + + +# ----- Refused operations ----- # + +REFUSED_OPERATIONS = [ + pytest.param( + lambda simulation: simulation.set_input("salary", PERIOD, OTHER_SALARY), + id="set_input", + ), + pytest.param( + lambda simulation: simulation.get_holder("salary").set_input( + periods.period(PERIOD), OTHER_SALARY + ), + id="holder-set_input", + ), + pytest.param( + lambda simulation: simulation.delete_arrays("salary", PERIOD), + id="delete_arrays-one-period", + ), + pytest.param( + lambda simulation: simulation.delete_arrays("income_tax"), + id="delete_arrays-every-period", + ), + pytest.param( + lambda simulation: simulation.get_holder("income_tax").delete_arrays(), + id="holder-delete_arrays", + ), + pytest.param( + lambda simulation: simulation.drop_computed_arrays(), + id="drop_computed_arrays", + ), + pytest.param( + lambda simulation: simulation.apply_reform(removal_basic_income), + id="apply_reform", + ), + pytest.param( + lambda simulation: simulation.subsample(n=1), + id="subsample", + ), + pytest.param( + lambda simulation: simulation.build_from_dataset(), + id="build_from_dataset", + ), + pytest.param( + lambda simulation: simulation.build_from_populations( + simulation.tax_benefit_system.instantiate_entities() + ), + id="build_from_populations", + ), + pytest.param( + lambda simulation: setattr( + simulation, + "tax_benefit_system", + simulation.tax_benefit_system.clone(), + ), + id="assign-tax_benefit_system", + ), +] + + +@pytest.mark.parametrize("refused_operation", REFUSED_OPERATIONS) +def test_a_read_only_simulation_refuses_the_operation_and_changes_nothing( + refused_operation, +): + simulation = build_simulation(CountryTaxBenefitSystem()) + for output in OUTPUTS: + simulation.calculate(output, PERIOD) + simulation.make_read_only() + values_before = stored_values(simulation) + system_before = simulation.tax_benefit_system + parameters_before = system_before.parameters + populations_before = dict(simulation.populations) + variables_before = dict(system_before.variables) + branches_before = dict(simulation.branches) + start_instant_before = simulation.start_instant + + with pytest.raises(errors.ReadOnlySimulationError): + refused_operation(simulation) + + assert_same_values(values_before, stored_values(simulation)) + assert simulation.tax_benefit_system is system_before + assert simulation.tax_benefit_system.parameters is parameters_before + assert simulation.tax_benefit_system.variables == variables_before + assert simulation.populations == populations_before + assert simulation.branches == branches_before + assert simulation.start_instant == start_instant_before + # It still calculates, and gives what it gave before. + for output in OUTPUTS: + assert np.array_equal( + simulation.calculate(output, PERIOD), + values_before[(output, "default", PERIOD)], + ) + + +# ----- Non-writable arrays ----- # + + +def test_inputs_stored_before_make_read_only_become_non_writable(shared_system): + simulation = build_simulation(shared_system) + salary = simulation.get_array("salary", PERIOD) + + simulation.make_read_only() + + assert not salary.flags.writeable + with pytest.raises(ValueError, match="read-only"): + salary[0] = 0.0 + assert simulation.calculate("salary", PERIOD).tolist() == SALARY + + +def test_values_calculated_before_make_read_only_become_non_writable(shared_system): + simulation = build_simulation(shared_system) + income_tax = simulation.calculate("income_tax", PERIOD) + expected = np.array(income_tax, copy=True) + + simulation.make_read_only() + + assert not simulation.get_array("income_tax", PERIOD).flags.writeable + # A repeated calculation is answered from the simulation's fast cache. + repeated = simulation.calculate("income_tax", PERIOD) + assert not repeated.flags.writeable + with pytest.raises(ValueError, match="read-only"): + repeated += 1 + assert np.array_equal(simulation.calculate("income_tax", PERIOD), expected) + + +def test_every_array_a_read_only_simulation_stores_is_non_writable(shared_system): + simulation = build_simulation(shared_system) + simulation.make_read_only() + + disposable_income = simulation.calculate("disposable_income", PERIOD) + simulation.calculate("household_income", PERIOD) + + assert not disposable_income.flags.writeable + arrays = stored_arrays(simulation) + assert ("disposable_income", f"default:{PERIOD}") in arrays + for key, array in arrays.items(): + assert not array.flags.writeable, key + + +class salary_doubled_in_place(Variable): + value_type = float + entity = Person + definition_period = periods.MONTH + label = "Salary doubled by writing into the salary array it read" + + def formula(person, period, parameters): + salary = person("salary", period) + salary *= 2 + return salary + + +def test_a_formula_writing_into_an_array_it_read_raises(): + system = CountryTaxBenefitSystem() + system.add_variable(salary_doubled_in_place) + simulation = build_simulation(system) + simulation.make_read_only() + + with pytest.raises(ValueError, match="read-only"): + simulation.calculate("salary_doubled_in_place", PERIOD) + + assert simulation.calculate("salary", PERIOD).tolist() == SALARY + + +def _simulation_storing_on_disk(tax_benefit_system) -> Simulation: + simulation = build_simulation(tax_benefit_system) + with warnings.catch_warnings(): + warnings.simplefilter("ignore") + # Every holder made from here on stores its values on disk. + simulation.memory_config = MemoryConfig(max_memory_occupation=0) + return simulation + + +def test_values_stored_on_disk_before_make_read_only_read_back_non_writable( + shared_system, +): + simulation = _simulation_storing_on_disk(shared_system) + simulation.calculate("income_tax", PERIOD) + assert simulation.get_holder("income_tax")._disk_storage.has(periods.period(PERIOD)) + + simulation.make_read_only() + + stored = simulation.get_array("income_tax", PERIOD) + assert not stored.flags.writeable + with pytest.raises(ValueError, match="read-only"): + stored[0] = 0.0 + + +def test_values_a_read_only_simulation_stores_on_disk_are_non_writable( + shared_system, +): + simulation = _simulation_storing_on_disk(shared_system) + simulation.make_read_only() + + income_tax = simulation.calculate("income_tax", PERIOD) + + assert simulation.get_holder("income_tax")._disk_storage.has(periods.period(PERIOD)) + assert not income_tax.flags.writeable + assert not simulation.get_array("income_tax", PERIOD).flags.writeable + + +def test_the_first_read_of_an_array_shared_with_another_simulation_is_non_writable( + shared_system, +): + simulation = build_simulation(shared_system) + simulation.calculate("income_tax", PERIOD) + # A branch starts by sharing its parent's arrays, and copies each one the + # first time it reads it. + branch = simulation.get_branch("made_read_only_later") + branch.make_read_only() + + income_tax = branch.get_array("income_tax", PERIOD) + + assert not income_tax.flags.writeable + assert not branch.calculate("salary", PERIOD).flags.writeable + + +# ----- Parameter changes ----- # + + +def _update_income_tax_rate(system): + system.parameters.taxes.income_tax_rate.update(start=INSTANT, value=0.5) + + +def _update_a_scale_bracket_rate(system): + system.parameters.taxes.social_security_contribution.brackets[0].rate.update( + start=INSTANT, value=0.5 + ) + + +def _mark_a_node_modified(system): + system.parameters.benefits.mark_as_modified() + + +def _mark_a_scale_modified(system): + system.parameters.taxes.social_security_contribution.mark_as_modified() + + +def _modify_parameters_with_a_dictionary(system): + system.modify_parameters({"taxes.income_tax_rate": {"2022-01-01": 0.5}}) + + +def _edit_values_in_place_through_modify_parameters(system): + def replace_income_tax_rate_values(parameters): + income_tax_rate = parameters.taxes.income_tax_rate + income_tax_rate.values_list = income_tax_rate.values_list[-1:] + return parameters + + system.modify_parameters(replace_income_tax_rate_values) + + +def _replace_the_parameter_tree(system): + system.parameters = system.parameters.clone() + + +PARAMETER_CHANGES = [ + pytest.param(_update_income_tax_rate, id="parameter-update"), + pytest.param(_update_a_scale_bracket_rate, id="scale-bracket-update"), + pytest.param(_mark_a_node_modified, id="node-marked-modified"), + pytest.param(_mark_a_scale_modified, id="scale-marked-modified"), + pytest.param(_modify_parameters_with_a_dictionary, id="modify_parameters-dict"), + pytest.param( + _edit_values_in_place_through_modify_parameters, + id="modify_parameters-in-place-edit", + ), + pytest.param(_replace_the_parameter_tree, id="new-parameter-tree"), +] + + +@pytest.mark.parametrize("change_parameters", PARAMETER_CHANGES) +def test_a_parameter_change_after_make_read_only_makes_the_next_calculation_raise( + change_parameters, +): + system = CountryTaxBenefitSystem() + simulation = build_simulation(system) + simulation.calculate("income_tax", PERIOD) + simulation.make_read_only() + + change_parameters(system) + + # A value it holds (answered from the fast cache) and a new one. + with pytest.raises(errors.ReadOnlySimulationError): + simulation.calculate("income_tax", PERIOD) + with pytest.raises(errors.ReadOnlySimulationError): + simulation.calculate("disposable_income", PERIOD) + + +@pytest.mark.parametrize("change_parameters", PARAMETER_CHANGES) +def test_a_parameter_change_before_make_read_only_is_accepted(change_parameters): + system = CountryTaxBenefitSystem() + simulation = build_simulation(system) + change_parameters(system) + + simulation.make_read_only() + + simulation.calculate("disposable_income", PERIOD) + + +def test_a_parameter_change_on_a_branch_with_its_own_system_is_accepted( + shared_system, +): + simulation = build_simulation(shared_system) + simulation.make_read_only() + branch = simulation.get_branch("own_system", clone_system=True) + + _update_income_tax_rate(branch.tax_benefit_system) + + income_tax = simulation.calculate("income_tax", PERIOD) + assert np.allclose(income_tax, np.array(SALARY) * BASELINE_INCOME_TAX_RATE) + + +def test_making_a_simulation_read_only_again_keeps_the_first_parameter_record(): + system = CountryTaxBenefitSystem() + simulation = build_simulation(system) + simulation.make_read_only() + _update_income_tax_rate(system) + + simulation.make_read_only() + + with pytest.raises(errors.ReadOnlySimulationError): + simulation.calculate("income_tax", PERIOD) + + +# ----- Branches ----- # + + +def test_a_branch_of_a_read_only_simulation_is_not_kept_in_its_branches( + shared_system, +): + simulation = build_simulation(shared_system) + simulation.make_read_only() + + branch = simulation.get_branch("what_if") + + assert "what_if" not in simulation.branches + assert simulation.get_branch("what_if") is not branch + assert branch.read_only is False + assert branch.parent_branch is simulation + + +def test_a_branch_of_a_read_only_simulation_takes_inputs_and_calculates_from_them( + shared_system, +): + simulation = build_simulation(shared_system) + simulation.calculate("income_tax", PERIOD) + simulation.make_read_only() + values_before = stored_values(simulation) + + branch = simulation.get_branch("what_if") + branch.set_input("salary", PERIOD, OTHER_SALARY) + branch_income_tax = branch.calculate("income_tax", PERIOD) + branch_disposable_income = branch.calculate("disposable_income", PERIOD) + + assert np.allclose( + branch_income_tax, np.array(OTHER_SALARY) * BASELINE_INCOME_TAX_RATE + ) + assert branch_disposable_income.flags.writeable + assert_same_values(values_before, stored_values(simulation)) + assert np.allclose( + simulation.calculate("income_tax", PERIOD), + np.array(SALARY) * BASELINE_INCOME_TAX_RATE, + ) + + +def test_a_branch_of_a_read_only_simulation_reads_its_values(shared_system): + simulation = build_simulation(shared_system) + simulation.make_read_only() + + branch = simulation.get_branch("what_if") + + assert branch.calculate("salary", PERIOD).tolist() == SALARY + assert np.array_equal( + branch.calculate("disposable_income", PERIOD), + simulation.calculate("disposable_income", PERIOD), + ) + + +def test_a_branch_of_a_read_only_simulation_keeps_branches_of_its_own( + shared_system, +): + simulation = build_simulation(shared_system) + simulation.make_read_only() + branch = simulation.get_branch("what_if") + + nested = branch.get_branch("nested") + + assert branch.branches["nested"] is nested + + +def test_a_branch_registered_before_make_read_only_is_returned_as_it_is( + shared_system, +): + simulation = build_simulation(shared_system) + earlier_branch = simulation.get_branch("earlier") + + simulation.make_read_only() + + assert simulation.get_branch("earlier") is earlier_branch + assert simulation.branches == {"earlier": earlier_branch} + + +def test_a_read_only_reform_simulation_still_calculates_against_its_baseline(): + reform = {"taxes.income_tax_rate": {"2022-01-01": REFORM_INCOME_TAX_RATE}} + simulation = Simulation(situation=SITUATION, reform=reform) + simulation.make_read_only() + + reform_income_tax = simulation.calculate("income_tax", PERIOD) + baseline_income_tax = simulation.baseline.calculate("income_tax", PERIOD) + + assert np.allclose(reform_income_tax, np.array(SALARY) * REFORM_INCOME_TAX_RATE) + assert np.allclose(baseline_income_tax, np.array(SALARY) * BASELINE_INCOME_TAX_RATE) + assert simulation.get_branch("baseline") is simulation.baseline + + +# ----- What a read-only simulation still does ----- # + + +def test_a_read_only_simulation_calculates_new_values_and_keeps_them(shared_system): + plain_simulation = build_simulation(shared_system) + simulation = build_simulation(shared_system) + simulation.make_read_only() + + for output in OUTPUTS: + result = simulation.calculate(output, PERIOD) + assert np.array_equal(result, plain_simulation.calculate(output, PERIOD)) + assert np.array_equal(simulation.get_array(output, PERIOD), result) + + +class spiral_this_month(Variable): + value_type = int + entity = Person + definition_period = periods.MONTH + label = "Reads spiral_last_month for the previous month" + + def formula(person, period): + return person("spiral_last_month", period.last_month) + 1 + + +class spiral_last_month(Variable): + value_type = int + entity = Person + definition_period = periods.MONTH + label = "Reads spiral_this_month for the same month" + + def formula(person, period): + return person("spiral_this_month", period) + 1 + + +def test_a_read_only_simulation_still_drops_the_values_a_spiral_invalidates(): + system = CountryTaxBenefitSystem() + system.add_variables(spiral_this_month, spiral_last_month) + plain_simulation = build_simulation(system) + simulation = build_simulation(system) + simulation.make_read_only() + + result = simulation.calculate("spiral_this_month", PERIOD) + + assert np.array_equal( + result, plain_simulation.calculate("spiral_this_month", PERIOD) + ) + assert stored_values(simulation).keys() == stored_values(plain_simulation).keys() From e5973b2bf2805b473dc83f26029f5128c0792edb Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Sat, 28 Nov 2026 00:55:59 +0400 Subject: [PATCH 02/15] Add read-only simulations Simulation.make_read_only() makes a simulation refuse changes to its inputs, stored values and tax-benefit system with ReadOnlySimulationError, while it still calculates and keeps values it does not hold yet: - set_input and delete_arrays (on the simulation or a holder), drop_computed_arrays, apply_reform, subsample, build_from_dataset, build_from_populations and assigning tax_benefit_system are refused; - in-memory and on-disk storages mark every array they hold, store or read back non-writable, so an in-place write into one raises; - each parameter tree counts the changes mark_as_modified records (and modify_parameters), and the read-only simulation's next calculation raises once its tree's count has moved or its system has another tree; - get_branch with a new name returns a branch that is not kept in the read-only simulation's branches and is not read-only itself. Co-Authored-By: Claude Opus 5.5 --- changelog.d/read-only-simulations.added.md | 1 + docs/python_api/errors.md | 13 ++ docs/python_api/simulations.md | 14 ++ .../data_storage/in_memory_storage.py | 27 +++ .../data_storage/non_writable.py | 13 ++ .../data_storage/on_disk_storage.py | 26 ++- policyengine_core/errors/__init__.py | 1 + .../errors/read_only_simulation_error.py | 23 +++ policyengine_core/holders/holder.py | 29 ++++ .../parameters/parameter_node.py | 10 ++ policyengine_core/simulations/simulation.py | 163 +++++++++++++++++- .../taxbenefitsystems/tax_benefit_system.py | 11 +- 12 files changed, 325 insertions(+), 6 deletions(-) create mode 100644 changelog.d/read-only-simulations.added.md create mode 100644 policyengine_core/data_storage/non_writable.py create mode 100644 policyengine_core/errors/read_only_simulation_error.py diff --git a/changelog.d/read-only-simulations.added.md b/changelog.d/read-only-simulations.added.md new file mode 100644 index 00000000..666e1007 --- /dev/null +++ b/changelog.d/read-only-simulations.added.md @@ -0,0 +1 @@ +Added `Simulation.make_read_only()`: a read-only simulation still calculates and keeps new values, but refuses input, array, parameter and system changes with `ReadOnlySimulationError`, stores only non-writable arrays, and makes private branches that are never kept in its `branches`. diff --git a/docs/python_api/errors.md b/docs/python_api/errors.md index a0bdcfe7..34c73c59 100644 --- a/docs/python_api/errors.md +++ b/docs/python_api/errors.md @@ -38,6 +38,19 @@ :show-inheritance: ``` +## ReadOnlySimulationError + +Raised when an operation would change a simulation made read-only with +`Simulation.make_read_only()`, and by its next calculation once its parameters +have changed. + +```{eval-rst} +.. autoclass:: policyengine_core.errors.read_only_simulation_error.ReadOnlySimulationError + :members: + :undoc-members: + :show-inheritance: +``` + ## SituationParsingError ```{eval-rst} diff --git a/docs/python_api/simulations.md b/docs/python_api/simulations.md index 176c4be8..ade143bd 100644 --- a/docs/python_api/simulations.md +++ b/docs/python_api/simulations.md @@ -12,6 +12,20 @@ The `policyengine_core.simulations` module contains the definition of `Simulatio :show-inheritance: ``` +### Read-only simulations + +`Simulation.make_read_only()` makes a simulation refuse every change to its +inputs, stored values and tax-benefit system, while it still calculates and +keeps values it does not hold yet. `set_input`, `delete_arrays`, +`drop_computed_arrays`, `apply_reform`, `subsample`, `build_from_dataset`, +`build_from_populations` and assigning `tax_benefit_system` raise +`ReadOnlySimulationError`. Every array it stores is non-writable, so a formula +that writes in place into an array it read raises numpy's `ValueError`. A +parameter change after `make_read_only()` makes its next calculation raise +`ReadOnlySimulationError`. `get_branch` with a new name returns a branch that is +not kept in `branches` and is not read-only itself. The method's docstring +lists what is not detected. + ## Microsimulation ```{eval-rst} diff --git a/policyengine_core/data_storage/in_memory_storage.py b/policyengine_core/data_storage/in_memory_storage.py index bc60c8fe..485fc881 100644 --- a/policyengine_core/data_storage/in_memory_storage.py +++ b/policyengine_core/data_storage/in_memory_storage.py @@ -4,6 +4,7 @@ from numpy.typing import ArrayLike from policyengine_core import periods +from policyengine_core.data_storage.non_writable import make_non_writable from policyengine_core.data_storage.storage_keys import check_storable from policyengine_core.data_storage.store_history import ( _period_from_storage_key, @@ -85,6 +86,10 @@ class InMemoryStorage: # every holder, so copying at each clone would cost a set per input # holder per branch for inputs most branches never change. _inputs: Union[Set[str], FrozenSet[str]] = _NO_INPUTS + # Whether every array this storage holds is non-writable: set by + # ``make_read_only`` for a read-only simulation's holders (see + # ``Simulation.make_read_only``). A clone is not read-only. + read_only: bool = False is_eternal: bool def __init__(self, is_eternal: bool): @@ -117,6 +122,16 @@ def __setstate__(self, state: dict) -> None: # those of stores made after unpickling it. if self._sequence_numbers: advance_sequence_past(max(self._sequence_numbers.values())) + # Unpickled arrays are writable again. + if self.read_only: + self.make_read_only() + + def make_read_only(self) -> None: + """Mark every array this storage holds non-writable, and every array + it stores or copies from here on (see ``put`` and ``get``).""" + self.read_only = True + for array in self._arrays.values(): + make_non_writable(array) def clone(self, share_arrays: bool = False) -> "InMemoryStorage": """Copy this storage. @@ -130,6 +145,10 @@ def clone(self, share_arrays: bool = False) -> "InMemoryStorage": it in place does not change this storage. (Masked arrays are copied straight away: a view would share their mask.) + The clone is not read-only, even when this storage is (see + ``make_read_only``): what it copies is writable, and what it shares + is copied on first read, as usual. + The clone has its own index in both cases: ``put`` and ``delete`` on either storage replace or drop index entries without touching the arrays, so neither storage sees what the other stores, replaces or @@ -183,6 +202,8 @@ def get(self, period: Period, branch_name: str = "default") -> ArrayLike: # First read of an array shared by ``clone``: from here on the # caller may write into it, so it needs to be this storage's own. values = values.copy() + if self.read_only: + make_non_writable(values) self._arrays[key] = values self._stop_sharing(key) return values @@ -284,6 +305,10 @@ def put( ``derived`` marks a value the simulation calculated rather than took as input (see ``_inputs``), and ``sequence_number`` records when the value was stored (a new number by default); see :meth:`drop_computed`. + + In a read-only storage (see ``make_read_only``) ``value`` itself is + marked non-writable, so a caller still holding it cannot write into + the stored value either. """ if self.is_eternal: period = periods.period(periods.ETERNITY) @@ -293,6 +318,8 @@ def put( # would be ambiguous to parse back, as ``OnDiskStorage.put`` does. check_storable(branch_name, period) key = f"{branch_name}:{period}" + if self.read_only: + make_non_writable(value) self._arrays[key] = value self._stop_sharing(key) if derived: diff --git a/policyengine_core/data_storage/non_writable.py b/policyengine_core/data_storage/non_writable.py new file mode 100644 index 00000000..d96aed5b --- /dev/null +++ b/policyengine_core/data_storage/non_writable.py @@ -0,0 +1,13 @@ +import numpy + + +def make_non_writable(value) -> None: + """Mark ``value``'s data non-writable, if it is a numpy array. + + The flag is set on the array object itself, so it holds for every holder + of that object: a later in-place write through it raises ``ValueError``. + A masked array's mask is a separate array and stays writable. Values that + are not numpy arrays are left as they are. + """ + if isinstance(value, numpy.ndarray): + value.flags.writeable = False diff --git a/policyengine_core/data_storage/on_disk_storage.py b/policyengine_core/data_storage/on_disk_storage.py index 13c899f9..e7705dee 100644 --- a/policyengine_core/data_storage/on_disk_storage.py +++ b/policyengine_core/data_storage/on_disk_storage.py @@ -9,6 +9,7 @@ from numpy.typing import ArrayLike from policyengine_core import periods +from policyengine_core.data_storage.non_writable import make_non_writable from policyengine_core.data_storage.store_history import ( _period_from_storage_key, advance_sequence_past, @@ -112,6 +113,10 @@ class OnDiskStorage: # Whether this storage writes only new files (see ``_path_to_write``). _detached = False _own_epoch = None + # Whether ``get`` returns, and ``put`` leaves, only non-writable arrays: + # set by ``make_read_only`` for a read-only simulation's holders (see + # ``Simulation.make_read_only``). A clone is not read-only. + read_only = False def __init__( self, @@ -290,6 +295,17 @@ def clone(self) -> "OnDiskStorage": self._own_paths = {} return clone + def make_read_only(self) -> None: + """Make ``get`` return non-writable arrays from here on, and ``put`` + mark the arrays it stores non-writable. + + Each ``get`` reads its file into a new array, so writing into one in + place never changed the stored value; the flag makes that write raise + all the same, as it does for a read-only ``InMemoryStorage``. The + files themselves are left as they are. + """ + self.read_only = True + def _decode_file(self, file: str) -> ArrayLike: enum = self._enums.get(file) if enum is not None: @@ -305,7 +321,10 @@ def get(self, period: Period, branch_name: str = "default") -> ArrayLike: values = self._files.get(f"{branch_name}_{period}") if values is None: return None - return self._decode_file(values) + array = self._decode_file(values) + if self.read_only: + make_non_writable(array) + return array def has(self, period: Period, branch_name: str = "default") -> bool: """Whether a value is stored for ``period`` under ``branch_name``. @@ -335,7 +354,8 @@ def put( """Store ``value`` for ``period`` on ``branch_name``. ``derived`` and ``sequence_number`` are as in - :meth:`InMemoryStorage.put`. + :meth:`InMemoryStorage.put`. In a read-only storage ``value`` is + marked non-writable, as there. """ if self.is_eternal: period = periods.period(periods.ETERNITY) @@ -345,6 +365,8 @@ def put( # ``InMemoryStorage.put`` rejects. A month anchored mid-month, say, # would be stored under the key of the calendar month. check_storable(branch_name, period) + if self.read_only: + make_non_writable(value) filename = f"{branch_name}_{period}" path = self._path_to_write(filename) diff --git a/policyengine_core/errors/__init__.py b/policyengine_core/errors/__init__.py index cd7cb6a0..4c80bc79 100644 --- a/policyengine_core/errors/__init__.py +++ b/policyengine_core/errors/__init__.py @@ -5,6 +5,7 @@ from .parameter_not_found_error import ParameterNotFoundError from .parameter_parsing_error import ParameterParsingError from .period_mismatch_error import PeriodMismatchError +from .read_only_simulation_error import ReadOnlySimulationError from .situation_parsing_error import SituationParsingError from .spiral_error import SpiralError from .variable_name_conflict_error import VariableNameConflictError diff --git a/policyengine_core/errors/read_only_simulation_error.py b/policyengine_core/errors/read_only_simulation_error.py new file mode 100644 index 00000000..433bd994 --- /dev/null +++ b/policyengine_core/errors/read_only_simulation_error.py @@ -0,0 +1,23 @@ +class ReadOnlySimulationError(RuntimeError): + """An operation would change a simulation made read-only. + + Raised by an operation that would change the inputs, stored values or + tax-benefit system of a simulation after ``Simulation.make_read_only()``, + and by its next calculation once its parameters have changed (see + ``Simulation.make_read_only``). + """ + + +def refuse_on_read_only(simulation, operation: str) -> None: + """Raise :class:`ReadOnlySimulationError` if ``simulation`` is read-only. + + ``operation`` names what was refused, for the message. ``simulation`` may + be ``None``, or a stand-in object without the flag: neither is read-only. + """ + if getattr(simulation, "read_only", False): + raise ReadOnlySimulationError( + f"{operation} would change a read-only simulation. " + "make_read_only() was called on it, so it refuses changes to its " + "inputs, stored values and tax-benefit system. Make the change on " + "a branch (get_branch) or a clone instead." + ) diff --git a/policyengine_core/holders/holder.py b/policyengine_core/holders/holder.py index e695126e..28e16e14 100644 --- a/policyengine_core/holders/holder.py +++ b/policyengine_core/holders/holder.py @@ -12,6 +12,7 @@ from policyengine_core.data_storage.store_history import next_sequence_number from policyengine_core.enums import Enum from policyengine_core.errors import PeriodMismatchError +from policyengine_core.errors.read_only_simulation_error import refuse_on_read_only from policyengine_core.periods import Period if TYPE_CHECKING: @@ -47,6 +48,15 @@ def __init__(self, variable: "Variable", population: "Population"): self._on_disk_storable = True if self.variable.name in self.simulation.memory_config.variables_to_drop: self._do_not_store = True + if getattr(self.simulation, "read_only", False): + self._make_read_only() + + def _make_read_only(self) -> None: + """Make every array this holder stores non-writable, now and from + here on (see ``Simulation.make_read_only``).""" + self._memory_storage.make_read_only() + if self._disk_storage is not None: + self._disk_storage.make_read_only() def _follow_definition(self, variable: "Variable") -> None: """Take ``variable`` as this holder's definition when its storage fits. @@ -147,6 +157,21 @@ def delete_arrays( A deleted value set with ``set_input`` stops counting as an input, so a value calculated later for the same period is not taken for one. + + Raises ``ReadOnlySimulationError`` for a read-only simulation's + holder (see ``Simulation.make_read_only``). + """ + refuse_on_read_only(getattr(self, "simulation", None), "delete_arrays") + self._delete_arrays(period, branch_name) + + def _delete_arrays( + self, period: Period = None, branch_name: str = "default" + ) -> None: + """:meth:`delete_arrays`, for a read-only simulation too. + + Core calls this when the deletion is part of a calculation: after a + spiral, it deletes the values calculated from the default the spiral + returned (``Simulation.purge_cache_of_invalid_values``). """ simulation = getattr(self, "simulation", None) user_input_keys = getattr(simulation, "_user_input_keys", None) @@ -616,7 +641,11 @@ def set_input( Custom handlers store replayable inputs with ``holder._set`` or ``holder.set_input``. Values written through ``put_in_cache`` are excluded from input export and reform replay. + + Raises ``ReadOnlySimulationError`` for a read-only simulation's + holder (see ``Simulation.make_read_only``). """ + refuse_on_read_only(getattr(self, "simulation", None), "set_input") period = periods.period(period) if ( diff --git a/policyengine_core/parameters/parameter_node.py b/policyengine_core/parameters/parameter_node.py index f1c2f84e..6f04cfe8 100644 --- a/policyengine_core/parameters/parameter_node.py +++ b/policyengine_core/parameters/parameter_node.py @@ -130,6 +130,15 @@ class ParameterNode(AtInstantLike): parent: "ParameterNode" = None """The parent of the node, or None if the node is the root of the tree.""" + _change_count: int = 0 + """How many times a change below this node was recorded: each + ``mark_as_modified`` that reaches the node (``Parameter.update`` calls it, + and so do the scale and node equivalents) adds one, as does + ``TaxBenefitSystem.modify_parameters`` for the tree it passes on. A + read-only simulation compares its tree's count with the one it recorded + (see ``Simulation.make_read_only``). An edit that bypasses those, such as + assigning ``values_list`` or calling ``add_child`` directly, adds nothing.""" + def __init__( self, name: str = "", @@ -391,6 +400,7 @@ def clear_parent_cache(self): def mark_as_modified(self): self.modified = True + self._change_count += 1 if self.parent is not None: self.parent.mark_as_modified() diff --git a/policyengine_core/simulations/simulation.py b/policyengine_core/simulations/simulation.py index 55c4a2f5..c954670b 100644 --- a/policyengine_core/simulations/simulation.py +++ b/policyengine_core/simulations/simulation.py @@ -15,6 +15,7 @@ from policyengine_core import commons, periods from policyengine_core.data.dataset import Dataset +from policyengine_core.data_storage.non_writable import make_non_writable from policyengine_core.data_storage.store_history import ( StoreHistory, next_sequence_number, @@ -25,7 +26,8 @@ ) from policyengine_core.entities.entity import Entity from policyengine_core.enums import Enum, EnumArray -from policyengine_core.errors import CycleError, SpiralError +from policyengine_core.errors import CycleError, ReadOnlySimulationError, SpiralError +from policyengine_core.errors.read_only_simulation_error import refuse_on_read_only from policyengine_core.holders.holder import Holder from policyengine_core.periods import Instant, Period from policyengine_core.periods.config import ETERNITY, MONTH, YEAR @@ -751,6 +753,14 @@ class Simulation: start_instant: str = None """The earliest data input instant of the simulation.""" + read_only: bool = False + """Whether the simulation refuses changes to its inputs, stored values and + tax-benefit system. Set by :meth:`make_read_only`, and copied to nothing + else: a clone or branch of a read-only simulation is not read-only.""" + + # The parameter tree and its change count when ``make_read_only`` ran. + _read_only_parameters: Optional[Tuple[Any, int]] = None + # The temporary folder this simulation made for the values it stores on # disk, if it made one (see ``data_storage_dir``). _storage_directory: TemporaryStorageDirectory = None @@ -785,6 +795,27 @@ def _data_storage_dir(self, path: Optional[str]) -> None: None if path is None else directory_containing(os.fspath(path)) ) + @property + def tax_benefit_system(self) -> "TaxBenefitSystem": + """The tax-benefit system the simulation calculates with. + + Kept in the instance's ``__dict__`` under the same name, which this + property takes precedence over, so ``clone`` copies it with the rest + of the instance. Assigning it on a read-only simulation raises + ``ReadOnlySimulationError`` (see :meth:`make_read_only`). + """ + try: + return self.__dict__["tax_benefit_system"] + except KeyError: + raise AttributeError( + f"{type(self).__name__!r} object has no attribute 'tax_benefit_system'" + ) from None + + @tax_benefit_system.setter + def tax_benefit_system(self, system: "TaxBenefitSystem") -> None: + refuse_on_read_only(self, "Assigning tax_benefit_system") + self.__dict__["tax_benefit_system"] = system + def __init__( self, tax_benefit_system: "TaxBenefitSystem" = None, @@ -960,7 +991,92 @@ def __init__( self.parent_branch = None + def make_read_only(self) -> None: + """Make this simulation refuse every change to its inputs, stored + values and tax-benefit system. + + It still calculates a value it does not hold yet, and keeps it. From + here on: + + - ``set_input`` and ``delete_arrays`` (on the simulation or one of its + holders), ``drop_computed_arrays``, ``apply_reform``, ``subsample``, + ``build_from_dataset``, ``build_from_populations`` and assigning + ``tax_benefit_system`` raise ``ReadOnlySimulationError`` and change + nothing. + - Every array it stores is non-writable: those it holds now (marked in + place, so for anything else holding the same array object too, such + as an array given to ``set_input`` that was stored as it was given), + those it calculates, and those its disk storage reads back. Writing + into one in place, as a formula that modifies an array it read + would, raises numpy's ``ValueError``. + - Its parameter tree is recorded with its change count (see + ``ParameterNode._change_count``). Its next calculation, including + one answered from what it holds, raises ``ReadOnlySimulationError`` + once that count has moved (an update anywhere in the tree, made + through any simulation or system that shares it) or its system has + another tree. + - ``get_branch`` with a name it has not registered returns a new + branch every time and keeps it out of ``branches``, so nothing done + through the branch stays in this simulation. The branch is part of + the simulation, reads its values, and is not read-only: it takes + inputs and keeps branches of its own. + + 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. + + Not detected: + + - formula changes made in place on its tax-benefit system object + (``neutralize_variable``, ``update_variable``, ``add_variable``), by + a branch that shares the system (``get_branch`` without + ``clone_system``) or anything else holding it; + - parameter edits that record no change: assigning ``values_list`` or + a ``ParameterAtInstant``'s value, or ``add_child``, outside + ``TaxBenefitSystem.modify_parameters``; + - writes made through a holder's low-level ``_set`` or + ``put_in_cache``, or straight into its storage, which still store + (non-writable) values, replacing what is stored; + - the populations' structure arrays (IDs, memberships and roles), + which stay writable: clones and branches share them. + """ + if self.read_only: + return + parameters = self.tax_benefit_system.parameters + self._read_only_parameters = ( + parameters, + getattr(parameters, "_change_count", 0), + ) + self.read_only = True + for population in getattr(self, "populations", {}).values(): + for holder in population._holders.values(): + holder._make_read_only() + for array in (getattr(self, "_fast_cache", None) or {}).values(): + make_non_writable(array) + + def _refuse_if_parameters_changed(self) -> None: + """Raise ``ReadOnlySimulationError`` if the parameters a read-only + simulation recorded have changed since (see :meth:`make_read_only`).""" + recorded_parameters, recorded_change_count = self._read_only_parameters + parameters = self.tax_benefit_system.parameters + if parameters is not recorded_parameters: + raise ReadOnlySimulationError( + "The tax-benefit system of this read-only simulation has a " + "different parameter tree from the one it had when " + "make_read_only() was called, so the values it holds may no " + "longer match its parameters." + ) + if getattr(parameters, "_change_count", 0) != recorded_change_count: + raise ReadOnlySimulationError( + "A parameter of this read-only simulation changed after " + "make_read_only() was called, so the values it holds may no " + "longer match its parameters." + ) + def apply_reform(self, reform: Union[tuple, Reform]): + refuse_on_read_only(self, "apply_reform") if isinstance(reform, tuple): for subreform in reform: self.apply_reform(subreform) @@ -1104,6 +1220,7 @@ def build_from_populations(self, populations: Dict[str, Population]) -> None: Args: populations (Dict[str, Population]): A dictionary of populations, indexed by entity key. """ + refuse_on_read_only(self, "build_from_populations") self.populations = populations self.link_to_entities_instances() self.create_shortcuts() @@ -1129,6 +1246,7 @@ def build_from_dataset(self) -> None: Explicit dataset role columns do not validate role capacity. ``default_role=None`` requires a role column. """ + refuse_on_read_only(self, "build_from_dataset") self.build_from_populations(self.tax_benefit_system.instantiate_entities()) from policyengine_core.simulations.simulation_builder import ( SimulationBuilder, @@ -1498,6 +1616,9 @@ def calculate( ArrayLike: The calculated variable. """ + if self.read_only: + self._refuse_if_parameters_changed() + if period is not None and not isinstance(period, Period): period = periods.period(period) elif period is None and self.default_calculation_period is not None: @@ -2078,6 +2199,9 @@ def _calculate(self, variable_name: str, period: Period = None) -> ArrayLike: smc.set_cache_value(cache_path, array) if hasattr(self, "_fast_cache") and unchanged: + if self.read_only: + # The default a spiral returns is kept here, not stored. + make_non_writable(array) self._fast_cache[(variable_name, period)] = array return array @@ -2158,7 +2282,13 @@ def _cache_result( first. A calculation that was running when an input set on this simulation dropped values may have read the replaced value, so its result is returned but not kept (see ``_drop_computed``). + + In a read-only simulation the value returned is non-writable, as what + is stored is: the caller, and the fast cache, may hold this array + rather than the stored one (storing can convert it). """ + if self.read_only: + make_non_writable(array) epoch, inputs_set, started_at = input_state if inputs_set != self._inputs_set: stored_input = self._input_set_meanwhile(holder, period, started_at) @@ -2190,7 +2320,8 @@ def purge_cache_of_invalid_values(self) -> None: return for _name, _period in invalidated_caches: holder = self.get_holder(_name) - holder.delete_arrays(_period) + # Part of a calculation, so a read-only simulation runs it too. + holder._delete_arrays(_period) if _fast_cache is not None: _fast_cache.pop((_name, _period), None) self.invalidated_caches = set() @@ -2719,7 +2850,11 @@ def delete_arrays(self, variable: str, period: Period = None) -> None: True >>> simulation.get_array('age', '2018-05') is None True + + Raises ``ReadOnlySimulationError`` on a read-only simulation (see + :meth:`make_read_only`). """ + refuse_on_read_only(self, "delete_arrays") holder = self.get_holder(variable) for branch_name in self._get_visible_branch_names(): holder.delete_arrays(period, branch_name) @@ -2750,9 +2885,13 @@ def drop_computed_arrays(self) -> int: ``set_input`` on a branch drops what depends on the input by itself. Branches already created from this simulation keep their values. + Raises ``ReadOnlySimulationError`` on a read-only simulation (see + :meth:`make_read_only`). + Returns: int: The number of arrays deleted. """ + refuse_on_read_only(self, "drop_computed_arrays") # Recalculate rather than read macro-cache files written before. self.macro_cache_read = False for frame in _calculation_frames.get(): @@ -2841,7 +2980,11 @@ def set_input(self, variable_name: str, period: Period, value: ArrayLike) -> Non their values; and a value another simulation calculated from the branch and kept stays when the branch's input changes after that calculation ended. + + Raises ``ReadOnlySimulationError`` on a read-only simulation (see + :meth:`make_read_only`); a branch of it takes inputs. """ + refuse_on_read_only(self, "set_input") period = periods.period(period) if self.start_instant is None or self.start_instant > period.start: self.start_instant = period.start @@ -3015,6 +3158,9 @@ def clone( "tracer", "branches", "_fast_cache", + # A copy of a read-only simulation is not read-only. + "read_only", + "_read_only_parameters", ): new_dict[key] = value # Aliases of this simulation's methods (``calc`` and ``df``, and any a @@ -3178,6 +3324,12 @@ def get_branch( tax-benefit system or parameters are changed should call :meth:`drop_computed_arrays` before calculating. + On a read-only simulation (see :meth:`make_read_only`), a name it has + not registered gives a new branch every time, which is not kept in + ``branches``: nothing done through it stays in this simulation. The + branch is not read-only. A name registered before ``make_read_only`` + gives that branch, as it is. + 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. @@ -3202,7 +3354,8 @@ def get_branch( finally: request.pending = False _branch_clone.reset(token) - self.branches[name] = branch + if not self.read_only: + self.branches[name] = branch branch.branch_name = name branch.parent_branch = self branch._fixed_point_branch = True @@ -3646,9 +3799,13 @@ def subsample( seed (int, optional): The key used to seed the random number generator. Defaults to the dataset name. time_period (str, optional): Sample households based on their weight in this time period. Defaults to the default calculation period. + Raises ``ReadOnlySimulationError`` on a read-only simulation (see + :meth:`make_read_only`). + Returns: Simulation: The quantized simulation. """ + refuse_on_read_only(self, "subsample") default_calculation_period = self.default_calculation_period # Set default key if not provided if seed is None: diff --git a/policyengine_core/taxbenefitsystems/tax_benefit_system.py b/policyengine_core/taxbenefitsystems/tax_benefit_system.py index 6137efe2..2c002a1f 100644 --- a/policyengine_core/taxbenefitsystems/tax_benefit_system.py +++ b/policyengine_core/taxbenefitsystems/tax_benefit_system.py @@ -835,7 +835,16 @@ def modify_parameters( period=periods.period(time_period), ) else: - reform_parameters = modifier_function(self.parameters) + parameters = self.parameters + try: + reform_parameters = modifier_function(parameters) + finally: + # The modifier may have changed the tree in place without + # ``update`` (assigning ``values_list``, say), so count a + # change, as ``mark_as_modified`` does (see + # ``ParameterNode._change_count``). + if isinstance(parameters, ParameterNode): + parameters._change_count += 1 if not isinstance(reform_parameters, ParameterNode): return ValueError( "modifier_function {} in module {} must return a ParameterNode".format( From 14b847801aa29ccb6584936ebccc0ed7ed9a0a48 Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Sat, 28 Nov 2026 01:35:17 +0400 Subject: [PATCH 03/15] Add failing tests for review round 1 findings A read-only simulation must refuse invalidate_cache_entry and deleting its tax_benefit_system, keep its values when a parent it shared arrays with writes into them in place, and keep them through its parent's apply_reform. Deleting tax_benefit_system must still work on a simulation that is not read-only. Co-Authored-By: Claude Opus 5.5 --- tests/core/test_read_only_simulation.py | 61 +++++++++++++++++++++++++ 1 file changed, 61 insertions(+) diff --git a/tests/core/test_read_only_simulation.py b/tests/core/test_read_only_simulation.py index 91aeecae..c683021b 100644 --- a/tests/core/test_read_only_simulation.py +++ b/tests/core/test_read_only_simulation.py @@ -173,6 +173,18 @@ def test_a_clone_of_a_read_only_simulation_is_not_read_only(shared_system): ), id="assign-tax_benefit_system", ), + pytest.param( + lambda simulation: delattr(simulation, "tax_benefit_system"), + id="delete-tax_benefit_system", + ), + pytest.param( + # The next calculation would delete the value (see + # ``purge_cache_of_invalid_values``). + lambda simulation: simulation.invalidate_cache_entry( + "salary", periods.period(PERIOD) + ), + id="invalidate_cache_entry", + ), ] @@ -332,6 +344,55 @@ def test_the_first_read_of_an_array_shared_with_another_simulation_is_non_writab assert not branch.calculate("salary", PERIOD).flags.writeable +def test_a_read_only_branch_keeps_its_values_when_its_parent_writes_in_place( + shared_system, +): + parent = build_simulation(shared_system) + income_tax = np.array(parent.calculate("income_tax", PERIOD), copy=True) + branch = parent.get_branch("made_read_only_later") + branch.make_read_only() + + # The parent is not read-only: a formula there could write into a value + # it stores, which the branch shared until it first read it. + parent.get_array("income_tax", PERIOD)[0] = -1.0 + + assert np.array_equal(branch.get_array("income_tax", PERIOD), income_tax) + assert np.array_equal(branch.calculate("income_tax", PERIOD), income_tax) + + +# ----- Simulations that are not read-only ----- # + + +def test_deleting_the_system_of_a_simulation_that_is_not_read_only_still_works( + shared_system, +): + simulation = build_simulation(shared_system) + + del simulation.tax_benefit_system + + assert not hasattr(simulation, "tax_benefit_system") + + +def test_a_parents_reform_leaves_a_read_only_branch_unchanged(): + parent = build_simulation(CountryTaxBenefitSystem()) + branch = parent.get_branch("own_system", clone_system=True) + for output in OUTPUTS: + branch.calculate(output, PERIOD) + branch.make_read_only() + branch_system = branch.tax_benefit_system + values_before = stored_values(branch) + + parent.apply_reform(removal_basic_income) + + assert branch.tax_benefit_system is branch_system + assert_same_values(values_before, stored_values(branch)) + for output in OUTPUTS: + assert np.array_equal( + branch.calculate(output, PERIOD), + values_before[(output, "own_system", PERIOD)], + ) + + # ----- Parameter changes ----- # From eeb3869b9ab402528130ccf4d5c79e540f4f80ea Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Sat, 28 Nov 2026 01:36:29 +0400 Subject: [PATCH 04/15] Close the read-only gaps review round 1 found - invalidate_cache_entry and deleting tax_benefit_system are refused on a read-only simulation; core's own spiral handling uses the internal _invalidate_cache_entry, so it still runs there. - A simulation that is not read-only can delete its tax_benefit_system again: the property has a deleter. - make_read_only copies the arrays a storage still shares with the one it was cloned from, so a parent's in-place write no longer reaches a read-only branch. - A parent's apply_reform no longer empties or rebinds a read-only registered branch. Co-Authored-By: Claude Opus 5.5 --- .../data_storage/in_memory_storage.py | 14 ++++- policyengine_core/simulations/simulation.py | 63 ++++++++++++++----- 2 files changed, 61 insertions(+), 16 deletions(-) diff --git a/policyengine_core/data_storage/in_memory_storage.py b/policyengine_core/data_storage/in_memory_storage.py index 485fc881..9d440803 100644 --- a/policyengine_core/data_storage/in_memory_storage.py +++ b/policyengine_core/data_storage/in_memory_storage.py @@ -128,10 +128,20 @@ def __setstate__(self, state: dict) -> None: def make_read_only(self) -> None: """Mark every array this storage holds non-writable, and every array - it stores or copies from here on (see ``put`` and ``get``).""" + it stores or copies from here on (see ``put`` and ``get``). + + An array still shared with the storage this one was cloned from (see + ``clone``) is copied first: the other storage can write into its own + array in place, which would change what this one reads. + """ self.read_only = True - for array in self._arrays.values(): + shared = self._shared + for key, array in list(self._arrays.items()): + if key in shared: + array = self._arrays[key] = array.copy() make_non_writable(array) + # Nothing is shared any more (see ``_release_if_empty``). + self.__dict__.pop("_shared", None) def clone(self, share_arrays: bool = False) -> "InMemoryStorage": """Copy this storage. diff --git a/policyengine_core/simulations/simulation.py b/policyengine_core/simulations/simulation.py index c954670b..b44fd3d4 100644 --- a/policyengine_core/simulations/simulation.py +++ b/policyengine_core/simulations/simulation.py @@ -816,6 +816,14 @@ def tax_benefit_system(self, system: "TaxBenefitSystem") -> None: refuse_on_read_only(self, "Assigning tax_benefit_system") self.__dict__["tax_benefit_system"] = system + @tax_benefit_system.deleter + def tax_benefit_system(self) -> None: + refuse_on_read_only(self, "Deleting tax_benefit_system") + try: + del self.__dict__["tax_benefit_system"] + except KeyError: + raise AttributeError("tax_benefit_system") from None + def __init__( self, tax_benefit_system: "TaxBenefitSystem" = None, @@ -999,16 +1007,21 @@ def make_read_only(self) -> None: here on: - ``set_input`` and ``delete_arrays`` (on the simulation or one of its - holders), ``drop_computed_arrays``, ``apply_reform``, ``subsample``, - ``build_from_dataset``, ``build_from_populations`` and assigning + holders), ``drop_computed_arrays``, ``invalidate_cache_entry``, + ``apply_reform``, ``subsample``, ``build_from_dataset``, + ``build_from_populations`` and assigning or deleting ``tax_benefit_system`` raise ``ReadOnlySimulationError`` and change - nothing. - - Every array it stores is non-writable: those it holds now (marked in - place, so for anything else holding the same array object too, such - as an array given to ``set_input`` that was stored as it was given), - those it calculates, and those its disk storage reads back. Writing - into one in place, as a formula that modifies an array it read - would, raises numpy's ``ValueError``. + nothing. As a registered branch, it keeps what it holds when its + parent applies a reform. + - Every array it stores is non-writable: those it holds now, those it + calculates, and those its disk storage reads back. Writing into one + in place, as a formula that modifies an array it read would, raises + numpy's ``ValueError``. The flag is set on the array object itself, + so it holds for anything else holding the same object: an array + given to ``set_input`` that was stored as it was given, or another + simulation's array that a formula returned as it was. An array it + still shares with the simulation it was branched from is copied + first. - Its parameter tree is recorded with its change count (see ``ParameterNode._change_count``). Its next calculation, including one answered from what it holds, raises ``ReadOnlySimulationError`` @@ -1025,7 +1038,8 @@ def make_read_only(self) -> None: 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. + ``get_branch`` still returns as it is. A pickled or deep-copied + read-only simulation is the same simulation, and stays read-only. Not detected: @@ -1040,7 +1054,10 @@ def make_read_only(self) -> None: ``put_in_cache``, or straight into its storage, which still store (non-writable) values, replacing what is stored; - the populations' structure arrays (IDs, memberships and roles), - which stay writable: clones and branches share them. + which stay writable: clones and branches share them; + - writes through a view of a stored array taken before this call, or + into an array object a formula returned as a view of another + simulation's writable array. """ if self.read_only: return @@ -1212,7 +1229,11 @@ def _invalidate_all_caches(self) -> None: for holder in population._holders.values(): holder._record_inputs(None) for branch in self.branches.values(): - branch._invalidate_all_caches() + # A read-only branch keeps what it holds (see ``make_read_only``): + # if the change reached its parameters, its next calculation + # raises instead. + if not branch.read_only: + branch._invalidate_all_caches() def build_from_populations(self, populations: Dict[str, Population]) -> None: """This method of initialisation requires the populations to be pre-initialised. @@ -1531,7 +1552,10 @@ def kept(name): ): self.input_variables = [name for name in input_variables if kept(name)] for branch in self.branches.values(): - branch._bind_to_tax_benefit_system() + # Binding can drop a read-only branch's holders, and with them + # what it holds (see ``make_read_only``). + if not branch.read_only: + branch._bind_to_tax_benefit_system() def create_shortcuts(self) -> None: for _key, population in self.populations.items(): @@ -2767,6 +2791,17 @@ def _check_for_cycle(self, variable: str, period: Period) -> None: raise SpiralError(message, variable) def invalidate_cache_entry(self, variable: str, period: Period) -> None: + """Delete the value of ``variable`` for ``period`` once the running + calculation ends (see :meth:`purge_cache_of_invalid_values`). + + Raises ``ReadOnlySimulationError`` on a read-only simulation (see + :meth:`make_read_only`). Core's own handling of a spiral, which is + part of a calculation, still invalidates values there. + """ + refuse_on_read_only(self, "invalidate_cache_entry") + self._invalidate_cache_entry(variable, period) + + def _invalidate_cache_entry(self, variable: str, period: Period) -> None: invalidated_caches = getattr(self, "invalidated_caches", None) if invalidated_caches is None: self.invalidated_caches = {(variable, period)} @@ -2780,7 +2815,7 @@ def invalidate_spiral_variables(self, variable: str) -> None: # for deletion from the cache once the calculation ends. count = 0 for frame in reversed(self.tracer.stack): - self.invalidate_cache_entry(frame["name"], frame["period"]) + self._invalidate_cache_entry(frame["name"], frame["period"]) if frame["name"] == variable: count += 1 if count > self.max_spiral_loops: From cd194867e0abae213cca8d082932df19b961085d Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Mon, 30 Nov 2026 17:25:57 +0400 Subject: [PATCH 05/15] Add failing tests for review round 2 findings A read-only simulation must catch a parameter change when its system's top parameter node is a shallow copy whose children still name the original as their parent (policyengine-us makes one for each traced simulation), and must not take such a copy, made later, for a change. A parent's apply_reform must still clear the branches of a read-only branch. Co-Authored-By: Claude Opus 5.5 --- tests/core/test_read_only_simulation.py | 63 +++++++++++++++++++++++++ 1 file changed, 63 insertions(+) diff --git a/tests/core/test_read_only_simulation.py b/tests/core/test_read_only_simulation.py index c683021b..189f69ec 100644 --- a/tests/core/test_read_only_simulation.py +++ b/tests/core/test_read_only_simulation.py @@ -21,6 +21,7 @@ from __future__ import annotations +import copy import warnings import numpy as np @@ -393,6 +394,29 @@ def test_a_parents_reform_leaves_a_read_only_branch_unchanged(): ) +def test_a_parents_reform_still_clears_the_branches_of_a_read_only_branch(): + parent = build_simulation(CountryTaxBenefitSystem()) + # Both branches share the parent's system, so the reform reaches them. + read_only_branch = parent.get_branch("read_only_branch") + nested_branch = read_only_branch.get_branch("nested_branch") + nested_branch.calculate("income_tax", PERIOD) + read_only_branch.make_read_only() + + parent.apply_reform( + {"taxes.income_tax_rate": {"2022-01-01": REFORM_INCOME_TAX_RATE}} + ) + + # The nested branch is not read-only: it recalculates under the reform. + assert np.allclose( + nested_branch.calculate("income_tax", PERIOD), + np.array(SALARY) * REFORM_INCOME_TAX_RATE, + ) + # The read-only branch keeps its values, and refuses to calculate with + # parameters that changed under it. + with pytest.raises(errors.ReadOnlySimulationError): + read_only_branch.calculate("income_tax", PERIOD) + + # ----- Parameter changes ----- # @@ -487,6 +511,45 @@ def test_a_parameter_change_on_a_branch_with_its_own_system_is_accepted( assert np.allclose(income_tax, np.array(SALARY) * BASELINE_INCOME_TAX_RATE) +def _give_the_system_a_shallow_copy_of_its_top_node(system): + """Replace the system's parameter tree's top node with a shallow copy, as + policyengine-us does for each traced simulation (``isolate_parameter_tracing``). + The copy shares the original's children, whose ``parent`` is still the + original top node.""" + private_top_node = copy.copy(system.parameters) + private_top_node._at_instant_cache = {} + system.parameters = private_top_node + system._parameters_at_instant_cache = {} + + +@pytest.mark.parametrize("change_parameters", PARAMETER_CHANGES) +def test_a_parameter_change_is_caught_when_the_top_node_is_a_shallow_copy( + change_parameters, +): + system = CountryTaxBenefitSystem() + _give_the_system_a_shallow_copy_of_its_top_node(system) + simulation = build_simulation(system) + simulation.calculate("income_tax", PERIOD) + simulation.make_read_only() + + change_parameters(system) + + with pytest.raises(errors.ReadOnlySimulationError): + simulation.calculate("income_tax", PERIOD) + + +def test_a_shallow_copy_of_the_top_node_made_later_is_not_a_parameter_change(): + system = CountryTaxBenefitSystem() + simulation = build_simulation(system) + expected = {output: simulation.calculate(output, PERIOD) for output in OUTPUTS} + simulation.make_read_only() + + _give_the_system_a_shallow_copy_of_its_top_node(system) + + for output in OUTPUTS: + assert np.array_equal(simulation.calculate(output, PERIOD), expected[output]) + + def test_making_a_simulation_read_only_again_keeps_the_first_parameter_record(): system = CountryTaxBenefitSystem() simulation = build_simulation(system) From c02c680ccb8471eaa9d11e23d0cacef9fde220bd Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Mon, 30 Nov 2026 17:28:10 +0400 Subject: [PATCH 06/15] Count parameter changes where shallow-copied top nodes send them policyengine-us gives each traced simulation a shallow copy of its parameter tree's top node. The copy shares the original's children, whose parent is still the original, so mark_as_modified counted a change on the original while a read-only simulation compared the copy's count: it missed an update made after make_read_only(), and took a copy made later for a new tree. change_counting_node finds the node a tree's changes are counted on, by going up the parent links from one of its children; make_read_only(), the check before each calculation and modify_parameters all use it. A read-only branch now skips only its own clearing and binding when its parent applies a reform, so the branches it holds are cleared as before. Co-Authored-By: Claude Opus 5.5 --- .../parameters/parameter_node.py | 30 +++++++- policyengine_core/simulations/simulation.py | 70 ++++++++++++------- .../taxbenefitsystems/tax_benefit_system.py | 8 ++- 3 files changed, 77 insertions(+), 31 deletions(-) diff --git a/policyengine_core/parameters/parameter_node.py b/policyengine_core/parameters/parameter_node.py index 6f04cfe8..5a77bbc3 100644 --- a/policyengine_core/parameters/parameter_node.py +++ b/policyengine_core/parameters/parameter_node.py @@ -93,6 +93,31 @@ def _clear_at_instant_caches_upward(node) -> None: node = getattr(node, "parent", None) +def change_counting_node(parameters): + """The node whose ``_change_count`` counts the changes made in the tree + under ``parameters``. + + ``mark_as_modified`` adds one to the count of every node it passes on its + way up the ``parent`` links, so the node at the top of those links counts + every change made below it. That is normally ``parameters`` itself. But a + shallow copy of a tree's top node (policyengine-us makes one for each + traced simulation) shares the original's children, whose ``parent`` is + still the original, so changes made through them are counted on the + original. This therefore goes up the ``parent`` links from one of + ``parameters``' children. It returns ``parameters`` itself when it has no + children, or is not a parameter node. + """ + children = getattr(parameters, "children", None) + if not children: + return parameters + node = next(iter(children.values())) + visited = set() + while getattr(node, "parent", None) is not None and id(node) not in visited: + visited.add(id(node)) + node = node.parent + return node + + class _AtInstantCache(dict): """A parameter node's nodes at instant, by instant. @@ -135,8 +160,9 @@ class ParameterNode(AtInstantLike): ``mark_as_modified`` that reaches the node (``Parameter.update`` calls it, and so do the scale and node equivalents) adds one, as does ``TaxBenefitSystem.modify_parameters`` for the tree it passes on. A - read-only simulation compares its tree's count with the one it recorded - (see ``Simulation.make_read_only``). An edit that bypasses those, such as + read-only simulation compares its tree's count, on the node + ``change_counting_node`` finds, with the one it recorded (see + ``Simulation.make_read_only``). An edit that bypasses those, such as assigning ``values_list`` or calling ``add_child`` directly, adds nothing.""" def __init__( diff --git a/policyengine_core/simulations/simulation.py b/policyengine_core/simulations/simulation.py index b44fd3d4..aeb96c84 100644 --- a/policyengine_core/simulations/simulation.py +++ b/policyengine_core/simulations/simulation.py @@ -180,6 +180,7 @@ def _latest_input_key(period: Period, definition_period: str) -> tuple: from policyengine_core.variables import Variable, QuantityType from policyengine_core.reforms.reform import Reform from policyengine_core.parameters import get_parameter +from policyengine_core.parameters.parameter_node import change_counting_node from policyengine_core.simulations.simulation_macro_cache import ( SimulationMacroCache, ) @@ -758,7 +759,8 @@ class Simulation: tax-benefit system. Set by :meth:`make_read_only`, and copied to nothing else: a clone or branch of a read-only simulation is not read-only.""" - # The parameter tree and its change count when ``make_read_only`` ran. + # The node counting changes to the parameter tree (see + # ``change_counting_node``) and its count when ``make_read_only`` ran. _read_only_parameters: Optional[Tuple[Any, int]] = None # The temporary folder this simulation made for the values it stores on @@ -1012,7 +1014,7 @@ def make_read_only(self) -> None: ``build_from_populations`` and assigning or deleting ``tax_benefit_system`` raise ``ReadOnlySimulationError`` and change nothing. As a registered branch, it keeps what it holds when its - parent applies a reform. + parent applies a reform; its own branches are cleared as usual. - Every array it stores is non-writable: those it holds now, those it calculates, and those its disk storage reads back. Writing into one in place, as a formula that modifies an array it read would, raises @@ -1022,24 +1024,31 @@ def make_read_only(self) -> None: simulation's array that a formula returned as it was. An array it still shares with the simulation it was branched from is copied first. - - Its parameter tree is recorded with its change count (see - ``ParameterNode._change_count``). Its next calculation, including - one answered from what it holds, raises ``ReadOnlySimulationError`` - once that count has moved (an update anywhere in the tree, made - through any simulation or system that shares it) or its system has - another tree. + - Its parameter tree's change count is recorded, on the node that + counts the tree's changes (see ``change_counting_node``: normally + the tree's top node, or the original a shallow copy of it shares + children with). Its next calculation, including one answered from + what it holds, raises ``ReadOnlySimulationError`` once that count + has moved (an update anywhere in the tree, made through any + simulation or system that shares it) or its system has another + tree. - ``get_branch`` with a name it has not registered returns a new branch every time and keeps it out of ``branches``, so nothing done through the branch stays in this simulation. The branch is part of the simulation, reads its values, and is not read-only: it takes - inputs and keeps branches of its own. + inputs and keeps branches of its own. A second ``get_branch`` with + the same name, including one made when core runs a calculation + again after an input change, gets another new branch, without what + was set on the first. 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 - read-only simulation is the same simulation, and stays read-only. + 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. Not detected: @@ -1061,10 +1070,10 @@ def make_read_only(self) -> None: """ if self.read_only: return - parameters = self.tax_benefit_system.parameters + counting_node = change_counting_node(self.tax_benefit_system.parameters) self._read_only_parameters = ( - parameters, - getattr(parameters, "_change_count", 0), + counting_node, + getattr(counting_node, "_change_count", 0), ) self.read_only = True for population in getattr(self, "populations", {}).values(): @@ -1076,16 +1085,16 @@ def make_read_only(self) -> None: def _refuse_if_parameters_changed(self) -> None: """Raise ``ReadOnlySimulationError`` if the parameters a read-only simulation recorded have changed since (see :meth:`make_read_only`).""" - recorded_parameters, recorded_change_count = self._read_only_parameters - parameters = self.tax_benefit_system.parameters - if parameters is not recorded_parameters: + recorded_counting_node, recorded_change_count = self._read_only_parameters + counting_node = change_counting_node(self.tax_benefit_system.parameters) + if counting_node is not recorded_counting_node: raise ReadOnlySimulationError( "The tax-benefit system of this read-only simulation has a " "different parameter tree from the one it had when " "make_read_only() was called, so the values it holds may no " "longer match its parameters." ) - if getattr(parameters, "_change_count", 0) != recorded_change_count: + if getattr(counting_node, "_change_count", 0) != recorded_change_count: raise ReadOnlySimulationError( "A parameter of this read-only simulation changed after " "make_read_only() was called, so the values it holds may no " @@ -1123,7 +1132,16 @@ def _invalidate_all_caches(self) -> None: else (formula outputs, cached short-path results, on-disk caches) is wiped so the next ``calculate`` recomputes under the new tax-benefit system. + + A read-only simulation (see ``make_read_only``) keeps what it holds, + and only its branches are cleared: it is reached here only as a + branch of a simulation applying a reform, and if the reform changed + its parameters, its next calculation raises instead. """ + if self.read_only: + for branch in self.branches.values(): + branch._invalidate_all_caches() + return self.invalidated_caches = set() # Snapshot user-provided inputs before wiping so they can be # replayed into the fresh storage. Use the storage API instead of @@ -1229,11 +1247,7 @@ def _invalidate_all_caches(self) -> None: for holder in population._holders.values(): holder._record_inputs(None) for branch in self.branches.values(): - # A read-only branch keeps what it holds (see ``make_read_only``): - # if the change reached its parameters, its next calculation - # raises instead. - if not branch.read_only: - branch._invalidate_all_caches() + branch._invalidate_all_caches() def build_from_populations(self, populations: Dict[str, Population]) -> None: """This method of initialisation requires the populations to be pre-initialised. @@ -1505,6 +1519,13 @@ def _bind_to_tax_benefit_system(self) -> None: gives it a list of its own. Between reforms, ``Population.get_holder`` keeps compatible holders on the current definitions. """ + if self.read_only: + # Binding can drop holders, and with them what a read-only + # simulation holds (see ``make_read_only``). Its branches are + # bound as usual. + for branch in self.branches.values(): + branch._bind_to_tax_benefit_system() + return system = self.tax_benefit_system if system is None: # A reform simulation of a class with no default system instance @@ -1552,10 +1573,7 @@ def kept(name): ): self.input_variables = [name for name in input_variables if kept(name)] for branch in self.branches.values(): - # Binding can drop a read-only branch's holders, and with them - # what it holds (see ``make_read_only``). - if not branch.read_only: - branch._bind_to_tax_benefit_system() + branch._bind_to_tax_benefit_system() def create_shortcuts(self) -> None: for _key, population in self.populations.items(): diff --git a/policyengine_core/taxbenefitsystems/tax_benefit_system.py b/policyengine_core/taxbenefitsystems/tax_benefit_system.py index 2c002a1f..300786d5 100644 --- a/policyengine_core/taxbenefitsystems/tax_benefit_system.py +++ b/policyengine_core/taxbenefitsystems/tax_benefit_system.py @@ -40,6 +40,7 @@ ParameterNodeAtInstant, Parameter, ) +from policyengine_core.parameters.parameter_node import change_counting_node from policyengine_core.parameters.operations.homogenize_parameters import ( homogenize_parameter_structures, ) @@ -841,10 +842,11 @@ def modify_parameters( finally: # The modifier may have changed the tree in place without # ``update`` (assigning ``values_list``, say), so count a - # change, as ``mark_as_modified`` does (see + # change where ``mark_as_modified`` would (see # ``ParameterNode._change_count``). - if isinstance(parameters, ParameterNode): - parameters._change_count += 1 + counting_node = change_counting_node(parameters) + if isinstance(counting_node, ParameterNode): + counting_node._change_count += 1 if not isinstance(reform_parameters, ParameterNode): return ValueError( "modifier_function {} in module {} must return a ParameterNode".format( From 10dc525f3e2d8bad3edd9d312211c658c83292bb Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Mon, 30 Nov 2026 17:56:36 +0400 Subject: [PATCH 07/15] Add failing tests for review round 3 findings SimulationBuilder must not build into a read-only simulation, and the public set_input helpers must not store inputs into one; either way the populations and stored values stay as they were. Co-Authored-By: Claude Opus 5.5 --- tests/core/test_read_only_simulation.py | 55 +++++++++++++++++++++++++ 1 file changed, 55 insertions(+) diff --git a/tests/core/test_read_only_simulation.py b/tests/core/test_read_only_simulation.py index 189f69ec..6c552d1c 100644 --- a/tests/core/test_read_only_simulation.py +++ b/tests/core/test_read_only_simulation.py @@ -37,6 +37,11 @@ removal_basic_income, ) from policyengine_core.experimental import MemoryConfig +from policyengine_core.holders import ( + set_input_dispatch_by_period, + set_input_divide_by_period, +) +from policyengine_core.simulations import SimulationBuilder from policyengine_core.variables import Variable PERIOD = "2022-01" @@ -186,9 +191,56 @@ def test_a_clone_of_a_read_only_simulation_is_not_read_only(shared_system): ), id="invalidate_cache_entry", ), + pytest.param( + lambda simulation: SimulationBuilder().build_from_dict( + simulation.tax_benefit_system, + { + "persons": {"x": {}, "y": {}, "z": {}}, + "households": {"h": {"parents": ["x", "y"], "children": ["z"]}}, + }, + simulation, + ), + id="builder-entities-into-it", + ), + pytest.param( + lambda simulation: SimulationBuilder().build_from_dict( + simulation.tax_benefit_system, + {"salary": {PERIOD: [1.0, 2.0, 3.0, 4.0, 5.0]}}, + simulation, + ), + id="builder-variables-into-it", + ), + pytest.param( + lambda simulation: set_input_divide_by_period( + simulation.get_holder("salary"), + periods.period("2022"), + np.array([12000.0, 24000.0]), + ), + id="set_input_divide_by_period", + ), + pytest.param( + lambda simulation: set_input_dispatch_by_period( + simulation.get_holder("salary"), + periods.period("2022"), + np.array([1000.0, 2000.0]), + ), + id="set_input_dispatch_by_period", + ), ] +def population_structure(simulation) -> dict: + """Each population's size, IDs and memberships.""" + return { + key: ( + population.count, + list(population.ids), + None if population.entity.is_person else list(population.members_entity_id), + ) + for key, population in simulation.populations.items() + } + + @pytest.mark.parametrize("refused_operation", REFUSED_OPERATIONS) def test_a_read_only_simulation_refuses_the_operation_and_changes_nothing( refused_operation, @@ -204,10 +256,13 @@ def test_a_read_only_simulation_refuses_the_operation_and_changes_nothing( variables_before = dict(system_before.variables) branches_before = dict(simulation.branches) start_instant_before = simulation.start_instant + structure_before = population_structure(simulation) with pytest.raises(errors.ReadOnlySimulationError): refused_operation(simulation) + assert population_structure(simulation) == structure_before + assert_same_values(values_before, stored_values(simulation)) assert simulation.tax_benefit_system is system_before assert simulation.tax_benefit_system.parameters is parameters_before From 355054ef5080ea9282913cf8463dd4d03e1cae7c Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Mon, 30 Nov 2026 17:57:09 +0400 Subject: [PATCH 08/15] Refuse building into, or set_input helpers on, a read-only simulation SimulationBuilder.build_from_dict, build_from_entities, build_from_variables and build_default_simulation refuse an existing read-only simulation before they change its populations, and set_input_dispatch_by_period and set_input_divide_by_period refuse a read-only simulation's holder before they drop or store anything. Co-Authored-By: Claude Opus 5.5 --- policyengine_core/holders/helpers.py | 7 +++++++ policyengine_core/simulations/simulation_builder.py | 5 +++++ 2 files changed, 12 insertions(+) diff --git a/policyengine_core/holders/helpers.py b/policyengine_core/holders/helpers.py index 1eba51ff..f6a86098 100644 --- a/policyengine_core/holders/helpers.py +++ b/policyengine_core/holders/helpers.py @@ -6,6 +6,7 @@ from policyengine_core import periods from policyengine_core.data_storage.store_history import _period_from_storage_key +from policyengine_core.errors.read_only_simulation_error import refuse_on_read_only from policyengine_core.holders.holder import Holder from policyengine_core.periods import Period @@ -76,8 +77,10 @@ def _store_input( The value is added to the simulation's record of inputs even when the helper is called directly instead of through ``Holder.set_input``, and ``calculate``'s fast cache drops the value it held for the period. + Raises ``ReadOnlySimulationError`` for a read-only simulation's holder. """ simulation = getattr(holder, "simulation", None) + refuse_on_read_only(simulation, "set_input") input_keys = getattr(simulation, "_user_input_keys", None) # Let the holder normalize and record the supplied-input tier, including # direct helper calls. Keep a legacy holder without an input record in @@ -261,6 +264,8 @@ def set_input_dispatch_by_period(holder: Holder, period: Period, array: ArrayLik To read more about ``set_input`` attributes, check the `documentation `_. """ + # Before anything is dropped or stored (see ``Simulation.make_read_only``). + refuse_on_read_only(getattr(holder, "simulation", None), "set_input") array = holder._to_array(array, validate_nan=True) period_size = period.size @@ -307,6 +312,8 @@ def set_input_divide_by_period(holder: Holder, period: Period, array: ArrayLike) To read more about ``set_input`` attributes, check the `documentation `_. """ + # Before anything is dropped or stored (see ``Simulation.make_read_only``). + refuse_on_read_only(getattr(holder, "simulation", None), "set_input") if not isinstance(array, numpy.ndarray): array = numpy.array(array) array = holder._to_array(array, validate_nan=True) diff --git a/policyengine_core/simulations/simulation_builder.py b/policyengine_core/simulations/simulation_builder.py index 6b65cfe9..5ac91606 100644 --- a/policyengine_core/simulations/simulation_builder.py +++ b/policyengine_core/simulations/simulation_builder.py @@ -16,6 +16,7 @@ ) from policyengine_core.periods import Period from policyengine_core.populations import GroupPopulation, Population +from policyengine_core.errors.read_only_simulation_error import refuse_on_read_only from policyengine_core.simulations.simulation import Simulation from policyengine_core.simulations.helpers import ( check_type, @@ -173,6 +174,7 @@ def build_from_dict( This method uses :any:`build_from_entities` if entities are fully specified, or :any:`build_from_variables` if not. """ + refuse_on_read_only(simulation, "SimulationBuilder.build_from_dict") input_dict = self.explicit_singular_entities(tax_benefit_system, input_dict) if any( @@ -218,6 +220,7 @@ def build_from_entities( 'households': {'household': {'parents': ['Javier']}} }) """ + refuse_on_read_only(simulation, "SimulationBuilder.build_from_entities") input_dict = copy.deepcopy(input_dict) if simulation is None: @@ -323,6 +326,7 @@ def build_from_variables( {'salary': {'2016-10': 12000}} ) """ + refuse_on_read_only(simulation, "SimulationBuilder.build_from_variables") count = _get_person_count(input_dict) simulation = self.build_default_simulation( tax_benefit_system, count, simulation @@ -356,6 +360,7 @@ def build_default_simulation( TypeError: if ``count`` is not an integer, as ``range(count)`` would. """ + refuse_on_read_only(simulation, "SimulationBuilder.build_default_simulation") # ``np.arange`` accepts 2.5 or 2.0, and the simulation then fails in # ``sum`` or ``calculate``; ``operator.index`` refuses what ``range`` From 1225e1616c3bd48696f9aa26345b3b67c31ea1c4 Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Mon, 30 Nov 2026 22:04:09 +0400 Subject: [PATCH 09/15] Add failing tests for the rest of review round 3's findings A read-only simulation's stored masked arrays must refuse masking in place. A shallow copy of a top node without children must not count as a new parameter tree. Updating a clone of a node, scale or parameter must not count as a change to the tree it was cloned from, and must leave that tree unmarked. An update to a child added through a shallow-copied top node must be caught. Co-Authored-By: Claude Opus 5.5 --- tests/core/test_read_only_simulation.py | 125 ++++++++++++++++++++++++ 1 file changed, 125 insertions(+) diff --git a/tests/core/test_read_only_simulation.py b/tests/core/test_read_only_simulation.py index 6c552d1c..be77dfca 100644 --- a/tests/core/test_read_only_simulation.py +++ b/tests/core/test_read_only_simulation.py @@ -41,6 +41,7 @@ set_input_dispatch_by_period, set_input_divide_by_period, ) +from policyengine_core.parameters import ParameterNode from policyengine_core.simulations import SimulationBuilder from policyengine_core.variables import Variable @@ -347,6 +348,53 @@ def test_a_formula_writing_into_an_array_it_read_raises(): assert simulation.calculate("salary", PERIOD).tolist() == SALARY +class salary_as_masked_array(Variable): + value_type = float + entity = Person + definition_period = periods.MONTH + label = "Salary, returned as a masked array" + + def formula(person, period, parameters): + return np.ma.masked_array(person("salary", period)) + + +def _assert_mask_refuses_changes(stored) -> None: + assert isinstance(stored, np.ma.MaskedArray) + with pytest.raises(ValueError, match="read-only"): + stored[0] = np.ma.masked + with pytest.raises(ValueError, match="read-only"): + stored.mask = [True, False] + assert not np.ma.getmaskarray(stored).any() + + +@pytest.mark.parametrize( + "masked_salary", + [ + pytest.param(np.ma.masked_array(SALARY), id="no-mask"), + pytest.param(np.ma.masked_array(SALARY, mask=[False, False]), id="mask"), + ], +) +def test_a_masked_array_stored_before_make_read_only_refuses_masking( + shared_system, masked_salary +): + simulation = build_simulation(shared_system) + simulation.set_input("salary", PERIOD, masked_salary) + simulation.make_read_only() + + _assert_mask_refuses_changes(simulation.get_array("salary", PERIOD)) + + +def test_a_masked_array_a_read_only_simulation_calculates_refuses_masking(): + system = CountryTaxBenefitSystem() + system.add_variable(salary_as_masked_array) + simulation = build_simulation(system) + simulation.make_read_only() + + simulation.calculate("salary_as_masked_array", PERIOD) + + _assert_mask_refuses_changes(simulation.get_array("salary_as_masked_array", PERIOD)) + + def _simulation_storing_on_disk(tax_benefit_system) -> Simulation: simulation = build_simulation(tax_benefit_system) with warnings.catch_warnings(): @@ -419,6 +467,19 @@ def test_a_read_only_branch_keeps_its_values_when_its_parent_writes_in_place( # ----- Simulations that are not read-only ----- # +def test_updating_a_clone_of_a_subtree_leaves_the_original_tree_unmarked(): + system = CountryTaxBenefitSystem() + assert not system.parameters.modified + taxes_copy = system.parameters.taxes.clone() + + taxes_copy.income_tax_rate.update(start=INSTANT, value=0.5) + + assert taxes_copy.parent is None + assert not system.parameters.modified + assert not system.parameters.taxes.modified + assert system.parameters.taxes.income_tax_rate(INSTANT) == BASELINE_INCOME_TAX_RATE + + def test_deleting_the_system_of_a_simulation_that_is_not_read_only_still_works( shared_system, ): @@ -605,6 +666,70 @@ def test_a_shallow_copy_of_the_top_node_made_later_is_not_a_parameter_change(): assert np.array_equal(simulation.calculate(output, PERIOD), expected[output]) +def test_a_shallow_copy_of_a_top_node_without_children_is_not_a_parameter_change(): + system = CountryTaxBenefitSystem() + system.parameters = ParameterNode("", data={}) + system._parameters_at_instant_cache = {} + simulation = build_simulation(system) + simulation.make_read_only() + + _give_the_system_a_shallow_copy_of_its_top_node(system) + + assert simulation.calculate("salary", PERIOD).tolist() == SALARY + + +def _update_a_clone_of_a_node(system): + taxes_copy = system.parameters.taxes.clone() + taxes_copy.income_tax_rate.update(start=INSTANT, value=0.5) + + +def _update_a_clone_of_a_scale(system): + scale_copy = system.parameters.taxes.social_security_contribution.clone() + scale_copy.brackets[0].rate.update(start=INSTANT, value=0.5) + + +def _update_a_clone_of_a_parameter(system): + rate_copy = system.parameters.taxes.income_tax_rate.clone() + rate_copy.update(start=INSTANT, value=0.5) + + +@pytest.mark.parametrize( + "update_a_clone", + [ + pytest.param(_update_a_clone_of_a_node, id="node"), + pytest.param(_update_a_clone_of_a_scale, id="scale"), + pytest.param(_update_a_clone_of_a_parameter, id="parameter"), + ], +) +def test_updating_a_clone_of_a_subtree_is_not_a_change_to_the_tree(update_a_clone): + system = CountryTaxBenefitSystem() + simulation = build_simulation(system) + simulation.make_read_only() + + update_a_clone(system) + + assert np.allclose( + simulation.calculate("income_tax", PERIOD), + np.array(SALARY) * BASELINE_INCOME_TAX_RATE, + ) + + +def test_a_change_to_a_child_added_through_a_shallow_copied_top_node_is_caught(): + system = CountryTaxBenefitSystem() + _give_the_system_a_shallow_copy_of_its_top_node(system) + added_node = ParameterNode( + "added_node", data={"rate": {"values": {"2000-01-01": 0.1}}} + ) + system.parameters.add_child("added_node", added_node) + simulation = build_simulation(system) + simulation.make_read_only() + + system.parameters.added_node.rate.update(start=INSTANT, value=0.5) + + with pytest.raises(errors.ReadOnlySimulationError): + simulation.calculate("income_tax", PERIOD) + + def test_making_a_simulation_read_only_again_keeps_the_first_parameter_record(): system = CountryTaxBenefitSystem() simulation = build_simulation(system) From 6db346fd4bd8fee9430634e66f2b1c0f6a7c569b Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Mon, 30 Nov 2026 22:07:14 +0400 Subject: [PATCH 10/15] Close the rest of review round 3's findings - make_non_writable also marks a masked array's mask non-writable, after giving an array with no mask an all-false one, so masking an entry of a stored masked array in place raises. - A read-only simulation identifies its parameter tree by the top node's children mapping, which a shallow copy of the top node shares and a clone does not, so a shallow copy of a top node without children is the same tree. - change_counting_nodes returns every node the top node's children lead to, so a change to a child added through a shallow-copied top node is counted on a node the read-only simulation recorded. - clone() of a node, scale or parameter returns a copy with no parent: a tree of its own, whose changes neither count as changes to the tree it was cloned from nor mark that tree modified or clear its caches. Parameter.update and mark_as_modified work on a parameter without a parent. Co-Authored-By: Claude Opus 5.5 --- .../data_storage/non_writable.py | 13 ++++- policyengine_core/parameters/parameter.py | 10 +++- .../parameters/parameter_node.py | 45 +++++++++------ .../parameters/parameter_scale.py | 3 + policyengine_core/simulations/simulation.py | 55 +++++++++++-------- .../taxbenefitsystems/tax_benefit_system.py | 9 +-- 6 files changed, 88 insertions(+), 47 deletions(-) diff --git a/policyengine_core/data_storage/non_writable.py b/policyengine_core/data_storage/non_writable.py index d96aed5b..ccf3ad10 100644 --- a/policyengine_core/data_storage/non_writable.py +++ b/policyengine_core/data_storage/non_writable.py @@ -6,8 +6,15 @@ def make_non_writable(value) -> None: The flag is set on the array object itself, so it holds for every holder of that object: a later in-place write through it raises ``ValueError``. - A masked array's mask is a separate array and stays writable. Values that + A masked array's mask is a separate array, so it is marked too, after + giving an array with no mask an all-false one of its own: otherwise + masking an entry in place would make a new, writable mask. Values that are not numpy arrays are left as they are. """ - if isinstance(value, numpy.ndarray): - value.flags.writeable = False + if not isinstance(value, numpy.ndarray): + return + value.flags.writeable = False + if isinstance(value, numpy.ma.MaskedArray): + if value._mask is numpy.ma.nomask: + value.mask = numpy.ma.make_mask_none(value.shape, value.dtype) + value._mask.flags.writeable = False diff --git a/policyengine_core/parameters/parameter.py b/policyengine_core/parameters/parameter.py index 171665c1..38bc642d 100644 --- a/policyengine_core/parameters/parameter.py +++ b/policyengine_core/parameters/parameter.py @@ -127,8 +127,11 @@ def __eq__(self, other): return (self.name == other.name) and (self.values_list == other.values_list) def clone(self): + """Copy this parameter and its values, with no parent (see + ``ParameterNode.clone``).""" clone = empty_clone(self) clone.__dict__ = self.__dict__.copy() + clone.parent = None # Own dict, shared values: see ParameterAtInstant.clone. clone.metadata = copy.copy(self.metadata) @@ -214,7 +217,9 @@ def update( self.values_list = new_values - self.parent.clear_parent_cache() + # A parameter cloned on its own has no parent (see ``clone``). + if getattr(self, "parent", None) is not None: + self.parent.clear_parent_cache() self.mark_as_modified() @@ -222,7 +227,8 @@ def update( def mark_as_modified(self): self.modified = True - self.parent.mark_as_modified() + if getattr(self, "parent", None) is not None: + self.parent.mark_as_modified() def get_descendants(self): return iter(()) diff --git a/policyengine_core/parameters/parameter_node.py b/policyengine_core/parameters/parameter_node.py index 5a77bbc3..ea4b3f13 100644 --- a/policyengine_core/parameters/parameter_node.py +++ b/policyengine_core/parameters/parameter_node.py @@ -93,29 +93,34 @@ def _clear_at_instant_caches_upward(node) -> None: node = getattr(node, "parent", None) -def change_counting_node(parameters): - """The node whose ``_change_count`` counts the changes made in the tree +def change_counting_nodes(parameters) -> tuple: + """The nodes whose ``_change_count`` count the changes made in the tree under ``parameters``. ``mark_as_modified`` adds one to the count of every node it passes on its way up the ``parent`` links, so the node at the top of those links counts - every change made below it. That is normally ``parameters`` itself. But a + every change made below it. For each child of ``parameters`` this follows + its ``parent`` links to the top, and returns each node reached once, in + the order of the children. That is normally just ``parameters``. But a shallow copy of a tree's top node (policyengine-us makes one for each traced simulation) shares the original's children, whose ``parent`` is - still the original, so changes made through them are counted on the - original. This therefore goes up the ``parent`` links from one of - ``parameters``' children. It returns ``parameters`` itself when it has no - children, or is not a parameter node. + still the original, while a child added through the copy has the copy as + its parent. Empty when ``parameters`` has no children (or is not a + parameter node): such a tree holds no parameter values. """ children = getattr(parameters, "children", None) if not children: - return parameters - node = next(iter(children.values())) - visited = set() - while getattr(node, "parent", None) is not None and id(node) not in visited: - visited.add(id(node)) - node = node.parent - return node + return () + counting_nodes = [] + for child in children.values(): + node = child + visited = set() + while getattr(node, "parent", None) is not None and id(node) not in visited: + visited.add(id(node)) + node = node.parent + if not any(node is counting_node for counting_node in counting_nodes): + counting_nodes.append(node) + return tuple(counting_nodes) class _AtInstantCache(dict): @@ -160,8 +165,8 @@ class ParameterNode(AtInstantLike): ``mark_as_modified`` that reaches the node (``Parameter.update`` calls it, and so do the scale and node equivalents) adds one, as does ``TaxBenefitSystem.modify_parameters`` for the tree it passes on. A - read-only simulation compares its tree's count, on the node - ``change_counting_node`` finds, with the one it recorded (see + read-only simulation compares the counts on the nodes + ``change_counting_nodes`` finds with the ones it recorded (see ``Simulation.make_read_only``). An edit that bypasses those, such as assigning ``values_list`` or calling ``add_child`` directly, adds nothing.""" @@ -379,8 +384,16 @@ def get_descendants(self) -> Iterable[Union["ParameterNode", Parameter]]: yield from child.get_descendants() def clone(self) -> "ParameterNode": + """Copy this node and everything below it. + + The copy has no parent: it is the top node of a tree of its own, so + changes made in it do not mark the tree this node is in modified, nor + clear its caches. Cloning the node holding this one sets the parent + of the copy it makes. + """ clone = commons.empty_clone(self) clone.__dict__ = self.__dict__.copy() + clone.parent = None # Own dict, shared values: see ParameterAtInstant.clone. clone.metadata = copy.copy(self.metadata) diff --git a/policyengine_core/parameters/parameter_scale.py b/policyengine_core/parameters/parameter_scale.py index 507d0151..b838013a 100644 --- a/policyengine_core/parameters/parameter_scale.py +++ b/policyengine_core/parameters/parameter_scale.py @@ -117,8 +117,11 @@ def mark_as_modified(self): self.parent.mark_as_modified() def clone(self) -> "ParameterScale": + """Copy this scale and its brackets, with no parent (see + ``ParameterNode.clone``).""" clone = commons.empty_clone(self) clone.__dict__ = self.__dict__.copy() + clone.parent = None clone.brackets = [bracket.clone() for bracket in self.brackets] for bracket in clone.brackets: diff --git a/policyengine_core/simulations/simulation.py b/policyengine_core/simulations/simulation.py index aeb96c84..2175ce2b 100644 --- a/policyengine_core/simulations/simulation.py +++ b/policyengine_core/simulations/simulation.py @@ -180,7 +180,7 @@ def _latest_input_key(period: Period, definition_period: str) -> tuple: from policyengine_core.variables import Variable, QuantityType from policyengine_core.reforms.reform import Reform from policyengine_core.parameters import get_parameter -from policyengine_core.parameters.parameter_node import change_counting_node +from policyengine_core.parameters.parameter_node import change_counting_nodes from policyengine_core.simulations.simulation_macro_cache import ( SimulationMacroCache, ) @@ -759,8 +759,9 @@ class Simulation: tax-benefit system. Set by :meth:`make_read_only`, and copied to nothing else: a clone or branch of a read-only simulation is not read-only.""" - # The node counting changes to the parameter tree (see - # ``change_counting_node``) and its count when ``make_read_only`` ran. + # The parameter tree's top node's ``children`` mapping, and the nodes + # counting changes to the tree (see ``change_counting_nodes``) with their + # counts, when ``make_read_only`` ran. _read_only_parameters: Optional[Tuple[Any, int]] = None # The temporary folder this simulation made for the values it stores on @@ -1024,14 +1025,14 @@ def make_read_only(self) -> None: simulation's array that a formula returned as it was. An array it still shares with the simulation it was branched from is copied first. - - Its parameter tree's change count is recorded, on the node that - counts the tree's changes (see ``change_counting_node``: normally - the tree's top node, or the original a shallow copy of it shares - children with). Its next calculation, including one answered from - what it holds, raises ``ReadOnlySimulationError`` once that count + - Its parameter tree's change counts are recorded, on the nodes + that count the tree's changes (see ``change_counting_nodes``: + normally the tree's top node, or the original a shallow copy of it + shares children with). Its next calculation, including one answered + from what it holds, raises ``ReadOnlySimulationError`` once a count has moved (an update anywhere in the tree, made through any simulation or system that shares it) or its system has another - tree. + tree. A clone of part of the tree is a tree of its own. - ``get_branch`` with a name it has not registered returns a new branch every time and keeps it out of ``branches``, so nothing done through the branch stays in this simulation. The branch is part of @@ -1070,10 +1071,13 @@ def make_read_only(self) -> None: """ if self.read_only: return - counting_node = change_counting_node(self.tax_benefit_system.parameters) + parameters = self.tax_benefit_system.parameters self._read_only_parameters = ( - counting_node, - getattr(counting_node, "_change_count", 0), + getattr(parameters, "children", None), + tuple( + (counting_node, getattr(counting_node, "_change_count", 0)) + for counting_node in change_counting_nodes(parameters) + ), ) self.read_only = True for population in getattr(self, "populations", {}).values(): @@ -1084,22 +1088,29 @@ def make_read_only(self) -> None: def _refuse_if_parameters_changed(self) -> None: """Raise ``ReadOnlySimulationError`` if the parameters a read-only - simulation recorded have changed since (see :meth:`make_read_only`).""" - recorded_counting_node, recorded_change_count = self._read_only_parameters - counting_node = change_counting_node(self.tax_benefit_system.parameters) - if counting_node is not recorded_counting_node: + simulation recorded have changed since (see :meth:`make_read_only`). + + The tree is the same while its top node holds the same ``children`` + mapping: a shallow copy of the top node (policyengine-us makes one + for each traced simulation) holds the original's, while a clone or + another tree holds its own. + """ + recorded_children, recorded_change_counts = self._read_only_parameters + parameters = self.tax_benefit_system.parameters + if getattr(parameters, "children", None) is not recorded_children: raise ReadOnlySimulationError( "The tax-benefit system of this read-only simulation has a " "different parameter tree from the one it had when " "make_read_only() was called, so the values it holds may no " "longer match its parameters." ) - if getattr(counting_node, "_change_count", 0) != recorded_change_count: - raise ReadOnlySimulationError( - "A parameter of this read-only simulation changed after " - "make_read_only() was called, so the values it holds may no " - "longer match its parameters." - ) + for counting_node, recorded_change_count in recorded_change_counts: + if getattr(counting_node, "_change_count", 0) != recorded_change_count: + raise ReadOnlySimulationError( + "A parameter of this read-only simulation changed after " + "make_read_only() was called, so the values it holds may " + "no longer match its parameters." + ) def apply_reform(self, reform: Union[tuple, Reform]): refuse_on_read_only(self, "apply_reform") diff --git a/policyengine_core/taxbenefitsystems/tax_benefit_system.py b/policyengine_core/taxbenefitsystems/tax_benefit_system.py index 300786d5..ba1980a7 100644 --- a/policyengine_core/taxbenefitsystems/tax_benefit_system.py +++ b/policyengine_core/taxbenefitsystems/tax_benefit_system.py @@ -40,7 +40,7 @@ ParameterNodeAtInstant, Parameter, ) -from policyengine_core.parameters.parameter_node import change_counting_node +from policyengine_core.parameters.parameter_node import change_counting_nodes from policyengine_core.parameters.operations.homogenize_parameters import ( homogenize_parameter_structures, ) @@ -844,9 +844,10 @@ def modify_parameters( # ``update`` (assigning ``values_list``, say), so count a # change where ``mark_as_modified`` would (see # ``ParameterNode._change_count``). - counting_node = change_counting_node(parameters) - if isinstance(counting_node, ParameterNode): - counting_node._change_count += 1 + for counting_node in change_counting_nodes(parameters): + counting_node._change_count = ( + getattr(counting_node, "_change_count", 0) + 1 + ) if not isinstance(reform_parameters, ParameterNode): return ValueError( "modifier_function {} in module {} must return a ParameterNode".format( From a91a76d8c0e8a9f50b03d17f834eddfcbb15e38c Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Mon, 30 Nov 2026 22:08:15 +0400 Subject: [PATCH 11/15] Add a changelog entry for parentless parameter clones Co-Authored-By: Claude Opus 5.5 --- changelog.d/parameter-clone-without-parent.changed.md | 1 + 1 file changed, 1 insertion(+) create mode 100644 changelog.d/parameter-clone-without-parent.changed.md diff --git a/changelog.d/parameter-clone-without-parent.changed.md b/changelog.d/parameter-clone-without-parent.changed.md new file mode 100644 index 00000000..825fe3b1 --- /dev/null +++ b/changelog.d/parameter-clone-without-parent.changed.md @@ -0,0 +1 @@ +`clone()` of a parameter node, scale or parameter now returns a copy with no parent, so changes made in a cloned part of a parameter tree no longer mark the tree it was cloned from as modified or clear that tree's caches. From 94d50302326b9ded3b70c003db16c3766d2ef464 Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Mon, 30 Nov 2026 22:56:39 +0400 Subject: [PATCH 12/15] Purge spiral values through a stand-in holder's delete_arrays purge_cache_of_invalid_values called Holder._delete_arrays, which a holder that is not core's (the stand-in in test_purge_cache_of_invalid_values_without_fast_cache_attribute) does not have. It now uses _delete_arrays when the holder has it, and the public delete_arrays otherwise. Co-Authored-By: Claude Opus 5.5 --- policyengine_core/simulations/simulation.py | 10 ++++++++-- 1 file changed, 8 insertions(+), 2 deletions(-) diff --git a/policyengine_core/simulations/simulation.py b/policyengine_core/simulations/simulation.py index 2175ce2b..ac5dcaff 100644 --- a/policyengine_core/simulations/simulation.py +++ b/policyengine_core/simulations/simulation.py @@ -2373,8 +2373,14 @@ def purge_cache_of_invalid_values(self) -> None: return for _name, _period in invalidated_caches: holder = self.get_holder(_name) - # Part of a calculation, so a read-only simulation runs it too. - holder._delete_arrays(_period) + # Part of a calculation, so a read-only simulation runs it too, + # through the holder's method that does not refuse. A holder that + # is not core's (a test's stand-in, say) may only have the public + # one. + delete_arrays = getattr(holder, "_delete_arrays", None) + if delete_arrays is None: + delete_arrays = holder.delete_arrays + delete_arrays(_period) if _fast_cache is not None: _fast_cache.pop((_name, _period), None) self.invalidated_caches = set() From e29f6cd9dfaf2aa1bf2f0212cb18d275fddac6e2 Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Tue, 1 Dec 2026 22:45:53 +0400 Subject: [PATCH 13/15] Add failing tests for review round 4 findings SimulationBuilder.finalize_variables_init must refuse a read-only simulation's population before changing it, a value a read-only simulation reads from the macro cache must be non-writable, and assigning read_only directly must be refused. Co-Authored-By: Claude Opus 5.5 --- tests/core/test_read_only_simulation.py | 53 +++++++++++++++++++++++++ 1 file changed, 53 insertions(+) diff --git a/tests/core/test_read_only_simulation.py b/tests/core/test_read_only_simulation.py index be77dfca..a4785e4d 100644 --- a/tests/core/test_read_only_simulation.py +++ b/tests/core/test_read_only_simulation.py @@ -22,6 +22,7 @@ from __future__ import annotations import copy +import types import warnings import numpy as np @@ -43,6 +44,9 @@ ) from policyengine_core.parameters import ParameterNode from policyengine_core.simulations import SimulationBuilder +from policyengine_core.simulations.simulation_macro_cache import ( + SimulationMacroCache, +) from policyengine_core.variables import Variable PERIOD = "2022-01" @@ -227,9 +231,19 @@ def test_a_clone_of_a_read_only_simulation_is_not_read_only(shared_system): ), id="set_input_dispatch_by_period", ), + pytest.param( + lambda simulation: _finalize_builder_persons_into(simulation), + id="builder-finalize_variables_init", + ), ] +def _finalize_builder_persons_into(simulation) -> None: + builder = SimulationBuilder() + builder.add_person_entity(simulation.persons.entity, {"x": {}, "y": {}, "z": {}}) + builder.finalize_variables_init(simulation.persons) + + def population_structure(simulation) -> dict: """Each population's size, IDs and memberships.""" return { @@ -533,6 +547,45 @@ def test_a_parents_reform_still_clears_the_branches_of_a_read_only_branch(): read_only_branch.calculate("income_tax", PERIOD) +def test_a_value_read_from_the_macro_cache_is_non_writable(tmp_path, monkeypatch): + system = CountryTaxBenefitSystem() + simulation = build_simulation(system) + simulation.make_read_only() + # Serve income_tax from a macro-cache file, as a simulation built over a + # dataset would. + cache_file_path = tmp_path / "income_tax.h5" + cache_file_path.touch() + simulation.macro_cache_read = True + simulation.dataset = types.SimpleNamespace( + file_path=tmp_path / "dataset.h5", name="dataset" + ) + monkeypatch.setattr(Simulation, "check_macro_cache", lambda *arguments: True) + monkeypatch.setattr(SimulationMacroCache, "set_cache_path", lambda *arguments: None) + monkeypatch.setattr( + SimulationMacroCache, "get_cache_path", lambda self: cache_file_path + ) + monkeypatch.setattr( + SimulationMacroCache, + "get_cache_value", + lambda self, path: np.array([600.0, 375.0], dtype=np.float32), + ) + + income_tax = simulation.calculate("income_tax", PERIOD) + + assert income_tax.tolist() == [600.0, 375.0] + assert not income_tax.flags.writeable + + +def test_assigning_read_only_directly_is_refused(shared_system): + simulation = build_simulation(shared_system) + + with pytest.raises(AttributeError): + simulation.read_only = True + + assert simulation.read_only is False + assert simulation.calculate("salary", PERIOD).tolist() == SALARY + + # ----- Parameter changes ----- # From 4fb4311940b32659f20a4a6df40c774a8872238e Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Tue, 1 Dec 2026 22:46:30 +0400 Subject: [PATCH 14/15] Close review round 4's findings - SimulationBuilder.finalize_variables_init refuses a read-only simulation's population before changing it. - A value a read-only simulation reads from the macro cache is marked non-writable, as one read back from disk storage is. - read_only is a property over a private flag that only make_read_only sets, so assigning it directly is refused instead of leaving a simulation marked read-only with no parameter record. - The parameter record's type annotation matches what it holds, the shared-array copy in a read-only storage says it is not reached today, and the API page and changelog entry list every refused operation and say that parameter changes are detected at the next calculation. Co-Authored-By: Claude Opus 5.5 --- changelog.d/read-only-simulations.added.md | 2 +- docs/python_api/simulations.md | 27 ++++++++++++------- .../data_storage/in_memory_storage.py | 3 +++ policyengine_core/simulations/simulation.py | 25 ++++++++++++----- .../simulations/simulation_builder.py | 6 +++++ 5 files changed, 46 insertions(+), 17 deletions(-) diff --git a/changelog.d/read-only-simulations.added.md b/changelog.d/read-only-simulations.added.md index 666e1007..5bdbeec3 100644 --- a/changelog.d/read-only-simulations.added.md +++ b/changelog.d/read-only-simulations.added.md @@ -1 +1 @@ -Added `Simulation.make_read_only()`: a read-only simulation still calculates and keeps new values, but refuses input, array, parameter and system changes with `ReadOnlySimulationError`, stores only non-writable arrays, and makes private branches that are never kept in its `branches`. +Added `Simulation.make_read_only()`: a read-only simulation still calculates and keeps new values, refuses changes to its inputs, stored arrays and tax-benefit system with `ReadOnlySimulationError`, raises on its next calculation after a parameter change, stores only non-writable arrays, and makes private branches that are never kept in its `branches`. diff --git a/docs/python_api/simulations.md b/docs/python_api/simulations.md index ade143bd..0aaf4d8b 100644 --- a/docs/python_api/simulations.md +++ b/docs/python_api/simulations.md @@ -16,15 +16,24 @@ The `policyengine_core.simulations` module contains the definition of `Simulatio `Simulation.make_read_only()` makes a simulation refuse every change to its inputs, stored values and tax-benefit system, while it still calculates and -keeps values it does not hold yet. `set_input`, `delete_arrays`, -`drop_computed_arrays`, `apply_reform`, `subsample`, `build_from_dataset`, -`build_from_populations` and assigning `tax_benefit_system` raise -`ReadOnlySimulationError`. Every array it stores is non-writable, so a formula -that writes in place into an array it read raises numpy's `ValueError`. A -parameter change after `make_read_only()` makes its next calculation raise -`ReadOnlySimulationError`. `get_branch` with a new name returns a branch that is -not kept in `branches` and is not read-only itself. The method's docstring -lists what is not detected. +keeps values it does not hold yet. + +- `set_input` and `delete_arrays` (on the simulation or a holder), + `drop_computed_arrays`, `invalidate_cache_entry`, `apply_reform`, + `subsample`, `build_from_dataset`, `build_from_populations`, + `SimulationBuilder` building into it, the `set_input_dispatch_by_period` and + `set_input_divide_by_period` helpers, and assigning or deleting + `tax_benefit_system` raise `ReadOnlySimulationError`. +- Every array it stores, reads back from disk storage or reads from the macro + cache is non-writable, so a formula that writes in place into an array it + read raises numpy's `ValueError`. +- A parameter change after `make_read_only()` is not refused, since other + simulations may share the parameter tree; the read-only simulation's next + calculation raises `ReadOnlySimulationError` instead. +- `get_branch` with a new name returns a branch that is not kept in `branches` + and is not read-only itself. + +The method's docstring lists what is not detected. ## Microsimulation diff --git a/policyengine_core/data_storage/in_memory_storage.py b/policyengine_core/data_storage/in_memory_storage.py index 9d440803..73f84232 100644 --- a/policyengine_core/data_storage/in_memory_storage.py +++ b/policyengine_core/data_storage/in_memory_storage.py @@ -212,6 +212,9 @@ def get(self, period: Period, branch_name: str = "default") -> ArrayLike: # First read of an array shared by ``clone``: from here on the # caller may write into it, so it needs to be this storage's own. values = values.copy() + # Not reached today, since ``make_read_only`` copies every shared + # array and only ``clone`` shares them, in a storage that is not + # read-only; kept so the rule holds if that changes. if self.read_only: make_non_writable(values) self._arrays[key] = values diff --git a/policyengine_core/simulations/simulation.py b/policyengine_core/simulations/simulation.py index ac5dcaff..bf1352d6 100644 --- a/policyengine_core/simulations/simulation.py +++ b/policyengine_core/simulations/simulation.py @@ -754,15 +754,23 @@ class Simulation: start_instant: str = None """The earliest data input instant of the simulation.""" - read_only: bool = False - """Whether the simulation refuses changes to its inputs, stored values and - tax-benefit system. Set by :meth:`make_read_only`, and copied to nothing - else: a clone or branch of a read-only simulation is not read-only.""" + # Set by ``make_read_only``; see ``read_only``. + _read_only: bool = False # The parameter tree's top node's ``children`` mapping, and the nodes # counting changes to the tree (see ``change_counting_nodes``) with their # counts, when ``make_read_only`` ran. - _read_only_parameters: Optional[Tuple[Any, int]] = None + _read_only_parameters: Optional[ + Tuple[Optional[Dict[str, Any]], Tuple[Tuple[Any, int], ...]] + ] = None + + @property + def read_only(self) -> bool: + """Whether the simulation refuses changes to its inputs, stored values + and tax-benefit system. Only :meth:`make_read_only` sets it, and it is + copied to nothing else: a clone or branch of a read-only simulation is + not read-only.""" + return self._read_only # The temporary folder this simulation made for the values it stores on # disk, if it made one (see ``data_storage_dir``). @@ -1079,7 +1087,7 @@ def make_read_only(self) -> None: for counting_node in change_counting_nodes(parameters) ), ) - self.read_only = True + self._read_only = True for population in getattr(self, "populations", {}).values(): for holder in population._holders.values(): holder._make_read_only() @@ -1951,6 +1959,9 @@ def _calculate(self, variable_name: str, period: Period = None) -> ArrayLike: sequence_number = next_sequence_number() holder._record_store(period, sequence_number) self._get_store_history().record_unknown_sources(sequence_number) + if self.read_only: + # As a value read back from disk storage is. + make_non_writable(value) return value if variable.requires_computation_after is not None: @@ -3229,7 +3240,7 @@ def clone( "branches", "_fast_cache", # A copy of a read-only simulation is not read-only. - "read_only", + "_read_only", "_read_only_parameters", ): new_dict[key] = value diff --git a/policyengine_core/simulations/simulation_builder.py b/policyengine_core/simulations/simulation_builder.py index 5ac91606..5f9f9db1 100644 --- a/policyengine_core/simulations/simulation_builder.py +++ b/policyengine_core/simulations/simulation_builder.py @@ -714,6 +714,12 @@ def add_variable_value( def finalize_variables_init(self, population): # Due to set_input mechanism, we must bufferize all inputs, then actually set them, # so that the months are set first and the years last. + # A read-only simulation's population is refused before anything in it + # changes (see ``Simulation.make_read_only``). + refuse_on_read_only( + getattr(population, "simulation", None), + "SimulationBuilder.finalize_variables_init", + ) plural_key = population.entity.plural if plural_key in self.entity_counts: population.count = self.get_count(plural_key) From 7d60a066b88680082ce9e175ee397faef5fda75f Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Tue, 1 Dec 2026 22:47:00 +0400 Subject: [PATCH 15/15] Cover calculate_add, calculate_divide, Microsimulation and pickling Tests that pass already: a read-only simulation's ADD and DIVIDE results are non-writable and equal a plain simulation's, a read-only Microsimulation gives the same weighted totals, and a pickled read-only simulation stays read-only with non-writable arrays. The module's docstring now lists every refused operation. Co-Authored-By: Claude Opus 5.5 --- tests/core/test_read_only_simulation.py | 77 ++++++++++++++++++++++--- 1 file changed, 70 insertions(+), 7 deletions(-) diff --git a/tests/core/test_read_only_simulation.py b/tests/core/test_read_only_simulation.py index a4785e4d..67782495 100644 --- a/tests/core/test_read_only_simulation.py +++ b/tests/core/test_read_only_simulation.py @@ -4,13 +4,15 @@ keeps them. It refuses everything that would change its inputs, its stored values or its tax-benefit system: -- ``set_input`` (on the simulation or a holder), ``delete_arrays`` (on the - simulation or a holder), ``drop_computed_arrays``, ``apply_reform``, - ``subsample``, ``build_from_dataset``, ``build_from_populations`` and - assigning ``tax_benefit_system`` raise ``ReadOnlySimulationError`` and - change nothing; -- every array it stores is non-writable, in memory or on disk, so writing - into one in place raises numpy's ``ValueError``; +- ``set_input`` and ``delete_arrays`` (on the simulation or a holder), + ``drop_computed_arrays``, ``invalidate_cache_entry``, ``apply_reform``, + ``subsample``, ``build_from_dataset``, ``build_from_populations``, + ``SimulationBuilder`` building into it, the ``set_input`` helpers, and + assigning or deleting ``tax_benefit_system`` raise + ``ReadOnlySimulationError`` and change nothing; +- every array it stores is non-writable, in memory or on disk, and so is a + value it reads from the macro cache, so writing into one in place raises + numpy's ``ValueError``; - a parameter change after ``make_read_only()`` (an update anywhere in its parameter tree, or a new tree) makes its next calculation raise. @@ -22,6 +24,7 @@ from __future__ import annotations import copy +import pickle import types import warnings @@ -31,6 +34,7 @@ from policyengine_core import errors, periods from policyengine_core.country_template import ( CountryTaxBenefitSystem, + Microsimulation, Simulation, ) from policyengine_core.country_template.entities import Person @@ -900,6 +904,65 @@ def test_a_read_only_simulation_calculates_new_values_and_keeps_them(shared_syst assert np.array_equal(simulation.get_array(output, PERIOD), result) +def test_values_calculate_add_and_calculate_divide_keep_are_non_writable( + shared_system, +): + plain_simulation = build_simulation(shared_system) + simulation = build_simulation(shared_system) + simulation.make_read_only() + + results = { + "salary over the year": simulation.calculate("salary", "2022"), + "salary summed": simulation.calculate_add("salary", "2022"), + "housing_tax over a month": simulation.calculate_divide("housing_tax", PERIOD), + } + + assert np.array_equal( + results["salary over the year"], plain_simulation.calculate("salary", "2022") + ) + assert np.array_equal( + results["salary summed"], plain_simulation.calculate_add("salary", "2022") + ) + assert np.array_equal( + results["housing_tax over a month"], + plain_simulation.calculate_divide("housing_tax", PERIOD), + ) + for description, result in results.items(): + assert not result.flags.writeable, description + for key, array in stored_arrays(simulation).items(): + assert not array.flags.writeable, key + + +def test_a_read_only_microsimulation_gives_the_same_weighted_results(): + plain_microsimulation = Microsimulation() + read_only_microsimulation = Microsimulation() + read_only_microsimulation.make_read_only() + + for variable_name in ("disposable_income", "income_tax", "housing_tax"): + period = "2022" if variable_name == "housing_tax" else PERIOD + assert ( + read_only_microsimulation.calculate(variable_name, period).sum() + == plain_microsimulation.calculate(variable_name, period).sum() + ) + for key, array in stored_arrays(read_only_microsimulation).items(): + assert not array.flags.writeable, key + + +def test_a_pickled_read_only_simulation_stays_read_only(shared_system): + simulation = build_simulation(shared_system) + expected = simulation.calculate("disposable_income", PERIOD).copy() + simulation.make_read_only() + + restored = pickle.loads(pickle.dumps(simulation)) + + assert restored.read_only is True + for key, array in stored_arrays(restored).items(): + assert not array.flags.writeable, key + with pytest.raises(errors.ReadOnlySimulationError): + restored.set_input("salary", PERIOD, OTHER_SALARY) + assert np.array_equal(restored.calculate("disposable_income", PERIOD), expected) + + class spiral_this_month(Variable): value_type = int entity = Person