Skip to content

Open the branching formulas' temporary branches with Simulation.temporary_branch - #11254

Open
anth-volk wants to merge 11 commits into
mainfrom
read-only-simulation-branch-removal
Open

anth-volk wants to merge 11 commits into
mainfrom
read-only-simulation-branch-removal

Conversation

@anth-volk

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

Copy link
Copy Markdown
Contributor

Fixes #11666
Do not merge: waiting for the requester's go-ahead to merge.

What and why

Four formulas calculate in a branch of their simulation with changed inputs or a neutralized variable:

  • the marginal tax rate helper (marginal_earnings_change), which marginal_tax_rate, marginal_tax_rate_including_health_benefits and the federal, state and FICA component rates use;
  • marginal_tax_rate_on_capital_gains;
  • employer_ss_tax_income_tax_revenue;
  • employer_medicare_tax_income_tax_revenue.

Each created the branch with get_branch and removed it afterwards with del simulation.branches[name]. That failed in two ways:

  • On a read-only simulation (policyengine-core's Simulation.make_read_only()), get_branch with a new name doesn't keep the branch in branches, so the del raised KeyError.
  • When a calculation inside the branch raised, the del never ran, and the branch stayed registered with the failed calculation's inputs.

policyengine-core 3.40.0 adds Simulation.temporary_branch (PolicyEngine/policyengine-core#677). It is a context manager that keeps the branch in branches only while its block runs, and removes it when the block ends, even after an error. A read-only simulation never keeps it. It also refuses, with ValueError, the simulation's own branch name or the name of a branch it holds. This PR moves the four formulas onto it and requires policyengine-core>=3.40.0. uv.lock moves only policyengine-core, from 3.37.2 to 3.40.0.

  • The marginal tax rate helper is split into two steps:
    • prepare_perturbation reads everything the raised branch needs from the simulation: inputs to keep, behavioral responses to hold, raised values. It runs before any branch exists.
    • apply_perturbation sets those on a branch.
  • perturbed_branch is a new context manager. It runs the first step, opens simulation.temporary_branch, runs the second step and yields the branch. marginal_earnings_change and the capital gains rate calculate inside its block.
  • create_perturbed_branch stays, built from the same two steps with get_branch, for the tests that keep a raised branch after the call.
  • The employer revenue formulas open their branch with sim.temporary_branch(name, clone_system=True).

The raised values used to be calculated on the simulation after the branch was created; now they're calculated before it. They are inputs (the pre-response variables, or an aggregate supplied as an input), and the branch drops every value other than inputs before setting them. So nothing changes, as the comparison below shows.

Values before and after

Five cases, calculated with main's code (c1fea42a) and this branch's:

  1. a California adult with wages and long-term gains, 2024;
  2. a Texas couple, 2024;
  3. a New York parent with two children, 2024;
  4. a California couple under a reform with a 47% top rate, CBO labor supply elasticities and a -0.62 capital gains elasticity (a nonzero labor supply response), 2026;
  5. a California adult with employer payroll tax counted in income, 2024.

All seven rates, household net income, both behavioral responses and both employer revenues are identical in two comparisons: the branch against main on core 3.40.0, and the branch on 3.40.0 against main on 3.37.2. The branches each simulation keeps afterwards are identical too.

On a read-only simulation (released core 3.40.0), one California adult with $50,000 of wages in 2024, plus $20,000 of long-term gains for the capital gains rate:

Variable Plain Read-only, main Read-only, this branch
marginal_tax_rate 0.42725 KeyError: 'mtr_for_adult_1' 0.42725
state_marginal_tax_rate 0.06 KeyError: 'state_mtr_for_adult_1' 0.06
fica_marginal_tax_rate 0.0875 KeyError: 'fica_mtr_for_adult_1' 0.0875
marginal_tax_rate_on_capital_gains 0.315 KeyError: 'adult_1_cg_rise' 0.315
employer_ss_tax_income_tax_revenue (reform in effect) 372 KeyError: 'without_employer_ss' 372
employer_medicare_tax_income_tax_revenue (reform in effect) 87 KeyError: 'without_employer_medicare' 87

Read-only simulations of reforms 4 and 5 above also give exactly their plain values for every variable listed, and their branches is unchanged.

Test plan

policyengine_us/tests/core/test_unkept_temporary_branches.py runs in the Rest core group. Each test has two cases: current law (marginal_tax_rate, marginal_tax_rate_on_capital_gains) and employer payroll tax in income (both employer revenues).

  • test_formulas_give_their_plain_values_on_a_read_only_simulation. Each formula opens its branch with temporary_branch. A plain simulation keeps none of those branches afterwards. A simulation made read-only with make_read_only gives exactly the plain values and keeps its branches unchanged.
  • test_formulas_remove_their_branch_when_its_calculation_raises. A step inside the branch is replaced by one that raises: drop_inherited_values for the rates, neutralize_variable for the revenues. Each formula opens its branch, the error reaches the caller, and the branch is gone afterwards.
  • test_formulas_refuse_to_calculate_in_a_branch_with_their_branch_name. In a branch named as the formula names its own branch, the formula raises ValueError. The branch's inputs and neutralized variables stay unchanged.
  • test_combined_behavioral_responses.py::test_combined_measurements_keep_inputs_set_on_baseline_and_reform. This existing test observed create_perturbed_branch, and now observes perturbed_branch. It still sees the earnings and capital gains branches of both behavioral-response measurement branches.

How each test behaved before and after the change:

  • Before (653dd5df): both cases of the first two tests failed on assertions. The formulas didn't open their branch with temporary_branch, and after an error the branch stayed registered. The refusal test passed through the own-name check of the time. That commit's message says "the last two fail today"; the failing ones are the first and third requirements it lists.
  • After (0e876997, then 5a7f9b52): all pass, run by node ID only.
  • ruff format and ruff check pass on the changed files.

Cost, measured locally on macOS with a load average of 7–8 from other processes:

  • The six cases and the observer test take 86 s of test time: 28.7 s for the read-only employer case, 15.6 s and 11.6 s for the error cases, 14.4 s for the observer test, and 8.3 s, 5.9 s and 1.0 s for the rest.
  • The process takes 124 s and peaks at 2.9 GB RSS.
  • The employer cases cost most: each revenue formula copies the tax-benefit system for its branch, and the cases build reformed simulations.

These checklist items apply as follows:

  • YAML tests from an external source: not applicable (no policy change)
  • Source-conflict register entry: not applicable
  • make format (ruff format and ruff check)
  • Changelog fragment in changelog.d/

axiom: n/a: no policy change; this changes how four formulas create and remove their temporary branches.

Review

The author and the reviewers are all Claude sessions, so this is a self-review.

This branch first took another approach: branches.pop(name, None) in place of del, plus an own-name check in policyengine-us. Three review rounds of that approach found no bug in its code. The requester then chose to handle this in policyengine-core, which became PolicyEngine/policyengine-core#677; the later commits here replace that approach.

One review round of the current code, by a separate reviewer, found no bug. It confirmed:

  • each claim above;
  • the dependency change;
  • that no calculation on the simulation runs while a block is open, so none can reopen the same branch name.

It also ran four existing tests that use these formulas or create_perturbed_branch, all of which passed.

Two of its notes were fixed in 5a7f9b52:

  • the error test now checks that the failure happened inside the branch;
  • create_perturbed_branch's docstring now says it doesn't refuse a name already in use.

Left as they are on main: the two employer revenue formulas duplicate each other, and they keep a bare except: pass around delete_arrays.

🤖 Generated with Claude Code

anth-volk and others added 6 commits November 28, 2026 02:17
…never kept

policyengine-core's read-only simulations (not yet released) give a new
branch for a name they have not registered and do not keep it in
simulation.branches, so del simulation.branches[name] raises KeyError.
The test gives a simulation a get_branch that keeps no new branch and
checks the marginal tax rates, the capital gains rate and the employer
Social Security and Medicare income tax revenues against plain values.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The marginal tax rate helper, the capital gains marginal tax rate and the
employer Social Security and Medicare income tax revenue formulas deleted
their branch with del simulation.branches[name]. A simulation that keeps
no branch it creates, such as one of policyengine-core's planned
read-only simulations, raised KeyError there. pop(name, None), which six
other formulas already use, removes the branch when the simulation kept
it.

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

In a branch named as a formula names the branch it creates
(mtr_for_adult_1, adult_1_cg_rise, without_employer_ss,
without_employer_medicare), get_branch returns the simulation being
calculated. The formula then raised that simulation's inputs or
neutralized variables in its system. del simulation.branches[name]
raised KeyError afterwards; pop(name, None) does not, so the result was
wrong. The formulas must refuse before changing anything.

state_marginal_tax_rate leaves the value test: it goes through the same
statement as marginal_tax_rate.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Add get_branch_to_change, which raises ValueError when get_branch
returns the simulation itself (asked for the simulation's own branch
name). The marginal tax rate helper's perturbed branch and the employer
Social Security and Medicare revenue formulas use it, so a formula
calculated in a branch with its branch name stops before raising that
simulation's inputs or neutralizing variables in its system.

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

codecov Bot commented Nov 27, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 95.34%. Comparing base (8999568) to head (5a7f9b5).
⚠️ Report is 430 commits behind head on main.

Additional details and impacted files
@@             Coverage Diff             @@
##              main   #11254      +/-   ##
===========================================
- Coverage   100.00%   95.34%   -4.66%     
===========================================
  Files            1        1              
  Lines           24       86      +62     
  Branches         0        2       +2     
===========================================
+ Hits            24       82      +58     
- Misses           0        4       +4     
Flag Coverage Δ
unittests 95.34% <ø> (-4.66%) ⬇️

Flags with carried forward coverage won't be shown. Click here to find out more.

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

Review round 3 found that deleting any of the four pop calls left every
new test passing. The plain-value test now asserts that the plain
simulation does not keep the formula's branch; with each pop removed in
turn, it fails at that formula. The module docstring now counts the
simulations the file builds and says where its time goes.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
anth-volk and others added 4 commits December 2, 2026 22:08
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The formulas must open their branch with core's temporary_branch, give
their plain values on a simulation made read-only with make_read_only
(replacing the stand-in for it), and leave no branch registered when the
calculation inside the branch raises. The last two fail today: the
formulas call get_branch, and their branch stays registered after an
error.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The marginal tax rate helper now prepares the raised values from the
simulation first, then opens core's temporary_branch and sets them in
the block (perturbed_branch); the capital gains rate uses it too. The
employer Social Security and Medicare revenue formulas open their
branch with temporary_branch directly. Core removes each branch when
the block ends, even after an error, and never keeps it on a read-only
simulation, so the pop calls and the own-name check added earlier on
this branch are gone. create_perturbed_branch stays for tests that keep
the branch, built from the same two steps.

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

Review round 1 found no bug. The error test now asserts each formula
opened its branch before the injected failure, so a formula failing
before it branches can't pass it. The Perturbation fields and the two
helpers get type annotations, and create_perturbed_branch's docstring
says it doesn't refuse a name already in use, unlike perturbed_branch.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@anth-volk anth-volk changed the title Remove temporary branches with branches.pop(name, None) Open the branching formulas' temporary branches with Simulation.temporary_branch Dec 2, 2026
@anth-volk
anth-volk requested a review from hua7450 December 2, 2026 20:45
@anth-volk
anth-volk marked this pull request as ready for review December 2, 2026 20:46

@hua7450 hua7450 left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Approving at 5a7f9b5. I read the diff against the released policyengine-core 3.40.0 wheel and found no defects.

  • Core behaves as described. temporary_branch removes its branch on normal exit and after an error, a read-only simulation never keeps it, and it raises ValueError for the simulation's own name or a held name before changing anything.
  • Calculating the raised values before the branch opens changes no result. The raised variables are inputs with no formula, or inputs already stored for the period, and the parent simulation makes the same calls in both orders.
  • No new failure path. Branch names are unique per formula. The two same-name cases that now raise ValueError already raised KeyError on main, after changing inputs or the tax-benefit system.
  • The employer revenue formulas are equivalent to main. The same statements run inside the with block, and the branch still has its own copy of the tax-benefit system.
  • The tests check what they claim. All three would fail on main's code, and all six cases pass in CI at this head.

One optional suggestion, not needed for this PR: employer_ss_tax_income_tax_revenue and employer_medicare_tax_income_tax_revenue still clear the branch's caches with a loop and a bare except: pass. The temporary_branch docstring points to drop_computed_arrays for that. Those lines are unchanged from main apart from indentation, and I did not check that the two are equivalent.

I ran nothing locally; all 37 checks pass. I am not merging, per the note in the description.

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.

Formulas that branch their simulation fail on a read-only simulation and leave their branch after an error

2 participants