Skip to content

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

fix(tracing): classify durable HITL pauses as suspended

Cuef067762a518f
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 14d63ec..c126af6 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -7,6 +7,15 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
## [Unreleased]
+### Fixed
+
+- **Durable HITL pauses now finalize traces as suspended rather than aborted.**
+ `Agent.detach()` commits the pending request first, then the owning activation
+ emits a terminal suspension event after runtime-state cleanup. Open agent,
+ turn, chat, and tool spans end with `cubepi.run.outcome="suspended"`; observer
+ failures cannot hide the terminal event, cancellation still propagates, and
+ `respond()` opens a distinct correlated activation trace.
+
## [0.13.3] - 2026-08-02
### Fixed
diff --git a/cubepi/agent/agent.py b/cubepi/agent/agent.py
index 99a803b..9886a91 100644
--- a/cubepi/agent/agent.py
+++ b/cubepi/agent/agent.py
@@ -50,6 +50,13 @@ from cubepi.types import JsonObject, StructuredValue
TMessage = TypeVar("TMessage")
+
+def _consume_control_exception(future: asyncio.Future[StructuredValue]) -> None:
+ """Mark a detach control exception retrieved without changing awaiters."""
+ if not future.cancelled():
+ future.exception()
+
+
if TYPE_CHECKING:
from cubepi.deferred.types import DeferredStrategy, DeferredToolGroup
from cubepi.providers.fallback import FallbackBoundModel
@@ -287,6 +294,7 @@ class Agent(Generic[TMessage]):
and hasattr(self.checkpointer, "mark_run_complete")
)
self._channel = channel
+ self._pending_suspension_event: HitlRequest | None = None
# _bind_emit is a _BaseChannel internal, not part of the HitlChannel
# protocol. Third-party channels that only implement the public
# protocol won't have it — skip the wiring instead of crashing.
@@ -384,6 +392,19 @@ class Agent(Generic[TMessage]):
cause=exc,
) from exc
+ async def _emit_suspended_event(self, outcome: RunOutcome) -> None:
+ """Publish suspension only after the run transition is committed."""
+ if outcome != "suspended":
+ self._pending_suspension_event = None
+ return
+ pending = self._pending_suspension_event
+ if pending is None:
+ return
+ self._pending_suspension_event = None
+ from cubepi.agent.types import AgentSuspendedEvent
+
+ await self._process_event(AgentSuspendedEvent(pending_request=pending))
+
def _validate_hitl_bindings(self, run_id: str | None, *, caller: str) -> None:
"""Reject HITL-bound tools/middleware that disagree with `run_id`.
@@ -518,6 +539,7 @@ class Agent(Generic[TMessage]):
await self._run_prompt(messages)
except BaseException:
# Spec §3.7: leave active_run_id SET on failure.
+ self._pending_suspension_event = None
raise
else:
outcome: RunOutcome = self._state.last_outcome or "abandoned"
@@ -526,6 +548,7 @@ class Agent(Generic[TMessage]):
# the clear line below is unreachable on the exception path.
await self._dispatch_outcome(outcome, effective_run_id)
self._state.active_run_id = None
+ await self._emit_suspended_event(outcome)
return effective_run_id
async def fork(
@@ -723,11 +746,13 @@ class Agent(Generic[TMessage]):
except BaseException:
# Spec §3.7 parity: leave active_run_id SET on failure so callers
# can observe which run failed.
+ self._pending_suspension_event = None
raise
else:
outcome: RunOutcome = self._state.last_outcome or "abandoned"
await self._dispatch_outcome(outcome, effective_run_id)
self._state.active_run_id = None
+ await self._emit_suspended_event(outcome)
return effective_run_id
def _build_stream_options(self, signal: asyncio.Event) -> StreamOptions:
@@ -803,8 +828,6 @@ class Agent(Generic[TMessage]):
)
async def detach(self) -> None:
- from cubepi.agent.types import AgentSuspendedEvent
-
if self._channel is None:
raise HitlError("agent has no channel bound")
pending = self._channel.pending
@@ -814,11 +837,14 @@ class Agent(Generic[TMessage]):
or self._channel._future.done()
):
return # nothing to detach
- # Emit the suspended event BEFORE triggering the exception, so listeners
- # see the real pending payload (codex pass 2 BLOCKING: previous draft
- # emitted from the loop with pending=None — fundamentally wrong).
- await self._process_event(AgentSuspendedEvent(pending_request=pending))
- self._channel._future.set_exception(HitlDetached())
+ # Snapshot the payload before the channel clears its in-memory pending slot,
+ # then commit the control-flow transition. The owning prompt/resume task
+ # publishes AgentSuspendedEvent only after it records the suspended outcome
+ # and clears active_run_id, so observers cannot report an uncommitted pause.
+ self._pending_suspension_event = pending
+ future = self._channel._future
+ future.add_done_callback(_consume_control_exception)
+ future.set_exception(HitlDetached())
async def load_pending_hitl_request(self) -> HitlRequest | None:
if self.checkpointer is None or self.thread_id is None:
@@ -898,14 +924,16 @@ class Agent(Generic[TMessage]):
await self._run_hitl_resume()
except BaseException:
# Spec §3.7: leave active_run_id SET on raise.
+ self._pending_suspension_event = None
raise
else:
# Legacy guard: pending persisted without run_id (older
# save_pending_request callers) cannot drive dispatch.
+ outcome: RunOutcome = self._state.last_outcome or "abandoned"
if recovered_run_id is not None:
- outcome: RunOutcome = self._state.last_outcome or "abandoned"
await self._dispatch_outcome(outcome, recovered_run_id)
self._state.active_run_id = None
+ await self._emit_suspended_event(outcome)
async def abort_pending(
self, reason: str = "aborted by host"
@@ -1233,7 +1261,23 @@ class Agent(Generic[TMessage]):
await self._emit_to_listeners(event)
async def _emit_to_listeners(self, event: AgentEvent) -> None:
- for listener in self._listeners:
- result = listener(event, self._active_signal)
- if asyncio.iscoroutine(result):
- await result
+ cancellation: asyncio.CancelledError | None = None
+ first_error: Exception | None = None
+ for listener in tuple(self._listeners):
+ try:
+ result = listener(event, self._active_signal)
+ if asyncio.iscoroutine(result):
+ await result
+ except asyncio.CancelledError as exc:
+ if cancellation is None:
+ cancellation = exc
+ except Exception as exc:
+ # One observer must not hide an event from later observers.
+ # Preserve existing error propagation after every listener had
+ # the chance to see the same committed state transition.
+ if first_error is None:
+ first_error = exc
+ if cancellation is not None:
+ raise cancellation
+ if first_error is not None:
+ raise first_error
diff --git a/cubepi/tracing/recorder.py b/cubepi/tracing/recorder.py
index 6e986bc..2ea5c5d 100644
--- a/cubepi/tracing/recorder.py
+++ b/cubepi/tracing/recorder.py
@@ -34,6 +34,7 @@ from opentelemetry.trace import SpanKind, Status, StatusCode
from cubepi.agent.types import (
AgentEndEvent,
AgentStartEvent,
+ AgentSuspendedEvent,
MessageEndEvent,
MessageStartEvent,
TurnEndEvent,
@@ -66,6 +67,7 @@ from cubepi.tracing.schema import (
CUBEPI_LLM_THINKING_LEVEL,
CUBEPI_OUTPUT_MESSAGES_COUNT,
CUBEPI_RUN_ID,
+ CUBEPI_RUN_OUTCOME,
CUBEPI_TOOL_BLOCK_REASON,
CUBEPI_TOOL_BLOCKED_BY_HOOK,
CUBEPI_TOOL_EXECUTION_MODE,
@@ -413,6 +415,8 @@ class Recorder:
self._on_message_end(event)
elif isinstance(event, TurnEndEvent):
self._on_turn_end(event)
+ elif isinstance(event, AgentSuspendedEvent):
+ self._on_agent_suspended()
elif isinstance(event, AgentEndEvent):
self._on_agent_end(event)
# MessageUpdateEvent / ToolExecutionUpdateEvent: IGNORED.
@@ -679,6 +683,49 @@ class Recorder:
if history:
self._run.transcript.extend(history)
+ def _on_agent_suspended(self) -> None:
+ """Finalize a durable HITL pause without classifying it as abort."""
+ run = self._run
+ if run is None:
+ return
+ for span in list(run.tool_spans.values()):
+ try:
+ span.set_attribute(CUBEPI_RUN_OUTCOME, "suspended")
+ span.end()
+ except Exception:
+ pass
+ run.tool_spans.clear()
+ if run.chat_span is not None:
+ try:
+ run.chat_span.set_attribute(CUBEPI_RUN_OUTCOME, "suspended")
+ run.chat_span.end()
+ except Exception:
+ pass
+ run.chat_span = None
+ run.chat_open_ns = None
+ run.chat_first_chunk_recorded = False
+ if run.turn_span is not None:
+ try:
+ run.turn_span.set_attribute(CUBEPI_RUN_OUTCOME, "suspended")
+ run.turn_span.end()
+ except Exception:
+ pass
+ run.turn_span = None
+ run.agent_span.set_attribute(CUBEPI_RUN_OUTCOME, "suspended")
+ run.agent_span.set_attribute(
+ CUBEPI_OUTPUT_MESSAGES_COUNT, len(run.output_messages)
+ )
+ run.agent_span.end()
+ self._sweep_tool_span_tokens(run)
+ if run.stream_file is not None:
+ try:
+ run.stream_file.close()
+ except Exception:
+ pass
+ run.stream_file = None
+ self._reset_active_run()
+ self._run = None
+
def _on_agent_end(self, event: AgentEndEvent) -> None:
run = self._run
if run is None:
@@ -760,9 +807,8 @@ class Recorder:
if run is None or run.turn_span is None:
return
msg = event.message
- # Track output messages: assistant + any tool_results from this turn.
- run.turn_output_messages.append(msg)
- run.output_messages.append(msg)
+ # Assistant output is captured at MessageEnd so a HITL suspension before
+ # TurnEnd still records it. Add only this turn's tool results here.
for tr in getattr(event, "tool_results", []) or []:
run.turn_output_messages.append(tr)
run.output_messages.append(tr)
@@ -948,6 +994,8 @@ class Recorder:
msg = event.message
if getattr(msg, "role", None) == "assistant":
run.transcript.append(msg)
+ run.turn_output_messages.append(msg)
+ run.output_messages.append(msg)
# ------------------------------------------------------------------
# Provider listeners — drive the chat span lifetime
diff --git a/cubepi/tracing/schema.py b/cubepi/tracing/schema.py
index 4f70610..dc369af 100644
--- a/cubepi/tracing/schema.py
+++ b/cubepi/tracing/schema.py
@@ -104,6 +104,7 @@ CUBEPI_AGENT_TOOLS = "cubepi.agent.tools"
CUBEPI_AGENT_SYSTEM_PROMPT_SHA256 = "cubepi.agent.system_prompt.sha256"
CUBEPI_INPUT_MESSAGES_COUNT = "cubepi.input.messages.count"
CUBEPI_OUTPUT_MESSAGES_COUNT = "cubepi.output.messages.count"
+CUBEPI_RUN_OUTCOME = "cubepi.run.outcome"
CUBEPI_ABORTED = "cubepi.aborted"
# Turn span attributes (cubepi.turn span — no gen_ai.operation.name)
diff --git a/dev/plans/2026-08-04-tracing-hitl-suspension.md b/dev/plans/2026-08-04-tracing-hitl-suspension.md
new file mode 100644
index 0000000..b59b62a
--- /dev/null
+++ b/dev/plans/2026-08-04-tracing-hitl-suspension.md
@@ -0,0 +1,74 @@
+# HITL Suspension Trace Semantics Implementation Plan
+
+**Goal:** Export durable HITL pauses as committed `suspended` activations,
+never as aborted, while preserving cancellation behavior and tracing cleanup.
+
+**Architecture:** Snapshot the pending request in `Agent.detach()`, commit the
+`HitlDetached` channel transition, and publish `AgentSuspendedEvent` from the
+owning run task after outcome dispatch and active-run cleanup. The recorder then
+finalizes the activation with explicit suspended attributes.
+
+**Tech stack:** Python 3.13, asyncio, FauxProvider, CheckpointedChannel,
+OpenTelemetry SDK, pytest, Ruff, mypy, uv.
+
+## Task 1: Pin the production-shaped regression
+
+- Add `tests/tracing/test_hitl_suspension.py` using a real Agent, HITL channel,
+ ask-user tool, Tracer, and in-memory exporter.
+- Record RED for the original false-abort behavior.
+- Add adversarial RED assertions for:
+ - event observers seeing pre-commit runtime state;
+ - cross-task `_active_run` retention;
+ - assistant output count incorrectly remaining zero;
+ - an earlier regular/cancelled listener hiding suspension from tracing;
+ - detach followed by immediate owner-task cancellation retaining the pending
+ payload and emitting an unhandled-future warning;
+ - same-tick `reset()` deleting a committed suspension snapshot before the
+ owner task can publish it.
+
+## Task 2: Commit suspension at the owning task boundary
+
+- Snapshot the pending request in `Agent.detach()` before the channel clears its
+ in-memory slot.
+- Set `HitlDetached` without publishing the terminal event from the host task.
+- After `prompt()`, `resume()`, or `respond()` records `outcome=suspended`,
+ performs outcome dispatch, and clears `active_run_id`, publish the event from
+ that same owning task.
+- Fan out agent events across regular exceptions and `CancelledError`; after
+ fan-out, give cancellation priority or re-raise the first regular exception.
+- Clear the pending snapshot on every failed owning activation; do not let
+ `reset()` clear a snapshot before that activation publishes its terminal.
+- Mark the detach control exception retrieved via a future done callback without
+ changing what channel awaiters receive.
+
+## Task 3: Add explicit trace semantics
+
+- Add the recorder-owned schema attribute `cubepi.run.outcome`.
+- Handle committed `AgentSuspendedEvent` in `Recorder`.
+- End open tool/chat/turn/root spans with outcome `suspended`.
+- Sweep tool-span registrations, close stream state, and clear the active run.
+- Move assistant output accumulation to `MessageEndEvent` so suspension before
+ `TurnEndEvent` still records the partial output.
+- Do not change `_close_open_spans()` cancellation semantics.
+
+## Task 4: Document the lifecycle contract
+
+- Update tracing guidance to distinguish cancellation from durable suspension.
+- Update HITL reference/durable examples to describe post-commit event timing.
+- State that resume creates a new activation trace.
+
+## Task 5: Verify
+
+Run:
+
+```bash
+uv run pytest tests/tracing/test_hitl_suspension.py -q
+uv run pytest tests/tracing tests/hitl -q
+uv run pytest tests/
+uv run ruff check cubepi/ tests/
+uv run ruff format --check cubepi/ tests/
+uv run mypy cubepi
+```
+
+Inspect `git diff --check` and confirm the branch contains only the spec, plan,
+focused tests, lifecycle fix, recorder/schema fix, and user-facing docs.
diff --git a/dev/specs/2026-08-04-tracing-hitl-suspension.md b/dev/specs/2026-08-04-tracing-hitl-suspension.md
new file mode 100644
index 0000000..72ea8e8
--- /dev/null
+++ b/dev/specs/2026-08-04-tracing-hitl-suspension.md
@@ -0,0 +1,120 @@
+# HITL Suspension Trace Semantics
+
+- Date: 2026-08-04
+- Status: Accepted
+- Companion plan: `dev/plans/2026-08-04-tracing-hitl-suspension.md`
+
+## Problem
+
+A durable HITL pause is a successful activation outcome, not a cancellation.
+The agent loop records `RunOutcome="suspended"`, but the tracing recorder did
+not have a committed suspension terminal. It therefore kept the root, turn,
+and active tool spans open until tracing detach, whose cancellation cleanup
+marked them `cubepi.aborted=true`.
+
+A first implementation consumed the existing `AgentSuspendedEvent` directly,
+but adversarial review found that event was emitted before `Agent.detach()` set
+`HitlDetached` on the channel future. A later listener could raise, prevent the
+future transition, and leave the prompt running while tracing had already
+exported a false suspended terminal. The handler also ran from the host detach
+task, so resetting a `ContextVar` token created by the prompt task failed and
+left the old `_RunState` retained in that task's context.
+
+## Goals
+
+- Finalize every open span only after suspension is committed.
+- Mark the activation with `cubepi.run.outcome="suspended"`.
+- Never add `cubepi.aborted=true` or `error.type=cubepi.aborted` to a suspended
+ activation.
+- Emit the terminal event from the owning prompt/resume task so recorder
+ context cleanup occurs in the token's original context.
+- Ensure one failing or cancelled observer cannot hide a committed event from
+ later observers; preserve exception propagation after fan-out and give
+ cancellation priority.
+- Clear the pending-request snapshot on every owning activation failure/exit and
+ avoid unhandled `HitlDetached` future warnings.
+- Preserve the existing run cancellation cleanup and classification.
+- Remove tool-span and MCP-provider registrations during normal tracing detach.
+- Count the assistant tool-call message as partial activation output.
+- Keep tracing observational: recorder failures must not affect the agent.
+
+## Non-goals
+
+- Changing HITL persistence, answer, or resume behavior.
+- Continuing one OTel trace across pause and resume. A resumed activation gets a
+ new `invoke_agent` root and can be correlated by host-supplied metadata.
+- Recording pending questions, answers, tool arguments, or other content.
+- Reclassifying provider errors or explicit cancellation.
+
+## Design
+
+### Commit suspension before publishing it
+
+`Agent.detach()` snapshots the real pending request, then sets
+`HitlDetached` on the channel future. It does not publish the terminal event.
+The owning `prompt()`, `resume()`, or `respond()` task lets the loop record
+`RunOutcome="suspended"`, performs outcome dispatch, clears `active_run_id`, and
+only then emits `AgentSuspendedEvent` using the snapshot.
+
+Because the event now runs in the task that received `AgentStartEvent`, the
+recorder can reset its `_active_run` token in the owning context. If an event
+listener raises, the committed runtime state remains suspended rather than
+pending.
+
+Agent event fan-out invokes every registered listener before propagating
+listener failures. If any listener raises `asyncio.CancelledError`, cancellation
+wins after fan-out; otherwise the first regular exception is re-raised. A user
+listener registered before tracing can no longer hide the committed suspension
+from the recorder.
+
+The pending snapshot is cleared from every `prompt()`, `resume()`, and
+`respond()` failure path. `reset()` deliberately does not touch a snapshot owned
+by an activation that has not yet published its committed terminal. The detach future registers a
+done callback that marks its control exception retrieved without changing what
+awaiters receive, preventing an immediate owner-task cancellation from leaving
+an unhandled-future warning.
+
+### Finalize the trace as suspended
+
+On the committed `AgentSuspendedEvent`, the recorder:
+
+1. ends open tool, chat, and turn spans with
+ `cubepi.run.outcome="suspended"`;
+2. ends the root span with the same outcome and the partial output-message count;
+3. sweeps any open tool-span registrations;
+4. closes an active stream file;
+5. releases recorder state so tracing detach is idempotent.
+
+No span receives error status or aborted attributes. The existing generic
+`_close_open_spans()` path remains cancellation-only.
+
+Assistant messages are added to `run.output_messages` at `MessageEndEvent`, not
+at `TurnEndEvent`. That keeps normal output unchanged while making the assistant
+tool-call visible when HITL suspension prevents `TurnEndEvent`.
+
+This aligns trace semantics with Cubepi's existing runtime outcome model.
+Durable agent runtimes similarly treat an interrupt/pause as resumable control
+flow rather than an execution error; Cubepi preserves that distinction without
+adopting a graph runtime or changing its public event payload.
+
+## Acceptance
+
+A real `Agent` using `FauxProvider`, `CheckpointedChannel`, `ask_user_tool`, and
+`Tracer` must demonstrate:
+
+- one exported `invoke_agent` root;
+- `cubepi.run.outcome="suspended"` on the root and open child spans;
+- `cubepi.output.messages.count=1` for the assistant tool-call;
+- zero exported spans with `cubepi.aborted=true`;
+- no leaked MCP provider or active tool-span registrations after tracing detach;
+- `_active_run.get()` is clear when the owning prompt task returns;
+- a listener sees `last_outcome="suspended"` and `active_run_id=None`, never the
+ pre-commit state;
+- tracing still receives the event when an earlier listener raises a regular
+ exception or `CancelledError`;
+- listener cancellation remains the propagated outcome after terminal fan-out;
+- detach followed by immediate owner-task cancellation clears the request
+ snapshot, exports a real aborted trace, and emits no unhandled-future warning;
+- `reset()` in the same tick after detach cannot steal the owning activation's
+ snapshot; the persisted pending remains and the trace is suspended;
+- unchanged passing cancellation, tracing, and HITL suites.
diff --git a/tests/tracing/test_hitl_suspension.py b/tests/tracing/test_hitl_suspension.py
new file mode 100644
index 0000000..c5795fb
--- /dev/null
+++ b/tests/tracing/test_hitl_suspension.py
@@ -0,0 +1,340 @@
+"""Tracing coverage for durable HITL suspension."""
+
+from __future__ import annotations
+
+import asyncio
+import gc
+from contextlib import suppress
+from typing import Any
+
+from opentelemetry.sdk.trace import ReadableSpan
+from opentelemetry.sdk.trace.export import SpanExporter, SpanExportResult
+
+from cubepi.agent.agent import Agent
+from cubepi.checkpointer.memory import MemoryCheckpointer
+from cubepi.hitl.ask_user import ask_user_tool
+from cubepi.hitl.channel import CheckpointedChannel
+from cubepi.mcp import _tracing as mcp_tracing
+from cubepi.providers.base import AssistantMessage, TextContent, ToolCall
+from cubepi.providers.faux import FauxProvider
+from cubepi.tracing import Tracer
+from cubepi.tracing import recorder as recorder_module
+
+
+class InMemoryExporter(SpanExporter):
+ def __init__(self) -> None:
+ self.spans: list[ReadableSpan] = []
+
+ def export(self, spans): # noqa: ANN001
+ self.spans.extend(spans)
+ return SpanExportResult.SUCCESS
+
+ def shutdown(self) -> None:
+ pass
+
+ def force_flush(self, timeout_millis: int = 30_000) -> bool:
+ return True
+
+
+def _build_suspending_agent(
+ thread_id: str,
+) -> tuple[Agent, CheckpointedChannel, InMemoryExporter, Tracer]:
+ cp = MemoryCheckpointer()
+ channel = CheckpointedChannel(
+ checkpointer=cp,
+ thread_id=thread_id,
+ run_id="R1",
+ )
+ provider = FauxProvider(provider_id="faux")
+ provider.set_responses(
+ [
+ AssistantMessage(
+ content=[
+ ToolCall(
+ id="ask-1",
+ name="ask_user",
+ arguments={"questions": [{"key": "answer", "prompt": "?"}]},
+ )
+ ],
+ stop_reason="tool_use",
+ ),
+ AssistantMessage(
+ content=[TextContent(text="done")],
+ stop_reason="end_turn",
+ ),
+ ]
+ )
+ agent = Agent(
+ model=provider.model("faux-model"),
+ tools=[ask_user_tool(channel)],
+ checkpointer=cp,
+ thread_id=thread_id,
+ channel=channel,
+ )
+ exporter = InMemoryExporter()
+ tracer = Tracer(service_name="test", agent_name="test-agent", exporters=[exporter])
+ return agent, channel, exporter, tracer
+
+
+async def _wait_for_pending(channel: CheckpointedChannel) -> None:
+ for _ in range(200):
+ if channel.pending is not None:
+ return
+ await asyncio.sleep(0.01)
+ raise AssertionError("agent did not suspend on HITL")
+
+
+async def _detach_tracing(detach: Any, tracer: Tracer) -> None:
+ flush_task = detach()
+ if flush_task is not None:
+ await flush_task
+ await tracer.shutdown()
+
+
+async def test_suspended_run_exports_suspended_trace_without_abort_or_leaks() -> None:
+ agent, channel, exporter, tracer = _build_suspending_agent("thread-1")
+ provider_stack_baseline = len(mcp_tracing._provider_stack)
+ active_entries_baseline = len(mcp_tracing._active_entries)
+ detach_tracing = tracer.attach(agent)
+
+ prompt_task = asyncio.create_task(agent.prompt("hi", run_id="R1"))
+ await _wait_for_pending(channel)
+ await agent.detach()
+ await prompt_task
+ await _detach_tracing(detach_tracing, tracer)
+
+ roots = [span for span in exporter.spans if span.name == "invoke_agent"]
+ assert len(roots) == 1
+ assert roots[0].attributes.get("cubepi.output.messages.count") == 1
+ suspended_spans = [
+ span
+ for span in exporter.spans
+ if span.name in {"invoke_agent", "cubepi.turn"}
+ or span.name.startswith("execute_tool ")
+ ]
+ assert {span.name for span in suspended_spans} == {
+ "invoke_agent",
+ "cubepi.turn",
+ "execute_tool ask_user",
+ }
+ assert all(
+ span.attributes.get("cubepi.run.outcome") == "suspended"
+ for span in suspended_spans
+ )
+ assert not [
+ span.name
+ for span in exporter.spans
+ if span.attributes.get("cubepi.aborted") is True
+ ]
+ assert len(mcp_tracing._provider_stack) == provider_stack_baseline
+ assert len(mcp_tracing._active_entries) == active_entries_baseline
+
+
+async def test_suspension_event_observes_committed_runtime_state() -> None:
+ agent, channel, _exporter, tracer = _build_suspending_agent("thread-2")
+ detach_tracing = tracer.attach(agent)
+ observed: list[tuple[str | None, str | None]] = []
+
+ async def fail_after_observing(event, signal=None): # noqa: ANN001, ANN202
+ del signal
+ if event.type == "agent_suspended":
+ observed.append((agent.state.last_outcome, agent.state.active_run_id))
+ raise RuntimeError("listener failed after observing suspension")
+
+ unsubscribe = agent.subscribe(fail_after_observing)
+ prompt_task = asyncio.create_task(agent.prompt("hi", run_id="R1"))
+ await _wait_for_pending(channel)
+
+ with suppress(RuntimeError):
+ await agent.detach()
+ timed_out = False
+ try:
+ await asyncio.wait_for(asyncio.shield(prompt_task), timeout=0.5)
+ except RuntimeError:
+ pass
+ except TimeoutError:
+ timed_out = True
+
+ unsubscribe()
+ if not prompt_task.done():
+ await agent.detach()
+ await prompt_task
+ await _detach_tracing(detach_tracing, tracer)
+
+ assert timed_out is False
+ assert observed == [("suspended", None)]
+
+
+async def test_earlier_listener_failure_cannot_hide_suspension_from_tracer() -> None:
+ agent, channel, exporter, tracer = _build_suspending_agent("thread-early-error")
+
+ async def fail_on_suspension(event, signal=None): # noqa: ANN001, ANN202
+ del signal
+ if event.type == "agent_suspended":
+ raise RuntimeError("earlier listener failed")
+
+ unsubscribe = agent.subscribe(fail_on_suspension)
+ detach_tracing = tracer.attach(agent)
+ prompt_task = asyncio.create_task(agent.prompt("hi", run_id="R1"))
+ await _wait_for_pending(channel)
+ await agent.detach()
+ with suppress(RuntimeError):
+ await prompt_task
+ unsubscribe()
+ await _detach_tracing(detach_tracing, tracer)
+
+ roots = [span for span in exporter.spans if span.name == "invoke_agent"]
+ assert len(roots) == 1
+ assert roots[0].attributes.get("cubepi.run.outcome") == "suspended"
+ assert roots[0].attributes.get("cubepi.aborted") is not True
+
+
+async def test_cancelled_listener_cannot_hide_suspension_from_tracer() -> None:
+ agent, channel, exporter, tracer = _build_suspending_agent(
+ "thread-cancelled-listener"
+ )
+
+ async def cancel_on_suspension(event, signal=None): # noqa: ANN001, ANN202
+ del signal
+ if event.type == "agent_suspended":
+ raise asyncio.CancelledError
+
+ unsubscribe = agent.subscribe(cancel_on_suspension)
+ detach_tracing = tracer.attach(agent)
+ prompt_task = asyncio.create_task(agent.prompt("hi", run_id="R1"))
+ await _wait_for_pending(channel)
+ await agent.detach()
+ with suppress(asyncio.CancelledError):
+ await prompt_task
+ unsubscribe()
+ await _detach_tracing(detach_tracing, tracer)
+
+ assert agent.state.last_outcome == "suspended"
+ assert agent.state.active_run_id is None
+ roots = [span for span in exporter.spans if span.name == "invoke_agent"]
+ assert len(roots) == 1
+ assert roots[0].attributes.get("cubepi.run.outcome") == "suspended"
+ assert roots[0].attributes.get("cubepi.aborted") is not True
+
+
+async def test_listener_cancellation_takes_priority_after_terminal_fanout() -> None:
+ agent, channel, exporter, tracer = _build_suspending_agent(
+ "thread-listener-priority"
+ )
+
+ async def fail_on_suspension(event, signal=None): # noqa: ANN001, ANN202
+ del signal
+ if event.type == "agent_suspended":
+ raise RuntimeError("regular listener failure")
+
+ async def cancel_on_suspension(event, signal=None): # noqa: ANN001, ANN202
+ del signal
+ if event.type == "agent_suspended":
+ raise asyncio.CancelledError
+
+ unsubscribe_fail = agent.subscribe(fail_on_suspension)
+ unsubscribe_cancel = agent.subscribe(cancel_on_suspension)
+ detach_tracing = tracer.attach(agent)
+ prompt_task = asyncio.create_task(agent.prompt("hi", run_id="R1"))
+ await _wait_for_pending(channel)
+ await agent.detach()
+ raised: BaseException | None = None
+ try:
+ await prompt_task
+ except BaseException as exc:
+ raised = exc
+ unsubscribe_fail()
+ unsubscribe_cancel()
+ await _detach_tracing(detach_tracing, tracer)
+
+ assert isinstance(raised, asyncio.CancelledError)
+ roots = [span for span in exporter.spans if span.name == "invoke_agent"]
+ assert len(roots) == 1
+ assert roots[0].attributes.get("cubepi.run.outcome") == "suspended"
+
+
+async def test_detach_then_owner_cancel_clears_suspension_snapshot() -> None:
+ agent, channel, exporter, tracer = _build_suspending_agent("thread-owner-cancel")
+ detach_tracing = tracer.attach(agent)
+ prompt_task = asyncio.create_task(agent.prompt("hi", run_id="R1"))
+ await _wait_for_pending(channel)
+ loop = asyncio.get_running_loop()
+ old_exception_handler = loop.get_exception_handler()
+ unhandled: list[dict[str, Any]] = []
+ loop.set_exception_handler(lambda _loop, context: unhandled.append(context))
+
+ try:
+ await agent.detach()
+ prompt_task.cancel()
+ with suppress(asyncio.CancelledError):
+ await prompt_task
+ await _detach_tracing(detach_tracing, tracer)
+ gc.collect()
+ await asyncio.sleep(0)
+ finally:
+ loop.set_exception_handler(old_exception_handler)
+
+ assert agent._pending_suspension_event is None
+ assert unhandled == []
+ roots = [span for span in exporter.spans if span.name == "invoke_agent"]
+ assert len(roots) == 1
+ assert roots[0].attributes.get("cubepi.run.outcome") is None
+ assert roots[0].attributes.get("cubepi.aborted") is True
+
+
+async def test_reset_before_owner_resumes_does_not_drop_suspension_snapshot() -> None:
+ agent, channel, exporter, tracer = _build_suspending_agent("thread-reset-race")
+ detach_tracing = tracer.attach(agent)
+ prompt_task = asyncio.create_task(agent.prompt("hi", run_id="R1"))
+ await _wait_for_pending(channel)
+
+ await agent.detach()
+ agent.reset()
+ await prompt_task
+ persisted_pending = await agent.load_pending_hitl_request()
+ await _detach_tracing(detach_tracing, tracer)
+
+ assert agent.state.last_outcome == "suspended"
+ assert persisted_pending is not None
+ roots = [span for span in exporter.spans if span.name == "invoke_agent"]
+ assert len(roots) == 1
+ assert roots[0].attributes.get("cubepi.run.outcome") == "suspended"
+ assert roots[0].attributes.get("cubepi.aborted") is not True
+
+
+async def test_respond_after_suspension_opens_a_new_activation_trace() -> None:
+ agent, channel, exporter, tracer = _build_suspending_agent("thread-respond")
+ detach_tracing = tracer.attach(agent)
+
+ prompt_task = asyncio.create_task(agent.prompt("hi", run_id="R1"))
+ await _wait_for_pending(channel)
+ await agent.detach()
+ await prompt_task
+ pending = await agent.load_pending_hitl_request()
+ assert pending is not None
+ await agent.respond(question_id=pending.question_id, answer="yes")
+ await _detach_tracing(detach_tracing, tracer)
+
+ roots = [span for span in exporter.spans if span.name == "invoke_agent"]
+ assert len(roots) == 2
+ assert roots[0].attributes.get("cubepi.run.outcome") == "suspended"
+ assert roots[1].attributes.get("cubepi.run.outcome") is None
+ assert roots[1].attributes.get("cubepi.aborted") is not True
+ assert roots[0].context.trace_id != roots[1].context.trace_id
+
+
+async def test_suspension_clears_active_run_in_owning_prompt_task() -> None:
+ agent, channel, _exporter, tracer = _build_suspending_agent("thread-3")
+ detach_tracing = tracer.attach(agent)
+
+ async def prompt_and_read_active_run():
+ await agent.prompt("hi", run_id="R1")
+ return recorder_module._active_run.get()
+
+ prompt_task = asyncio.create_task(prompt_and_read_active_run())
+ await _wait_for_pending(channel)
+ await agent.detach()
+ active_run_after_prompt = await prompt_task
+ await _detach_tracing(detach_tracing, tracer)
+
+ assert active_run_after_prompt is None
diff --git a/website/docs/guides/hitl/durable.md b/website/docs/guides/hitl/durable.md
index 328c950..eba9d37 100644
--- a/website/docs/guides/hitl/durable.md
+++ b/website/docs/guides/hitl/durable.md
@@ -51,10 +51,12 @@ async with PostgresCheckpointer("postgresql://...") as cp:
# tool_name="bash", args={"cmd":"rm /tmp/foo"}, ...)
# Graceful suspend — persist the assistant message + unresolved
- # tool_calls, keep pending_request in DB, emit AgentSuspendedEvent.
+ # tool_calls and keep pending_request in DB. detach() commits the
+ # HitlDetached transition; prompt() then emits AgentSuspendedEvent
+ # after recording outcome=suspended.
# The HTTP handler returns 200 { status: "awaiting_approval" }.
await agent.detach()
- await task # prompt() unwinds with HitlDetached
+ await task
# ---------- Process 2: HTTP POST /respond ----------
diff --git a/website/docs/guides/hitl/reference.md b/website/docs/guides/hitl/reference.md
index 9a1fd2b..12dbd50 100644
--- a/website/docs/guides/hitl/reference.md
+++ b/website/docs/guides/hitl/reference.md
@@ -34,7 +34,7 @@ agent listeners. A `_run_lock` (`asyncio.Lock`) serialises `prompt`,
| Method | Signature | Description |
|---|---|---|
| `load_pending_hitl_request()` | `async → HitlRequest \| None` | Reads the pending from the checkpointer (even post-detach). |
-| `detach()` | `async → None` | Emits `AgentSuspendedEvent(pending_request=...)` then triggers `HitlDetached` on the channel future. The loop exits silently; assistant message retains unresolved tool calls; `pending_request` stays persisted. |
+| `detach()` | `async → None` | Snapshots the pending request and triggers `HitlDetached` on the channel future. After the owning run task records `outcome=suspended` and clears its active run, it emits `AgentSuspendedEvent(pending_request=...)`. The assistant message retains unresolved tool calls and `pending_request` stays persisted. |
| `respond(*, question_id=, answer=)` | `async → None` | Resumes a suspended run. Validates qid matches persistent pending, attaches answer to channel, re-enters the loop via `run_agent_loop_resume`. |
| `abort_pending(reason=)` | `async → None` | Closes the conversation. Two-phase: Phase 1 signals in-flight await (no lock). Phase 2 appends synthetic deny tool_results + terminal `stop_reason="aborted"` assistant (under lock). |
@@ -50,14 +50,15 @@ Four new events are emitted on the agent's event stream:
|---|---|---|
| `HitlRequestEvent` | Channel receives a new `confirm/approve/ask`. | `request: HitlRequest` |
| `HitlAnswerEvent` | `channel.answer()` or `channel.cancel()` fires. | `question_id: str`, `answer: Any`, `cancelled: bool`, `timed_out: bool` |
-| `AgentSuspendedEvent` | `agent.detach()` called while HITL was pending. | `pending_request: HitlRequest` |
+| `AgentSuspendedEvent` | A detach-triggered run has committed `outcome=suspended`. | `pending_request: HitlRequest` |
| `AgentAbortedEvent` | `agent.abort_pending()` closes the conversation. | `reason: str` |
These are all included in the `AgentEvent` union, so typed listeners
automatically cover them. `HitlRequestEvent` and `HitlAnswerEvent` are
emitted by the channel through the agent's emit binding. `AgentSuspendedEvent`
-and `AgentAbortedEvent` are emitted by the Agent layer (not the loop — the
-Agent has the channel handle to populate the real `pending_request` payload).
+and `AgentAbortedEvent` are emitted by the Agent layer. Suspension payload is
+snapshotted by `detach()`, then published by the owning run task only after the
+suspended transition is committed.
## Trace spans
diff --git a/website/docs/guides/tracing/getting-started.md b/website/docs/guides/tracing/getting-started.md
index a1a0a19..9f977d7 100644
--- a/website/docs/guides/tracing/getting-started.md
+++ b/website/docs/guides/tracing/getting-started.md
@@ -140,15 +140,19 @@ The recorder treats cancellation as a control signal, not a failure:
- `agent.abort()` mid-stream → spans close with `cubepi.aborted=true` and
`error.type=cubepi.aborted`, **status UNSET** (per OTel guidance — cancellation
isn't an error).
+- `agent.detach()` at a durable HITL prompt → open spans close with
+ `cubepi.run.outcome=suspended` and no aborted/error classification. A later
+ `respond()` is a new activation trace; correlate the two with metadata such as
+ a host run or conversation ID.
- A provider raising → chat/turn/root close with **status ERROR**, an
`exception` event on the chat span, and `error.type` derived from the
exception class (`timeout`, `connection_error`, fully-qualified class name, …).
- An MCP `tools/call` returning `isError=true` → CLIENT span closes
ERROR + `error.type=mcp.is_error`.
-Either way, `detach()` and `tracer.shutdown()` always close any span the run
-left open, so cancelled runs are still visible in your backend rather than
-silently disappearing.
+In every case, `detach()` and `tracer.shutdown()` close any span the activation
+left open, so cancelled and suspended runs remain visible in your backend rather
+than silently disappearing.
## What's on each span