Skip to content

Add read-only simulations - #672

Merged
anth-volk merged 15 commits into
masterfrom
read-only-simulations
Dec 1, 2026
Merged

anth-volk merged 15 commits into
masterfrom
read-only-simulations

Conversation

@anth-volk

@anth-volk anth-volk commented Nov 30, 2026 •

Copy link
Copy Markdown
Collaborator

Fixes #673

What this adds

Simulation.make_read_only() makes a simulation refuse every change to its inputs, stored values and tax-benefit system, while it still calculates values it does not hold yet and keeps them. It is groundwork for a read-only current-law copy that reform runs read current-law values from; the declared reads and stored current-law values that use it follow in later PRs.

On a read-only simulation:

  • Refused operations. 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 (including finalize_variables_init on its population), the set_input_dispatch_by_period and set_input_divide_by_period helpers, and assigning or deleting tax_benefit_system raise the new ReadOnlySimulationError and change nothing.
  • Non-writable arrays. Every array it stores is non-writable: those it holds when it is made read-only, those it calculates, those its disk storage reads back, values it reads from the macro cache, the fast cache, and a masked array's mask. An in-place write into one, as a formula that modifies an array it read would make, raises numpy's ValueError. Arrays it still shares with the simulation it was branched from are copied first.
  • Parameter changes. Each parameter tree counts the changes mark_as_modified records (Parameter.update and the node and scale equivalents), and TaxBenefitSystem.modify_parameters counts one for the tree it passes on. The read-only simulation records the counts and raises ReadOnlySimulationError on its next calculation, including one answered from the fast cache, once a count has moved or its system holds another tree. This also works when the top node is a shallow copy that shares the original's children, as policyengine-us makes for each traced simulation (isolate_parameter_tracing): the tree is identified by its top node's children mapping, and changes are counted on every node the children's parent links lead to (change_counting_nodes).
  • Branches. get_branch with a new name returns a branch that is not kept in branches, so nothing done through it stays in the read-only simulation. The branch is part of the simulation, reads its values, and is not read-only itself: it takes inputs and keeps branches of its own. A branch registered before make_read_only(), such as a reform simulation's baseline, is returned as it is.
  • Copied to nothing else. read_only is a property that only make_read_only() sets. A clone or branch of a read-only simulation is not read-only. As a registered branch, a read-only simulation keeps what it holds when its parent applies a reform; its own branches are cleared as usual.

Changes for every simulation

  • clone() of a parameter node, scale or parameter returns a copy with no parent. Changes made in a cloned part of a tree no longer mark the tree it was cloned from as modified or clear that tree's caches. Parameter.update and mark_as_modified work on a parameter without a parent. (Changelog entry parameter-clone-without-parent.changed.md.)
  • Simulation.tax_benefit_system is a property over the instance's __dict__, so clone, pickling and copying are unchanged.
  • Core's own clean-up after a spiral uses the new internal Holder._delete_arrays and Simulation._invalidate_cache_entry.

Not detected (stated in make_read_only's docstring)

  • Formula changes made in place on a tax-benefit system object shared with the read-only simulation (neutralize_variable, update_variable, add_variable).
  • Parameter edits that record no change: assigning values_list or a ParameterAtInstant's value, or add_child, outside modify_parameters.
  • Writes through a holder's low-level _set or put_in_cache, or straight into storage.
  • The populations' structure arrays (IDs, memberships and roles), which clones and branches share.
  • Writes through a view of a stored array taken before make_read_only().
  • Marking is done on the array object itself, so another simulation or caller holding the same object sees it as non-writable too.
  • After pickling or deep-copying, a value kept only in the fast cache comes back writable.
  • Because branches are private, a second get_branch with the same name, including one when core runs a calculation again after an input change, gets a new branch without what was set on the first.

Checks

  • Tests. tests/core/test_read_only_simulation.py, 77 tests. Each test of new behaviour was added and seen to fail before the change that makes it pass (one failing-test commit before each fix commit); the last commit adds three tests of behaviour that already held (ADD and DIVIDE results, Microsimulation, pickling). I ran only that file locally, plus the one existing test CI reported failing, not the full suite.
  • policyengine-us main (c1fea42a; spm.py is unchanged at c5385383), year 2026, household_net_income and .py's output variables, on subsamples of the default dataset made read-only after they were built:
    • 300 and 3,000 households: no formula wrote in place into an array it read, and no change was refused.
    • A plain run that hashed every array when stored and again at the end: none of 31,527 arrays changed after being stored.
    • A sweep of 7,861 variables on a household gave the same values as a plain simulation, except eight marginal-rate variables. Those raise KeyError because four policyengine-us formulas del simulation.branches[name] after get_branch; a policyengine-us change to branches.pop(name, None) is in progress.
  • Cost (2,000 households, retired instructions per run, since load on the machine made CPU seconds vary by about 25% between identical runs):
    • Read-only off: 615–616 G instructions, against 620–623 G on master, so no measurable change.
    • Read-only on: 628–631 G, about 2% more for the whole run. make_read_only() took under 1 ms.
    • Outputs were identical in every run.
    • Measured at e5973b2b to eeb3869b; later commits change only the refusals and the parameter check.
  • Review. Four adversarial review rounds, each followed by fixes with failing tests first. The fourth round found two low-priority bugs, both fixed: SimulationBuilder.finalize_variables_init changed a read-only simulation's population before refusing, and values read from the macro cache came back writable. From its code-quality findings, read_only became a property, the parameter record's type annotation was corrected, the docs and changelog now list every refused operation, and tests now cover ADD and DIVIDE results, Microsimulation and pickling. Its remaining suggestion, a small named type for the parameter record, is not done. The fixes after the fourth round were not reviewed again.
  • Not run: make documentation.

Overlapping open PRs

These overlap textually; whichever merges second resolves the conflicts.

🤖 Generated with Claude Code

anth-volk and others added 15 commits November 28, 2026 00:52
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 <noreply@anthropic.com>
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 <noreply@anthropic.com>
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 <noreply@anthropic.com>
- 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 <noreply@anthropic.com>
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 <noreply@anthropic.com>
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 <noreply@anthropic.com>
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 <noreply@anthropic.com>
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 <noreply@anthropic.com>
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 <noreply@anthropic.com>
- 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 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
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 <noreply@anthropic.com>
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 <noreply@anthropic.com>
- 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 <noreply@anthropic.com>
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 <noreply@anthropic.com>
@anth-volk
anth-volk marked this pull request as ready for review December 1, 2026 19:59
@anth-volk
anth-volk merged commit 887e44a into master Dec 1, 2026
19 checks passed
@anth-volk
anth-volk deleted the read-only-simulations branch December 1, 2026 19:59
anth-volk added a commit that referenced this pull request Dec 1, 2026
Brings in the merged #672 (read-only
simulations, final head 7d60a06) and the 3.39.0 release commit.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Let a simulation be made read-only

1 participant