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>
@MaxGhenis

Copy link
Copy Markdown
Contributor Author

Agent review for Max, written by Codex and posted by Antigravity for Max Ghenis (exact reviewed head 3a07e8c8e212f70b42fc9851fda2581ebae3a65f).

VERDICT: REQUEST_CHANGES
HEAD: 3a07e8c

The absent-period fix works, but the same change lets an explicitly deleted calculated value survive in the recurrence scheduler and return a stale result.

P1 · policyengine_core/holders/holder.py:485 · Exact deletion can reuse a deleted calculation. I ran a one-person recurrence starting in 2010, R(y) = R(y−1) + increment(y), with a spiral limit of 1. The caller first computes R(2012)=3, which stores R(2011)=2. It then uses Parameter.update to set the 2011 increment to 4, calls Holder.delete_array for R(2011), and confirms the holder entry is gone. The next read should return 1 + 4 = 5. The prior head returned 5 and this head returned 2, in both trace modes. The new predicate omits the mutation notification when the removed value is derived, so _calculate can reuse the scheduler’s finished value after the holder lookup misses. A second probe seeded a derived source(2010)=1 and deleted it between two recurrence reads. The traced result regressed from 30 → 15 to 30 → 29. The untraced result was 30 → 30 at both revisions. Invalidate dependent fast-cache and deferred results when an explicit exact deletion actually removes a value, including a derived value. Preserve the no-op behavior for absent keys and the scheduler’s derived_only=True cleanup. Add the parameter-update regression in both trace modes and cover derived deletion in both storage tiers. Deletion predicate · Deferred read · Storage contract

P3 · PR description line 16 · The test link points to the wrong file. tests/core/test_cycles.py:68 leads to a variable label. Point it to tests/core/test_branch_input_invalidation.py:535, which checks holder cleanup, dependency history, and the fresh-simulation result. PR description · Named test

Earlier findings

Finding Status and observed result
P1 · Absent exact deletion cuts a recurrence Closed. The formula adds one each year from 2010, so the 2011 and 2024 results are 2 and 15. This head returned both with zero generation changes in both trace modes. The prior traced run returned 1 for each, with 13 and 39 generation changes. The prior untraced run returned 2 and 15 with the same spurious changes.
P2 · Exact input deletion leaves stale deferred results Closed for the reported supplied-input case. Across the 15 formula years, deleting source(2010)=1 gave 15 → 0, or 30 → 15 with a further +1 per year, in both trace modes. Memory and disk tests confirmed one generation change for a real input deletion and zero for a repeat. Contained deletion remains an inherited follow-up. It returned stale 15 and 30 untraced at both revisions. A separately stored dependent also stayed at 1 after exact input deletion at both revisions.
P2 · Parent and branch call order Still closed for the reported cases. In both trace modes, parent A(2010)=40 gave cold and warm B(2024)=67, with A(2024)=68 during warm-up. Branch B(2010)=40 gave cold A(2024)=69, then B(2024)=68. Each complete parent–branch step adds 2.
P3 · Cut-derived macro values Still closed for new writes. Successive unanchored reads returned 1. The cut ADD, DIVIDE and settled-retry cases returned 78, 1/12 and 6 and wrote no files. The dated control returned and wrote 3. A seeded same-version file still produced 2 versus a fresh 1 at both revisions, an inherited read-path limitation.

Delta, description, and sources

The merge base was baf74aa5030f88c766654e4c3bde00db7ddc49e2. The range from 20e33f2c contains one nonmerge commit across five files. It preserves the existing deletion cases and adds trace-mode, nonzero-result, and generation checks. Both storage tiers normalize the lookup key the same way as exact deletion. The holder’s statement that “Deleting an absent period leaves the input state unchanged” matches the probes. The data-storage statement that temporary results are discarded after “computed-value invalidation” differs from the derived-deletion result above. Round-three diff · Holder contract

The title and description lines 1 and 12 hold for the supplied-input and absent-period cases. Line 12 needs to account for explicit deletion of calculated values, and the storage documentation needs to agree with the implementation. The scheduling, cut cleanup, conversion precedence, trace selection, and macro-write claims matched the implementation and targeted tests. Line 20 is accurate for the build’s master tip. Current master is a310bdf64169d8610a548562690a8de58d46b4ef, 27 commits beyond the merge base. GitHub reports conflicts, and a read-only merge preview showed four conflict blocks in simulation.py. The PR is a draft with zero reviews and comments. PR · Build CI

PE-US 2035 household example confirmed. At PE-US 6c5170fd, formula_2025 reads period.last_year. With 40 weeks supplied for 2024, historical Core master returned 0 weeks, $0 cold and 40 weeks, $1,800.14 after calculating 2030. Initial PR commit 67fbece28 and the reviewed head returned 40 weeks, $1,800.14 cold and warm. Without a supplied input, all three returned 0 weeks, $0. These results held in both trace modes. For one eligible adult, the pinned calculation is 40 × 0.85 × $41.17 × 398.4 / 309.794, rounded to cents. Census and historical BLS sources confirm the base inputs. The CBO workbook returned HTTP 403, so the projection was verified against the pinned PE-US parameter only. Description line 66’s claim about the historical eCPS file remains unverified. Public CPS build code carries weeks_worked, so the claim should identify the specific benchmark artifact. PE-US formula · Pinned CPI · Census methodology, p. 15 · Census 2024 amount, p. 16 · BLS Table A-1 · CBO workbook · CPS field addition

Verification

I used GPT-6 Codex. The reasoning-effort setting was unavailable. Local runs used the existing macOS Python 3.13.9 environment with pytest 9.1.1 and imported Core from the review checkout.

  • Reviewed head: 314 passed across all 11 PR test modules, each run separately with exit 0. This includes 40 integration and 16 storage tests in the two files changed by the round-three commit. The shared tests/fixtures/spirals.py module collected zero tests when invoked directly, as expected, and exited 5.
  • Prior head: 54 passed across integration, storage, and macro-cache tests, all exit 0. The deletion and seeded-cache diagnostics exited 0 and printed the observed values reported above. All 18 synthetic PE-US cases passed.
  • YAML and static checks: The delta changes no variable or parameter definitions referenced by YAML. The country-template target still passed 39 cases at each revision, including 38 cases from 12 YAML files. The YAML runner passed 14 tests. Ruff lint, format, and git diff --check exited 0.
  • CI and limits: All 19 checks succeeded. Linux CI corroborated 4,513 passes, four skips, three xfails, and 34 documentation warnings. I did not independently verify the build’s reported 584 and 570 focused-suite totals, local runtime, or intermediate e10e1f39 commit, which GitHub returned HTTP 422 for. I did not run tests/smoke/test_us.py, tests/smoke/test_country_init.py, or the historical or current full-sample downstream comparisons locally. No microdata was downloaded. CI run · Linux test and documentation log

The review checkout and scratch directories were removed. No GitHub writes were made.

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