CubeLoop — a Pythonic, async-native agent harness core designed for high performance, readability, and production-grade persistence.
Python agent-frameworkagent-harnessagent-runtimeagentic-aiai-agentsai-frameworkanthropicharnessharness-engineeringharness-frameworklanggraphlanggraph-alternativellmmcpopenaipi-agentpi-agent-corepythonpython-agent
fix(hitl): two-phase parallel tool execution to avoid duplicate side effects
xf gong388df675b19a
diff --git a/cubepi/agent/tools.py b/cubepi/agent/tools.pyindex f007c77..0a94e53 100644--- a/cubepi/agent/tools.py+++ b/cubepi/agent/tools.py@@ -373,8 +373,13 @@ async def _execute_parallel(signal: asyncio.Event | None,emit_fn: Callable,) -> ToolCallBatch:- entries: list[_FinalizedOutcome | asyncio.Task] = []-+ # 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.+ entries: list[_FinalizedOutcome | _PreparedToolCall] = []for tc in tool_calls:await emit_event(emit_fn,@@ -410,36 +415,42 @@ async def _execute_parallel()entries.append(finalized)else:+ entries.append(preparation)- async def _run(prep=preparation):- result, is_error = await _execute_prepared(prep, signal, emit_fn)- fin = await _finalize(- context,- assistant_message,- prep,- result,- is_error,- after_tool_call,- signal,- )- await emit_event(- emit_fn,- ToolExecutionEndEvent(- tool_call_id=prep.tool_call.id,- tool_name=prep.tool_call.name,- result=fin.result,- is_error=fin.is_error,- terminate=bool(fin.result.terminate),- blocked_by_hook=fin.blocked_by_hook,- block_reason=fin.block_reason,- ),- )- return fin-- entries.append(asyncio.create_task(_run()))-+ async def _run(prep: _PreparedToolCall) -> _FinalizedOutcome:+ result, is_error = await _execute_prepared(prep, signal, emit_fn)+ fin = await _finalize(+ context,+ assistant_message,+ prep,+ result,+ is_error,+ after_tool_call,+ signal,+ )+ await emit_event(+ emit_fn,+ ToolExecutionEndEvent(+ tool_call_id=prep.tool_call.id,+ tool_name=prep.tool_call.name,+ result=fin.result,+ is_error=fin.is_error,+ terminate=bool(fin.result.terminate),+ blocked_by_hook=fin.blocked_by_hook,+ block_reason=fin.block_reason,+ ),+ )+ return fin++ # Now that every prepare has succeeded, fan out the executions.+ scheduled: list[_FinalizedOutcome | asyncio.Task] = [+ entry+ if isinstance(entry, _FinalizedOutcome)+ else asyncio.create_task(_run(entry))+ for entry in entries+ ]finalized_list: list[_FinalizedOutcome] = []- for entry in entries:+ for entry in scheduled:if isinstance(entry, asyncio.Task):finalized_list.append(await entry)else:diff --git a/tests/hitl/test_loop_hitl_passthrough.py b/tests/hitl/test_loop_hitl_passthrough.pyindex 0c1c625..17d6a45 100644--- a/tests/hitl/test_loop_hitl_passthrough.py+++ b/tests/hitl/test_loop_hitl_passthrough.py@@ -1,5 +1,5 @@import pytest-from cubepi.hitl.exceptions import HitlAborted, HitlCancelled+from cubepi.hitl.exceptions import HitlAborted, HitlCancelled, HitlDetachedfrom cubepi.agent.tools import execute_tool_callsfrom cubepi.agent.types import AgentContext, AgentTool, AgentToolResultfrom cubepi.providers.base import AssistantMessage, TextContent, ToolCall@@ -10,13 +10,13 @@ class _NoParams(BaseModel):pass-def _make_tool(name: str, executor):+def _make_tool(name: str, executor, execution_mode: str = "sequential"):return AgentTool(name=name,description="t",parameters=_NoParams,execute=executor,- execution_mode="sequential",+ execution_mode=execution_mode,)@@ -65,3 +65,61 @@ async def test_hitl_control_in_before_tool_call_propagates():with pytest.raises(HitlCancelled):await execute_tool_calls(ctx, msg, before_tool_call=before, emit=lambda e: None)+++async def test_parallel_detach_does_not_start_earlier_tools():+ """Regression: when a later before_tool_call raises HitlDetached, earlier+ parallel tools must NOT have been started — otherwise their side effects+ happen but their ToolResultMessage is never emitted/checkpointed, and+ Agent.respond() re-runs them, duplicating the side effects.++ Codex PR #127 review feedback (P1, agent/tools.py).+ """+ t1_calls = 0+ t2_calls = 0++ async def t1_execute(call_id, args, *, signal=None, on_update=None):+ nonlocal t1_calls+ t1_calls += 1+ return AgentToolResult(content=[TextContent(text="t1 ran")])++ async def t2_execute(call_id, args, *, signal=None, on_update=None):+ nonlocal t2_calls+ t2_calls += 1+ return AgentToolResult(content=[TextContent(text="t2 ran")])++ 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++ with pytest.raises(HitlDetached):+ await execute_tool_calls(+ ctx,+ msg,+ tool_execution="parallel",+ before_tool_call=before,+ emit=lambda e: None,+ )++ # Yield once so any leaked background task has a chance to run.+ import asyncio++ await asyncio.sleep(0)++ assert t1_calls == 0, (+ "t1 was started even though t2's prepare detached — its result will "+ "never be emitted/checkpointed, so resume will duplicate the side effect"+ )+ assert t2_calls == 0