Skip to content

Add Simulation.temporary_branch for a branch used by one block of code - #677

Merged
anth-volk merged 6 commits into
masterfrom
temporary-branch-context-manager
Dec 2, 2026
Merged

anth-volk merged 6 commits into
masterfrom
temporary-branch-context-manager

Conversation

@anth-volk

@anth-volk anth-volk commented Dec 2, 2026 •

Copy link
Copy Markdown
Collaborator

Fixes #676

What and why

Some country-package formulas need a changed copy of their simulation for one calculation, then remove it. policyengine-us has four: its marginal tax rate helper, the capital gains marginal tax rate, and the employer Social Security and Medicare income tax revenue variables. Each calls get_branch(name), calculates in the branch, then runs del simulation.branches[name]. On a read-only simulation (#672), get_branch with a new name doesn't keep the branch in branches, so that del raises KeyError. And when the calculation inside the branch raises, the branch stays registered, and the next get_branch with that name returns it with the failed calculation's inputs.

This adds Simulation.temporary_branch(name="branch", clone_system=False), a context manager:

with simulation.temporary_branch("raised_earnings") as branch:
    branch.set_input("employment_income", period, raised_earnings)
    raised = branch.calculate("household_net_income", period)
  • The branch is made by get_branch, so a subclass's get_branch override still runs, and the branch is part of the simulation as any other branch is.
  • A simulation that keeps its branches holds it in branches only while the block runs. When the block ends, normally or by raising, the branch is removed; the exception still reaches the caller. If the block removed the branch itself or put another branch under the same name, that one stays. If making the branch fails (a get_branch override raising after core registered it), nothing is left under its name.
  • A read-only simulation never keeps it: each block gets a new branch, and there is nothing to remove.
  • A name the simulation already holds in branches, or its own branch_name, raises ValueError before anything changes: get_branch would return that branch, or the simulation itself, which the block would then change and remove.

Docs: a "Temporary branches" section in docs/usage/branches.md, a bullet in the read-only list of docs/python_api/simulations.md, and the method's docstring (also rendered by the API page's autoclass). Changelog: changelog.d/temporary-branch.added.md.

A policyengine-us PR will move the four formulas onto this once it is released.

Tests

tests/core/test_temporary_branch.py, 16 tests on the country template:

  • a plain simulation holds the branch only inside the block; the branch calculates from its own inputs and leaves the simulation's values unchanged;
  • the branch is removed when the block raises, and a later block with the same name starts from the simulation again, on a plain and a read-only simulation;
  • a get_branch override that raises after core registered the branch leaves nothing registered;
  • a read-only simulation never keeps the branch and gives a new one for each block;
  • nested temporary branches are removed from their own parents; clone_system=True gives the branch its own system;
  • a held name (on a plain and a read-only simulation) and the simulation's own name raise ValueError without running the block or changing the held branch;
  • a branch the block puts under the same name stays;
  • a formula that opens a temporary branch while it calculates gives the value a simulation with the changed input gives, keeps no branch, and the simulation keeps the formula's result, on a plain and a read-only simulation;
  • a subclass's get_branch override makes the branch and receives clone_system.

Results, run by node ID only:

  • The first 11 tests were committed before the change (0dcf31eb). All 11 failed there because Simulation.temporary_branch didn't exist, and all pass after a4a7f1e5.
  • Three tests were added after review round 1 (b8612901): the formula test, which runs in two cases, and the override test. They pass.
  • Two were added after review round 2 (00b0e18a). The failed-creation test failed there on its assertion, because the branch stayed registered, and passes after c3f74da4. The read-only raise test adds coverage and passed from the start.
  • All 16 pass in the environment from uv.lock.
  • ruff format and ruff check pass on the changed Python files.
  • mypy 0.991 from the lock file stops in this environment, asking for the typed_ast package, so it wasn't run; CI doesn't run it.

Review

Two adversarial review rounds, each by a separate reviewer, found no bug. Round 1 checked:

  • the interaction with the calculation frames' branch records, attempt caches and the re-runs after an input change;
  • context-manager exits by error and return;
  • read-only simulations and nested use.

It found two cases covered only by reasoning and some missing documentation; the last commit adds those tests and fixes the docs:

  • a formula that opens the branch while it calculates;
  • a get_branch override;
  • clone_system=True for system or parameter changes;
  • a branch put under the same name inside the block.

Round 2 also checked the description's claims and ran six existing tests, by node ID, that delete branches during re-runs and branch read-only simulations; all passed. It checked:

  • threads;
  • microsimulations and subsampled simulations;
  • cloning, pickling and applying a reform while a block is open;
  • generator exits.

It raised three points, now addressed:

  • a branch left registered when a get_branch override raises after core registered it (fixed, with a test that failed first; get_branch followed by del leaks the same way today);
  • no test of a block that raises on a read-only simulation (added);
  • two wording gaps in the docs about which names are refused (fixed).

Limitations it reported, which this PR doesn't change:

  • Threads. Checking that the name is free and creating the branch are not one atomic step, so two threads opening blocks with the same name on one simulation can share a branch. get_branch's docstring already says that a branch, like the rest of a simulation, isn't safe to read from several threads at once.
  • Copies. A simulation pickled or deep-copied while a block is open keeps the branch registered in the copy, where a later block with that name raises ValueError.
  • Re-runs. No test opens a block in a formula whose calculation runs again after an input change. The reviewers checked that path by reading the code: a re-run starts only after the block has ended.

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

Merge

Every earlier task this builds on has merged; it branches from master at 8eabab83. The requester gave the go-ahead to merge once the checks pass.

🤖 Generated with Claude Code

anth-volk and others added 6 commits December 2, 2026 18:18
A formula that needs a changed copy of its simulation creates a branch,
calculates in it, and should leave nothing behind. The tests describe a
context manager that keeps the branch in a plain simulation's branches
only inside its block, removes it when the block ends or raises, never
keeps it in a read-only simulation, and refuses with ValueError a name
the simulation already holds or is named. They fail before the change
because the method does not exist.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
A context manager that gives a new branch, made by get_branch, for one
block. A plain simulation holds it in branches only while the block
runs and removes it when the block ends or raises; a read-only
simulation never keeps it. A name the simulation already holds, or its
own branch name, raises ValueError before anything changes.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Review round 1 found no bug, but two cases were covered only by
reasoning: a formula that opens a temporary branch while it calculates,
on a plain and a read-only simulation, and a subclass whose get_branch
override must make the branch. The docs now say that system or
parameter changes need clone_system=True, that a branch the block put
under the same name stays, and which names are refused.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Review round 2 found that a get_branch override raising after core has
registered the branch leaves it in branches, so the next block with
that name raises ValueError instead. The test fails on that assertion.
A second test covers a block that raises on a read-only simulation.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
temporary_branch checks the name is free before calling get_branch, so
an entry under it after get_branch raised was registered by that call.
Remove it before re-raising. Also say in the docstring's Raises entry
and the read-only API notes which names are refused.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
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.

Give formulas a branch that is removed when their block of code ends

1 participant