Skip to content

Commit 165390c

Browse files
authored
fix(extensions): keep the current branch when a forced delete_branch fails (#5081)
1 parent 65a9921 commit 165390c

2 files changed

Lines changed: 38 additions & 0 deletions

File tree

‎src/agents/extensions/memory/advanced_sqlite_session.py‎

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1153,6 +1153,13 @@ async def delete_branch(self, branch_id: str, force: bool = False) -> None:
11531153
f"Cannot delete current branch '{branch_id}'. Use force=True or switch branches first" # noqa: E501
11541154
)
11551155
else:
1156+
# Confirm the branch is known before switching away from it; the delete
1157+
# below raises for an unknown branch, which would otherwise leave the
1158+
# session pointing at 'main'.
1159+
if not any(
1160+
branch["branch_id"] == branch_id for branch in await self.list_branches()
1161+
):
1162+
raise ValueError(f"Branch '{branch_id}' does not exist")
11561163
# Switch to main before deleting
11571164
await self.switch_to_branch("main")
11581165

‎tests/extensions/memory/test_advanced_sqlite_session.py‎

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2176,6 +2176,37 @@ async def test_branch_deletion_with_force():
21762176
session.close()
21772177

21782178

2179+
async def test_failed_force_delete_keeps_current_branch():
2180+
"""A force delete that raises must not move the session off its current branch."""
2181+
session = AdvancedSQLiteSession(session_id="failed_force_delete", create_tables=True)
2182+
main_items: list[TResponseInputItem] = [
2183+
{"role": "user", "content": "Main question"},
2184+
{"role": "assistant", "content": "Main answer"},
2185+
]
2186+
branch_items: list[TResponseInputItem] = [
2187+
{"role": "user", "content": "Branch question"},
2188+
]
2189+
2190+
try:
2191+
await session.add_items(main_items)
2192+
2193+
# Branching from turn 1 copies no messages, so the new branch has no history yet.
2194+
branch_id = await session.create_branch_from_turn(1, "alternative_path")
2195+
assert session._current_branch_id == branch_id
2196+
2197+
with pytest.raises(ValueError, match="Branch 'alternative_path' does not exist"):
2198+
await session.delete_branch(branch_id, force=True)
2199+
2200+
assert session._current_branch_id == branch_id
2201+
2202+
# The next turn must stay on the branch instead of landing in main.
2203+
await session.add_items(branch_items)
2204+
assert await session.get_items() == branch_items
2205+
assert await session.get_items(branch_id="main") == main_items
2206+
finally:
2207+
session.close()
2208+
2209+
21792210
async def test_get_items_with_parameters():
21802211
"""Test get_items with new parameters (include_inactive, branch_id)."""
21812212
session_id = "get_items_params_test"

0 commit comments

Comments
 (0)