Skip to content

CubeLoop — a Pythonic, async-native agent harness core designed for high performance, readability, and production-grade persistence.

fix(agent): defer ToolExecutionStartEvent until tool is scheduled

xf gong25218c58486b
diff --git a/cubepi/agent/tools.py b/cubepi/agent/tools.py
index 0a94e53..1bea0f7 100644
--- a/cubepi/agent/tools.py
+++ b/cubepi/agent/tools.py
@@ -375,24 +375,30 @@ async def _execute_parallel(
) -> ToolCallBatch:
# Two-phase: prepare ALL tool calls (which may raise HitlDetached or other
# HitlControlException from before_tool_call) BEFORE scheduling any
- # asyncio.create_task. Otherwise a later prepare detaching the run would
- # leak already-started tool tasks: their side effects happen, but their
- # ToolResultMessage is never emitted/checkpointed, and the resumed run
- # re-executes them — duplicating the side effects.
+ # asyncio.create_task or emitting any ToolExecutionStartEvent. Otherwise:
+ # (a) a later prepare detach would leak already-started tool tasks
+ # (side effects happen but ToolResultMessage is never emitted/
+ # checkpointed, so the resumed run duplicates the side effects);
+ # (b) Start events emitted in the prepare loop would have no matching
+ # End event when prepare later raised, leaving state.pending_tool_calls
+ # and trace spans permanently open.
entries: list[_FinalizedOutcome | _PreparedToolCall] = []
for tc in tool_calls:
- await emit_event(
- emit_fn,
- ToolExecutionStartEvent(
- tool_call_id=tc.id, tool_name=tc.name, args=tc.arguments
- ),
- )
-
preparation = await _prepare_tool_call(
context, assistant_message, tc, before_tool_call, signal
)
if isinstance(preparation, _ImmediateOutcome):
+ # Immediate outcomes get a paired Start+End right here (the
+ # "execution" was the prepare step itself — e.g. blocked by hook
+ # or unknown tool). Pairing keeps the event stream balanced
+ # even though no real tool body runs.
+ await emit_event(
+ emit_fn,
+ ToolExecutionStartEvent(
+ tool_call_id=tc.id, tool_name=tc.name, args=tc.arguments
+ ),
+ )
finalized = _FinalizedOutcome(
tool_call=tc,
result=preparation.result,
@@ -418,6 +424,17 @@ async def _execute_parallel(
entries.append(preparation)
async def _run(prep: _PreparedToolCall) -> _FinalizedOutcome:
+ # Start event lives inside _run so it is emitted only for tools
+ # that actually get scheduled. If a later prepare raises before
+ # we get here, no Start is leaked.
+ await emit_event(
+ emit_fn,
+ ToolExecutionStartEvent(
+ tool_call_id=prep.tool_call.id,
+ tool_name=prep.tool_call.name,
+ args=prep.tool_call.arguments,
+ ),
+ )
result, is_error = await _execute_prepared(prep, signal, emit_fn)
fin = await _finalize(
context,
diff --git a/tests/hitl/test_loop_hitl_passthrough.py b/tests/hitl/test_loop_hitl_passthrough.py
index 17d6a45..0b4acb0 100644
--- a/tests/hitl/test_loop_hitl_passthrough.py
+++ b/tests/hitl/test_loop_hitl_passthrough.py
@@ -123,3 +123,53 @@ async def test_parallel_detach_does_not_start_earlier_tools():
"never be emitted/checkpointed, so resume will duplicate the side effect"
)
assert t2_calls == 0
+
+
+async def test_parallel_detach_does_not_leak_start_events():
+ """Regression: when t2's prepare raises HitlDetached during a parallel
+ batch, no `ToolExecutionStartEvent` for t1 or t2 may have been emitted —
+ otherwise `state.pending_tool_calls` and the corresponding trace span
+ are stuck open with no matching ToolExecutionEndEvent.
+
+ Codex PR #127 review feedback (P2 agent/tools.py).
+ """
+ from cubepi.agent.types import ToolExecutionStartEvent
+
+ async def t1_execute(call_id, args, *, signal=None, on_update=None):
+ return AgentToolResult(content=[TextContent(text="ok")])
+
+ async def t2_execute(call_id, args, *, signal=None, on_update=None):
+ return AgentToolResult(content=[TextContent(text="ok")])
+
+ t1 = _make_tool("t1", t1_execute, execution_mode="parallel")
+ t2 = _make_tool("t2", t2_execute, execution_mode="parallel")
+ ctx = AgentContext(system_prompt="", messages=[], tools=[t1, t2])
+ msg = AssistantMessage(
+ content=[
+ ToolCall(id="tc-1", name="t1", arguments={}),
+ ToolCall(id="tc-2", name="t2", arguments={}),
+ ],
+ stop_reason="tool_use",
+ )
+
+ async def before(before_ctx, *, signal=None):
+ if before_ctx.tool_call.id == "tc-2":
+ raise HitlDetached()
+ return None
+
+ events: list = []
+ with pytest.raises(HitlDetached):
+ await execute_tool_calls(
+ ctx,
+ msg,
+ tool_execution="parallel",
+ before_tool_call=before,
+ emit=lambda e: events.append(e),
+ )
+
+ start_events = [e for e in events if isinstance(e, ToolExecutionStartEvent)]
+ assert start_events == [], (
+ f"leaked {len(start_events)} ToolExecutionStartEvent(s) with no End — "
+ f"state.pending_tool_calls / trace spans would be stuck open: "
+ f"{[(e.tool_call_id, e.tool_name) for e in start_events]}"
+ )