Skip to content

Stored current-law values: export, save, load and supply to reform simulations - #679

Draft
anth-volk wants to merge 22 commits into
masterfrom
current-law-values
Draft

anth-volk wants to merge 22 commits into
masterfrom
current-law-values

Conversation

@anth-volk

@anth-volk anth-volk commented Dec 2, 2026 •

Copy link
Copy Markdown
Collaborator

Fixes #678

What this adds

A simulation run without a reform can save the current-law values a reform simulation over the same population would otherwise calculate again, and a reform simulation can use them instead of building its current-law copy. New module policyengine_core.simulations.current_law_values.

  • Export. export_current_law_values(simulation, period=None, source_run_id=None) calculates every variable that declares current_law_read = True: a yearly variable for the calculation year (by default default_calculation_period), a monthly variable for each of its twelve months, an eternal variable once (a variable defined for days is left out, with a warning). It returns a CurrentLawValues: arrays keyed by variable and PeriodKey (unit, first day, size; not str(period)), each entity's ID array, and source_run_id. Every value type core stores is kept: numbers, booleans, dates, strings, and Enum values as positions with their member names. Arrays are copied and not writable. It refuses a simulation that compares with current law.
  • Save and load. values.save(path) writes one HDF5 file: entity_ids/<entity> and arrays/<n> datasets, and a JSON manifest in the root attribute manifest (format name, format version 1, core version, source_run_id, calculated_values, and each dataset's variable, period, dtype and Enum member names). It writes a temporary file of its own beside path and moves it into place. CurrentLawValues.load(path) refuses another format or a newer version and ignores groups the manifest does not list, so a later format (a seeds file) can extend this one.
  • Supplying. Simulation(..., current_law_values=values) calls the new public simulation.supply_current_law_values(values) once its population is built. A caller that builds the population after construction (.py's US model), or a simulation that does not run core's constructor (policyengine-uk), calls it once the population is in place.
    • Check. Each entity's ID array must equal the saved one, element by element, with the same entities on both sides (byte-string IDs compare as text). To build arrays it can read, core also maps each Enum value to the variable's Enum class in the current-law system by member name, refuses positions outside the saved names, and checks each array's length against its entity. Any failure raises the new CurrentLawValuesMismatchError (a ValueError) naming the entity or the variable, and leaves the simulation as it was. Every other check on where the values came from belongs to the caller.
    • Supplying is refused on a branch (or a clone of one), once the current-law copy core builds exists, and on a read-only simulation.
  • Reads. While the simulation compares with current law:
    • Population.current_law(...) without options returns a supplied value, not writable, without building the copy. ADD and DIVIDE reads and periods not supplied go to the copy.
    • The new simulation.supplied_current_law_value(variable, period) returns the supplied array or None, never builds the copy, and is reported to the tracer as a declared call.
    • Neither uses a supplied value where the simulation held an input for that variable and period when the values were supplied: current law starts from that input, as a copy built from those inputs does.
  • The copy. A copy core builds starts from the supplied values, stored with put_in_cache(..., derived=True) as calculated values, so its branches do too. They are never inputs: not in input_variables or the input record, and never an uprating or carry-over base. A simulation assigned to baseline is kept as given and not filled.
  • Branches, clones, subsamples.
    • Branches made with get_branch read the supplied values, as they read the simulation's copy.
    • A clone made before the copy is built does not keep them: it builds its own copy from its own inputs, as a clone does without them (Declare current-law reads and build the current-law copy on demand #675). A clone made once the copy exists keeps a copy of that copy and the values.
    • Deep copies and pickles keep them.
    • subsample (just before it rebuilds the population) and build_from_populations drop them and log a warning on the logger policyengine_core.simulations.current_law_values. So does a read, or a copy being built, after the population changed some other way.

The values describe current law for the inputs the simulation held when they were supplied. Inputs set afterwards on the simulation, or on its copy through the deprecated baseline alias, are not reflected in them. Dropping the values whenever an input changes would discard them in policyengine-us, whose constructor moves inputs after core's __init__ supplies them, and decision D1 leaves those checks to the caller.

Docs: docs/python_api/simulations.md ("Stored current-law values") and docs/python_api/errors.md. Changelog: changelog.d/current-law-values.added.md.

Builds on #675

This branch starts from #675's head 13aad572 (declared-current-law-reads, still open), which adds the declared current-law calls and the copy built on demand. Until #675 merges, this PR's diff against master includes #675's commits. This PR's own commits are those after 13aad572. Population.current_law's declaration check moved into Simulation._declared_current_law_variable, shared with supplied_current_law_value; its message is unchanged.

Known limits for country packages

  • policyengine-us: passes keyword arguments to core's constructor, so current_law_values= reaches it. Its constructor reads baseline (migrate_social_security_inputs), which builds and fills a copy, then _rebuild_baseline_branch assigns its own branch, which core keeps unfilled. So only declared reads without options use the values, until project 14's task 2.5 · 1 turns that rebuild into a _build_current_law_simulation override. No policyengine-us variable declares current_law_read yet.
  • policyengine-uk: never calls core's constructor and assigns baseline on every simulation, so every UK simulation compares with current law and export_current_law_values refuses it until task 2.7 · 1 changes that.
  • .py: builds the US reform simulation from situation={} and its population afterwards, so it supplies values with supply_current_law_values (task 3.3 · 1).

Checks

  • Tests. tests/core/test_current_law_values.py, 41 tests. Each test commit precedes the change or fix it tests, and each test was run by node ID:
    • The change. 23 tests (0f4feafc, count corrected in 24da6442): all 23 failed on the assertion that the new module exists. 2 more (8ccf920e, pickling the values and deep-copying a simulation) also fail there on that commit. Against the first, uncommitted version of the change they failed on a caught TypeError, because MappingProxyType does not pickle. All 25 pass on the change commit 87f832dc.
    • Review round 1. 13 tests (62f78c71): 10 failed on assertions before the fixes in b559d18c. The other 3 cover behaviour that already held: branches and clones made with the copy, an assigned baseline left unfilled, and ADD reads going to the copy.
    • Review round 2. 2 tests (d1b537b9): both failed before the fixes in d3a80380.
    • Review round 3. 2 tests (69202604): both failed before the fixes in 702bd199. One round-1 test now sets its input before the values are supplied.
    • On the final commit, all 41 pass.
    • Not run locally. The full suite, and Declare current-law reads and build the current-law copy on demand #675's existing tests. CI runs them.
  • Values before and after (before: Declare current-law reads and build the current-law copy on demand #675's head 13aad572; after: this branch). Core's country template with test variables of every value type, a reform income tax rate of 0.42 against 0.15 from 2022, and two people in one household. Compared: 85 values, each registered variable's reform value and its current_law read for every exported period, plus income_tax. They are identical before and after without supplied values, and identical again with values exported from a current-law run and supplied.
  • ruff format --check . and ruff check on the changed files are clean.

Review rounds

Three rounds of adversarial review before this PR opened:

  • Round 1: 1 medium, 4 low. All fixed:
    • Supplied values kept answering after inputs changed, for clones and for an input held on a supplied variable. Clones and the input case are fixed; the rest is documented, as above.
    • A population rebuilt other than by subsample kept the values.
    • Enum positions were not range-checked.
    • Byte-string IDs were refused after save and load.
    • A copy built through baseline handed out non-writable values.
  • Round 2: 2 low, both fixed. The saved file was readable only by its owner, and filling a copy after the population had changed raised on the length.
  • Round 3: 2 low, both fixed. Reading the umask briefly set it to 0, so two threads saving at once could leave it there. An input set after a supplied read changed later reads but not earlier results.

Left (code quality, no bug found):

  • load raises KeyError or TypeError, not ValueError, for unexpected content under the same format version.
  • Supplying to a simulation that does not compare with current law is accepted silently. The values apply once it compares.
  • A clone drops the values without a log, and one population change can log the drop twice.
  • Export's guard refuses only a simulation that compares with current law. .py's named checks cover the rest.
  • No tests for concurrent saves, removal of the temporary file after a failed write, clones of branches or of clones announced as branches, or derivative().

Merge order

This PR waits for these earlier tasks in the same set to merge; nothing here uses the first two, and none needs a release first:

No release of another package is needed before this merges.

🤖 Generated with Claude Code

anth-volk and others added 22 commits December 1, 2026 22:31
Tests that fail before the change: Population.current_law reads a variable
declared with current_law_read, an undeclared read raises, each declared call
is reported to the tracer, a reform simulation builds no current-law copy
while it is constructed, the copy is built from the inputs held when it is
first needed and made read-only by the first declared call, and assigning
baseline replaces the copy. Two existing tests read the baseline branch before
anything built it; they now build it through simulation.baseline, or drop it
only if it exists.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Core requires a label on every variable, and income tax is calculated in
float32, so the tests compare it with the expected amounts to one part in a
million.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
A variable that must be calculated after another raises in the current-law
copy when the copy has not requested that other variable, as it did when
construction built the copy, even if the reform simulation requested it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Formulas read current law through declared calls, each reported to the
simulation's tracer (record_current_law_call; the full tracer keeps them on
TraceNode.current_law_calls):

- Population.current_law(variable, period) reads a variable declaring
  current_law_read = True, and raises UndeclaredCurrentLawReadError for any
  other; without a reform it returns the simulation's own value.
- Simulation.compares_with_current_law and Simulation.current_law_system,
  which never build a copy.
- Simulation.current_law_simulation(), the simulation that calculates
  current-law values.

A reform simulation no longer branches its current-law copy while it is
constructed. The overridable _build_current_law_simulation() builds it the
first time it is needed: a branch named baseline under the default system
instance, keeping the inputs held then and dropping calculated values. The
first declared call that reaches it makes it read-only. Branches read their
parent's copy, and clone() and subsample() keep a copy only if one was built.
Simulation.baseline is now a deprecated property: reading it returns the copy,
left writable, and is reported to the tracer; assigning a simulation makes it
the copy, kept as given, and assigning None stops the comparison.
get_branch("baseline") still returns the copy.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Tests that fail before the fixes: current_law is projected through entity
projections like a population call; current_law without a period raises
before building the copy and names the calling code; a derivative does not
depend on whether the copy was built before it; removing the registered copy
lets get_branch("baseline") make a new branch; a simulation saved with
baseline in its instance dictionary keeps it; an AttributeError while building
the copy is not read as "no baseline".

Tests for behaviour that already holds: options pass through current_law; a
copy built inside a calculation ignores that calculation's reform values; a
clone of a simulation with a read-only copy gets its own copy; a branch of a
branch reads the first simulation's copy; a deep copy keeps its own copy; the
declaration check reads an assigned simulation's system. One edited test now
builds the baseline by reading it, and two test modules no longer say
construction builds the branch.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
- current_law is projectable, so person.household.current_law(...) returns
  one value per person, as person.household(...) does.
- current_law checks the period before building the copy, so a missing
  period builds nothing and the error names the calling code.
- derivative builds the current-law copy before cloning, so its result does
  not depend on whether an earlier call built the copy: the changed clone
  compares with the current law of the simulation's own inputs, as before.
- get_branch("baseline") returns a built copy missing from branches only on a
  read-only simulation; elsewhere, code that removed the registered copy gets
  a new branch, as before.
- subsample builds a copy core built again with _build_current_law_simulation,
  so an override applies and the copy starts with nothing requested; other
  baseline branches are rebuilt as before.
- The builder also clears pending cache invalidations.
- A simulation that kept baseline in its instance dictionary (saved by an
  earlier core) keeps it as its current-law copy.
- An AttributeError while building the copy through the baseline property is
  raised as a RuntimeError, so getattr(simulation, "baseline", None) does not
  read it as "no baseline".
- Docstrings no longer say construction builds the copy.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Tests that fail before the fixes: a read-only simulation registers the
current-law copy it builds, so a clone of it keeps its copy registered and
get_branch("baseline") and subsample see it; a saved simulation's own
baseline branch, kept in its instance dictionary by an earlier core, is
copied by clone rather than shared; assigning baseline on a read-only
simulation raises.

Tests for behaviour that already holds: subsample builds a read-only copy
again as a writable one, and does so with an overridden builder; a copy built
in a calculation that runs again after an input change reads the new input.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
- A read-only simulation registers the current-law copy it builds, so a
  clone of it keeps its copy registered and get_branch("baseline") and
  subsample see it. get_branch("baseline") now returns the record's copy
  only while it is not built.
- clone() and get_branch() turn a baseline kept in the instance dictionary by
  an earlier core into a record before deciding, so a clone copies a saved
  simulation's own baseline branch rather than sharing it.
- Assigning baseline on a read-only simulation raises
  ReadOnlySimulationError, as assigning tax_benefit_system does.
- The builder and subsample set up the baseline branch with one helper,
  _make_current_law_branch, and subsample gives the simulation a new record
  in both of its paths.
- Docstrings: the builder is also called by subsample; get_branch's
  "baseline" case applies to a reform simulation, not its branches; a
  current_law result from a read-only copy is non-writable.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
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>
Tests that fail before the fixes: a clone announced as a branch outside
get_branch (as policyengine-uk's subsample makes one, to share arrays) builds
its own current-law copy from its own inputs and does not keep its source
alive through the current-law record; assigning baseline on a simulation
saved by an earlier core drops the saved attribute, so its clones do not
carry it.

Test for behaviour that already holds: a traced clone of a simulation whose
copy is built traces the clone's copy in the clone. The clone test module's
docstring now says when a test's clone builds a copy of its own.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The template's module-level system names the last simulation built from it,
which keeps that simulation alive whatever the clone holds, so the test now
checks that the clone's current-law record refers to the clone and not to its
source. It fails before the fix.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
- A clone announced as a branch outside get_branch (policyengine-uk's
  subsample announces one to share arrays) gets a current-law record of its
  own that does not refer to its source, so it no longer keeps the source
  alive, and builds its own copy from its own inputs. get_branch gives the
  branch its parent's record once the clone is made.
- Assigning baseline drops a baseline kept in the instance dictionary by an
  earlier core, so clones and pickles no longer carry it.
- Docstrings: current_law_system names the default system of the simulation
  the copy is built from; current_law_simulation states that the copy is
  registered, also on a read-only simulation; current_law states the
  exception for an assigned simulation; TraceNode.current_law_calls says the
  values read are children only when the calculating simulation shares the
  tracer.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Tests that fail before the change: export, save, load and supply give the
current-law copy's values for every registered variable and value type; ID
arrays that differ are refused naming the entity; Enum values are supplied by
member name; supplied values are calculated values, never inputs or uprating
bases; a run with every read supplied builds no copy; a subsample drops the
values and logs it; the file is one versioned HDF5 file.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…ed values

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
export_current_law_values calculates every variable that declares
current_law_read = True on a simulation without a reform (the calculation
year, its months for monthly variables, eternity for eternal ones) and returns
a CurrentLawValues with each entity's ID array and the source run id. save and
load write one HDF5 file whose JSON manifest names the format and its version;
load refuses another format or a newer version and ignores groups it does not
list. Numbers, booleans, dates, strings and Enum values are kept, Enum values
as positions with their member names.

A simulation takes them with current_law_values= or
supply_current_law_values, which checks each entity's ID array element by
element and maps Enum values to the current-law system's Enum classes by
member name, raising CurrentLawValuesMismatchError naming the entity or
variable. Declared reads and supplied_current_law_value return supplied
values, not writable, without building the current-law copy; a copy core
builds starts from them as calculated values, never inputs. Clones and
branches keep them; subsample drops them and logs a warning.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Clones made before the copy is built read current law of their own inputs; a
declared read of a variable holding an input reads the input; a rebuilt
population drops supplied values and logs it; Enum positions outside the saved
members and arrays of the wrong length are refused naming the variable;
byte-string IDs are accepted after save and load; a copy built through the
baseline alias hands out writable values; supplying to a branch is refused; a
failed subsample keeps the values. Two tests cover behaviour that already
holds: an assigned baseline is not filled, and ADD reads go to the copy.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
A clone made before the current-law copy is built no longer keeps supplied
values, so it calculates current law from its own inputs, as a clone does
without them; get_branch gives branches the simulation's values. Declared
reads and supplied_current_law_value skip a supplied value where the
simulation holds an input for that variable and period. build_from_populations
drops supplied values with the same logged warning as subsample, and a read
whose array no longer fits the population drops them too; subsample drops
them only once its own checks have passed. Supplying refuses Enum positions
outside the saved member names, arrays whose length differs from their
entity's IDs, and a branch. Byte-string IDs compare as text. A copy is filled
with writable copies of the arrays. save writes through a temporary file of
its own. Docs describe which inputs the values reflect.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The saved file gets the mode a new file gets, and a population replaced
without build_from_populations drops the supplied values before a copy is
filled from them.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
save gives the file the mode a newly created file gets, not the owner-only
mode of its temporary file. Filling a copy checks each supplied array's length
against the copy's population first, and drops the values with the logged
warning when the population changed some way that did not drop them. The
refusal on a branch names clones of branches too; docs describe deep copies
and the input exception.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
An input set after a supplied read does not change later reads, as it does not
without supplied values; saving never changes the process umask. The input
exception's test now sets the input before the values are supplied.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
save creates its temporary file with os.open and mode 0o666, so the process
umask gives it a new file's mode, instead of changing the umask and the
file's mode. Whether a supplied value is skipped for an input the simulation
holds is decided once, when the values are supplied, so an input set later
cannot make one run give two current-law values for the same variable and
period. Docs and the changelog fragment name the error class, the logged
drops, export's default period and the eternity key.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

This branch has not been deployed

No deployments
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.

Export, save and supply stored current-law values to reform simulations

1 participant