Skip to content

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

fix(tracing): address codex overall-review findings (7 commits) (#88)

Chris8aff05ce91d8
diff --git a/cubepi/mcp/_adapter.py b/cubepi/mcp/_adapter.py
index b435b23..705550a 100644
--- a/cubepi/mcp/_adapter.py
+++ b/cubepi/mcp/_adapter.py
@@ -2,6 +2,7 @@
from __future__ import annotations
+import asyncio
from typing import Any, Awaitable, Callable, Literal
from pydantic import BaseModel, Field, create_model
@@ -152,7 +153,32 @@ def make_mcp_agent_tool(
server_port=server_port,
parent_tool_call_id=tool_call_id,
) as span:
- result = await call_remote(name, args_dict)
+ result = await _await_with_signal(call_remote(name, args_dict), signal)
+ if result is _ABORTED_SENTINEL:
+ # Cooperative abort fired while the MCP RPC was in
+ # flight. Mark the CLIENT span aborted (Status UNSET,
+ # cubepi.aborted=true) so the trace shows the
+ # interruption, then return a synthetic tool result.
+ # Returning rather than raising preserves the agent
+ # lifecycle that non-MCP provider aborts use: the
+ # ``ToolExecutionEndEvent`` fires, the loop advances
+ # to the next turn, the provider's stream loop sees
+ # ``signal.is_set()`` and emits an aborted
+ # ``AssistantMessage``, and ``TurnEnd`` / ``AgentEnd``
+ # close the run normally. Callers that
+ # ``agent.abort(); await prompt_task`` therefore see
+ # no new exception type from MCP-backed tools (codex
+ # round-1 follow-up on PR #88).
+ if span is not None:
+ try:
+ span.set_attribute("cubepi.aborted", True)
+ span.set_attribute("error.type", "cubepi.aborted")
+ except Exception:
+ pass
+ return AgentToolResult(
+ content=[],
+ details={"aborted": True},
+ )
# MCP server-reported tool failure (``isError: true``): the
# JSON-RPC call succeeded but the tool's logic failed. Mark
# the CLIENT span ERROR so backends count it as a failure,
@@ -187,3 +213,104 @@ def make_mcp_agent_tool(
parameters=parameters_model,
execute=_execute,
)
+
+
+def _consume_task_exception(task: "asyncio.Task[Any]") -> None:
+ """``add_done_callback`` target that swallows the result/exception
+ of a fire-and-forget cancelled task. Without this, asyncio logs
+ "task exception was never retrieved" at GC time for tasks we
+ cancelled and don't await."""
+ try:
+ task.exception()
+ except (asyncio.CancelledError, asyncio.InvalidStateError):
+ pass
+
+
+# Sentinel returned by :func:`_await_with_signal` on cooperative abort.
+# The MCP ``_execute`` adapter checks for it and synthesizes a tool
+# result rather than raising ``asyncio.CancelledError``, so callers
+# that do ``agent.abort(); await prompt_task`` don't see a new
+# exception shape from MCP-backed tools — the agent loop runs its
+# normal abort lifecycle (ToolExecutionEnd → next turn →
+# provider stream sees signal → AssistantMessage(stop_reason="aborted")
+# → TurnEnd → AgentEnd). See codex round-1 follow-up on PR #88.
+_ABORTED_SENTINEL: Any = object()
+
+
+async def _await_with_signal(coro: Awaitable[Any], signal: Any) -> Any:
+ """Await ``coro``, but bail out with :data:`_ABORTED_SENTINEL` if
+ ``signal`` (an ``asyncio.Event`` set by ``agent.abort()``) fires
+ while the awaitable is in flight.
+
+ ``Agent.abort()`` only sets the cooperative signal — it does NOT
+ cancel the running task — so without a co-watching coroutine an
+ in-flight MCP ``tools/call`` would block until response or
+ transport timeout regardless of abort. Cancellation latency would
+ be bounded by the MCP timeout (30s default), not by the user's
+ intent. Racing the signal here lets ``abort()`` propagate
+ through MCP within a tick (codex overall-review MAJOR).
+
+ Returning a sentinel rather than raising ``asyncio.CancelledError``
+ keeps the agent lifecycle intact: the MCP ``_execute`` adapter
+ converts the sentinel into a synthetic ``AgentToolResult`` so the
+ normal ``ToolExecutionEnd`` / ``TurnEnd`` / ``AgentEnd`` flow
+ completes without surfacing a new exception type to callers that
+ only catch ``Exception`` (codex round-1 follow-up on PR #88).
+
+ When ``signal`` is ``None`` (e.g. tool invoked outside the agent
+ loop, or by a non-cubepi caller), just await the coroutine.
+ """
+ if signal is None or not hasattr(signal, "wait"):
+ return await coro
+ if signal.is_set():
+ # Already aborted before we even started. Close the coroutine
+ # so the caller doesn't get a "coroutine was never awaited"
+ # warning — ``coro`` is fresh and hasn't started executing.
+ if hasattr(coro, "close"):
+ coro.close()
+ return _ABORTED_SENTINEL
+ call_task = asyncio.ensure_future(coro)
+ signal_task = asyncio.ensure_future(signal.wait())
+ try:
+ done, pending = await asyncio.wait(
+ {call_task, signal_task},
+ return_when=asyncio.FIRST_COMPLETED,
+ )
+ except BaseException:
+ # Outer cancellation: clean up both tasks and re-raise.
+ # Same fire-and-forget cleanup as the signal-won branch —
+ # don't block on slow transport teardown.
+ for t in (call_task, signal_task):
+ if not t.done():
+ t.cancel()
+ t.add_done_callback(_consume_task_exception)
+ raise
+ if signal_task in done:
+ # Cooperative abort fired first — cancel the in-flight RPC
+ # and return the sentinel so ``_execute`` can synthesize a
+ # graceful tool result.
+ #
+ # Don't ``await call_task`` here: ``call_remote`` may catch
+ # ``CancelledError`` for slow transport cleanup (HTTP socket
+ # close, MCP session shutdown), and awaiting would reintroduce
+ # the abort-latency problem this helper was meant to fix —
+ # the prompt task would still hang until the MCP transport
+ # timeout despite the signal having won the race (codex
+ # round-2 follow-up on PR #88).
+ #
+ # Cancellation is dispatched eagerly; the cleanup finishes
+ # out-of-band. The ``add_done_callback`` consumes the
+ # eventual exception so asyncio doesn't log a
+ # "task exception was never retrieved" warning at GC time.
+ if not call_task.done():
+ call_task.cancel()
+ call_task.add_done_callback(_consume_task_exception)
+ return _ABORTED_SENTINEL
+ # call_task completed first; tidy the signal watcher.
+ if not signal_task.done():
+ signal_task.cancel()
+ try:
+ await signal_task
+ except BaseException:
+ pass
+ return call_task.result()
diff --git a/cubepi/mcp/http_loader.py b/cubepi/mcp/http_loader.py
index 9ebd647..361e618 100644
--- a/cubepi/mcp/http_loader.py
+++ b/cubepi/mcp/http_loader.py
@@ -6,7 +6,7 @@ import asyncio
from collections.abc import AsyncIterator
from contextlib import asynccontextmanager
from datetime import timedelta
-from typing import Any, Literal
+from typing import Any, Callable, Literal
from cubepi.mcp._adapter import make_mcp_agent_tool
from cubepi.mcp.types import (
@@ -25,14 +25,19 @@ async def _open_session(
headers: dict[str, str] | None,
timeout: float,
transport: Transport,
-) -> AsyncIterator[Any]:
+) -> AsyncIterator[tuple[Any, Callable[[], str | None]]]:
"""Open an MCP ClientSession over the requested transport.
- Normalises the two SDK transport client signatures: ``sse_client``
- yields a 2-tuple ``(read, write)`` while ``streamablehttp_client``
- yields a 3-tuple ``(read, write, get_session_id_callable)``. We drop
- the session-id callable and expose a single ``ClientSession`` to the
- caller.
+ Yields ``(session, get_session_id)``:
+
+ - ``session`` is the live ``ClientSession``.
+ - ``get_session_id()`` returns the current MCP session id for the
+ Streamable HTTP transport (``mcp.session.id`` per the GenAI MCP
+ semconv), or ``None`` for SSE (which has no session-id concept).
+ Callers use this to stamp ``mcp.session.id`` onto the CLIENT
+ span inside ``_call_remote`` rather than at loader time —
+ loader-time stamping was impossible because each call opens a
+ fresh session with its own id (codex overall-review MINOR).
"""
from mcp import ClientSession
@@ -50,9 +55,9 @@ async def _open_session(
headers=headers,
timeout=timeout_td,
sse_read_timeout=timeout_td,
- ) as (read_stream, write_stream, _get_session_id):
+ ) as (read_stream, write_stream, get_session_id):
async with ClientSession(read_stream, write_stream) as session:
- yield session
+ yield session, get_session_id
return
if transport == "sse":
@@ -65,12 +70,45 @@ async def _open_session(
sse_read_timeout=timeout,
) as (read_stream, write_stream):
async with ClientSession(read_stream, write_stream) as session:
- yield session
+ yield session, _no_session_id
return
raise ValueError(f"unsupported MCP transport '{transport}'")
+def _no_session_id() -> str | None:
+ """SSE transport has no MCP session id; this stub yields ``None``
+ so callers can treat both transports uniformly."""
+ return None
+
+
+def _stamp_session_id(session_id: str | None) -> None:
+ """Attach ``mcp.session.id`` to the current OTel span if both the
+ id and ``opentelemetry`` are present.
+
+ The CLIENT span was opened by ``cubepi.mcp._adapter._execute``
+ via ``mcp_client_span``; ``use_span`` makes it the current span
+ while ``call_remote`` runs, so reading ``get_current_span()``
+ inside the loader's call path resolves to the right span. No-op
+ when OTel isn't installed or the loader is called outside an
+ active span context.
+ """
+ if not session_id:
+ return
+ try:
+ from opentelemetry import trace as _otel_trace
+ except ImportError:
+ return
+ span = _otel_trace.get_current_span()
+ ctx = span.get_span_context()
+ if not getattr(ctx, "is_valid", False):
+ return
+ try:
+ span.set_attribute("mcp.session.id", str(session_id))
+ except Exception:
+ pass
+
+
async def load_mcp_tools_http(
server_url: str,
*,
@@ -124,8 +162,12 @@ async def load_mcp_tools_http(
async with _open_session(
server_url, headers=call_headers, timeout=timeout, transport=transport
- ) as session:
+ ) as (session, get_session_id):
await asyncio.wait_for(session.initialize(), timeout=timeout)
+ # Stamp mcp.session.id on the active CLIENT span (the one
+ # opened by _adapter._execute via ``mcp_client_span``).
+ # Per-call session id can only be read after initialize().
+ _stamp_session_id(get_session_id())
resp = await asyncio.wait_for(
session.call_tool(tool_name, args), timeout=timeout
)
@@ -133,7 +175,7 @@ async def load_mcp_tools_http(
async with _open_session(
server_url, headers=headers, timeout=timeout, transport=transport
- ) as session:
+ ) as (session, _get_session_id):
init_result = await asyncio.wait_for(session.initialize(), timeout=timeout)
tools_resp = await asyncio.wait_for(session.list_tools(), timeout=timeout)
tool_descs = tools_resp.tools
diff --git a/cubepi/tracing/meter.py b/cubepi/tracing/meter.py
index 5684fde..7125ae6 100644
--- a/cubepi/tracing/meter.py
+++ b/cubepi/tracing/meter.py
@@ -17,6 +17,7 @@ Histograms emitted (per OTel GenAI semconv):
from __future__ import annotations
import time
+from dataclasses import dataclass, field
from typing import TYPE_CHECKING, Any, Callable
from opentelemetry.sdk.metrics import MeterProvider
@@ -130,14 +131,6 @@ class Meter:
explicit_bucket_boundaries_advisory=list(_DEFAULT_DURATION_BUCKETS),
)
self._shutdown = False
- # Per-run state for timing.
- self._chat_open_ns: int | None = None
- self._chat_first_chunk_ns: int | None = None
- self._chat_attrs: dict[str, Any] = {}
- self._tool_open_ns: dict[str, int] = {}
- self._tool_attrs: dict[str, dict[str, Any]] = {}
- self._agent_open_ns: int | None = None
- self._agent_attrs: dict[str, Any] = {}
# -- public API ---------------------------------------------------
@@ -148,16 +141,44 @@ class Meter:
return self._otel_meter
def attach(self, agent: "Agent") -> Callable[[], None]:
- """Subscribe to ``agent`` and start emitting metrics."""
+ """Subscribe to ``agent`` and start emitting metrics.
+
+ Each ``attach()`` call gets its own :class:`_MeterState` so
+ multiple concurrent agents attached to the same Meter don't
+ clobber each other's open-ns timestamps and attribute dicts
+ (codex overall-review MAJOR — previously all state lived on
+ the Meter instance, so a second agent's ``provider_request``
+ overwrote the first agent's ``_chat_open_ns`` / ``_chat_attrs``
+ before its response landed).
+ """
from cubepi.providers.base import BaseProvider
- unsub_agent = agent.subscribe(self._on_agent_event)
+ state = _MeterState()
+
+ async def _on_agent_event(event: Any, signal: Any | None = None) -> None:
+ del signal
+ self._handle_agent_event(state, event)
+
+ def _on_request(payload: dict, model: "Model") -> None:
+ self._handle_provider_request(state, payload, model)
+
+ def _on_chunk(event: Any, model: "Model") -> None:
+ self._handle_provider_chunk(state, event, model)
+
+ def _on_response(
+ body: dict | None,
+ model: "Model",
+ exc: BaseException | None,
+ ) -> None:
+ self._handle_provider_response(state, body, model, exc)
+
+ unsub_agent = agent.subscribe(_on_agent_event)
provider = getattr(agent, "_provider", None) or getattr(agent, "provider", None)
detachers: list[Callable[[], None]] = []
if isinstance(provider, BaseProvider):
- detachers.append(provider.subscribe_request(self._on_provider_request))
- detachers.append(provider.subscribe_chunk(self._on_provider_chunk))
- detachers.append(provider.subscribe_response(self._on_provider_response))
+ detachers.append(provider.subscribe_request(_on_request))
+ detachers.append(provider.subscribe_chunk(_on_chunk))
+ detachers.append(provider.subscribe_response(_on_response))
def detach() -> None:
unsub_agent()
@@ -186,22 +207,24 @@ class Meter:
await self.shutdown()
# -- event handlers -----------------------------------------------
+ #
+ # Each handler takes a per-attach ``_MeterState`` so concurrent
+ # agents attached to one Meter never share timing/attribute state.
- async def _on_agent_event(self, event: Any, signal: Any | None = None) -> None:
- del signal
+ def _handle_agent_event(self, state: "_MeterState", event: Any) -> None:
try:
type_name = getattr(event, "type", "")
if type_name == "agent_start":
- self._agent_open_ns = time.time_ns()
- self._agent_attrs = {GEN_AI_OPERATION_NAME: OP_INVOKE_AGENT}
+ state.agent_open_ns = time.time_ns()
+ state.agent_attrs = {GEN_AI_OPERATION_NAME: OP_INVOKE_AGENT}
elif type_name == "agent_end":
- if self._agent_open_ns is not None:
- duration = (time.time_ns() - self._agent_open_ns) / 1e9
- self._duration_hist.record(duration, self._agent_attrs)
- self._agent_open_ns = None
- self._agent_attrs = {}
+ if state.agent_open_ns is not None:
+ duration = (time.time_ns() - state.agent_open_ns) / 1e9
+ self._duration_hist.record(duration, state.agent_attrs)
+ state.agent_open_ns = None
+ state.agent_attrs = {}
elif type_name == "tool_execution_start":
- self._tool_open_ns[event.tool_call_id] = time.time_ns()
+ state.tool_open_ns[event.tool_call_id] = time.time_ns()
# Carry the most-recent provider onto tool metrics so
# ``execute_tool`` duration observations can be filtered
# alongside chat metrics. ``_on_provider_request`` fires
@@ -210,79 +233,86 @@ class Meter:
# time here from the latest chat attrs instead
# (codex P2 finding on PR #85).
attrs: dict[str, Any] = {GEN_AI_OPERATION_NAME: OP_EXECUTE_TOOL}
- provider_name = self._chat_attrs.get(GEN_AI_PROVIDER_NAME) or (
- self._agent_attrs.get(GEN_AI_PROVIDER_NAME)
- if self._agent_attrs
+ provider_name = state.chat_attrs.get(GEN_AI_PROVIDER_NAME) or (
+ state.agent_attrs.get(GEN_AI_PROVIDER_NAME)
+ if state.agent_attrs
else None
)
if provider_name is not None:
attrs[GEN_AI_PROVIDER_NAME] = provider_name
- self._tool_attrs[event.tool_call_id] = attrs
+ state.tool_attrs[event.tool_call_id] = attrs
elif type_name == "tool_execution_end":
- start = self._tool_open_ns.pop(event.tool_call_id, None)
- attrs = self._tool_attrs.pop(event.tool_call_id, None)
+ start = state.tool_open_ns.pop(event.tool_call_id, None)
+ attrs = state.tool_attrs.pop(event.tool_call_id, None)
if start is not None and attrs is not None:
duration = (time.time_ns() - start) / 1e9
self._duration_hist.record(duration, attrs)
except Exception:
pass
- def _on_provider_request(self, payload: dict, model: "Model") -> None:
+ def _handle_provider_request(
+ self, state: "_MeterState", payload: dict, model: "Model"
+ ) -> None:
+ del payload
provider_name = map_provider_name(model.provider)
- self._chat_open_ns = time.time_ns()
- self._chat_first_chunk_ns = None
+ state.chat_open_ns = time.time_ns()
+ state.chat_first_chunk_ns = None
# Include gen_ai.request.model so failed/cancelled chat metrics
# (where the response body never lands and gen_ai.response.model
# cannot be set) can still be grouped by the requested model
# (codex P2 finding on PR #85).
- self._chat_attrs = {
+ state.chat_attrs = {
GEN_AI_OPERATION_NAME: OP_CHAT,
GEN_AI_PROVIDER_NAME: provider_name,
GEN_AI_REQUEST_MODEL: model.id,
}
# Stamp the agent + tool attrs with provider too, so all metrics
# from this run can be filtered by provider in one shot.
- if self._agent_attrs:
- self._agent_attrs.setdefault(GEN_AI_PROVIDER_NAME, provider_name)
- for _, attrs in self._tool_attrs.items():
+ if state.agent_attrs:
+ state.agent_attrs.setdefault(GEN_AI_PROVIDER_NAME, provider_name)
+ for _, attrs in state.tool_attrs.items():
attrs.setdefault(GEN_AI_PROVIDER_NAME, provider_name)
- def _on_provider_chunk(self, event: Any, model: "Model") -> None:
+ def _handle_provider_chunk(
+ self, state: "_MeterState", event: Any, model: "Model"
+ ) -> None:
del model
- if self._chat_first_chunk_ns is not None or self._chat_open_ns is None:
+ if state.chat_first_chunk_ns is not None or state.chat_open_ns is None:
return
ev_type = getattr(event, "type", "")
if ev_type in ("text_delta", "thinking_delta", "toolcall_delta"):
- self._chat_first_chunk_ns = time.time_ns()
+ state.chat_first_chunk_ns = time.time_ns()
- def _on_provider_response(
+ def _handle_provider_response(
self,
+ state: "_MeterState",
body: dict | None,
model: "Model",
exc: BaseException | None,
) -> None:
- if self._chat_open_ns is None:
+ del model
+ if state.chat_open_ns is None:
return
try:
now = time.time_ns()
- duration = (now - self._chat_open_ns) / 1e9
+ duration = (now - state.chat_open_ns) / 1e9
response_model: str | None = None
if isinstance(body, dict):
response_model = body.get("model") or None
- attrs = dict(self._chat_attrs)
+ attrs = dict(state.chat_attrs)
if response_model:
attrs[GEN_AI_RESPONSE_MODEL] = response_model
self._duration_hist.record(duration, attrs)
- if self._chat_first_chunk_ns is not None:
- ttfc = (self._chat_first_chunk_ns - self._chat_open_ns) / 1e9
+ if state.chat_first_chunk_ns is not None:
+ ttfc = (state.chat_first_chunk_ns - state.chat_open_ns) / 1e9
self._ttfc_hist.record(ttfc, attrs)
# Token usage — one observation per type.
if isinstance(body, dict) and not exc:
self._record_token_usage(body, attrs)
finally:
- self._chat_open_ns = None
- self._chat_first_chunk_ns = None
- self._chat_attrs = {}
+ state.chat_open_ns = None
+ state.chat_first_chunk_ns = None
+ state.chat_attrs = {}
def _record_token_usage(self, body: dict, attrs: dict) -> None:
usage = body.get("usage") if isinstance(body.get("usage"), dict) else None
@@ -316,3 +346,24 @@ class Meter:
self._token_hist.record(
compl_t, {**attrs, "gen_ai.token.type": "output"}
)
+
+
+@dataclass
+class _MeterState:
+ """Per-attach mutable state. One per :meth:`Meter.attach` call so
+ concurrent agents on the same Meter never share their open-ns
+ timestamps or attribute dicts (codex overall-review MAJOR).
+
+ Previously these fields lived on the Meter instance — a second
+ agent's ``provider_request`` would overwrite the first agent's
+ ``chat_open_ns`` / ``chat_attrs`` before its response listener
+ fired, corrupting the recorded duration and token-usage points.
+ """
+
+ chat_open_ns: int | None = None
+ chat_first_chunk_ns: int | None = None
+ chat_attrs: dict[str, Any] = field(default_factory=dict)
+ tool_open_ns: dict[str, int] = field(default_factory=dict)
+ tool_attrs: dict[str, dict[str, Any]] = field(default_factory=dict)
+ agent_open_ns: int | None = None
+ agent_attrs: dict[str, Any] = field(default_factory=dict)
diff --git a/cubepi/tracing/recorder.py b/cubepi/tracing/recorder.py
index a3f3293..50bbe0b 100644
--- a/cubepi/tracing/recorder.py
+++ b/cubepi/tracing/recorder.py
@@ -213,9 +213,9 @@ class Recorder:
)
def _sync_detach() -> None:
- """All synchronous cleanup: unsubscribe + sweep leaked
- registrations. Runs eagerly in ``detach()`` so the
- cancellation-leak cleanup is observable on the next line —
+ """All synchronous cleanup: unsubscribe + close any spans
+ still open + sweep leaked registrations. Runs eagerly in
+ ``detach()`` so cleanup is observable on the next line —
not deferred to a loop tick that may never arrive if the
caller immediately awaits ``tracer.shutdown()`` or exits
``asyncio.run`` (codex round-11).
@@ -226,29 +226,39 @@ class Recorder:
d()
except Exception:
pass
- # Final cleanup of any leaked tool-span registrations from
- # a cancelled run — CancelledError bypasses the agent's
- # ``except Exception`` handler so _on_agent_end /
- # _on_tool_exec_end never fire (codex round-10).
+ # Close any spans that an in-flight cancelled run left
+ # open, then sweep MCP registrations (codex round-10 /
+ # overall-review BLOCKING). CancelledError bypasses the
+ # agent's ``except Exception`` handler so the per-event
+ # end handlers never fire.
+ self._close_open_spans(self._run)
self._sweep_tool_span_tokens(self._run)
- async def _detach_async() -> None:
- _sync_detach()
- await self._tracer.force_flush()
-
- def detach() -> None:
- # Synchronous part runs immediately in either path so the
- # caller can rely on cleanup having happened by the time
- # ``detach()`` returns.
+ def detach():
+ """Synchronous cleanup + scheduled flush.
+
+ The unsubscribe / open-span close / MCP-token sweep all
+ run synchronously here — observable on the line after
+ ``detach()`` returns. The flush is scheduled as an
+ ``asyncio.Task`` and returned so callers who need the
+ buffered spans persisted before they proceed can
+ ``await detach()`` — the previous fire-and-forget
+ ``create_task(...)`` left them in ``BatchSpanProcessor``
+ indefinitely if the caller exited ``asyncio.run`` (codex
+ overall-review MAJOR).
+
+ Outside an async context (no running loop) returns
+ ``None`` — sync cleanup is done but flush is the caller's
+ responsibility via ``await tracer.shutdown()``.
+ """
_sync_detach()
try:
import asyncio
loop = asyncio.get_running_loop()
except RuntimeError:
- return # no loop — sync cleanup already done.
- # Inside a loop — schedule the remaining async flush.
- loop.create_task(self._tracer.force_flush())
+ return None
+ return loop.create_task(self._tracer.force_flush())
return detach
@@ -337,12 +347,68 @@ class Recorder:
pass
run.tool_span_tokens.clear()
+ def _close_open_spans(self, run: "_RunState | None") -> None:
+ """End any spans still open on ``run``.
+
+ Normal flow ends ``execute_tool`` / ``chat`` / ``cubepi.turn`` /
+ ``invoke_agent`` spans in their respective event handlers. But
+ ``asyncio.CancelledError`` bypasses cubepi's agent-loop
+ ``except Exception`` handler — no ``ToolExecutionEnd`` /
+ ``TurnEnd`` / ``AgentEnd`` is emitted. Without this sweep the
+ spans never reach ``span.end()`` and ``BatchSpanProcessor``
+ never exports them: cancelled runs simply disappear from the
+ backend (codex overall-review BLOCKING).
+
+ Each span gets ``cubepi.aborted=true`` + ``error.type`` so the
+ backend sees the run was interrupted rather than silently
+ succeeding. Status is left UNSET — cancellation isn't a
+ failure.
+ """
+ if run is None:
+ return
+ for span in list(run.tool_spans.values()):
+ try:
+ span.set_attribute(CUBEPI_ABORTED, True)
+ span.set_attribute(ERROR_TYPE, "cubepi.aborted")
+ span.end()
+ except Exception:
+ pass
+ run.tool_spans.clear()
+ if run.chat_span is not None:
+ try:
+ run.chat_span.set_attribute(CUBEPI_ABORTED, True)
+ run.chat_span.set_attribute(ERROR_TYPE, "cubepi.aborted")
+ 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_ABORTED, True)
+ run.turn_span.end()
+ except Exception:
+ pass
+ run.turn_span = None
+ if run.agent_span is not None:
+ try:
+ run.agent_span.set_attribute(CUBEPI_ABORTED, True)
+ run.agent_span.end()
+ except Exception:
+ pass
+ # Don't null agent_span — _RunState gets dropped wholesale.
+
def _on_agent_start(self) -> None:
- # Defensive sweep: if a prior run was cancelled (CancelledError
- # inherits BaseException — cubepi's agent loop doesn't emit
- # ToolExecutionEndEvent in that path), its tool-span registrations
- # could still be live in cubepi.mcp._tracing. Clean before
- # opening the new _RunState.
+ # Defensive cleanup: if a prior run was cancelled
+ # (CancelledError inherits BaseException — cubepi's agent loop
+ # doesn't emit ToolExecutionEnd / TurnEnd / AgentEnd in that
+ # path), its open spans never reached span.end() and its MCP
+ # tool-span registrations are still live. Close + sweep both
+ # before opening the new _RunState so the prior run is at
+ # least visible (marked aborted) in the backend and shared
+ # state stays consistent.
+ self._close_open_spans(self._run)
self._sweep_tool_span_tokens(self._run)
run_id = str(uuid.uuid4())
@@ -676,8 +742,14 @@ class Recorder:
}
# Pull StreamOptions-derived params from the payload where the
# provider exposed them as final kwargs.
+ #
+ # Note: OpenAI Responses uses ``max_output_tokens`` in place of
+ # the chat-completions ``max_tokens`` field — accept either so
+ # the resulting ``gen_ai.request.max_tokens`` attribute is
+ # consistent across providers (codex overall-review MINOR).
for key, attr in (
("max_tokens", GEN_AI_REQUEST_MAX_TOKENS),
+ ("max_output_tokens", GEN_AI_REQUEST_MAX_TOKENS),
("temperature", GEN_AI_REQUEST_TEMPERATURE),
("top_p", GEN_AI_REQUEST_TOP_P),
):
@@ -1050,8 +1122,28 @@ def _extract_system_prompt(payload: dict) -> str | None:
def _safe_tool_name(t: Any) -> str:
+ """Best-effort tool-name extractor across provider payload shapes.
+
+ Three shapes seen in the wild:
+
+ - Anthropic / cubepi.AgentTool: top-level ``{"name": ...}``
+ - OpenAI Responses: top-level ``{"name": ..., "type": "function"}``
+ - OpenAI Chat: nested ``{"type": "function", "function": {"name": ...}}``
+
+ Falls back to an attribute lookup for plain objects. Without the
+ nested-function branch, OpenAI Chat tool lists produced
+ ``[""]`` on the root span attribute (codex overall-review MINOR).
+ """
if isinstance(t, dict):
- return str(t.get("name") or "")
+ top = t.get("name")
+ if top:
+ return str(top)
+ fn = t.get("function")
+ if isinstance(fn, dict):
+ nested = fn.get("name")
+ if nested:
+ return str(nested)
+ return ""
name = getattr(t, "name", None)
return str(name) if name else ""
diff --git a/cubepi/tracing/tracer.py b/cubepi/tracing/tracer.py
index 163f2a3..8d5d1b2 100644
--- a/cubepi/tracing/tracer.py
+++ b/cubepi/tracing/tracer.py
@@ -128,13 +128,25 @@ class Tracer:
"""
return self._redact
- def attach(self, agent: "Agent") -> Callable[[], None]:
+ def attach(self, agent: "Agent") -> Callable[[], Any]:
"""Wire the cubepi recorder to ``agent``.
- Returns a ``detach()`` callable that unsubscribes every hook
- installed by this attach, then calls :meth:`force_flush` to
- ensure spans produced by the agent's runs are persisted before
- the caller proceeds.
+ Returns a ``detach()`` callable. When invoked:
+
+ - Synchronously: unsubscribes every hook, closes any spans
+ still open from a cancelled run, sweeps MCP tool-span
+ registrations — observable on the next line.
+ - Schedules a flush on the running event loop and returns the
+ resulting ``asyncio.Task`` so callers can ``await detach()``
+ to block until buffered spans have been exported. Outside
+ an async context returns ``None`` — call
+ ``await tracer.shutdown()`` separately to flush.
+
+ Either ``await detach()`` or ``await tracer.shutdown()`` (or
+ both) must be used in the caller's ``finally`` block; the
+ synchronous ``detach()`` alone does not guarantee that ended
+ spans have left ``BatchSpanProcessor`` (codex overall-review
+ MAJOR).
Also registers this Tracer's private TracerProvider with
:mod:`cubepi.mcp._tracing` so MCP CLIENT spans flow through
@@ -165,13 +177,18 @@ class Tracer:
except ImportError: # pragma: no cover — mcp module always present
mcp_tracing = None
- def detach() -> None:
- recorder_detach()
+ def detach():
+ # Forward the recorder's detach return — when called from
+ # an async context it's an ``asyncio.Task`` for the
+ # flush; callers can ``await detach()`` to wait for
+ # buffered spans to land (codex overall-review MAJOR).
+ flush_task = recorder_detach()
if mcp_tracing is not None and mcp_token is not None:
try:
mcp_tracing.unregister_provider(mcp_token)
except Exception:
pass
+ return flush_task
return detach
diff --git a/tests/mcp/test_adapter.py b/tests/mcp/test_adapter.py
index a471336..864b16c 100644
--- a/tests/mcp/test_adapter.py
+++ b/tests/mcp/test_adapter.py
@@ -1,5 +1,7 @@
"""MCP adapter unit tests (D2.1)."""
+from contextlib import asynccontextmanager
+
import pytest
from cubepi.mcp._adapter import (
@@ -249,3 +251,273 @@ async def test_make_mcp_agent_tool_omits_none_optional_args() -> None:
f"Optional field not provided should be omitted, got: {captured['args']!r}"
)
assert captured["args"] == {"query": "cats"}
+
+
+async def test_signal_abort_cancels_in_flight_mcp_call() -> None:
+ """``agent.abort()`` only sets a cooperative ``asyncio.Event``;
+ it does NOT cancel the running task. An in-flight MCP
+ ``tools/call`` would block until the response or transport
+ timeout regardless of abort. The adapter must watch the signal
+ and bail out with ``CancelledError`` so cancellation latency
+ isn't bounded by MCP timeout (codex overall-review MAJOR)."""
+ import asyncio as _asyncio
+
+ from cubepi.mcp._adapter import make_mcp_agent_tool
+
+ started = _asyncio.Event()
+ finished = _asyncio.Event()
+
+ async def _slow_call(_name: str, _args: dict) -> dict:
+ started.set()
+ try:
+ await _asyncio.sleep(10.0) # would block well past test budget
+ except _asyncio.CancelledError:
+ finished.set()
+ raise
+ return {"content": [], "isError": False}
+
+ tool = make_mcp_agent_tool(
+ name="slow",
+ description="slow tool",
+ input_schema={"type": "object", "properties": {}, "required": []},
+ call_remote=_slow_call,
+ )
+ signal = _asyncio.Event()
+ args = tool.parameters()
+ task = _asyncio.create_task(
+ tool.execute("tc-abort", args, signal=signal, on_update=None)
+ )
+ await started.wait()
+ # Cooperative abort: set the signal but do NOT cancel the task.
+ signal.set()
+ # Adapter must complete with a synthetic AgentToolResult (NOT
+ # raise CancelledError) so the agent's normal abort lifecycle
+ # runs — callers that do ``agent.abort(); await prompt_task``
+ # must not see a new exception shape from MCP-backed tools
+ # (codex round-1 follow-up on PR #88).
+ try:
+ result = await _asyncio.wait_for(task, timeout=1.0)
+ except _asyncio.TimeoutError:
+ task.cancel()
+ raise AssertionError(
+ "MCP adapter ignored abort signal; tools/call did not bail out"
+ )
+ # The inner call_remote was cancelled too.
+ assert finished.is_set(), "call_remote was not cancelled when signal fired"
+ # Synthetic tool result carries the aborted flag in details.
+ assert result.details.get("aborted") is True
+ # No spurious error status — abort isn't a failure.
+ assert result.is_error is None or result.is_error is False
+ assert result.content == []
+
+
+async def test_agent_abort_during_mcp_call_does_not_raise() -> None:
+ """The full ``agent.abort(); await prompt_task`` contract: when
+ a real cubepi Agent calls an MCP tool that's still in flight and
+ the user fires ``agent.abort()``, the prompt task must complete
+ without surfacing ``CancelledError`` to the caller — matching
+ the lifecycle non-MCP provider aborts use. Codex round-1
+ follow-up on PR #88."""
+ import asyncio as _asyncio
+
+ from cubepi.agent.agent import Agent
+ from cubepi.mcp._adapter import make_mcp_agent_tool
+ from cubepi.providers.base import Model, ToolCall
+ from cubepi.providers.faux import FauxProvider, faux_assistant_message
+
+ in_flight = _asyncio.Event()
+
+ async def _slow(_name, _args):
+ in_flight.set()
+ await _asyncio.sleep(10.0)
+ return {"content": [], "isError": False}
+
+ mcp_tool = make_mcp_agent_tool(
+ name="slow",
+ description="slow",
+ input_schema={"type": "object", "properties": {}, "required": []},
+ call_remote=_slow,
+ )
+ provider = FauxProvider()
+ provider.append_responses(
+ [
+ faux_assistant_message(
+ [ToolCall(id="tc1", name="slow", arguments={})],
+ stop_reason="tool_use",
+ ),
+ # Even though abort will kick in first, queue a follow-up
+ # in case the loop somehow advances to a second turn.
+ faux_assistant_message("done"),
+ ]
+ )
+ agent = Agent(
+ provider=provider,
+ model=Model(id="faux-1", provider="faux"),
+ system_prompt="s",
+ tools=[mcp_tool],
+ )
+
+ prompt_task = _asyncio.create_task(agent.prompt("go"))
+ await in_flight.wait()
+ agent.abort()
+ # The contract: prompt_task completes (returns None) without
+ # raising. With the previous CancelledError-raising path this
+ # would either propagate or wedge.
+ try:
+ await _asyncio.wait_for(prompt_task, timeout=2.0)
+ except _asyncio.CancelledError:
+ raise AssertionError(
+ "agent.abort() during MCP call surfaced CancelledError to "
+ "the caller — expected normal lifecycle completion"
+ )
+ except _asyncio.TimeoutError:
+ prompt_task.cancel()
+ raise AssertionError("prompt_task did not complete after abort()")
+
+
+async def test_signal_abort_swallows_span_set_attribute_errors(monkeypatch) -> None:
+ """The cooperative-abort branch in ``_execute`` marks the CLIENT
+ span aborted before returning the synthetic result. If
+ ``span.set_attribute`` raises (broken OTel SDK, recording-only
+ span, …) the helper must swallow rather than corrupt the abort
+ path (defensive-branch coverage)."""
+ import asyncio as _asyncio
+
+ from cubepi.mcp._adapter import make_mcp_agent_tool
+ from cubepi.mcp import _tracing as mcp_tracing
+
+ # Force mcp_client_span to yield a span whose set_attribute raises.
+ class _BoomSpan:
+ def set_attribute(self, *_a, **_kw):
+ raise RuntimeError("set_attribute boom")
+
+ def end(self):
+ pass
+
+ def get_span_context(self):
+ class _Ctx:
+ is_valid = False
+
+ return _Ctx()
+
+ @asynccontextmanager
+ async def _fake_span(**_kw):
+ yield _BoomSpan()
+
+ monkeypatch.setattr("cubepi.mcp._adapter.mcp_client_span", _fake_span)
+
+ async def _call(_name, _args):
+ return {"content": [], "isError": False}
+
+ tool = make_mcp_agent_tool(
+ name="t",
+ description="t",
+ input_schema={"type": "object", "properties": {}, "required": []},
+ call_remote=_call,
+ )
+ signal = _asyncio.Event()
+ signal.set()
+ # set_attribute will raise; the abort branch must swallow it
+ # and still return the synthetic aborted result.
+ result = await tool.execute(
+ "tc-x", tool.parameters(), signal=signal, on_update=None
+ )
+ assert result.details.get("aborted") is True
+
+ # Silence the unused-import guard for mcp_tracing — it's documented
+ # context for why span methods exist.
+ del mcp_tracing
+
+
+async def test_signal_abort_does_not_block_on_slow_call_cleanup() -> None:
+ """``call_remote`` implementations sometimes catch
+ ``CancelledError`` to do slow transport cleanup (close an HTTP
+ socket, finalize an MCP session). The abort path must NOT block
+ on that cleanup — otherwise we reintroduce the abort-latency
+ problem the helper was meant to solve, just bounded by the
+ cleanup duration instead of the MCP timeout (codex round-2
+ follow-up on PR #88)."""
+ import asyncio as _asyncio
+ import time as _time
+
+ from cubepi.mcp._adapter import make_mcp_agent_tool
+
+ in_flight = _asyncio.Event()
+ cleanup_started = _asyncio.Event()
+ cleanup_finished = _asyncio.Event()
+
+ async def _slow_cleanup_call(_name, _args):
+ in_flight.set()
+ try:
+ await _asyncio.sleep(10.0)
+ except _asyncio.CancelledError:
+ cleanup_started.set()
+ # Simulate a slow teardown — 0.5s.
+ try:
+ await _asyncio.sleep(0.5)
+ except _asyncio.CancelledError:
+ pass
+ cleanup_finished.set()
+ raise
+ return {"content": [], "isError": False}
+
+ tool = make_mcp_agent_tool(
+ name="slow-cleanup",
+ description="slow cleanup tool",
+ input_schema={"type": "object", "properties": {}, "required": []},
+ call_remote=_slow_cleanup_call,
+ )
+ signal = _asyncio.Event()
+ task = _asyncio.create_task(
+ tool.execute("tc1", tool.parameters(), signal=signal, on_update=None)
+ )
+ await in_flight.wait()
+ signal.set()
+ t0 = _time.monotonic()
+ result = await _asyncio.wait_for(task, timeout=1.0)
+ elapsed = _time.monotonic() - t0
+ # The fix: the helper does NOT await the cancelled call_task, so
+ # _execute returns within a tick. Slow-cleanup work (the 0.5s
+ # _asyncio.sleep inside the CancelledError handler) continues in
+ # the background and must not delay this return.
+ assert elapsed < 0.3, (
+ f"abort path blocked on call_remote cleanup ({elapsed:.2f}s); "
+ "expected immediate sentinel-based return"
+ )
+ assert result.details.get("aborted") is True
+ # Cleanup started (cancellation dispatched) but may not be finished
+ # yet — that's the whole point of the fix.
+ assert cleanup_started.is_set()
+ # Let the background cleanup finish so the test exits cleanly.
+ await _asyncio.wait_for(cleanup_finished.wait(), timeout=2.0)
+
+
+async def test_signal_already_set_before_call_aborts_immediately() -> None:
+ """Pre-set signal: adapter returns the aborted synthetic result
+ without invoking ``call_remote`` at all (codex round-1 follow-up
+ on PR #88)."""
+ import asyncio as _asyncio
+
+ from cubepi.mcp._adapter import make_mcp_agent_tool
+
+ called = False
+
+ async def _call(_name: str, _args: dict) -> dict:
+ nonlocal called
+ called = True
+ return {"content": [], "isError": False}
+
+ tool = make_mcp_agent_tool(
+ name="t",
+ description="t",
+ input_schema={"type": "object", "properties": {}, "required": []},
+ call_remote=_call,
+ )
+ signal = _asyncio.Event()
+ signal.set() # already aborted before _execute even starts
+ result = await tool.execute(
+ "tc-pre", tool.parameters(), signal=signal, on_update=None
+ )
+ assert called is False, "pre-set signal should skip call_remote entirely"
+ assert result.details.get("aborted") is True
+ assert result.content == []
diff --git a/tests/mcp/test_http_loader.py b/tests/mcp/test_http_loader.py
index c79f3f6..96834e8 100644
--- a/tests/mcp/test_http_loader.py
+++ b/tests/mcp/test_http_loader.py
@@ -506,3 +506,107 @@ async def test_load_mcp_tools_http_handles_missing_server_icons(monkeypatch) ->
assert discovery.server is not None
assert discovery.server.icons == ()
assert discovery.server.website_url is None
+
+
+def test_stamp_session_id_handles_otel_missing(monkeypatch) -> None:
+ """When opentelemetry isn't importable, ``_stamp_session_id``
+ must no-op silently — the loader can't assume the optional
+ tracing extra is installed (defensive-branch coverage)."""
+ import builtins
+
+ from cubepi.mcp import http_loader
+
+ real_import = builtins.__import__
+
+ def _no_otel(name, *args, **kwargs):
+ if name.startswith("opentelemetry"):
+ raise ImportError("opentelemetry not installed")
+ return real_import(name, *args, **kwargs)
+
+ monkeypatch.setattr(builtins, "__import__", _no_otel)
+ # Must not raise.
+ http_loader._stamp_session_id("sess-x")
+
+
+def test_stamp_session_id_noop_without_active_span() -> None:
+ """When no recording span is active (``ctx.is_valid == False``)
+ ``_stamp_session_id`` must return without touching the span
+ (defensive-branch coverage)."""
+ from cubepi.mcp import http_loader
+
+ # No tracer provider set up — get_current_span returns the OTel
+ # NonRecordingSpan whose ctx.is_valid is False.
+ http_loader._stamp_session_id("sess-y")
+
+
+def test_stamp_session_id_swallows_set_attribute_errors(monkeypatch) -> None:
+ """When the current span's ``set_attribute`` raises,
+ ``_stamp_session_id`` must swallow — observability never gets
+ in the loader's way (defensive-branch coverage)."""
+ from opentelemetry import trace as _otel_trace
+
+ class _BoomSpan:
+ def get_span_context(self):
+ class _Ctx:
+ is_valid = True
+
+ return _Ctx()
+
+ def set_attribute(self, *_a, **_kw):
+ raise RuntimeError("boom")
+
+ from cubepi.mcp import http_loader
+
+ monkeypatch.setattr(_otel_trace, "get_current_span", lambda: _BoomSpan())
+ # Must not raise.
+ http_loader._stamp_session_id("sess-x")
+
+
+async def test_stamp_session_id_attaches_attr_to_current_span() -> None:
+ """``_stamp_session_id`` reads the active OTel span and writes
+ ``mcp.session.id`` onto it. The streamable HTTP loader calls it
+ inside ``_call_remote`` after ``initialize()`` returns, while the
+ CLIENT span opened by ``mcp_client_span`` is current.
+
+ Codex overall-review MINOR finding: previously the HTTP loader
+ dropped the ``_get_session_id`` callable yielded by
+ ``streamablehttp_client``, so the CLIENT span never carried
+ ``mcp.session.id`` for HTTP MCP servers."""
+ from opentelemetry.sdk.trace import TracerProvider
+ from opentelemetry.sdk.trace.export import (
+ SimpleSpanProcessor,
+ SpanExporter,
+ SpanExportResult,
+ )
+
+ class _Capture(SpanExporter):
+ def __init__(self) -> None:
+ self.spans: list = []
+
+ 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
+
+ exporter = _Capture()
+ provider = TracerProvider()
+ provider.add_span_processor(SimpleSpanProcessor(exporter))
+ tracer = provider.get_tracer("test")
+
+ from cubepi.mcp.http_loader import _stamp_session_id
+
+ with tracer.start_as_current_span("test-span"):
+ _stamp_session_id("session-abc-123")
+ # No-op cases (must not raise).
+ _stamp_session_id(None)
+ _stamp_session_id("")
+
+ assert exporter.spans
+ attrs = dict(exporter.spans[0].attributes or {})
+ assert attrs.get("mcp.session.id") == "session-abc-123"
diff --git a/tests/tracing/test_meter.py b/tests/tracing/test_meter.py
index eb192ab..029142a 100644
--- a/tests/tracing/test_meter.py
+++ b/tests/tracing/test_meter.py
@@ -46,13 +46,6 @@ def _build_meter() -> tuple[Meter, InMemoryMetricReader]:
"gen_ai.client.operation.time_to_first_chunk", unit="s"
)
meter._shutdown = False
- meter._chat_open_ns = None
- meter._chat_first_chunk_ns = None
- meter._chat_attrs = {}
- meter._tool_open_ns = {}
- meter._tool_attrs = {}
- meter._agent_open_ns = None
- meter._agent_attrs = {}
return meter, reader
@@ -212,6 +205,70 @@ class TestProviderOnToolMetrics:
)
+class TestConcurrentAgents:
+ """Two agents attached to the same Meter must produce independent
+ measurements — codex overall-review MAJOR. Previously timing /
+ attribute state lived on the Meter instance, so a second agent's
+ provider_request overwrote the first agent's ``_chat_open_ns`` /
+ ``_chat_attrs`` before its response landed and corrupted the
+ duration + token recordings."""
+
+ async def test_interleaved_provider_requests_dont_share_state(self):
+ """Drive the meter's provider listeners directly with the two
+ attaches' state interleaved (request A → request B → response
+ A → response B). With instance-level state the first response
+ would record duration against B's attrs; with per-attach state
+ each one records against its own attrs."""
+ agent_a = Agent(provider=FauxProvider(), model=MODEL, system_prompt="s")
+ agent_b = Agent(
+ provider=FauxProvider(),
+ model=Model(id="faux-2", provider="faux"),
+ system_prompt="s",
+ )
+ meter, reader = _build_meter()
+ meter.attach(agent_a)
+ meter.attach(agent_b)
+
+ # Walk the agents' provider listener registries directly so
+ # we control the ordering. Each agent has its own listener
+ # callable bound to its own _MeterState.
+ prov_a = agent_a._provider
+ prov_b = agent_b._provider
+ req_a = next(iter(prov_a._request_listeners))
+ req_b = next(iter(prov_b._request_listeners))
+ resp_a = next(iter(prov_a._response_listeners))
+ resp_b = next(iter(prov_b._response_listeners))
+
+ # Open both chat windows.
+ req_a({"messages": []}, MODEL)
+ req_b({"messages": []}, Model(id="faux-2", provider="faux"))
+ # Close them in original order.
+ body_a = {"model": "faux-1", "usage": {"input_tokens": 1, "output_tokens": 2}}
+ body_b = {"model": "faux-2", "usage": {"input_tokens": 3, "output_tokens": 4}}
+ resp_a(body_a, MODEL, None)
+ resp_b(body_b, Model(id="faux-2", provider="faux"), None)
+
+ points = _all_metric_points(reader)
+ chat_durations = [
+ dp
+ for n, dp in points
+ if n == "gen_ai.client.operation.duration"
+ and dict(dp.attributes).get("gen_ai.operation.name") == "chat"
+ ]
+ # Exactly two chat-duration observations, one per agent, each
+ # carrying its own request model. With instance-shared state
+ # both observations would carry the second request's model.
+ assert len(chat_durations) == 2, (
+ f"expected 2 chat durations, got {len(chat_durations)}"
+ )
+ request_models = sorted(
+ dict(dp.attributes).get("gen_ai.request.model") for dp in chat_durations
+ )
+ assert request_models == ["faux-1", "faux-2"], (
+ f"meter shared chat_attrs across attaches; got models {request_models}"
+ )
+
+
class TestNoMetricsWithoutListeners:
async def test_detach_stops_emission(self):
provider = FauxProvider()
diff --git a/tests/tracing/test_recorder.py b/tests/tracing/test_recorder.py
index ec9463c..e3020f0 100644
--- a/tests/tracing/test_recorder.py
+++ b/tests/tracing/test_recorder.py
@@ -494,6 +494,202 @@ class TestErrorAndAbort:
assert fallback_chat.status.status_code == StatusCode.UNSET
+class TestSafeToolName:
+ """``_safe_tool_name`` must handle all three tool payload shapes:
+ Anthropic/cubepi top-level ``name``, OpenAI Responses top-level
+ ``name``, and OpenAI Chat's nested ``{type: function, function:
+ {name: ...}}``. Without the nested branch the root span's tool
+ list was filled with ``[""]`` for OpenAI Chat (codex
+ overall-review MINOR)."""
+
+ def test_top_level_name(self):
+ from cubepi.tracing.recorder import _safe_tool_name
+
+ assert _safe_tool_name({"name": "search"}) == "search"
+
+ def test_openai_chat_nested_function_shape(self):
+ from cubepi.tracing.recorder import _safe_tool_name
+
+ assert (
+ _safe_tool_name({"type": "function", "function": {"name": "fetch"}})
+ == "fetch"
+ )
+
+ def test_object_attribute(self):
+ from cubepi.tracing.recorder import _safe_tool_name
+
+ class _T:
+ name = "calc"
+
+ assert _safe_tool_name(_T()) == "calc"
+
+ def test_missing_name_returns_empty(self):
+ from cubepi.tracing.recorder import _safe_tool_name
+
+ assert _safe_tool_name({}) == ""
+ assert _safe_tool_name({"type": "function"}) == ""
+
+
+class TestRequestMaxTokensCrossProvider:
+ """OpenAI Responses uses ``max_output_tokens`` while
+ chat-completions / Anthropic use ``max_tokens``. The recorder
+ must capture either into ``gen_ai.request.max_tokens`` so the
+ attribute is consistent across providers (codex overall-review
+ MINOR)."""
+
+ async def test_max_output_tokens_lands_in_request_max_tokens(self):
+ provider = FauxProvider()
+ agent = Agent(provider=provider, model=MODEL, system_prompt="s")
+ exporter = InMemoryExporter()
+ tracer = Tracer(service_name="t", agent_name="a", exporters=[exporter])
+ tracer.attach(agent)
+
+ recorder = _find_attached_recorder(provider)
+ assert recorder is not None
+ from cubepi.agent.types import AgentStartEvent, TurnStartEvent
+
+ await recorder._on_agent_event(AgentStartEvent())
+ await recorder._on_agent_event(TurnStartEvent())
+ # Simulate an OpenAI Responses request payload shape.
+ recorder._on_provider_request(
+ {"messages": [], "max_output_tokens": 4096},
+ MODEL,
+ )
+ recorder._on_provider_response({"model": "faux-1"}, MODEL, None)
+ await tracer.shutdown()
+
+ chats = [s for s in exporter.spans if s.name.startswith("chat ")]
+ assert chats, "no chat span captured"
+ # The most recent chat span carries the value.
+ attrs = _attrs(chats[-1])
+ assert attrs.get("gen_ai.request.max_tokens") == 4096
+
+
+class TestDetachFlushGuarantee:
+ """``Tracer.attach()``'s ``detach()`` must let callers await the
+ flush so buffered spans land before they proceed — previously the
+ flush was scheduled fire-and-forget and the caller could exit
+ asyncio.run before BatchSpanProcessor drained (codex overall-
+ review MAJOR)."""
+
+ async def test_detach_returns_awaitable_task(self):
+ agent, provider, exporter, tracer = await _build()
+ provider.append_responses([faux_assistant_message("ok")])
+ await agent.prompt("x")
+ await agent.wait_for_idle()
+
+ # Replicate Tracer.attach's detach: it should return a Task.
+ detach = tracer.attach(agent)
+ # `attach()` already happened in _build, so detach has been
+ # consumed. Build a fresh attach here.
+ await agent.prompt("y")
+ await agent.wait_for_idle()
+ result = detach()
+ assert result is not None, (
+ "detach() inside running loop must return a flush Task; got None"
+ )
+ assert asyncio.isfuture(result) or asyncio.iscoroutine(result), (
+ f"detach() must return an awaitable; got {type(result).__name__}"
+ )
+ # Awaiting it must complete the flush.
+ flushed = await result
+ # force_flush returns a bool — exporter should have spans.
+ del flushed
+ await tracer.shutdown()
+ assert exporter.spans, "no spans landed after awaited detach"
+
+ def test_detach_outside_loop_returns_none(self):
+ # Build a Tracer + Agent in sync context (no running loop).
+ provider = FauxProvider()
+ agent = Agent(provider=provider, model=MODEL, system_prompt="s")
+ tracer = Tracer(service_name="t", agent_name="a", exporters=[])
+ detach = tracer.attach(agent)
+ # No running loop → flush is the caller's responsibility.
+ assert detach() is None
+
+
+class TestCancellationExportsSpans:
+ """``asyncio.CancelledError`` bypasses cubepi's agent-loop
+ ``except Exception``, so no AgentEnd / TurnEnd / ToolExecutionEnd
+ event is emitted on cancel. Without an explicit close path the
+ open spans never reach ``span.end()`` and ``BatchSpanProcessor``
+ drops them — cancelled runs simply disappear from the backend
+ (codex overall-review BLOCKING)."""
+
+ async def test_cancelled_run_still_exports_invoke_agent_span(self):
+ provider = FauxProvider(tokens_per_second=10.0)
+ agent = Agent(provider=provider, model=MODEL, system_prompt="s")
+ exporter = InMemoryExporter()
+ tracer = Tracer(service_name="t", agent_name="a", exporters=[exporter])
+ detach = tracer.attach(agent)
+
+ provider.append_responses([faux_assistant_message("x" * 600)])
+
+ run = asyncio.create_task(agent.prompt("hi"))
+ await asyncio.sleep(0.05)
+ run.cancel()
+ try:
+ await run
+ except asyncio.CancelledError:
+ pass
+
+ detach()
+ await tracer.shutdown()
+
+ # invoke_agent + cubepi.turn + chat must all have been ended
+ # and exported, even though no AgentEnd/TurnEnd fired.
+ names = {s.name for s in exporter.spans}
+ assert "invoke_agent" in names, (
+ f"cancelled run's invoke_agent span not exported; got {names}"
+ )
+ assert "cubepi.turn" in names
+ assert any(n.startswith("chat ") for n in names)
+
+ # Each must carry cubepi.aborted so the backend sees the
+ # interruption rather than thinking the run completed.
+ for span in exporter.spans:
+ if span.name in ("invoke_agent", "cubepi.turn") or span.name.startswith(
+ "chat "
+ ):
+ attrs = _attrs(span)
+ assert attrs.get("cubepi.aborted") is True, (
+ f"{span.name} missing cubepi.aborted after cancellation"
+ )
+
+
+class TestCloseOpenSpansDefensive:
+ """``_close_open_spans`` swallows any exception raised while
+ marking a span aborted — the cleanup must continue across all
+ open spans even if one raises. Pin those defensive branches
+ (codex overall-review BLOCKING follow-up: pure coverage)."""
+
+ def test_close_open_spans_swallows_set_attribute_errors(self):
+ from cubepi.tracing.recorder import Recorder, _RunState
+
+ tracer = Tracer(service_name="t", exporters=[])
+ recorder = Recorder(tracer)
+
+ class _BoomSpan:
+ def set_attribute(self, *_a, **_kw):
+ raise RuntimeError("set_attribute boom")
+
+ def end(self):
+ raise RuntimeError("end boom")
+
+ run = _RunState(run_id="r", agent_span=_BoomSpan())
+ run.tool_spans = {"tc1": _BoomSpan(), "tc2": _BoomSpan()}
+ run.chat_span = _BoomSpan()
+ run.turn_span = _BoomSpan()
+
+ # All four branches' exception handlers must fire without
+ # propagating. Post-condition: tool_spans cleared, others
+ # nulled, no exception raised.
+ recorder._close_open_spans(run)
+ assert run.tool_spans == {}
+ assert run.chat_span is None
+ assert run.turn_span is None
+
+
class TestAgentSignalHelper:
"""Unit-level coverage for the defensive branches of
``Recorder._agent_signal_is_set`` introduced in PR #87. The