From 0dcf31ebe62cf9c66f4333cf9b5a660a9c0702a4 Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Wed, 2 Dec 2026 18:18:03 +0400 Subject: [PATCH 1/6] Test Simulation.temporary_branch 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 --- tests/core/test_temporary_branch.py | 174 ++++++++++++++++++++++++++++ 1 file changed, 174 insertions(+) create mode 100644 tests/core/test_temporary_branch.py diff --git a/tests/core/test_temporary_branch.py b/tests/core/test_temporary_branch.py new file mode 100644 index 00000000..44baf833 --- /dev/null +++ b/tests/core/test_temporary_branch.py @@ -0,0 +1,174 @@ +"""``Simulation.temporary_branch``: a branch for one block of code. + +A formula that needs a changed copy of its simulation (raised earnings, a +neutralized variable) creates a branch, calculates in it, and should leave +nothing behind. ``with simulation.temporary_branch(name) as branch:`` gives a +new branch, which a plain simulation keeps in ``branches`` only until the +block ends, whether it ends normally or raises. A read-only simulation (see +``make_read_only``) never keeps it, so there is nothing to remove. + +The branch must be new: a name the simulation already holds, or its own +branch name, would make ``get_branch`` return a branch the block does not own +(or the simulation itself), which the block would then change and remove. So +those names raise ``ValueError`` before anything changes. +""" + +from __future__ import annotations + +import numpy as np +import pytest + +from policyengine_core.country_template import ( + CountryTaxBenefitSystem, + Simulation, +) + +PERIOD = "2022-01" +SALARY = [4000.0, 2500.0] +RAISED_SALARY = [5000.0, 2500.0] +SITUATION = { + "persons": { + "a": {"salary": {PERIOD: SALARY[0]}, "age": {PERIOD: 40}}, + "b": {"salary": {PERIOD: SALARY[1]}, "age": {PERIOD: 30}}, + }, + "households": {"h": {"parents": ["a", "b"]}}, +} + + +class FailureInsideTheBlock(Exception): + """Raised by a test inside a temporary branch's block.""" + + +@pytest.fixture(scope="module") +def shared_system(): + """A system the tests in this module read but never change.""" + return CountryTaxBenefitSystem() + + +@pytest.fixture +def simulation(shared_system) -> Simulation: + return Simulation(tax_benefit_system=shared_system, situation=SITUATION) + + +def test_a_plain_simulation_keeps_a_temporary_branch_only_inside_its_block( + simulation, +): + registered_before = dict(simulation.branches) + with simulation.temporary_branch("temporary") as branch: + assert simulation.branches["temporary"] is branch + assert branch is not simulation + assert branch.branch_name == "temporary" + assert branch.parent_branch is simulation + assert simulation.branches == registered_before + + +def test_a_temporary_branch_calculates_from_its_own_inputs(simulation): + income_tax = simulation.calculate("income_tax", PERIOD).copy() + with simulation.temporary_branch("raised_salary") as branch: + branch.set_input("salary", PERIOD, np.array(RAISED_SALARY)) + raised_income_tax = branch.calculate("income_tax", PERIOD) + assert raised_income_tax[0] > income_tax[0] + np.testing.assert_array_equal(raised_income_tax[1], income_tax[1]) + np.testing.assert_array_equal( + simulation.calculate("income_tax", PERIOD), income_tax + ) + np.testing.assert_array_equal(simulation.calculate("salary", PERIOD), SALARY) + + +def test_a_temporary_branch_is_removed_when_its_block_raises(simulation): + registered_before = dict(simulation.branches) + with pytest.raises(FailureInsideTheBlock): + with simulation.temporary_branch("temporary") as branch: + branch.set_input("salary", PERIOD, np.array(RAISED_SALARY)) + raise FailureInsideTheBlock() + assert simulation.branches == registered_before + # A later block with the same name starts from the simulation again, + # not from the raised salary the failed block set. + with simulation.temporary_branch("temporary") as branch: + np.testing.assert_array_equal(branch.calculate("salary", PERIOD), SALARY) + + +def test_a_read_only_simulation_never_keeps_a_temporary_branch(simulation): + income_tax = simulation.calculate("income_tax", PERIOD).copy() + registered_before = dict(simulation.branches) + simulation.make_read_only() + with simulation.temporary_branch("raised_salary") as branch: + assert simulation.branches == registered_before + assert branch.parent_branch is simulation + assert not branch.read_only + branch.set_input("salary", PERIOD, np.array(RAISED_SALARY)) + raised_income_tax = branch.calculate("income_tax", PERIOD) + assert raised_income_tax[0] > income_tax[0] + assert simulation.branches == registered_before + np.testing.assert_array_equal( + simulation.calculate("income_tax", PERIOD), income_tax + ) + + +def test_a_read_only_simulation_gives_a_new_temporary_branch_every_time( + simulation, +): + simulation.make_read_only() + with simulation.temporary_branch("temporary") as first: + first.set_input("salary", PERIOD, np.array(RAISED_SALARY)) + with simulation.temporary_branch("temporary") as second: + assert second is not first + np.testing.assert_array_equal(second.calculate("salary", PERIOD), SALARY) + + +def test_a_temporary_branch_of_a_temporary_branch_is_removed_from_its_parent( + simulation, +): + with simulation.temporary_branch("outer") as outer: + with outer.temporary_branch("inner") as inner: + assert outer.branches["inner"] is inner + assert inner.parent_branch is outer + assert "inner" not in outer.branches + assert simulation.branches["outer"] is outer + assert "outer" not in simulation.branches + + +def test_a_temporary_branch_with_its_own_system_leaves_the_parents_system( + simulation, +): + with simulation.temporary_branch("neutralized", clone_system=True) as branch: + assert branch.tax_benefit_system is not simulation.tax_benefit_system + branch.tax_benefit_system.neutralize_variable("income_tax") + np.testing.assert_array_equal(branch.calculate("income_tax", PERIOD), [0, 0]) + assert not simulation.tax_benefit_system.get_variable("income_tax").is_neutralized + assert np.all(simulation.calculate("income_tax", PERIOD) > 0) + + +@pytest.mark.parametrize("read_only", [False, True], ids=["plain", "read-only"]) +def test_a_temporary_branch_refuses_a_name_the_simulation_holds(simulation, read_only): + held = simulation.get_branch("taken") + held.set_input("salary", PERIOD, np.array(RAISED_SALARY)) + if read_only: + simulation.make_read_only() + block_ran = False + with pytest.raises(ValueError, match="taken"): + with simulation.temporary_branch("taken"): + block_ran = True + assert not block_ran + assert simulation.branches["taken"] is held + np.testing.assert_array_equal(held.calculate("salary", PERIOD), RAISED_SALARY) + + +def test_a_temporary_branch_refuses_the_simulations_own_name(simulation): + branch = simulation.get_branch("own_name") + block_ran = False + with pytest.raises(ValueError, match="own_name"): + with branch.temporary_branch("own_name"): + block_ran = True + assert not block_ran + assert simulation.branches["own_name"] is branch + np.testing.assert_array_equal(branch.calculate("salary", PERIOD), SALARY) + + +def test_a_block_that_replaces_its_branch_keeps_the_replacement(simulation): + """The block's end removes only the branch it gave.""" + with simulation.temporary_branch("temporary") as branch: + del simulation.branches["temporary"] + replacement = simulation.get_branch("temporary") + assert replacement is not branch + assert simulation.branches["temporary"] is replacement From a4a7f1e59cb9bf7fff0369dd506961e30c21edbd Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Wed, 2 Dec 2026 18:18:36 +0400 Subject: [PATCH 2/6] Add Simulation.temporary_branch 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 --- policyengine_core/simulations/simulation.py | 74 ++++++++++++++++++++- 1 file changed, 72 insertions(+), 2 deletions(-) diff --git a/policyengine_core/simulations/simulation.py b/policyengine_core/simulations/simulation.py index bf1352d6..f62432d3 100644 --- a/policyengine_core/simulations/simulation.py +++ b/policyengine_core/simulations/simulation.py @@ -1,11 +1,21 @@ import hashlib import os -from contextlib import nullcontext +from contextlib import contextmanager, nullcontext import types from contextvars import ContextVar from dataclasses import dataclass from threading import Lock -from typing import TYPE_CHECKING, Any, Dict, List, Optional, Tuple, Type, Union +from typing import ( + TYPE_CHECKING, + Any, + Dict, + Iterator, + List, + Optional, + Tuple, + Type, + Union, +) import numpy as np import pandas as pd @@ -3451,6 +3461,66 @@ def get_branch( branch.tracer = self.tracer return branch + @contextmanager + def temporary_branch( + self, name: str = "branch", clone_system: bool = False + ) -> Iterator["Simulation"]: + """Give a new branch for the length of a ``with`` block. + + For a formula that needs a changed copy of this simulation (raised + inputs, a neutralized variable) and should leave nothing behind:: + + with simulation.temporary_branch("raised_earnings") as branch: + branch.set_input("earnings", period, raised_earnings) + raised = branch.calculate("net_income", period) + + The branch is made by :meth:`get_branch`, so it is part of this + 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. A + read-only simulation (see :meth:`make_read_only`) never keeps it, so + there is nothing to remove, and each block gets a new branch. + + The branch must be new. A name this simulation already holds in + ``branches``, or its own ``branch_name``, raises ``ValueError`` + before anything changes: :meth:`get_branch` would return that + branch, or this simulation itself, which the block would then change + and remove. + + Args: + name (str, optional): Name of the branch. Defaults to "branch". + clone_system (bool, optional): Whether the branch gets its own + copy of the tax-benefit system, as in :meth:`get_branch`. + Defaults to False. + + Yields: + Simulation: The new branch. + + Raises: + ValueError: ``name`` is this simulation's branch name, or a + branch this simulation holds. + """ + if name == self.branch_name: + raise ValueError( + f"A temporary branch can't be named {name!r}: that is this " + "simulation's own branch name, so get_branch would return " + "the simulation itself." + ) + if name in self.branches: + raise ValueError( + f"A temporary branch can't be named {name!r}: this simulation " + "already holds a branch with that name, which the block would " + "change and remove." + ) + branch = self.get_branch(name, clone_system=clone_system) + try: + yield branch + finally: + # Remove only the branch this block was given: the block may have + # replaced it, and a read-only simulation never kept it. + if self.branches.get(name) is branch: + del self.branches[name] + def derivative( self, variable: str, wrt: str, period: Period = None, delta: float = 1 ) -> ArrayLike: From 36eb49779a60bf0487b0aafaeafede0b283a80ab Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Wed, 2 Dec 2026 18:18:54 +0400 Subject: [PATCH 3/6] Document Simulation.temporary_branch and add its changelog fragment Co-Authored-By: Claude Opus 5.5 --- changelog.d/temporary-branch.added.md | 1 + docs/python_api/simulations.md | 2 ++ docs/usage/branches.md | 21 +++++++++++++++++++++ 3 files changed, 24 insertions(+) create mode 100644 changelog.d/temporary-branch.added.md diff --git a/changelog.d/temporary-branch.added.md b/changelog.d/temporary-branch.added.md new file mode 100644 index 00000000..6dedd144 --- /dev/null +++ b/changelog.d/temporary-branch.added.md @@ -0,0 +1 @@ +Added `Simulation.temporary_branch`, a context manager that gives a new branch for one `with` block and removes it from `branches` when the block ends or raises; a read-only simulation never keeps it. diff --git a/docs/python_api/simulations.md b/docs/python_api/simulations.md index 0aaf4d8b..b80cefb8 100644 --- a/docs/python_api/simulations.md +++ b/docs/python_api/simulations.md @@ -32,6 +32,8 @@ keeps values it does not hold yet. calculation raises `ReadOnlySimulationError` instead. - `get_branch` with a new name returns a branch that is not kept in `branches` and is not read-only itself. +- `temporary_branch` gives a new branch for each `with` block and never keeps + it in `branches`. The method's docstring lists what is not detected. diff --git a/docs/usage/branches.md b/docs/usage/branches.md index eec1ae1d..ade8f509 100644 --- a/docs/usage/branches.md +++ b/docs/usage/branches.md @@ -20,6 +20,27 @@ the branch is created does not reach the branch, and what the branch stores does not reach the parent. A branch of a branch reads its own values first, then its parent's, then those of the simulation at the root. +## Temporary branches + +A formula that needs a branch only while it calculates, and should leave +nothing behind, uses `temporary_branch`: + +```python +with simulation.temporary_branch("raised_earnings") as branch: + branch.set_input("employment_income", 2026, raised_earnings) + raised_net_income = branch.calculate("household_net_income", 2026) +``` + +The branch is made by `get_branch`, so it starts with everything described +above. The simulation holds it in `branches` only while the block runs: when +the block ends, normally or by raising, the branch is removed. A read-only +simulation (see `make_read_only`) never keeps it, so each block gets a new +branch and there is nothing to remove. + +The branch must be new: a name the simulation already holds, or its own +branch name, raises `ValueError` before the block runs, because `get_branch` +would return that branch or the simulation itself. + ## Inputs set on a branch `set_input` on a branch stores the new value and drops every value the branch From b86129019be6b18b653993570d6226dbe130520c Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Wed, 2 Dec 2026 18:38:13 +0400 Subject: [PATCH 4/6] Test temporary_branch from a formula and through a get_branch override 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 --- docs/python_api/simulations.md | 4 +- docs/usage/branches.md | 15 +++- policyengine_core/simulations/simulation.py | 31 +++++--- tests/core/test_temporary_branch.py | 81 +++++++++++++++++++++ 4 files changed, 115 insertions(+), 16 deletions(-) diff --git a/docs/python_api/simulations.md b/docs/python_api/simulations.md index b80cefb8..e2f985ed 100644 --- a/docs/python_api/simulations.md +++ b/docs/python_api/simulations.md @@ -32,8 +32,8 @@ keeps values it does not hold yet. calculation raises `ReadOnlySimulationError` instead. - `get_branch` with a new name returns a branch that is not kept in `branches` and is not read-only itself. -- `temporary_branch` gives a new branch for each `with` block and never keeps - it in `branches`. +- `temporary_branch` with a name it doesn't hold gives a new branch for each + `with` block and never keeps it in `branches`. The method's docstring lists what is not detected. diff --git a/docs/usage/branches.md b/docs/usage/branches.md index ade8f509..4e7b768a 100644 --- a/docs/usage/branches.md +++ b/docs/usage/branches.md @@ -33,13 +33,20 @@ with simulation.temporary_branch("raised_earnings") as branch: The branch is made by `get_branch`, so it starts with everything described above. The simulation holds it in `branches` only while the block runs: when -the block ends, normally or by raising, the branch is removed. A read-only +the block ends, normally or by raising, the branch is removed, unless the block +already removed it or put another branch under its name. A read-only simulation (see `make_read_only`) never keeps it, so each block gets a new branch and there is nothing to remove. -The branch must be new: a name the simulation already holds, or its own -branch name, raises `ValueError` before the block runs, because `get_branch` -would return that branch or the simulation itself. +Without `clone_system=True` the branch shares the simulation's tax-benefit +system, so a change to the system or its parameters made through the branch +also changes the simulation, and stays after the block. Use +`clone_system=True` for such changes, as described under "Dropping calculated +values" below. + +A name the simulation already holds, or its own branch name, raises +`ValueError` before the block runs, because `get_branch` would return that +branch or the simulation itself. ## Inputs set on a branch diff --git a/policyengine_core/simulations/simulation.py b/policyengine_core/simulations/simulation.py index f62432d3..a4ba5706 100644 --- a/policyengine_core/simulations/simulation.py +++ b/policyengine_core/simulations/simulation.py @@ -3468,7 +3468,7 @@ def temporary_branch( """Give a new branch for the length of a ``with`` block. For a formula that needs a changed copy of this simulation (raised - inputs, a neutralized variable) and should leave nothing behind:: + inputs, for example) and should leave nothing behind:: with simulation.temporary_branch("raised_earnings") as branch: branch.set_input("earnings", period, raised_earnings) @@ -3477,15 +3477,26 @@ def temporary_branch( The branch is made by :meth:`get_branch`, so it is part of this 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. A - read-only simulation (see :meth:`make_read_only`) never keeps it, so - there is nothing to remove, and each block gets a new branch. - - The branch must be new. A name this simulation already holds in - ``branches``, or its own ``branch_name``, raises ``ValueError`` - before anything changes: :meth:`get_branch` would return that - branch, or this simulation itself, which the block would then change - and remove. + block ends, normally or by raising, the branch is removed, unless + the block already removed it or put another branch under its name, + which then stays. A read-only simulation (see :meth:`make_read_only`) + never keeps it, so there is nothing to remove, and each block gets a + new branch. + + Without ``clone_system`` the branch shares this simulation's + tax-benefit system, so a change to the system or its parameters made + through the branch (``neutralize_variable``, a parameter update) + changes this simulation too, and stays after the block. Pass + ``clone_system=True`` for such changes, and call + :meth:`drop_computed_arrays` on the branch before calculating, as + with :meth:`get_branch`. + + A name this simulation already holds in ``branches``, or its own + ``branch_name``, raises ``ValueError`` before anything changes: + :meth:`get_branch` would return that branch, or this simulation + itself, which the block would then change and remove. Other names + are accepted, as by :meth:`get_branch`, including the branch name of + a simulation this one was branched from. Args: name (str, optional): Name of the branch. Defaults to "branch". diff --git a/tests/core/test_temporary_branch.py b/tests/core/test_temporary_branch.py index 44baf833..f37a932e 100644 --- a/tests/core/test_temporary_branch.py +++ b/tests/core/test_temporary_branch.py @@ -22,6 +22,9 @@ CountryTaxBenefitSystem, Simulation, ) +from policyengine_core.country_template.entities import Person +from policyengine_core.periods import MONTH +from policyengine_core.variables import Variable PERIOD = "2022-01" SALARY = [4000.0, 2500.0] @@ -172,3 +175,81 @@ def test_a_block_that_replaces_its_branch_keeps_the_replacement(simulation): replacement = simulation.get_branch("temporary") assert replacement is not branch assert simulation.branches["temporary"] is replacement + + +SALARY_RISE = 1000.0 + + +class income_tax_after_a_salary_rise(Variable): + """Income tax if salary rose by SALARY_RISE, from a temporary branch.""" + + value_type = float + entity = Person + definition_period = MONTH + label = "Income tax after a salary rise" + + def formula(person, period, parameters): + simulation = person.simulation + raised_salary = person("salary", period) + SALARY_RISE + with simulation.temporary_branch("salary_rise") as branch: + branch.set_input("salary", period, raised_salary) + return branch.calculate("income_tax", period) + + +@pytest.fixture(scope="module") +def system_with_a_branching_formula(): + """A system the tests in this module read but never change.""" + system = CountryTaxBenefitSystem() + system.add_variable(income_tax_after_a_salary_rise) + return system + + +@pytest.mark.parametrize("read_only", [False, True], ids=["plain", "read-only"]) +def test_a_formula_calculates_in_a_temporary_branch_and_keeps_its_result( + system_with_a_branching_formula, read_only +): + raised_situation = { + "persons": { + name: {**person, "salary": {PERIOD: salary + SALARY_RISE}} + for (name, person), salary in zip(SITUATION["persons"].items(), SALARY) + }, + "households": SITUATION["households"], + } + expected = Simulation( + tax_benefit_system=system_with_a_branching_formula, + situation=raised_situation, + ).calculate("income_tax", PERIOD) + + simulation = Simulation( + tax_benefit_system=system_with_a_branching_formula, situation=SITUATION + ) + if read_only: + simulation.make_read_only() + registered_before = dict(simulation.branches) + value = simulation.calculate("income_tax_after_a_salary_rise", PERIOD) + + np.testing.assert_array_equal(value, expected) + assert simulation.branches == registered_before + held = simulation.get_holder("income_tax_after_a_salary_rise").get_array(PERIOD) + np.testing.assert_array_equal(held, expected) + np.testing.assert_array_equal(simulation.calculate("salary", PERIOD), SALARY) + + +class SimulationWithABranchOverride(Simulation): + """Marks each branch its own ``get_branch`` returns, with the request.""" + + def get_branch(self, name="branch", clone_system=False): + branch = super().get_branch(name, clone_system) + branch.request_seen_by_the_override = (name, clone_system) + return branch + + +def test_a_temporary_branch_is_made_by_the_simulations_own_get_branch( + shared_system, +): + simulation = SimulationWithABranchOverride( + tax_benefit_system=shared_system, situation=SITUATION + ) + with simulation.temporary_branch("temporary", clone_system=True) as branch: + assert branch.request_seen_by_the_override == ("temporary", True) + assert "temporary" not in simulation.branches From 00b0e18a75179d26084178e3532b9c47172ad78e Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Wed, 2 Dec 2026 19:01:18 +0400 Subject: [PATCH 5/6] Test that a failed branch creation leaves nothing registered 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 --- tests/core/test_temporary_branch.py | 37 +++++++++++++++++++++++++++++ 1 file changed, 37 insertions(+) diff --git a/tests/core/test_temporary_branch.py b/tests/core/test_temporary_branch.py index f37a932e..caae2716 100644 --- a/tests/core/test_temporary_branch.py +++ b/tests/core/test_temporary_branch.py @@ -253,3 +253,40 @@ def test_a_temporary_branch_is_made_by_the_simulations_own_get_branch( with simulation.temporary_branch("temporary", clone_system=True) as branch: assert branch.request_seen_by_the_override == ("temporary", True) assert "temporary" not in simulation.branches + + +class FailureAfterTheBranchIsRegistered(Exception): + """Raised by a ``get_branch`` override after core registered the branch.""" + + +class SimulationWhoseBranchOverrideFails(Simulation): + """Its ``get_branch`` registers a branch through core, then raises.""" + + def get_branch(self, name="branch", clone_system=False): + super().get_branch(name, clone_system) + raise FailureAfterTheBranchIsRegistered() + + +def test_a_branch_whose_creation_fails_after_registering_is_removed(shared_system): + simulation = SimulationWhoseBranchOverrideFails( + tax_benefit_system=shared_system, situation=SITUATION + ) + registered_before = dict(simulation.branches) + block_ran = False + with pytest.raises(FailureAfterTheBranchIsRegistered): + with simulation.temporary_branch("temporary"): + block_ran = True + assert not block_ran + assert simulation.branches == registered_before + + +def test_a_read_only_simulation_keeps_nothing_when_a_block_raises(simulation): + simulation.make_read_only() + registered_before = dict(simulation.branches) + with pytest.raises(FailureInsideTheBlock): + with simulation.temporary_branch("temporary") as branch: + branch.set_input("salary", PERIOD, np.array(RAISED_SALARY)) + raise FailureInsideTheBlock() + assert simulation.branches == registered_before + with simulation.temporary_branch("temporary") as branch: + np.testing.assert_array_equal(branch.calculate("salary", PERIOD), SALARY) From c3f74da4cab730e02e9516101b0594d17b71822a Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Wed, 2 Dec 2026 19:01:30 +0400 Subject: [PATCH 6/6] Remove a branch whose creation failed after it was registered 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 --- docs/python_api/simulations.md | 6 ++++-- policyengine_core/simulations/simulation.py | 16 ++++++++++++---- 2 files changed, 16 insertions(+), 6 deletions(-) diff --git a/docs/python_api/simulations.md b/docs/python_api/simulations.md index e2f985ed..fd1fd840 100644 --- a/docs/python_api/simulations.md +++ b/docs/python_api/simulations.md @@ -32,8 +32,10 @@ keeps values it does not hold yet. calculation raises `ReadOnlySimulationError` instead. - `get_branch` with a new name returns a branch that is not kept in `branches` and is not read-only itself. -- `temporary_branch` with a name it doesn't hold gives a new branch for each - `with` block and never keeps it in `branches`. +- `temporary_branch` gives a new branch for each `with` block and never keeps + it in `branches`. As on any simulation, it refuses the simulation's own branch + name and the name of a branch it holds (one registered before + `make_read_only`). The method's docstring lists what is not detected. diff --git a/policyengine_core/simulations/simulation.py b/policyengine_core/simulations/simulation.py index a4ba5706..cf06ff6b 100644 --- a/policyengine_core/simulations/simulation.py +++ b/policyengine_core/simulations/simulation.py @@ -3479,7 +3479,8 @@ def temporary_branch( branches holds it in ``branches`` only while the block runs: when the block ends, normally or by raising, the branch is removed, unless the block already removed it or put another branch under its name, - which then stays. A read-only simulation (see :meth:`make_read_only`) + which then stays. If making the branch fails, nothing is left under + its name. A read-only simulation (see :meth:`make_read_only`) never keeps it, so there is nothing to remove, and each block gets a new branch. @@ -3508,8 +3509,8 @@ def temporary_branch( Simulation: The new branch. Raises: - ValueError: ``name`` is this simulation's branch name, or a - branch this simulation holds. + ValueError: ``name`` is this simulation's branch name, or the + name of a branch this simulation holds. """ if name == self.branch_name: raise ValueError( @@ -3523,7 +3524,14 @@ def temporary_branch( "already holds a branch with that name, which the block would " "change and remove." ) - branch = self.get_branch(name, clone_system=clone_system) + try: + branch = self.get_branch(name, clone_system=clone_system) + except BaseException: + # The name was free before this call, so a branch now under it + # was registered by this call (by core, before an override of + # get_branch raised). + self.branches.pop(name, None) + raise try: yield branch finally: