Skip to content

Remove temporary branches with branches.pop(name, None) - #11254

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

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

Conversation

@anth-volk

Copy link
Copy Markdown
Contributor

What and why

This prepares for policyengine-core's read-only simulations (Simulation.make_read_only()). The core change is not released and its PR is not open yet.

On a read-only simulation, get_branch with a name the simulation has not registered returns a new branch every time and does not keep it in simulation.branches. Four policyengine-us formulas create a branch with get_branch, calculate in it, then remove it with del simulation.branches[name], which raises KeyError when the branch was never kept:

  • marginal_earnings_change in marginal_tax_rate_helpers.py, 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 in capital_gains_responses.py;
  • employer_ss_tax_income_tax_revenue;
  • employer_medicare_tax_income_tax_revenue.

Each now removes its branch with simulation.branches.pop(name, None), as the Missouri TANF, Colorado Medicaid and Medicaid formulas, the behavioral response measurements and tools/tob.py already do. On a plain simulation get_branch keeps every branch it creates, so pop removes it exactly as del did and results are unchanged.

A formula calculated in a branch with its own branch name

If a simulation's own branch name is the name one of these formulas gives its branch (mtr_for_adult_1, adult_1_cg_rise, without_employer_ss, without_employer_medicare, …), get_branch returns that simulation itself. The formula then raised that simulation's inputs, or neutralized variables in its system, in place. On main, the del raised KeyError afterwards. With pop, the formula would finish and return a wrong value: for a Texas couple with $80,000 and $30,000 of wages in 2024, marginal_tax_rate gave -0.437 for the second earner, where a plain simulation gives 0.2815.

The new get_branch_to_change (tools/branched_simulation.py) raises ValueError when get_branch returns the simulation itself, before anything changes. The perturbed branch of the marginal tax rate helper (which the capital gains rate also uses) and both employer revenue formulas create their branch through it. No model formula calculates these variables in a branch with those names, and every such calculation raised KeyError on main.

Checked against the core branch

I installed policyengine-core's read-only-simulations branch (eeb3869b) in a scratch environment, with the other dependencies from uv.lock. The household is one California adult with $50,000 of wages in 2024, plus $20,000 of long-term capital gains for the capital gains rate. The employer revenues are calculated with gov.contrib.crfb.tax_employer_payroll_tax in effect at 100%.

Variable Plain simulation 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 372 KeyError: 'without_employer_ss' 372
employer_medicare_tax_income_tax_revenue 87 KeyError: 'without_employer_medicare' 87

On this branch, each read-only value equals the plain value exactly, and the read-only simulation's branches is unchanged afterwards.

Test plan

Each new test failed before its fix: the tests are committed before the changes.

policyengine_us/tests/core/test_unkept_temporary_branches.py runs in the Rest core group. Released core keeps every branch get_branch creates, so the tests replace core's get_branch (with monkeypatch) by one that removes each new branch a chosen simulation creates from its branches before returning it, as a read-only simulation keeps none. The replacement changes only which branches are kept; the rest of what make_read_only does is not reproduced here.

  • test_the_test_simulation_keeps_no_branch_it_creates checks that replacement: a new branch every call, none kept, and the branch itself still keeps its own branches.
  • test_formulas_give_their_plain_values_when_their_branches_are_not_kept, two cases:
    • current law: marginal_tax_rate and marginal_tax_rate_on_capital_gains;
    • employer payroll tax in income: both employer revenue variables.
    • Each formula gives the same value as on a plain simulation of the same household, and its branch was created and not kept.
    • On main, both cases raised KeyError ('mtr_for_adult_1', 'without_employer_ss').
  • test_formulas_refuse_to_calculate_in_a_branch_with_their_branch_name, the same two cases. Each formula raises ValueError in a branch with its branch name, and the branch's inputs and neutralized variables are unchanged. Before get_branch_to_change, no error was raised.
  • They are Python tests because YAML tests can't replace get_branch or calculate in a named branch.

Cost, measured locally on macOS with a load average of about 10 from other processes:

  • The file's tests take 53–77 s over two runs. One run: 51 s and 15 s for the two employer cases, 9 s and 1.4 s for the current-law cases.
  • The process takes 83–107 s and peaks at 2.8–2.9 GB RSS. Collecting the file alone takes 41 s and peaks at 0.85 GB.
  • The employer cases cost most: each builds reformed simulations, and each revenue formula copies the tax-benefit system for its branch.
  • The core group's CI resource report will show the change within the group.

Only these tests were run locally, by node ID, on core 3.37.2 (from uv.lock).

  • 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 remove their temporary branches.

Self-review

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

Two adversarial review rounds, each by a separate reviewer, checked the diff against the acceptance condition. Both ran the formulas on real read-only simulations from core eeb3869b.

  • Round 1 found two problems, both fixed with a failing test first where code changed:
    • No changelog fragment, which the PR validation check requires: added.
    • A formula calculated in a branch with its own branch name returned a wrong value once del became pop. This is now refused with ValueError (see above).
  • Round 2 found no bug. Its runs covered a California couple with a child, the eight rate and revenue variables, a reform with labor supply and capital gains elasticities (a nonzero labor supply response) and that reform's baseline branch. Every read-only value equals the plain value; on main all eight raise KeyError.

Limitations the reviews reported, which this PR doesn't change:

  • The tests' stand-in for a read-only simulation only stops branches being kept. It does not refuse set_input or make arrays non-writable. So a later change that wrote into the simulation being calculated, instead of its branch, would pass these tests and fail on a real read-only simulation. No formula here does that today, and the real read-only runs pass. A test with the real make_read_only can replace the stand-in once core releases it.
  • A temporary branch name registered before make_read_only. If a read-only simulation already holds one of these names (an earlier calculation raised before removing its branch), the formula reuses that branch and the pop removes the name from the read-only simulation's branches. main's del does the same. None of these formulas removes its branch in a finally, on main either.
  • Other fixed-name branches. tools/tob.py and the behavioral response measurement branches already use pop(name, None) and work on a read-only simulation. They don't use the new check, so calculated in a branch with their own names they would change the simulation being calculated (unchanged from main).
  • Repeated work. tools/period_branch.get_override_branch (the itemization branches and others) works on a read-only simulation, but finds no kept branch, so it creates a new one on every call and calculates its values again.
  • Selective tests. Changing marginal_tax_rate_helpers.py makes the Quick Feedback selective-test runner choose tests/microsimulation and tests/policy/baseline/household, by the repository's existing mapping.

🤖 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 82.55%. Comparing base (8999568) to head (7fceae5).
⚠️ Report is 354 commits behind head on main.

Additional details and impacted files
@@             Coverage Diff              @@
##              main   #11254       +/-   ##
============================================
- Coverage   100.00%   82.55%   -17.45%     
============================================
  Files            1        1               
  Lines           24       86       +62     
  Branches         0        2        +2     
============================================
+ Hits            24       71       +47     
- Misses           0       14       +14     
- Partials         0        1        +1     
Flag Coverage Δ
unittests 82.55% <ø> (-17.45%) ⬇️

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.

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