Repository navigation
Conversation
…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 Report✅ All modified and coverable lines are covered by tests. 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
Flags with carried forward coverage won't be shown. Click here to find out more. ☔ View full report in Codecov by Harness. 🚀 New features to boost your workflow:
|
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>
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>
hua7450
left a comment
There was a problem hiding this comment.
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_branchremoves its branch on normal exit and after an error, a read-only simulation never keeps it, and it raisesValueErrorfor 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
ValueErroralready raisedKeyErroronmain, after changing inputs or the tax-benefit system. - The employer revenue formulas are equivalent to
main. The same statements run inside thewithblock, 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.
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:
marginal_earnings_change), whichmarginal_tax_rate,marginal_tax_rate_including_health_benefitsand 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_branchand removed it afterwards withdel simulation.branches[name]. That failed in two ways:Simulation.make_read_only()),get_branchwith a new name doesn't keep the branch inbranches, so thedelraisedKeyError.delnever 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 inbranchesonly 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, withValueError, the simulation's own branch name or the name of a branch it holds. This PR moves the four formulas onto it and requirespolicyengine-core>=3.40.0.uv.lockmoves only policyengine-core, from 3.37.2 to 3.40.0.prepare_perturbationreads everything the raised branch needs from the simulation: inputs to keep, behavioral responses to hold, raised values. It runs before any branch exists.apply_perturbationsets those on a branch.perturbed_branchis a new context manager. It runs the first step, openssimulation.temporary_branch, runs the second step and yields the branch.marginal_earnings_changeand the capital gains rate calculate inside its block.create_perturbed_branchstays, built from the same two steps withget_branch, for the tests that keep a raised branch after the call.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:All seven rates, household net income, both behavioral responses and both employer revenues are identical in two comparisons: the branch against
mainon core 3.40.0, and the branch on 3.40.0 againstmainon 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:
mainmarginal_tax_rateKeyError: 'mtr_for_adult_1'state_marginal_tax_rateKeyError: 'state_mtr_for_adult_1'fica_marginal_tax_rateKeyError: 'fica_mtr_for_adult_1'marginal_tax_rate_on_capital_gainsKeyError: 'adult_1_cg_rise'employer_ss_tax_income_tax_revenue(reform in effect)KeyError: 'without_employer_ss'employer_medicare_tax_income_tax_revenue(reform in effect)KeyError: 'without_employer_medicare'Read-only simulations of reforms 4 and 5 above also give exactly their plain values for every variable listed, and their
branchesis unchanged.Test plan
policyengine_us/tests/core/test_unkept_temporary_branches.pyruns in the Restcoregroup. 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 withtemporary_branch. A plain simulation keeps none of those branches afterwards. A simulation made read-only withmake_read_onlygives exactly the plain values and keeps itsbranchesunchanged.test_formulas_remove_their_branch_when_its_calculation_raises. A step inside the branch is replaced by one that raises:drop_inherited_valuesfor the rates,neutralize_variablefor 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 raisesValueError. 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 observedcreate_perturbed_branch, and now observesperturbed_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:
653dd5df): both cases of the first two tests failed on assertions. The formulas didn't open their branch withtemporary_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.0e876997, then5a7f9b52): all pass, run by node ID only.ruff formatandruff checkpass on the changed files.Cost, measured locally on macOS with a load average of 7–8 from other processes:
These checklist items apply as follows:
make format(ruff format and ruff check)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 ofdel, 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:
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: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 bareexcept: passarounddelete_arrays.🤖 Generated with Claude Code