Skip to content

Evaluate recursions over periods in full when they reach an input or the start of a formula - #572

Draft
MaxGhenis wants to merge 20 commits into
masterfrom
fix-spiral-anchored-recursion
Draft

MaxGhenis wants to merge 20 commits into
masterfrom
fix-spiral-anchored-recursion

Conversation

@MaxGhenis

@MaxGhenis MaxGhenis commented Oct 2, 2026 •

Copy link
Copy Markdown
Contributor

For stable inputs, Core evaluates a finite period recurrence in full when it reaches a supplied input or a formula boundary in the direction of recursion. It schedules deeper periods first and checks each frame’s own simulation for anchors, including registered parent and branch calls. An exact deletion of an absent period leaves the input state unchanged. (policyengine_core/simulations/simulation.py:3159, policyengine_core/holders/holder.py:485)

The existing depth limit still applies to recurrences with only masks or conditional formula base cases, and to nested calls on unrelated simulations. For registered simulations, Core clears cut-derived holder and fast-cache entries when the calculation ends. It keeps new cut-derived values out of the macro cache. (policyengine_core/simulations/simulation.py:3077, policyengine_core/simulations/simulation.py:3143, policyengine_core/simulations/simulation.py:2446)

Caller-visible changes

  • Anchored calculations traverse additional periods. This can expose deeper formula errors and increase time and memory use. Formulas can run more than once while Core schedules deeper periods. (policyengine_core/simulations/simulation.py:1750)
  • Unanchored calculations keep their depth limit. Core clears cut-derived holder and fast-cache entries when the calculation ends. get_array, known-period inspection, cloning and later calculations can observe the change. (docs/python_api/data_storage.md:5, policyengine_core/simulations/simulation.py:3820)
  • Core returns cut-derived ADD and DIVIDE aggregates without keeping them. It still uses inputs supplied for the requested period while the conversion runs. (docs/python_api/data_storage.md:17)
  • Each simulation keeps its explicit invalidations. A parent clears its descendant’s cut-derived entries while the descendant’s explicit invalidations stay pending. (docs/python_api/data_storage.md:13)
  • Flat traces select accepted completed attempts. Computation and performance logs keep retries. (docs/python_api/tracers.md:14)
  • Holder.delete_array, InMemoryStorage.delete_exact and OnDiskStorage.delete_exact remove one stored period. Removing a stored input through Holder.delete_array invalidates deferred results and clears the simulation’s fast cache. Deleting an absent period leaves the input generation unchanged. (docs/python_api/data_storage.md:5, policyengine_core/holders/holder.py:467)
  • Conditional formula-only base cases, masks and unrelated simulations still meet the existing depth limit. (policyengine_core/simulations/simulation.py:3107, policyengine_core/simulations/simulation.py:3143)
  • Anchor checks use the variable definition, holder and branch name of the simulation that owns the frame. (policyengine_core/simulations/simulation.py:3159)
  • The macro cache skips cut-derived formulas, period conversions and results from settled input retries. Eligible cut-free values still reach it. (tests/core/test_spiral_macro_cache.py:32, tests/core/test_spiral_macro_cache.py:52, tests/core/test_spiral_macro_cache.py:72, tests/core/test_spiral_macro_cache.py:119)
  • test_value_a_spiral_defaults_is_tracked checks that a cut clears intermediate storage. It also checks dependency history and compares the result with a fresh simulation. (tests/core/test_cycles.py:68)

Merge with master

This branch includes master baf74aa5. The merge check against that tip returned Already up to date with no conflicts.

Conflict Resolution
simulation.py, start of ADD Record the cut generation for this attempt and the first input sequence for the whole sum.
simulation.py, ADD result Pass both values to the option cache check.
simulation.py, DIVIDE result Carry the source period’s fallback status and pass the cut generation.
simulation.py, option helper signature Keep the cut generation and the optional initial input sequence.
simulation.py, option cache write Check for a supplied input first. Keep master’s fallback rules and skip caching aggregates reached by a cut.
trace_node.py, fields Keep formula_ran and the provisional attempt flag.

The holder merge keeps branch-visible periods, reform rebinding and eviction of sums and twelfths after an own-period input. Both stores keep master’s key checks and the exact deletion methods. The disk store keeps contained-period deletion. Both API pages retain the incoming master sections.

Tests

  • In both trace modes, a recurrence that repeatedly deletes an absent source returns 2 in 2011 and 15 in 2024 with zero input changes. At 20e33f2c, those traced calculations returned 1 and recorded 13 and 39 changes. (tests/core/test_spiral_merge_integration.py:350)
  • Exact input deletion returns 15 before deletion and 0 afterward in the original probe. With +1 at each step, the corresponding values are 30 and 15 in both trace modes. The +1 variant returned 1 after deletion with tracing on and a stale 30 with tracing off at 20e33f2c. (tests/core/test_spiral_merge_integration.py:390)
  • In both trace modes, cold branch B(2024) returns 67 with a parent input. Parent A(2024) returns 68 and warmed B(2024) returns 67. A branch input gives cold parent A(2024)=69 and B(2024)=68. (tests/core/test_spiral_merge_integration.py:334)
  • A cut recurrence returns 1 in successive years, matching a fresh simulation. The formula, ADD, DIVIDE and settled retry cases leave no cut-derived macro files. The cut-free recurrence still writes 3. (tests/core/test_spiral_macro_cache.py:32)
Command Result
timeout 900 python -m pytest -q -p no:cacheprovider <file> for each PR test file and related cache, storage and YAML runner test file 584 passed across 22 files. A merge with master passed 570 tests across 21 files. All exited 0.
timeout 900 make test-country-template 39 passed before and after, both exit 0.
timeout 1500 python -m pytest -q -p no:cacheprovider tests 4,513 passed, 4 skipped, 3 xfailed. Exit 0 in 406.93 seconds.
ruff format --check policyengine_core/holders/holder.py tests/core/test_spiral_merge_integration.py tests/core/test_spiral_storage.py All three files formatted. Exit 0.
ruff check policyengine_core/holders/holder.py tests/core/test_spiral_merge_integration.py tests/core/test_spiral_storage.py All checks passed. Exit 0.
make documentation Exit 0 with 34 warnings.
git diff --check Exit 0.

The full suite ran on Linux with Python 3.13.5 and pytest 9.2.0. The downstream US microsimulation smoke test needs microdata and did not run. The country-package initialization tests require the corresponding packages.

Historical downstream evidence

The original comparisons ran on master b78b0ba9 and on #571, #572 and #573 merged together. These measurements predate the current head.

Run Outputs compared Result
policyengine-us 6c5170fd, eCPS 2024, 3,000-household subsample, 2026 (income tax, itemizing and SALT branches, state taxes, CTC, EITC, SNAP, household and SPM net income, weights, marginal tax rates) 25 arrays bitwise identical
Same, 2035 25 arrays bitwise identical
policyengine-uk 7b9fc379, enhanced FRS 2024–25, full sample, 2026 (income tax, NI, UC and legacy benefits, Pension Credit, HB, council tax, HBAI income, poverty, marginal tax rates) 36 arrays bitwise identical

The PE-US 2026 comparison also ran on each branch alone. The 2035 comparison ran on #572 alone. Both sets of comparisons found bitwise identical outputs.

A probe on master covered PE-US 2026 and 2035 and PE-UK 2026 and 2042. It found one recursion cut, in the 2035 PE-US weeks_worked calculation. The formula_2025 at that revision reads the previous year’s value.

The eCPS file carries no weeks_worked, so every year is the default 0 and the cut changes nothing in those comparisons.

In a historical household check, one worker supplied 40 weeks for 2024.

2035 New simulation After calculating 2030
master b78b0ba9, weeks_worked and spm_unit_work_expenses 0, $0 40, $1,800.14
original #572, same outputs 40, $1,800.14 40, $1,800.14

The PR stays a draft until a ruling on the caller-visible changes.

impact: pending a comparison at the current head. Downstream microsimulation runs need microdata and have not run.
axiom: n/a: core engine repair, no policy encoding.

🤖 Generated with Claude Code

max_spiral_loops capped how many uncached frames of one variable the
stack could hold, returning the default where the cap fell. Since it
counted uncached frames only, a recursion's result depended on what had
been calculated before: with an input of 1 in 2010 and
recursive(t) = recursive(t - 1) + 1, 2021 was 10 in a new simulation
and 12 after calculating 2020. policyengine-us weeks_worked
(formula_2025 reading the year before, input in 2024) is cut this way
from 2035 on.

A recursion that reaches the limit while heading towards an input, or a
period with no formula, now unwinds to the outermost calculate, which
calculates the deepest period first and starts again; the chain is
evaluated all the way down, max_spiral_loops frames at a time. One with
no anchor is still cut, but no value calculated while a cut is on the
stack outlives that calculation (values above a cut used to be kept),
spiral purges delete exactly the period under the calculating branch's
name (they deleted contained periods under the default branch), and
each clone has its own invalidated set.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
MaxGhenis and others added 9 commits October 6, 2026 07:30
Conflicts:
- holders/holder.py (put_in_cache): kept master's derived guard (a
  derived value never replaces a readable input) and derived=True
  storage, then the PR's _note_cached_value call after the store.
- simulations/simulation.py (clone): kept master's storage-directory
  and _user_input_keys copying, then the PR's per-clone
  invalidated_caches.

Semantic integration: delete_exact now uses master's bookkeeping. On
memory, _stop_sharing (master's _shared is a frozenset while nothing is
shared, so .discard raised AttributeError) and _unmark_input; on disk,
the _derived mark is discarded with the file.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Branch and copy cleanup (findings 1 and 4). A cut in a simulation's
calculation no longer deletes its branch-name key from every
descendant, which deleted a descendant's own input stored under the
same name. A copy (clone or branch) instead drops, when it is made, the
values the simulation it copies is waiting to purge: every such value
is marked by the time it is cached, and a copy never sees what is
cached after. Purges delete only values the simulation calculated
(derived), never an input.

Swallowed requests (2). Each request to finish a deeper period first is
recorded as outstanding when raised. A formula that returns while one
is outstanding (a bare except caught it) has its value dropped and the
request raised again; an error raised while one is outstanding is
treated as the request.

requires_computation_after (3). A deferred period keeps the names of
the variables that needed it, so its caller still counts while it is
calculated with an empty stack.

Tracing and storage (6, 7). The flat trace prefers a completed node to
an abandoned one. Deferred values are kept for the outermost
calculation in its own cache, which _calculate reads, so deferral works
the same traced or not and when the holder stores nothing; values
calculated under a cut are marked for purging when written to the fast
cache too.

Termination (8). MAX_SPIRAL_DEFERRALS is gone: it cut long chains
depending on what was cached. Each deferred period starts at most once
per outermost calculation, and only on the requested simulation or its
registered branches (a copy made in a formula is made anew on every
retry), so the calculation still ends.

Finding 5 is settled by master's #562 (only inputs carry over); its
regression test passes on the merge commit.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Keep master clone aliases, system entities, independent baselines, and explicit input/contained-period invalidations. Distinguish spiral cleanup from explicit invalidation, and prefer accepted trace results over provisional cut retries.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Retain the original recurrence order generator. Compare finite anchored systems against an independent iterative NumPy evaluator across caller authorization, bare exception handlers, tracing, cache policies, copies and descendant inputs. Compare exact-deletion snapshots and provenance across copied memory, shared memory and disk storage.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Describe the shared behavior without claiming disk delete uses contained-period deletion.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Use readable storage provenance instead of stale input registry keys. Preserve replay bookkeeping and inherited inputs. Add traced and untraced deletion regressions and a bounded provenance property; clarify deferred-key retry invariants.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Preserve the canonical docs release job without changing scheduler, holder, storage or tracer behavior.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Retain all example counts and semantic assertions. Suppress only the slow-generation health check for the bounded two-variable generator after a 47-second draw interrupted otherwise passing properties on the shared host.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Preserve the incoming Population protocol guards, EnumArray serialization, release artifacts, and focused copy coverage alongside deferred recursion scheduling.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
MaxGhenis and others added 9 commits October 19, 2026 04:07
Keep the recursion cut checks alongside input precedence and trace fields.

Co-Authored-By: GPT-6.2 Sol <noreply@openai.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Track active periods across registered simulations so parent and branch formulas read their own inputs.

Co-Authored-By: GPT-6.2 Sol <noreply@openai.com>
Record exact deletes the same way as period deletes. Skip the input change record when cleaning up calculated values.

Co-Authored-By: GPT-6.2 Sol <noreply@openai.com>
Check for cuts before writing values from formulas, period conversions, or settled input retries.

Co-Authored-By: GPT-6.2 Sol <noreply@openai.com>
Describe how deleting an input clears deferred and temporary results.

Co-Authored-By: GPT-6.2 Sol <noreply@openai.com>
Co-Authored-By: GPT-6.2 Sol <noreply@openai.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.

1 participant