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(session): isolate terminal settlement state
xfgong96894b336e7a
diff --git a/cubeloop/session/session.py b/cubeloop/session/session.pyindex 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 = Noneself._active_run_id: str | None = Noneself._cancel_requested = False+ self._accepting_cancel = Falseself._accepting_input = Falseself._idle = asyncio.Event()self._idle.set()@@ -138,6 +139,8 @@ class ExecutionSession:return datadef request_cancel(self) -> None:+ if not self._accepting_cancel:+ returnself._cancel_requested = Trueself._agent.abort()@@ -263,6 +266,7 @@ class ExecutionSession:self._active_attempt_id = request.attempt_idself._active_run_id = request.run_idself._cancel_requested = False+ self._accepting_cancel = Trueself._accepting_input = Trueself._seq = 0self._delivery_errors = []@@ -301,6 +305,7 @@ class ExecutionSession:raisefinally:self._accepting_input = False+ self._accepting_cancel = Falsetry:try:@@ -377,6 +382,7 @@ class ExecutionSession:returnif isinstance(event, AgentEndEvent):self._accepting_input = False+ self._accepting_cancel = Falseif 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.errorresult = 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 = Trueif 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.pyindex 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() -> Noneassert 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.asyncioasync 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.pyindex 48a32c7..30a2678 100644--- a/tests/agent/test_session_events.py+++ b/tests/agent/test_session_events.py@@ -6,6 +6,7 @@ import pytestfrom cubeloop import Agentfrom cubeloop.agent.types import AgentStartEvent+from cubeloop.checkpointer.memory import MemoryCheckpointerfrom cubeloop.providers.base import UserMessagefrom cubeloop.providers.base import AssistantMessage, TextContentfrom 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.asyncioasync def test_final_notification_timeout_preserves_settled_result() -> None:agent = _agent()