Skip to content

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

fix(session): isolate terminal settlement state

xfgong96894b336e7a
diff --git a/cubeloop/session/session.py b/cubeloop/session/session.py
index 2fa07fe..94cd5ae 100644
--- a/cubeloop/session/session.py
+++ b/cubeloop/session/session.py
@@ -80,6 +80,7 @@ class ExecutionSession:
self._active_attempt_id: str | None = None
self._active_run_id: str | None = None
self._cancel_requested = False
+ self._accepting_cancel = False
self._accepting_input = False
self._idle = asyncio.Event()
self._idle.set()
@@ -138,6 +139,8 @@ class ExecutionSession:
return data
def request_cancel(self) -> None:
+ if not self._accepting_cancel:
+ return
self._cancel_requested = True
self._agent.abort()
@@ -263,6 +266,7 @@ class ExecutionSession:
self._active_attempt_id = request.attempt_id
self._active_run_id = request.run_id
self._cancel_requested = False
+ self._accepting_cancel = True
self._accepting_input = True
self._seq = 0
self._delivery_errors = []
@@ -301,6 +305,7 @@ class ExecutionSession:
raise
finally:
self._accepting_input = False
+ self._accepting_cancel = False
try:
try:
@@ -377,6 +382,7 @@ class ExecutionSession:
return
if isinstance(event, AgentEndEvent):
self._accepting_input = False
+ self._accepting_cancel = False
if isinstance(event, AgentSuspendedEvent):
self._pending_request = event.pending_request.model_copy(deep=True)
committed_input_id: str | None = None
@@ -489,11 +495,13 @@ class ExecutionSession:
event = event.model_copy(deep=True)
elif isinstance(event, ExecutionFinished):
pending = event.result.pending_request
+ error = event.result.error
result = replace(
event.result,
pending_request=(
pending.model_copy(deep=True) if pending is not None else None
),
+ error=replace(error, cause=None) if error is not None else None,
)
event = ExecutionFinished(result=result)
return replace(envelope, event=event)
@@ -553,7 +561,7 @@ class ExecutionSession:
load_pending = getattr(self._agent.checkpointer, "load_pending", None)
if load_pending is not None:
loaded = await load_pending(self._agent.thread_id)
- if loaded is not None:
+ if loaded is not None and loaded[1] == request.run_id:
pending = loaded[0].model_copy(deep=True)
pending_is_durable = True
if pending is None:
@@ -599,7 +607,7 @@ class ExecutionSession:
run_id=request.run_id,
attempt_id=request.attempt_id,
outcome=outcome,
- pending_request=pending,
+ pending_request=pending if outcome == "suspended" else None,
error=error,
checkpoint_committed=checkpoint_committed,
history_consistent=history_consistent,
diff --git a/tests/agent/test_execution_session.py b/tests/agent/test_execution_session.py
index 8459ab5..0b5766b 100644
--- a/tests/agent/test_execution_session.py
+++ b/tests/agent/test_execution_session.py
@@ -435,6 +435,13 @@ async def test_detach_rejects_outside_hitl_safe_point() -> None:
async def test_in_memory_detach_returns_pending_request() -> None:
channel = InMemoryChannel(thread_id="thread-1")
checkpointer = MemoryCheckpointer()
+ stale = HitlRequest(
+ question_id="stale-question",
+ thread_id="thread-1",
+ payload=ConfirmRequest(prompt="stale"),
+ created_at=0,
+ )
+ await checkpointer.save_pending_request("thread-1", stale, run_id="old-run")
provider = _provider(
AssistantMessage(
content=[
@@ -504,6 +511,31 @@ async def test_loaded_pending_request_is_copied_before_result_exposure() -> None
assert loaded[0].payload.prompt == "original"
+async def test_completed_attempt_does_not_expose_pending_from_another_run() -> None:
+ checkpointer = MemoryCheckpointer()
+ stale = HitlRequest(
+ question_id="stale-question",
+ thread_id="thread-1",
+ payload=ConfirmRequest(prompt="stale"),
+ created_at=0,
+ )
+ await checkpointer.save_pending_request("thread-1", stale, run_id="old-run")
+ agent = Agent(
+ model=_provider(_answer()).model("faux-model"),
+ checkpointer=checkpointer,
+ thread_id="thread-1",
+ )
+
+ result = await agent.session.execute(
+ PromptExecutionRequest(run_id="run-1", attempt_id="attempt-1", message="hi")
+ )
+
+ assert result.outcome == "completed"
+ assert result.pending_request is None
+ assert result.checkpoint_committed is True
+
+
@pytest.mark.asyncio
async def test_cancel_requested_during_startup_reaches_new_run_signal() -> None:
entered = asyncio.Event()
diff --git a/tests/agent/test_session_events.py b/tests/agent/test_session_events.py
index 48a32c7..30a2678 100644
--- a/tests/agent/test_session_events.py
+++ b/tests/agent/test_session_events.py
@@ -6,6 +6,7 @@ import pytest
from cubeloop import Agent
from cubeloop.agent.types import AgentStartEvent
+from cubeloop.checkpointer.memory import MemoryCheckpointer
from cubeloop.providers.base import UserMessage
from cubeloop.providers.base import AssistantMessage, TextContent
from cubeloop.providers.faux import FauxProvider
@@ -128,6 +129,67 @@ async def test_consumers_receive_isolated_agent_event_snapshots() -> None:
assert agent.state.messages[0].content[0].text == "original"
+async def test_terminal_event_sanitizes_error_cause_for_consumers() -> None:
+ class BrokenPendingCheckpointer(MemoryCheckpointer):
+ async def load_pending(self, thread_id: str):
+ del thread_id
+ raise RuntimeError("storage failed")
+
+ provider = FauxProvider(provider_id="faux")
+ provider.set_responses(
+ [AssistantMessage(content=[TextContent(text="done")], stop_reason="end_turn")]
+ )
+ agent = Agent(
+ model=provider.model("faux-model"),
+ checkpointer=BrokenPendingCheckpointer(),
+ thread_id="thread-1",
+ )
+ observed_causes = []
+
+ def listener(envelope):
+ if envelope.event.type == "execution_finished":
+ assert envelope.event.result.error is not None
+ observed_causes.append(envelope.event.result.error.cause)
+
+ agent.session.subscribe(listener, name="first")
+ agent.session.subscribe(listener, name="second")
+
+ result = await agent.session.execute(
+ PromptExecutionRequest(run_id="run-1", attempt_id="attempt-1", message="hi")
+ )
+
+ assert result.error is not None
+ assert isinstance(result.error.cause, RuntimeError)
+ assert observed_causes == [None, None]
+
+
+async def test_cancel_from_agent_end_consumer_does_not_override_completion() -> None:
+ provider = FauxProvider(provider_id="faux")
+ provider.set_responses(
+ [AssistantMessage(content=[TextContent(text="done")], stop_reason="end_turn")]
+ )
+ agent = Agent(
+ model=provider.model("faux-model"),
+ checkpointer=MemoryCheckpointer(),
+ thread_id="thread-1",
+ )
+
+ def cancel_too_late(envelope):
+ if envelope.event.type == "agent_end":
+ agent.session.request_cancel()
+
+ agent.session.subscribe(cancel_too_late)
+
+ result = await agent.session.execute(
+ PromptExecutionRequest(run_id="run-1", attempt_id="attempt-1", message="hi")
+ )
+
+ assert result.outcome == "completed"
+ assert result.checkpoint_committed is True
+
+
@pytest.mark.asyncio
async def test_final_notification_timeout_preserves_settled_result() -> None:
agent = _agent()