Skip to content

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

fix(agent): backfill tool_results for tool_calls orphaned by a cancel (#116)

Chrisca832422d534
diff --git a/cubepi/agent/agent.py b/cubepi/agent/agent.py
index 933b9d0..af4aeb5 100644
--- a/cubepi/agent/agent.py
+++ b/cubepi/agent/agent.py
@@ -26,6 +26,8 @@ from cubepi.providers.base import (
StreamOptions,
TextContent,
ThinkingLevel,
+ ToolCall,
+ ToolResultMessage,
Usage,
UserMessage,
)
@@ -328,6 +330,14 @@ class Agent(Generic[TMessage]):
try:
await executor(signal)
+ except asyncio.CancelledError:
+ # A cancel can land after the assistant message (carrying
+ # tool_calls) was checkpointed but before the tool_results were.
+ # That leaves the persisted history with orphan tool_calls, which
+ # every provider rejects on the next turn. Backfill synthetic
+ # tool_results so the thread stays resumable, then re-raise.
+ await self._complete_cancelled_tool_calls()
+ raise
except Exception as error:
await self._handle_run_failure(error, signal.is_set())
finally:
@@ -353,6 +363,61 @@ class Agent(Generic[TMessage]):
)
await self._process_event(AgentEndEvent(messages=[failure_message]))
+ async def _complete_cancelled_tool_calls(self) -> None:
+ """Backfill tool_results for tool_calls left dangling by a cancel.
+
+ Best-effort: a checkpoint failure here must never mask the
+ CancelledError that triggered cleanup. Only the most recent assistant
+ message can have un-answered tool_calls (the loop appends tool_results
+ immediately after), so we scan back to it and synthesize a result for
+ every tool_call id that has no ToolResultMessage yet.
+ """
+ try:
+ last_idx = -1
+ for i in range(len(self._state._messages) - 1, -1, -1):
+ if isinstance(self._state._messages[i], AssistantMessage):
+ last_idx = i
+ break
+ if last_idx == -1:
+ return
+ last_assistant = self._state._messages[last_idx]
+ assert isinstance(last_assistant, AssistantMessage)
+
+ # Only results from this turn count as answered — tool_call ids
+ # are not globally unique, so scanning all history could treat a
+ # reused id from an earlier turn as already answered and skip the
+ # backfill, leaving the thread wedged.
+ answered = {
+ m.tool_call_id
+ for m in self._state._messages[last_idx + 1 :]
+ if isinstance(m, ToolResultMessage)
+ }
+ synthetic: list[Message] = []
+ for block in last_assistant.content:
+ if not isinstance(block, ToolCall) or block.id in answered:
+ continue
+ synthetic.append(
+ ToolResultMessage(
+ tool_call_id=block.id,
+ tool_name=block.name,
+ content=[
+ TextContent(text="[Tool execution cancelled by user]")
+ ],
+ is_error=True,
+ timestamp=time.time(),
+ )
+ )
+
+ if not synthetic:
+ return
+ self._state._messages.extend(synthetic)
+ if self.checkpointer and self.thread_id:
+ await self.checkpointer.append(self.thread_id, synthetic)
+ except asyncio.CancelledError: # pragma: no cover - re-raise the trigger
+ raise
+ except Exception: # pragma: no cover - cleanup must never mask the cancel
+ pass
+
async def _process_event(self, event: AgentEvent) -> None:
if event.type == "message_start":
self._state.streaming_message = event.message
diff --git a/tests/agent/test_checkpointer_integration.py b/tests/agent/test_checkpointer_integration.py
index a5ef46c..a41e552 100644
--- a/tests/agent/test_checkpointer_integration.py
+++ b/tests/agent/test_checkpointer_integration.py
@@ -1,9 +1,19 @@
+import asyncio
+
+import pytest
from pydantic import BaseModel
from cubepi.agent.agent import Agent
from cubepi.agent.types import AgentTool, AgentToolResult
from cubepi.checkpointer.memory import MemoryCheckpointer
-from cubepi.providers.base import Model, TextContent, ToolResultMessage
+from cubepi.providers.base import (
+ AssistantMessage,
+ Model,
+ TextContent,
+ ToolCall,
+ ToolResultMessage,
+ UserMessage,
+)
from cubepi.providers.faux import (
FauxProvider,
faux_assistant_message,
@@ -181,3 +191,178 @@ class TestCheckpointerIntegration:
# New messages
assert agent2.state.messages[4].role == "user"
assert agent2.state.messages[5].role == "assistant"
+
+ async def test_cancel_mid_tool_backfills_tool_result(self):
+ """A cancel during tool execution must not leave an orphan tool_call.
+
+ The assistant message (with the tool_call) is checkpointed before the
+ tool runs; if the tool execution is cancelled, the loop backfills a
+ synthetic tool_result so the persisted thread stays resumable.
+ """
+
+ class BlockParams(BaseModel):
+ pass
+
+ async def cancel_execute(tool_call_id, params, *, signal=None, on_update=None):
+ raise asyncio.CancelledError()
+
+ block_tool = AgentTool(
+ name="block",
+ description="Never returns; simulates a cancelled tool call",
+ parameters=BlockParams,
+ execute=cancel_execute,
+ )
+
+ checkpointer = MemoryCheckpointer()
+ provider = FauxProvider()
+ provider.set_responses(
+ [
+ faux_assistant_message(
+ faux_tool_call("block", {}, id="tc-cancel"),
+ stop_reason="tool_use",
+ ),
+ ]
+ )
+ agent = Agent(
+ provider=provider,
+ model=make_model(),
+ tools=[block_tool],
+ checkpointer=checkpointer,
+ thread_id="thread-cancel",
+ )
+
+ with pytest.raises(asyncio.CancelledError):
+ await agent.prompt("Run the blocking tool")
+
+ data = await checkpointer.load("thread-cancel")
+ assert data is not None
+ # user + assistant(tool_call) + synthetic tool_result = 3
+ assert [m.role for m in data.messages] == ["user", "assistant", "tool_result"]
+ tool_result = data.messages[2]
+ assert isinstance(tool_result, ToolResultMessage)
+ assert tool_result.tool_call_id == "tc-cancel"
+ assert tool_result.is_error is True
+
+ async def test_cancel_backfill_handles_reused_tool_call_id(self):
+ """A reused tool_call_id from an earlier (answered) turn must not
+ suppress the backfill for the current cancelled turn.
+
+ tool_call ids carry no global-uniqueness guarantee, so 'answered'
+ must be scoped to results after the last assistant message.
+ """
+
+ class BlockParams(BaseModel):
+ pass
+
+ async def cancel_execute(tool_call_id, params, *, signal=None, on_update=None):
+ raise asyncio.CancelledError()
+
+ block_tool = AgentTool(
+ name="block",
+ description="Cancels on execution",
+ parameters=BlockParams,
+ execute=cancel_execute,
+ )
+
+ checkpointer = MemoryCheckpointer()
+ # Pre-seed an earlier, fully-answered turn that already used id "dup".
+ await checkpointer.append(
+ "thread-reuse",
+ [
+ UserMessage(content=[TextContent(text="first")]),
+ AssistantMessage(
+ content=[ToolCall(id="dup", name="block", arguments={})],
+ stop_reason="tool_use",
+ ),
+ ToolResultMessage(
+ tool_call_id="dup",
+ tool_name="block",
+ content=[TextContent(text="ok")],
+ ),
+ ],
+ )
+
+ provider = FauxProvider()
+ provider.set_responses(
+ [
+ faux_assistant_message(
+ faux_tool_call("block", {}, id="dup"),
+ stop_reason="tool_use",
+ ),
+ ]
+ )
+ agent = Agent(
+ provider=provider,
+ model=make_model(),
+ tools=[block_tool],
+ checkpointer=checkpointer,
+ thread_id="thread-reuse",
+ )
+
+ with pytest.raises(asyncio.CancelledError):
+ await agent.prompt("second")
+
+ data = await checkpointer.load("thread-reuse")
+ assert data is not None
+ # Earlier turn (3) + new user + assistant + synthetic tool_result = 6
+ assert [m.role for m in data.messages] == [
+ "user",
+ "assistant",
+ "tool_result",
+ "user",
+ "assistant",
+ "tool_result",
+ ]
+ backfilled = data.messages[5]
+ assert isinstance(backfilled, ToolResultMessage)
+ assert backfilled.tool_call_id == "dup"
+ assert backfilled.is_error is True
+
+ async def test_cancel_backfill_only_for_unanswered_calls(self):
+ """Backfill skips already-answered tool_calls and only fills orphans —
+ e.g. one of two parallel calls finished before the cancel landed."""
+ agent = Agent(provider=FauxProvider(), model=make_model())
+ agent._state._messages = [
+ UserMessage(content=[TextContent(text="go")]),
+ AssistantMessage(
+ content=[
+ TextContent(text="working"),
+ ToolCall(id="done", name="a", arguments={}),
+ ToolCall(id="orphan", name="b", arguments={}),
+ ],
+ stop_reason="tool_use",
+ ),
+ ToolResultMessage(
+ tool_call_id="done",
+ tool_name="a",
+ content=[TextContent(text="ok")],
+ ),
+ ]
+ await agent._complete_cancelled_tool_calls()
+ results = [
+ m for m in agent._state._messages if isinstance(m, ToolResultMessage)
+ ]
+ # "done" already answered; only "orphan" is backfilled.
+ assert [r.tool_call_id for r in results] == ["done", "orphan"]
+ assert results[1].is_error is True
+
+ async def test_cancel_backfill_noop_without_orphans(self):
+ """No assistant message, or no unanswered tool_calls — nothing added."""
+ agent = Agent(provider=FauxProvider(), model=make_model())
+ # No assistant at all.
+ agent._state._messages = [UserMessage(content=[TextContent(text="hi")])]
+ await agent._complete_cancelled_tool_calls()
+ assert len(agent._state._messages) == 1
+ # Assistant with a fully-answered tool_call.
+ agent._state._messages = [
+ UserMessage(content=[TextContent(text="go")]),
+ AssistantMessage(
+ content=[ToolCall(id="a", name="t", arguments={})],
+ stop_reason="tool_use",
+ ),
+ ToolResultMessage(
+ tool_call_id="a", tool_name="t", content=[TextContent(text="ok")]
+ ),
+ ]
+ await agent._complete_cancelled_tool_calls()
+ assert len(agent._state._messages) == 3