Repository navigation
Add read-only simulations - #672
Merged
Merged
Conversation
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
marked this pull request as ready for review
December 1, 2026 19:59
This was referenced Dec 1, 2026
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
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:
set_inputanddelete_arrays(on the simulation or a holder),drop_computed_arrays,invalidate_cache_entry,apply_reform,subsample,build_from_dataset,build_from_populations,SimulationBuilderbuilding into it (includingfinalize_variables_initon its population), theset_input_dispatch_by_periodandset_input_divide_by_periodhelpers, and assigning or deletingtax_benefit_systemraise the newReadOnlySimulationErrorand change nothing.ValueError. Arrays it still shares with the simulation it was branched from are copied first.mark_as_modifiedrecords (Parameter.updateand the node and scale equivalents), andTaxBenefitSystem.modify_parameterscounts one for the tree it passes on. The read-only simulation records the counts and raisesReadOnlySimulationErroron 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'schildrenmapping, and changes are counted on every node the children'sparentlinks lead to (change_counting_nodes).get_branchwith a new name returns a branch that is not kept inbranches, 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 beforemake_read_only(), such as a reform simulation'sbaseline, is returned as it is.read_onlyis a property that onlymake_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.updateandmark_as_modifiedwork on a parameter without a parent. (Changelog entryparameter-clone-without-parent.changed.md.)Simulation.tax_benefit_systemis a property over the instance's__dict__, soclone, pickling and copying are unchanged.Holder._delete_arraysandSimulation._invalidate_cache_entry.Not detected (stated in
make_read_only's docstring)neutralize_variable,update_variable,add_variable).values_listor aParameterAtInstant's value, oradd_child, outsidemodify_parameters._setorput_in_cache, or straight into storage.make_read_only().get_branchwith 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/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.main(c1fea42a;spm.pyis unchanged atc5385383), year 2026,household_net_incomeand .py's output variables, on subsamples of the default dataset made read-only after they were built:KeyErrorbecause four policyengine-us formulasdel simulation.branches[name]afterget_branch; a policyengine-us change tobranches.pop(name, None)is in progress.master, so no measurable change.make_read_only()took under 1 ms.e5973b2btoeeb3869b; later commits change only the refusals and the parameter check.SimulationBuilder.finalize_variables_initchanged a read-only simulation's population before refusing, and values read from the macro cache came back writable. From its code-quality findings,read_onlybecame 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,Microsimulationand 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.make documentation.Overlapping open PRs
These overlap textually; whichever merges second resolves the conflicts.
holder.py,in_memory_storage.py,on_disk_storage.py,simulation.py); Replace a simulation's population when the builder writes a situation into it #611, Build a reform simulation's baseline from the situation under the baseline system #613, Keep loaded roles and IDs through subsample without backing variables #622 and Make flat-file datasets safe to load, map and round-trip #646 (simulation.py).parameter_node.py,reform.py,tax_benefit_system.py) restructuresTaxBenefitSystem.modify_parametersand lets a modifier edit the tree in place. Whichever merges second should keep this PR's change count inmodify_parameters(added for every node fromchange_counting_nodes(parameters)), in Stop deep-copying the parameter tree in Reform.modify_parameters, and read in-place edits fresh #645'sfinallyblock, so an in-place edit still counts as a change for a read-only simulation.parameter_node.py). Stop the YAML test runner keeping every case's simulation and reform system #569 also stops caching tracing wrappers on parameter nodes; that does not interact with the change counts.parameter_node.py,simulation.py) is still open but was superseded by the merged Record scale, child-list and undated parameter reads in the tracer #664.🤖 Generated with Claude Code