Skip to content

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

fix(session): close durable retry gaps

xfgong93bab7d57539
diff --git a/cubeloop/agent/agent.py b/cubeloop/agent/agent.py
index 614b11a..692671d 100644
--- a/cubeloop/agent/agent.py
+++ b/cubeloop/agent/agent.py
@@ -1361,7 +1361,11 @@ class Agent(Generic[TMessage]):
self._state.streaming_message = None
self._state._messages.append(msg)
if self.checkpointer and self.thread_id:
- await self.checkpointer.append(self.thread_id, [msg])
+ try:
+ await self.checkpointer.append(self.thread_id, [msg])
+ except BaseException:
+ self.session._mark_checkpoint_write_failure()
+ raise
elif event.type == "tool_execution_start":
self._state._pending_tool_calls = self._state._pending_tool_calls | {
event.tool_call_id
diff --git a/cubeloop/agent/loop.py b/cubeloop/agent/loop.py
index 148e392..98995f7 100644
--- a/cubeloop/agent/loop.py
+++ b/cubeloop/agent/loop.py
@@ -381,6 +381,9 @@ async def _run_agent_loop_resume_body( # pragma: no cover — E2E tested
current_context.messages.append(msg)
new_messages.append(msg)
+ if current_context.set_input_admission is not None:
+ current_context.set_input_admission(False)
+
# Honor should_stop_after_turn (codex BLOCKING: previous draft skipped this).
should_stop = False
if should_stop_after_turn:
@@ -401,14 +404,14 @@ async def _run_agent_loop_resume_body( # pragma: no cover — E2E tested
# Terminate-by-tool semantics (codex BLOCKING: previous draft ignored).
if terminated_by_tool and not resumed_follow_ups:
- if current_context.set_input_admission is not None:
- current_context.set_input_admission(False)
await emit_event(emit, AgentEndEvent(messages=new_messages))
if set_outcome is not None:
set_outcome("complete")
return new_messages
# Fall through to the normal loop for the next model turn.
+ if current_context.set_input_admission is not None:
+ current_context.set_input_admission(True)
await _run_loop(
current_context=current_context,
new_messages=new_messages,
diff --git a/cubeloop/session/session.py b/cubeloop/session/session.py
index bc3f0b8..e296b37 100644
--- a/cubeloop/session/session.py
+++ b/cubeloop/session/session.py
@@ -1,6 +1,7 @@
from __future__ import annotations
import asyncio
+import copy
import inspect
from collections.abc import Callable
from dataclasses import dataclass, replace
@@ -92,6 +93,7 @@ class ExecutionSession:
self._input_durability: dict[str, InputDurability] = {}
self._queued_inputs: dict[str, Message] = {}
self._delivery_errors: list[DeliveryError] = []
+ self._checkpoint_write_failed = False
self._turn_contexts: list[TurnExecutionContext] = []
self._resume_turn_context: TurnExecutionContext | None = None
self._pending_request: HitlRequest | None = None
@@ -138,6 +140,7 @@ class ExecutionSession:
self._agent._extra.clear()
self._agent._extra.update(extra)
self._agent._checkpoint_loaded = True
+ self._drop_memory_input_receipts()
return data
def request_cancel(self) -> None:
@@ -264,6 +267,17 @@ class ExecutionSession:
self._input_durability.clear()
self._queued_inputs.clear()
+ def _drop_memory_input_receipts(self) -> None:
+ for input_id, durability in tuple(self._input_durability.items()):
+ if durability != "memory":
+ continue
+ self._input_status.pop(input_id, None)
+ self._input_durability.pop(input_id, None)
+ self._queued_inputs.pop(input_id, None)
+
+ def _mark_checkpoint_write_failure(self) -> None:
+ self._checkpoint_write_failed = True
+
def _reconcile_consumed_inputs(self) -> list[str]:
committed: list[str] = []
for input_id, status in tuple(self._input_status.items()):
@@ -292,12 +306,13 @@ class ExecutionSession:
self._accepting_input = True
self._seq = 0
self._delivery_errors = []
+ self._checkpoint_write_failed = False
self._reconcile_consumed_inputs()
for input_id, status in tuple(self._input_status.items()):
if status != "queued":
continue
- removed = self._agent._steering_queue.remove(input_id)
- removed = self._agent._follow_up_queue.remove(input_id) or removed
+ self._agent._steering_queue.remove(input_id)
+ self._agent._follow_up_queue.remove(input_id)
del self._input_status[input_id]
self._input_durability.pop(input_id, None)
self._queued_inputs.pop(input_id, None)
@@ -312,6 +327,8 @@ class ExecutionSession:
None,
)
self._turn_contexts.clear()
+ if self._resume_turn_context is not None:
+ self._turn_contexts.append(self._resume_turn_context)
self._pending_request = None
caught: BaseException | None = None
try:
@@ -323,9 +340,10 @@ class ExecutionSession:
payload = payload.model_copy(deep=True)
await self._agent._execute_prompt(payload, run_id=request.run_id)
elif isinstance(request, RespondExecutionRequest):
+ answer = copy.deepcopy(request.answer)
await self._agent._execute_respond(
question_id=request.question_id,
- answer=request.answer,
+ answer=answer,
expected_run_id=request.run_id,
)
elif isinstance(request, ContinueExecutionRequest):
@@ -355,6 +373,9 @@ class ExecutionSession:
except Exception as exc:
if caught is None:
caught = exc
+ except BaseException:
+ self._release_attempt()
+ raise
try:
try:
@@ -598,7 +619,7 @@ class ExecutionSession:
request: ExecutionRequest,
caught: BaseException | None,
) -> ExecutionResult:
- history_consistent = True
+ tool_cycle_consistent = True
run_messages = [
message
for message in self._agent.state.messages
@@ -607,7 +628,8 @@ class ExecutionSession:
try:
check_tool_cycle(run_messages)
except ToolCycleViolation:
- history_consistent = False
+ tool_cycle_consistent = False
+ history_consistent = tool_cycle_consistent and not self._checkpoint_write_failed
pending = None
pending_is_durable = False
@@ -651,7 +673,7 @@ class ExecutionSession:
)
elif private_outcome == "suspended":
outcome = "suspended"
- elif not history_consistent or private_outcome == "incomplete":
+ elif not tool_cycle_consistent or private_outcome == "incomplete":
outcome = "incomplete"
error = ExecutionError(
kind="inconsistent",
diff --git a/tests/agent/test_execution_session.py b/tests/agent/test_execution_session.py
index a5d554d..c4fdbc9 100644
--- a/tests/agent/test_execution_session.py
+++ b/tests/agent/test_execution_session.py
@@ -3,9 +3,14 @@ from __future__ import annotations
import asyncio
import pytest
+from pydantic import BaseModel
from cubeloop import Agent
-from cubeloop.agent.types import AfterToolCallResult, AgentToolResult
+from cubeloop.agent.types import (
+ AfterToolCallResult,
+ AgentTool,
+ AgentToolResult,
+)
from cubeloop.checkpointer.base import CheckpointData
from cubeloop.checkpointer.memory import MemoryCheckpointer
from cubeloop.hitl.ask_user import ask_user_tool
@@ -244,6 +249,91 @@ async def test_prompt_snapshots_mutable_payload_before_checkpoint_await() -> Non
assert user_messages[0].run_id == "run-1"
+async def test_respond_snapshots_mutable_answer_before_checkpoint_await() -> None:
+ entered = asyncio.Event()
+ release = asyncio.Event()
+
+ class SlowPendingCheckpointer(MemoryCheckpointer):
+ block_pending = False
+
+ async def load_pending(self, thread_id: str):
+ if self.block_pending:
+ entered.set()
+ await release.wait()
+ return await super().load_pending(thread_id)
+
+ checkpointer = SlowPendingCheckpointer()
+ channel = CheckpointedChannel(
+ checkpointer=checkpointer,
+ thread_id="thread-1",
+ run_id="run-1",
+ )
+ observed: list[str] = []
+
+ async def final_response(messages, model):
+ del model
+ observed.append(messages[-1].content[0].text)
+ return _answer()
+
+ provider = _provider()
+ provider.set_responses(
+ [
+ AssistantMessage(
+ content=[
+ ToolCall(
+ id="ask-1",
+ name="ask_user",
+ arguments={
+ "questions": [{"key": "answer", "prompt": "Continue?"}]
+ },
+ )
+ ],
+ stop_reason="tool_use",
+ ),
+ final_response,
+ ]
+ )
+ agent = Agent(
+ model=provider.model("faux-model"),
+ tools=[ask_user_tool(channel)],
+ channel=channel,
+ checkpointer=checkpointer,
+ thread_id="thread-1",
+ )
+ first = asyncio.create_task(agent.prompt("hi", run_id="run-1"))
+ for _ in range(100):
+ if channel.pending is not None:
+ break
+ await asyncio.sleep(0.01)
+ assert channel.pending is not None
+ question_id = channel.pending.question_id
+ await agent.session.request_detach()
+ await first
+ checkpointer.block_pending = True
+ answer = {"answer": "original"}
+ resumed = asyncio.create_task(
+ agent.session.execute(
+ RespondExecutionRequest(
+ run_id="run-1",
+ attempt_id="attempt-2",
+ question_id=question_id,
+ answer=answer,
+ )
+ )
+ )
+ await asyncio.wait_for(entered.wait(), timeout=1)
+
+ answer["answer"] = "mutated"
+ release.set()
+ result = await resumed
+
+ assert result.outcome == "completed"
+ assert len(observed) == 1
+ assert "original" in observed[0]
+ assert "mutated" not in observed[0]
+
+
@pytest.mark.asyncio
async def test_hitl_resume_uses_tool_binding_captured_before_detach() -> None:
checkpointer = MemoryCheckpointer()
@@ -296,6 +386,16 @@ async def test_hitl_resume_uses_tool_binding_captured_before_detach() -> None:
assert (await first).outcome == "suspended"
tool.execute = replacement_execute
+ stale = await agent.session.execute(
+ RespondExecutionRequest(
+ run_id="run-1",
+ attempt_id="attempt-stale",
+ question_id="stale-question",
+ answer={"answer": "no"},
+ )
+ )
+ assert stale.outcome == "failed"
+
resumed = await agent.session.execute(
RespondExecutionRequest(
run_id="run-1",
@@ -319,6 +419,8 @@ async def test_terminating_hitl_resume_drains_accepted_follow_up() -> None:
)
resume_entered = asyncio.Event()
release_resume = asyncio.Event()
+ stop_entered = asyncio.Event()
+ release_stop = asyncio.Event()
async def terminate_after_resume(context, signal=None):
del context, signal
@@ -326,6 +428,12 @@ async def test_terminating_hitl_resume_drains_accepted_follow_up() -> None:
await release_resume.wait()
return AfterToolCallResult(terminate=True)
+ async def slow_stop(context):
+ del context
+ stop_entered.set()
+ await release_stop.wait()
+ return True
+
provider = _provider(
AssistantMessage(
content=[
@@ -346,6 +454,7 @@ async def test_terminating_hitl_resume_drains_accepted_follow_up() -> None:
checkpointer=checkpointer,
thread_id="thread-1",
after_tool_call=terminate_after_resume,
+ should_stop_after_turn=slow_stop,
)
first = asyncio.create_task(
agent.session.execute(
@@ -378,6 +487,16 @@ async def test_terminating_hitl_resume_drains_accepted_follow_up() -> None:
)
assert agent.session.submit_input(envelope).status == "queued"
release_resume.set()
+ await asyncio.wait_for(stop_entered.wait(), timeout=1)
+ late = agent.session.submit_input(
+ InputEnvelope(
+ input_id="too-late",
+ message=UserMessage(content=[TextContent(text="missed drain")]),
+ mode="follow_up",
+ )
+ )
+ assert late.status == "closed"
+ release_stop.set()
result = await resumed
assert result.outcome == "completed"
@@ -387,6 +506,43 @@ async def test_terminating_hitl_resume_drains_accepted_follow_up() -> None:
assert provider.call_count == 2
+async def test_checkpoint_message_write_failure_marks_history_inconsistent() -> None:
+ class Args(BaseModel):
+ value: str
+
+ class FailingToolResultCheckpointer(MemoryCheckpointer):
+ async def append(self, thread_id, messages):
+ if any(message.role == "tool_result" for message in messages):
+ raise RuntimeError("tool result write failed")
+ await super().append(thread_id, messages)
+
+ async def execute(tool_call_id, args, *, signal=None, on_update=None):
+ del tool_call_id, args, signal, on_update
+ return AgentToolResult(content=[TextContent(text="done")])
+
+ tool = AgentTool(name="work", description="work", parameters=Args, execute=execute)
+ provider = _provider(
+ AssistantMessage(
+ content=[ToolCall(id="call-1", name="work", arguments={"value": "x"})],
+ stop_reason="tool_use",
+ )
+ )
+ agent = Agent(
+ model=provider.model("faux-model"),
+ tools=[tool],
+ checkpointer=FailingToolResultCheckpointer(),
+ thread_id="thread-1",
+ )
+
+ result = await agent.session.execute(
+ PromptExecutionRequest(run_id="run-1", attempt_id="attempt-1", message="hi")
+ )
+
+ assert result.outcome == "failed"
+ assert result.history_consistent is False
+
+
@pytest.mark.asyncio
async def test_agent_prompt_and_session_share_one_admission_gate() -> None:
entered = asyncio.Event()
@@ -525,6 +681,8 @@ async def test_load_checkpoint_restores_extra_in_place_even_without_messages() -
thread_id="thread-1",
)
live_context = agent.session.state_context
+ agent.session._input_status["memory-input"] = "committed"
+ agent.session._input_durability["memory-input"] = "memory"
loaded = await agent.session.load_checkpoint()
@@ -532,6 +690,8 @@ async def test_load_checkpoint_restores_extra_in_place_even_without_messages() -
assert loaded.messages == []
assert live_context is agent.session.state_context
assert live_context == {"todo": ["ship"]}
+ assert "memory-input" not in agent.session._input_status
+ assert "memory-input" not in agent.session._input_durability
live_context["memory"] = "pinned"
await agent.prompt("hi", run_id="run-1")
persisted = await checkpointer.load("thread-1")
@@ -833,3 +993,52 @@ async def test_process_control_exception_releases_session_ownership() -> None:
assert agent.session.active_attempt_id is None
await asyncio.wait_for(agent.wait_for_idle(), timeout=1)
+
+
+async def test_reconciled_input_process_control_releases_session_ownership() -> None:
+ class ProcessExit(BaseException):
+ pass
+
+ entered = asyncio.Event()
+ release = asyncio.Event()
+ agent = Agent(model=_provider().model("faux-model"))
+
+ async def consume_without_publishing(message, *, run_id=None):
+ del message, run_id
+ entered.set()
+ await release.wait()
+ accepted = agent._follow_up_queue.drain()
+ agent._state._messages.extend(accepted)
+ agent._state.last_outcome = "complete"
+ return "run-1"
+
+ agent._execute_prompt = consume_without_publishing # type: ignore[method-assign]
+
+ def stop_host(envelope):
+ if envelope.event.type == "input_committed":
+ raise ProcessExit("stop host")
+
+ agent.session.subscribe(stop_host)
+ task = asyncio.create_task(
+ agent.session.execute(
+ PromptExecutionRequest(run_id="run-1", attempt_id="attempt-1", message="hi")
+ )
+ )
+ await asyncio.wait_for(entered.wait(), timeout=1)
+ assert (
+ agent.session.submit_input(
+ InputEnvelope(
+ input_id="input-1",
+ message=UserMessage(content=[TextContent(text="accepted")]),
+ mode="follow_up",
+ )
+ ).status
+ == "queued"
+ )
+ release.set()
+
+ with pytest.raises(ProcessExit, match="stop host"):
+ await task
+ assert agent.session.active_attempt_id is None
+ await asyncio.wait_for(agent.wait_for_idle(), timeout=1)