Skip to content

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

feat(tracing): Phase 1 MVP — OTel-compatible tracing module (#82)

Chris633c0a8fa8bd
diff --git a/cubepi/tracing/__init__.py b/cubepi/tracing/__init__.py
new file mode 100644
index 0000000..a0d12a6
--- /dev/null
+++ b/cubepi/tracing/__init__.py
@@ -0,0 +1,28 @@
+"""cubepi.tracing — OpenTelemetry-compatible observability for cubepi agents.
+
+Build a :class:`Tracer`, attach it to an :class:`~cubepi.agent.Agent`, and
+spans will flow to whichever :class:`~opentelemetry.sdk.trace.export.SpanExporter`
+implementations you configure (e.g. :class:`JsonlSpanExporter` for local
+files, or the OTLP exporter shipped with ``opentelemetry-exporter-otlp-proto-http``).
+
+This module requires the optional ``opentelemetry-sdk`` dependency; install
+with ``pip install cubepi[tracing]``.
+"""
+
+try: # noqa: SIM105 — explicit ImportError handling for the optional extra.
+ import opentelemetry.sdk.trace # noqa: F401
+except ImportError as exc: # pragma: no cover — exercised only without the extra.
+ raise ImportError(
+ "cubepi.tracing requires the 'opentelemetry-sdk' package. "
+ "Install it via: pip install cubepi[tracing]"
+ ) from exc
+
+from cubepi.tracing.exporters import JsonlSpanExporter
+from cubepi.tracing.schema import SCHEMA_URL
+from cubepi.tracing.tracer import Tracer
+
+__all__ = [
+ "JsonlSpanExporter",
+ "SCHEMA_URL",
+ "Tracer",
+]
diff --git a/cubepi/tracing/errors.py b/cubepi/tracing/errors.py
new file mode 100644
index 0000000..30c618f
--- /dev/null
+++ b/cubepi/tracing/errors.py
@@ -0,0 +1,40 @@
+"""``error.type`` value derivation for cubepi tracing.
+
+The OTel GenAI semantic convention does NOT prescribe a closed enum for
+``error.type``. We adopt the cubepi conventions documented in
+``docs/specs/2026-05-18-cubepi-tracing-design.md`` §12.3:
+
+- Provider HTTP 4xx/5xx → ``"<provider>.<status>"``
+- Provider client class raised → fully-qualified Python class name
+- Network timeout → ``"timeout"``
+- Connection refused → ``"connection_error"``
+- Agent aborted → ``"cubepi.aborted"``
+- Tool / business error → exception class name
+"""
+
+from __future__ import annotations
+
+import asyncio
+
+
+def cubepi_error_type_for(exc: BaseException) -> str:
+ """Derive an ``error.type`` value for a thrown exception.
+
+ Cheap and best-effort; observers should rely on the
+ ``gen_ai.client.operation.exception`` event for full details.
+ """
+ if isinstance(exc, asyncio.CancelledError):
+ return "cubepi.aborted"
+ if isinstance(exc, asyncio.TimeoutError):
+ return "timeout"
+ if isinstance(exc, TimeoutError): # builtin in 3.11+
+ return "timeout"
+ if isinstance(exc, ConnectionError):
+ return "connection_error"
+
+ cls = type(exc)
+ module = cls.__module__
+ name = cls.__qualname__
+ if module in {"builtins", "__main__"}:
+ return name
+ return f"{module}.{name}"
diff --git a/cubepi/tracing/exporters/__init__.py b/cubepi/tracing/exporters/__init__.py
new file mode 100644
index 0000000..7327cc8
--- /dev/null
+++ b/cubepi/tracing/exporters/__init__.py
@@ -0,0 +1,5 @@
+"""Span exporter implementations for cubepi.tracing."""
+
+from cubepi.tracing.exporters.jsonl import JsonlSpanExporter
+
+__all__ = ["JsonlSpanExporter"]
diff --git a/cubepi/tracing/exporters/jsonl.py b/cubepi/tracing/exporters/jsonl.py
new file mode 100644
index 0000000..201df99
--- /dev/null
+++ b/cubepi/tracing/exporters/jsonl.py
@@ -0,0 +1,132 @@
+"""Append-only JSONL span exporter.
+
+One span per line, OTLP/JSON-shaped via ``span.to_json()``. Files are
+sharded ``<directory>/<YYYY-MM-DD>/<run_id>.jsonl`` so each run lands
+in its own file and per-day directories don't grow unbounded.
+"""
+
+from __future__ import annotations
+
+import json
+import os
+from collections.abc import Sequence
+from datetime import datetime, timezone
+from pathlib import Path
+from typing import Any
+
+from opentelemetry.sdk.trace import ReadableSpan
+from opentelemetry.sdk.trace.export import SpanExporter, SpanExportResult
+
+from cubepi.tracing.schema import CUBEPI_RUN_ID
+
+
+class JsonlSpanExporter(SpanExporter):
+ """Write each ReadableSpan as one JSON line.
+
+ Files: ``<directory>/<YYYY-MM-DD>/<run_id>.jsonl``. The date used for
+ the subdirectory is the span's start time (UTC). The ``run_id`` comes
+ from the ``cubepi.run_id`` attribute set by the cubepi Recorder;
+ spans without that attribute fall back to ``"unknown-run"``.
+
+ Permissions: files are created mode ``0o600`` (user-only).
+ """
+
+ def __init__(
+ self,
+ directory: str | os.PathLike[str] = "./cubepi-traces",
+ ) -> None:
+ self._directory = Path(directory)
+ self._shutdown = False
+
+ def export(self, spans: Sequence[ReadableSpan]) -> SpanExportResult:
+ if self._shutdown:
+ return SpanExportResult.FAILURE
+ if not spans:
+ return SpanExportResult.SUCCESS
+
+ # Group by destination file so we open each at most once per
+ # export batch.
+ grouped: dict[Path, list[str]] = {}
+ for span in spans:
+ try:
+ path = self._path_for(span)
+ line = self._encode(span)
+ except Exception:
+ # Per the SpanExporter contract: never raise from export.
+ return SpanExportResult.FAILURE
+ grouped.setdefault(path, []).append(line)
+
+ try:
+ for path, lines in grouped.items():
+ path.parent.mkdir(parents=True, exist_ok=True)
+ self._append(path, lines)
+ except Exception:
+ return SpanExportResult.FAILURE
+
+ return SpanExportResult.SUCCESS
+
+ def shutdown(self) -> None:
+ self._shutdown = True
+
+ def force_flush(self, timeout_millis: int = 30_000) -> bool:
+ # Writes are synchronous + ``open(..., "a")`` flushes on close.
+ # No background buffer to drain.
+ return True
+
+ # ------------------------------------------------------------------
+ # internals
+ # ------------------------------------------------------------------
+
+ def _path_for(self, span: ReadableSpan) -> Path:
+ start_ns = span.start_time or 0
+ if start_ns:
+ dt = datetime.fromtimestamp(start_ns / 1_000_000_000, tz=timezone.utc)
+ date_dir = dt.strftime("%Y-%m-%d")
+ else:
+ date_dir = datetime.now(tz=timezone.utc).strftime("%Y-%m-%d")
+ run_id = (span.attributes or {}).get(CUBEPI_RUN_ID, "unknown-run")
+ # Sanitize: run_ids are uuids in practice, but defend against odd
+ # characters slipping through extra_attrs.
+ safe = _safe_filename(str(run_id))
+ return self._directory / date_dir / f"{safe}.jsonl"
+
+ @staticmethod
+ def _encode(span: ReadableSpan) -> str:
+ # ``span.to_json`` returns indented JSON by default; collapse to
+ # one line so each file remains jsonl-grep-friendly.
+ raw = span.to_json(indent=None)
+ # Some SDK versions emit a trailing newline; strip.
+ raw = raw.rstrip("\n")
+ # Sanity check: must be one line.
+ if "\n" in raw:
+ # Re-serialize via stdlib to flatten if SDK ever changes.
+ data: Any = json.loads(raw)
+ raw = json.dumps(data, separators=(",", ":"))
+ return raw
+
+ @staticmethod
+ def _append(path: Path, lines: list[str]) -> None:
+ flags = os.O_WRONLY | os.O_APPEND | os.O_CREAT
+ fd = os.open(path, flags, 0o600)
+ try:
+ with os.fdopen(fd, "a", encoding="utf-8") as f:
+ for line in lines:
+ f.write(line)
+ f.write("\n")
+ except Exception:
+ try:
+ os.close(fd)
+ except OSError:
+ pass
+ raise
+
+
+def _safe_filename(name: str) -> str:
+ # Allow alnum, dash, underscore, dot. Replace everything else.
+ out = []
+ for ch in name:
+ if ch.isalnum() or ch in ("-", "_", "."):
+ out.append(ch)
+ else:
+ out.append("_")
+ return "".join(out) or "unknown-run"
diff --git a/cubepi/tracing/recorder.py b/cubepi/tracing/recorder.py
new file mode 100644
index 0000000..84c5dda
--- /dev/null
+++ b/cubepi/tracing/recorder.py
@@ -0,0 +1,732 @@
+"""Map cubepi :class:`AgentEvent` + provider listener callbacks to
+OpenTelemetry spans.
+
+Span hierarchy::
+
+ invoke_agent <agent_name> [INTERNAL]
+ └── cubepi.turn [INTERNAL]
+ ├── chat <model> [CLIENT] (lifetime: provider listeners)
+ └── execute_tool <tool_name> [INTERNAL]
+
+The ``chat`` span lifetime is **driven by provider listeners**, NOT by
+the agent's ``MessageStartEvent`` / ``MessageEndEvent`` — those fire
+after ``after_model_response`` middleware hooks and so would conflate
+hook time with the LLM roundtrip. The chat span opens at
+``provider.on_request`` and closes at ``provider.on_response`` (success
+or error). See ``docs/specs/2026-05-18-cubepi-tracing-design.md`` §9.
+"""
+
+from __future__ import annotations
+
+import hashlib
+import time
+import traceback
+import uuid
+from dataclasses import dataclass, field
+from typing import TYPE_CHECKING, Any, Callable
+
+from opentelemetry import trace
+from opentelemetry.trace import SpanKind, Status, StatusCode
+
+from cubepi.agent.types import (
+ AgentEndEvent,
+ AgentStartEvent,
+ MessageEndEvent,
+ MessageStartEvent,
+ TurnEndEvent,
+ TurnStartEvent,
+ ToolExecutionEndEvent,
+ ToolExecutionStartEvent,
+)
+from cubepi.providers.base import (
+ StreamEvent,
+ ToolResultMessage,
+ UserMessage,
+)
+from cubepi.tracing.errors import cubepi_error_type_for
+from cubepi.tracing.schema import (
+ CUBEPI_ABORTED,
+ CUBEPI_AGENT_SYSTEM_PROMPT_SHA256,
+ CUBEPI_AGENT_TOOLS,
+ CUBEPI_INPUT_MESSAGES_COUNT,
+ CUBEPI_LLM_THINKING_LEVEL,
+ CUBEPI_OUTPUT_MESSAGES_COUNT,
+ CUBEPI_RUN_ID,
+ CUBEPI_TOOL_BLOCK_REASON,
+ CUBEPI_TOOL_BLOCKED_BY_HOOK,
+ CUBEPI_TOOL_EXECUTION_MODE,
+ CUBEPI_TOOL_IS_ERROR,
+ CUBEPI_TOOL_TERMINATE,
+ CUBEPI_TURN_INDEX,
+ CUBEPI_TURN_STOP_REASON,
+ CUBEPI_TURN_TERMINATED_BY_TOOL,
+ CUBEPI_TURN_TOOL_CALLS_COUNT,
+ ERROR_TYPE,
+ EVENT_GEN_AI_EXCEPTION,
+ GEN_AI_OPERATION_NAME,
+ GEN_AI_PROVIDER_NAME,
+ GEN_AI_REQUEST_MAX_TOKENS,
+ GEN_AI_REQUEST_MODEL,
+ GEN_AI_REQUEST_STREAM,
+ GEN_AI_REQUEST_TEMPERATURE,
+ GEN_AI_REQUEST_TOP_P,
+ GEN_AI_RESPONSE_FINISH_REASONS,
+ GEN_AI_RESPONSE_ID,
+ GEN_AI_RESPONSE_MODEL,
+ GEN_AI_RESPONSE_TIME_TO_FIRST_CHUNK,
+ GEN_AI_TOOL_CALL_ID,
+ GEN_AI_TOOL_DESCRIPTION,
+ GEN_AI_TOOL_NAME,
+ GEN_AI_TOOL_TYPE,
+ GEN_AI_USAGE_CACHE_CREATION_INPUT_TOKENS,
+ GEN_AI_USAGE_CACHE_READ_INPUT_TOKENS,
+ GEN_AI_USAGE_INPUT_TOKENS,
+ GEN_AI_USAGE_OUTPUT_TOKENS,
+ GEN_AI_USAGE_REASONING_OUTPUT_TOKENS,
+ OP_CHAT,
+ OP_EXECUTE_TOOL,
+ OP_INVOKE_AGENT,
+ SPAN_NAME_CHAT,
+ SPAN_NAME_EXECUTE_TOOL,
+ SPAN_NAME_INVOKE_AGENT,
+ SPAN_NAME_TURN,
+ map_provider_name,
+)
+
+if TYPE_CHECKING:
+ from cubepi.agent.agent import Agent
+ from cubepi.providers.base import Model
+ from cubepi.tracing.tracer import Tracer
+
+
+@dataclass
+class _RunState:
+ """Per-run mutable state. One per attached agent run."""
+
+ run_id: str
+ agent_span: Any # opentelemetry.trace.Span
+ turn_span: Any | None = None
+ turn_index: int = -1
+ chat_span: Any | None = None
+ chat_open_ns: int | None = None
+ chat_first_chunk_recorded: bool = False
+ tool_spans: dict[str, Any] = field(default_factory=dict)
+ # Caller-supplied extra attrs for this run (set via run_scope, future).
+ extra_attrs: dict[str, Any] = field(default_factory=dict)
+ # Counts for invoke_agent attrs.
+ new_message_count: int = 0
+ # Whether any tool reported terminate=True in the current turn.
+ turn_terminated_by_tool: bool = False
+
+
+class Recorder:
+ """Subscribe to agent + provider events and produce OTel spans.
+
+ Lifetime: one :class:`Recorder` per :meth:`Tracer.attach` call. The
+ recorder maintains per-run state keyed by a generated run_id; one
+ agent can host many sequential runs over the recorder's lifetime.
+ """
+
+ def __init__(self, tracer: "Tracer", *, record_content: bool = False) -> None:
+ self._tracer = tracer
+ self._record_content = record_content
+ # Active run state. cubepi agents serialize runs (one
+ # ``agent.run()`` at a time per Agent), so a single slot is
+ # enough — but defensively key by AgentStartEvent identity
+ # in case the contract changes.
+ self._run: _RunState | None = None
+ # Set on attach() so the recorder can look up AgentTool
+ # definitions (description, execution_mode) at tool-exec span
+ # open. ``None`` if the agent doesn't expose a tool registry.
+ self._agent: Any | None = None
+
+ # ------------------------------------------------------------------
+ # Attach / detach
+ # ------------------------------------------------------------------
+
+ def attach(self, agent: "Agent") -> Callable[[], None]:
+ from cubepi.providers.base import BaseProvider
+
+ self._agent = agent
+ unsub_agent = agent.subscribe(self._on_agent_event)
+ # ``Agent`` stores the provider as a private attribute; accept
+ # either the (private) ``_provider`` or a public ``provider``
+ # alias should one be added later.
+ provider = getattr(agent, "_provider", None) or getattr(agent, "provider", None)
+ provider_detachers: list[Callable[[], None]] = []
+ if isinstance(provider, BaseProvider):
+ provider_detachers.append(
+ provider.subscribe_request(self._on_provider_request)
+ )
+ provider_detachers.append(provider.subscribe_chunk(self._on_provider_chunk))
+ provider_detachers.append(
+ provider.subscribe_response(self._on_provider_response)
+ )
+
+ async def _detach_async() -> None:
+ unsub_agent()
+ for d in provider_detachers:
+ try:
+ d()
+ except Exception:
+ pass
+ await self._tracer.force_flush()
+
+ def detach() -> None:
+ # Synchronous shim. Tests can also call ``detach_async``.
+ import asyncio
+
+ try:
+ loop = asyncio.get_running_loop()
+ except RuntimeError:
+ # No running loop — best-effort sync detach.
+ unsub_agent()
+ for d in provider_detachers:
+ try:
+ d()
+ except Exception:
+ pass
+ return
+ # Inside a loop — schedule the async detach.
+ loop.create_task(_detach_async())
+
+ return detach
+
+ # ------------------------------------------------------------------
+ # Agent event handler
+ # ------------------------------------------------------------------
+
+ async def _on_agent_event(self, event: Any, signal: Any | None = None) -> None:
+ # The agent calls listeners with (event, signal). We don't use signal.
+ del signal
+ try:
+ if isinstance(event, AgentStartEvent):
+ self._on_agent_start()
+ elif isinstance(event, TurnStartEvent):
+ self._on_turn_start()
+ elif isinstance(event, ToolExecutionStartEvent):
+ self._on_tool_exec_start(event)
+ elif isinstance(event, ToolExecutionEndEvent):
+ self._on_tool_exec_end(event)
+ elif isinstance(event, MessageStartEvent):
+ self._on_message_start(event)
+ elif isinstance(event, MessageEndEvent):
+ self._on_message_end(event)
+ elif isinstance(event, TurnEndEvent):
+ self._on_turn_end(event)
+ elif isinstance(event, AgentEndEvent):
+ self._on_agent_end(event)
+ # MessageUpdateEvent / ToolExecutionUpdateEvent: IGNORED.
+ except Exception:
+ # Recorders must never crash the agent.
+ pass
+
+ # ------------------------------------------------------------------
+ # invoke_agent
+ # ------------------------------------------------------------------
+
+ def _on_agent_start(self) -> None:
+ run_id = str(uuid.uuid4())
+ # Open the root invoke_agent span. Caller-context propagation
+ # (parent_trace_id / parent_span_id from a host service) lands
+ # here in a future run_scope feature.
+ span = self._tracer.otel_tracer.start_span(
+ name=SPAN_NAME_INVOKE_AGENT,
+ kind=SpanKind.INTERNAL,
+ attributes={
+ GEN_AI_OPERATION_NAME: OP_INVOKE_AGENT,
+ CUBEPI_RUN_ID: run_id,
+ # gen_ai.provider.name is required by semconv; we set a
+ # placeholder here and overwrite at the first chat span
+ # with the actual provider id.
+ GEN_AI_PROVIDER_NAME: "cubepi",
+ },
+ )
+ # Resource carries gen_ai.agent.name at process level — agents
+ # that vary per-run set their own value via _ensure_agent_name.
+ self._run = _RunState(run_id=run_id, agent_span=span)
+
+ def _on_agent_end(self, event: AgentEndEvent) -> None:
+ run = self._run
+ if run is None:
+ return
+ run.new_message_count = len(event.messages)
+ run.agent_span.set_attribute(
+ CUBEPI_OUTPUT_MESSAGES_COUNT, run.new_message_count
+ )
+ run.agent_span.end()
+ self._run = None
+
+ # ------------------------------------------------------------------
+ # cubepi.turn
+ # ------------------------------------------------------------------
+
+ def _on_turn_start(self) -> None:
+ run = self._run
+ if run is None:
+ return
+ run.turn_index += 1
+ ctx = trace.set_span_in_context(run.agent_span)
+ run.turn_span = self._tracer.otel_tracer.start_span(
+ name=SPAN_NAME_TURN,
+ kind=SpanKind.INTERNAL,
+ context=ctx,
+ attributes={
+ CUBEPI_TURN_INDEX: run.turn_index,
+ # Propagate run_id so every child span carries it —
+ # OTel does NOT inherit attributes from parent spans, and
+ # JsonlSpanExporter shards by ``cubepi.run_id`` per span.
+ CUBEPI_RUN_ID: run.run_id,
+ },
+ )
+ run.turn_terminated_by_tool = False
+
+ def _on_turn_end(self, event: TurnEndEvent) -> None:
+ run = self._run
+ if run is None or run.turn_span is None:
+ return
+ msg = event.message
+ # Map cubepi stop_reason to gen_ai.response.finish_reasons on
+ # the chat span — already done in _on_provider_response. Here we
+ # record the cubepi-normalized stop_reason on the turn span.
+ stop_reason = getattr(msg, "stop_reason", None)
+ if stop_reason:
+ run.turn_span.set_attribute(CUBEPI_TURN_STOP_REASON, stop_reason)
+ tool_calls_count = sum(
+ 1
+ for c in getattr(msg, "content", [])
+ if getattr(c, "type", "") == "tool_call"
+ )
+ run.turn_span.set_attribute(CUBEPI_TURN_TOOL_CALLS_COUNT, tool_calls_count)
+ if run.turn_terminated_by_tool:
+ run.turn_span.set_attribute(CUBEPI_TURN_TERMINATED_BY_TOOL, True)
+ # Error handling on the turn: if assistant message stopped with
+ # "error", mark turn ERROR. Abort path leaves UNSET + sets
+ # cubepi.aborted on the invoke_agent root.
+ if stop_reason == "error":
+ err_msg = getattr(msg, "error_message", None) or "model error"
+ run.turn_span.set_status(Status(StatusCode.ERROR, err_msg[:256]))
+ run.turn_span.set_attribute(ERROR_TYPE, "cubepi.error")
+ elif stop_reason == "aborted":
+ run.turn_span.set_attribute(CUBEPI_ABORTED, True)
+ run.agent_span.set_attribute(CUBEPI_ABORTED, True)
+ run.turn_span.end()
+ run.turn_span = None
+
+ # ------------------------------------------------------------------
+ # execute_tool
+ # ------------------------------------------------------------------
+
+ def _on_tool_exec_start(self, event: ToolExecutionStartEvent) -> None:
+ run = self._run
+ if run is None or run.turn_span is None:
+ return
+ ctx = trace.set_span_in_context(run.turn_span)
+ attrs: dict[str, Any] = {
+ GEN_AI_OPERATION_NAME: OP_EXECUTE_TOOL,
+ GEN_AI_TOOL_NAME: event.tool_name,
+ GEN_AI_TOOL_CALL_ID: event.tool_call_id,
+ GEN_AI_TOOL_TYPE: "function",
+ # Per-span run_id so JsonlSpanExporter shards correctly.
+ CUBEPI_RUN_ID: run.run_id,
+ }
+ # Lookup AgentTool for description + execution_mode.
+ tool_obj = self._find_tool(event.tool_name)
+ if tool_obj is not None:
+ if tool_obj.description:
+ attrs[GEN_AI_TOOL_DESCRIPTION] = tool_obj.description
+ mode = tool_obj.execution_mode or "parallel"
+ attrs[CUBEPI_TOOL_EXECUTION_MODE] = mode
+ span = self._tracer.otel_tracer.start_span(
+ name=f"{SPAN_NAME_EXECUTE_TOOL} {event.tool_name}",
+ kind=SpanKind.INTERNAL,
+ context=ctx,
+ attributes=attrs,
+ )
+ run.tool_spans[event.tool_call_id] = span
+
+ def _on_tool_exec_end(self, event: ToolExecutionEndEvent) -> None:
+ run = self._run
+ if run is None:
+ return
+ span = run.tool_spans.pop(event.tool_call_id, None)
+ if span is None:
+ return
+ span.set_attribute(CUBEPI_TOOL_IS_ERROR, event.is_error)
+ if event.terminate:
+ span.set_attribute(CUBEPI_TOOL_TERMINATE, True)
+ run.turn_terminated_by_tool = True
+ if event.blocked_by_hook:
+ span.set_attribute(CUBEPI_TOOL_BLOCKED_BY_HOOK, True)
+ if event.block_reason is not None:
+ span.set_attribute(CUBEPI_TOOL_BLOCK_REASON, event.block_reason)
+ if event.is_error:
+ span.set_status(Status(StatusCode.ERROR, "tool error"))
+ err_type = (
+ "cubepi.tool.blocked_by_hook"
+ if event.blocked_by_hook
+ else "cubepi.tool.error"
+ )
+ span.set_attribute(ERROR_TYPE, err_type)
+ span.end()
+
+ # ------------------------------------------------------------------
+ # MessageStart/End — used to enrich invoke_agent attrs but NOT to
+ # drive the chat span lifetime (that's the provider listeners' job).
+ # ------------------------------------------------------------------
+
+ def _on_message_start(self, event: MessageStartEvent) -> None:
+ run = self._run
+ if run is None:
+ return
+ msg = event.message
+ # Count user-provided + tool-result messages as input.
+ if isinstance(msg, (UserMessage, ToolResultMessage)):
+ run.agent_span.set_attribute(
+ CUBEPI_INPUT_MESSAGES_COUNT,
+ int(
+ (run.agent_span.attributes or {}).get(
+ CUBEPI_INPUT_MESSAGES_COUNT, 0
+ )
+ )
+ + 1,
+ )
+
+ def _on_message_end(self, event: MessageEndEvent) -> None:
+ # Reserved for future use. Currently no-op — chat span is
+ # closed by the provider response listener, and turn span
+ # gets its stop_reason from TurnEndEvent.
+ del event
+
+ # ------------------------------------------------------------------
+ # Provider listeners — drive the chat span lifetime
+ # ------------------------------------------------------------------
+
+ def _on_provider_request(self, payload: dict, model: "Model") -> None:
+ run = self._run
+ if run is None or run.turn_span is None:
+ return
+ ctx = trace.set_span_in_context(run.turn_span)
+ attrs: dict[str, Any] = {
+ GEN_AI_OPERATION_NAME: OP_CHAT,
+ GEN_AI_PROVIDER_NAME: map_provider_name(model.provider),
+ GEN_AI_REQUEST_MODEL: model.id,
+ GEN_AI_REQUEST_STREAM: True,
+ # Per-span run_id so JsonlSpanExporter shards correctly.
+ CUBEPI_RUN_ID: run.run_id,
+ }
+ # Pull StreamOptions-derived params from the payload where the
+ # provider exposed them as final kwargs.
+ for key, attr in (
+ ("max_tokens", GEN_AI_REQUEST_MAX_TOKENS),
+ ("temperature", GEN_AI_REQUEST_TEMPERATURE),
+ ("top_p", GEN_AI_REQUEST_TOP_P),
+ ):
+ if key in payload and payload[key] is not None:
+ attrs[attr] = payload[key]
+
+ # Thinking level on cubepi.* namespace.
+ thinking = payload.get("thinking")
+ if isinstance(thinking, dict) and thinking.get("type") == "enabled":
+ attrs[CUBEPI_LLM_THINKING_LEVEL] = "on"
+ elif thinking is None and (
+ payload.get("reasoning", {}).get("effort")
+ if payload.get("reasoning")
+ else None
+ ):
+ attrs[CUBEPI_LLM_THINKING_LEVEL] = payload["reasoning"]["effort"]
+
+ # System prompt sha256 on root agent span (once per run).
+ self._maybe_record_system_prompt_hash(payload, run)
+
+ # Update root's gen_ai.provider.name with the first concrete one.
+ if (run.agent_span.attributes or {}).get(GEN_AI_PROVIDER_NAME) == "cubepi":
+ run.agent_span.set_attribute(
+ GEN_AI_PROVIDER_NAME, attrs[GEN_AI_PROVIDER_NAME]
+ )
+
+ # Tool count on root.
+ tools = payload.get("tools")
+ if isinstance(tools, list) and tools:
+ run.agent_span.set_attribute(
+ CUBEPI_AGENT_TOOLS, [_safe_tool_name(t) for t in tools]
+ )
+
+ chat_span = self._tracer.otel_tracer.start_span(
+ name=f"{SPAN_NAME_CHAT} {model.id}",
+ kind=SpanKind.CLIENT,
+ context=ctx,
+ attributes=attrs,
+ )
+ run.chat_span = chat_span
+ run.chat_open_ns = time.time_ns()
+ run.chat_first_chunk_recorded = False
+ # cubepi.llm.raw_request is content; MVP is record_content=False.
+
+ def _on_provider_chunk(self, event: StreamEvent, model: "Model") -> None:
+ del model
+ run = self._run
+ if run is None or run.chat_span is None or run.chat_first_chunk_recorded:
+ return
+ # Only count "content" chunks for time-to-first-chunk (not 'start').
+ if event.type in (
+ "text_delta",
+ "thinking_delta",
+ "toolcall_delta",
+ ):
+ opened = run.chat_open_ns or time.time_ns()
+ ttft_s = (time.time_ns() - opened) / 1e9
+ run.chat_span.set_attribute(GEN_AI_RESPONSE_TIME_TO_FIRST_CHUNK, ttft_s)
+ run.chat_first_chunk_recorded = True
+
+ def _on_provider_response(
+ self,
+ body: dict | None,
+ model: "Model",
+ exc: BaseException | None,
+ ) -> None:
+ del model
+ run = self._run
+ if run is None or run.chat_span is None:
+ return
+ span = run.chat_span
+ try:
+ if body is not None:
+ self._record_chat_response_attrs(span, body)
+ # Cooperative abort: providers may finish the response
+ # listener with ``exc is None`` and a body whose finish
+ # reason is ``"aborted"`` (faux + the agent's signal path).
+ # Mark the chat span aborted in that case so it matches
+ # the contract for hard cancels.
+ if body is not None and _body_is_aborted(body):
+ span.set_attribute(CUBEPI_ABORTED, True)
+ span.set_attribute(ERROR_TYPE, "cubepi.aborted")
+
+ if exc is None:
+ # Healthy completion — leave Status UNSET per OTel guidance.
+ pass
+ elif _is_cancelled_error(exc):
+ # Hard cancel: not a failure. Mark and leave UNSET.
+ span.set_attribute(CUBEPI_ABORTED, True)
+ span.set_attribute(ERROR_TYPE, "cubepi.aborted")
+ else:
+ span.set_status(Status(StatusCode.ERROR, str(exc)[:256]))
+ span.set_attribute(ERROR_TYPE, cubepi_error_type_for(exc))
+ span.add_event(
+ name=EVENT_GEN_AI_EXCEPTION,
+ attributes={
+ "exception.type": type(exc).__name__,
+ "exception.message": str(exc),
+ "exception.stacktrace": "".join(
+ traceback.format_exception(exc)
+ ),
+ },
+ )
+ finally:
+ span.end()
+ run.chat_span = None
+ run.chat_open_ns = None
+ run.chat_first_chunk_recorded = False
+
+ # ------------------------------------------------------------------
+ # helpers
+ # ------------------------------------------------------------------
+
+ def _find_tool(self, name: str):
+ """Look up an :class:`AgentTool` by name on the attached agent.
+
+ Read directly from the agent's tool registry; the Recorder is
+ attached for the agent's lifetime so the reference is stable.
+ Returns ``None`` if the agent exposes no tool list or the name
+ isn't registered.
+ """
+ agent = self._agent
+ if agent is None:
+ return None
+ tools = getattr(agent, "_state", None)
+ if tools is None:
+ return None
+ tool_list = getattr(tools, "_tools", None) or []
+ for t in tool_list:
+ if getattr(t, "name", None) == name:
+ return t
+ return None
+
+ def _record_chat_response_attrs(self, span: Any, body: dict) -> None:
+ # Anthropic-shaped body
+ if "stop_reason" in body and "usage" in body:
+ usage = body.get("usage") or {}
+ self._set_usage_anthropic_like(span, usage)
+ finish_reason = body.get("stop_reason")
+ if finish_reason:
+ span.set_attribute(GEN_AI_RESPONSE_FINISH_REASONS, [finish_reason])
+ if "model" in body and body["model"]:
+ span.set_attribute(GEN_AI_RESPONSE_MODEL, body["model"])
+ if "id" in body and body["id"]:
+ span.set_attribute(GEN_AI_RESPONSE_ID, body["id"])
+ return
+ # OpenAI chat.completion-shaped body
+ if "choices" in body and isinstance(body.get("choices"), list):
+ usage = body.get("usage") or {}
+ self._set_usage_openai_like(span, usage)
+ choices = body["choices"]
+ if choices:
+ first = choices[0] or {}
+ finish = first.get("finish_reason")
+ if finish:
+ span.set_attribute(GEN_AI_RESPONSE_FINISH_REASONS, [finish])
+ if body.get("id"):
+ span.set_attribute(GEN_AI_RESPONSE_ID, body["id"])
+ if body.get("model"):
+ span.set_attribute(GEN_AI_RESPONSE_MODEL, body["model"])
+ return
+ # OpenAI Responses-shaped body
+ if body.get("object") == "response" or "output" in body:
+ usage = body.get("usage") or {}
+ self._set_usage_openai_responses_like(span, usage)
+ status = body.get("status")
+ if status:
+ span.set_attribute(GEN_AI_RESPONSE_FINISH_REASONS, [status])
+ if body.get("id"):
+ span.set_attribute(GEN_AI_RESPONSE_ID, body["id"])
+ if body.get("model"):
+ span.set_attribute(GEN_AI_RESPONSE_MODEL, body["model"])
+ return
+ # Unknown shape — record what we can defensively.
+ if isinstance(body.get("model"), str):
+ span.set_attribute(GEN_AI_RESPONSE_MODEL, body["model"])
+
+ @staticmethod
+ def _set_usage_anthropic_like(span: Any, usage: dict) -> None:
+ # Anthropic's input_tokens excludes cached tokens; semconv expects
+ # the inclusive count. Reconcile.
+ input_t = int(usage.get("input_tokens", 0) or 0)
+ cache_read = int(usage.get("cache_read_input_tokens", 0) or 0)
+ cache_create = int(usage.get("cache_creation_input_tokens", 0) or 0)
+ span.set_attribute(
+ GEN_AI_USAGE_INPUT_TOKENS, input_t + cache_read + cache_create
+ )
+ span.set_attribute(
+ GEN_AI_USAGE_OUTPUT_TOKENS, int(usage.get("output_tokens", 0) or 0)
+ )
+ if cache_read:
+ span.set_attribute(GEN_AI_USAGE_CACHE_READ_INPUT_TOKENS, cache_read)
+ if cache_create:
+ span.set_attribute(GEN_AI_USAGE_CACHE_CREATION_INPUT_TOKENS, cache_create)
+
+ @staticmethod
+ def _set_usage_openai_like(span: Any, usage: dict) -> None:
+ # OpenAI uses prompt_tokens / completion_tokens; cached separately.
+ prompt = int(usage.get("prompt_tokens", 0) or 0)
+ details = usage.get("prompt_tokens_details") or {}
+ cache_read = (
+ int(details.get("cached_tokens", 0) or 0)
+ if isinstance(details, dict)
+ else 0
+ )
+ # prompt_tokens already includes cached; semconv input_tokens is
+ # the total prompt count — emit as-is.
+ span.set_attribute(GEN_AI_USAGE_INPUT_TOKENS, prompt)
+ span.set_attribute(
+ GEN_AI_USAGE_OUTPUT_TOKENS, int(usage.get("completion_tokens", 0) or 0)
+ )
+ if cache_read:
+ span.set_attribute(GEN_AI_USAGE_CACHE_READ_INPUT_TOKENS, cache_read)
+
+ @staticmethod
+ def _set_usage_openai_responses_like(span: Any, usage: dict) -> None:
+ # OpenAI Responses API surfaces input_tokens / output_tokens.
+ span.set_attribute(
+ GEN_AI_USAGE_INPUT_TOKENS, int(usage.get("input_tokens", 0) or 0)
+ )
+ span.set_attribute(
+ GEN_AI_USAGE_OUTPUT_TOKENS, int(usage.get("output_tokens", 0) or 0)
+ )
+ details = usage.get("input_tokens_details") or {}
+ if isinstance(details, dict):
+ cache_read = int(details.get("cached_tokens", 0) or 0)
+ if cache_read:
+ span.set_attribute(GEN_AI_USAGE_CACHE_READ_INPUT_TOKENS, cache_read)
+ out_details = usage.get("output_tokens_details") or {}
+ if isinstance(out_details, dict):
+ reasoning = int(out_details.get("reasoning_tokens", 0) or 0)
+ if reasoning:
+ span.set_attribute(GEN_AI_USAGE_REASONING_OUTPUT_TOKENS, reasoning)
+
+ def _maybe_record_system_prompt_hash(self, payload: dict, run: _RunState) -> None:
+ if (run.agent_span.attributes or {}).get(CUBEPI_AGENT_SYSTEM_PROMPT_SHA256):
+ return
+ text = _extract_system_prompt(payload)
+ if not text:
+ return
+ digest = hashlib.sha256(text.encode("utf-8")).hexdigest()[:16]
+ run.agent_span.set_attribute(CUBEPI_AGENT_SYSTEM_PROMPT_SHA256, digest)
+
+
+def _extract_system_prompt(payload: dict) -> str | None:
+ """Find the system prompt text in a provider's wire payload.
+
+ Provider shape variance is real; check the known forms in turn:
+
+ - Anthropic: ``payload["system"]`` is a string OR a list of
+ ``{"type": "text", "text": ...}`` cache-control blocks.
+ - Faux: ``payload["system_prompt"]`` is a string.
+ - OpenAI chat-completions: ``payload["messages"][0]`` is
+ ``{"role": "system", "content": ...}`` when a prompt was set.
+ - OpenAI Responses: ``payload["input"][0]`` is ``{"role":
+ "developer" | "system", "content": ...}`` when a prompt was set.
+ """
+ system = payload.get("system")
+ if isinstance(system, str):
+ return system
+ if isinstance(system, list):
+ parts = []
+ for block in system:
+ if isinstance(block, dict) and block.get("type") == "text":
+ parts.append(block.get("text") or "")
+ joined = "".join(parts)
+ if joined:
+ return joined
+ if isinstance(payload.get("system_prompt"), str):
+ return payload["system_prompt"]
+ for key in ("messages", "input"):
+ seq = payload.get(key)
+ if isinstance(seq, list) and seq:
+ first = seq[0]
+ if isinstance(first, dict) and first.get("role") in ("system", "developer"):
+ content = first.get("content")
+ if isinstance(content, str):
+ return content
+ return None
+
+
+def _safe_tool_name(t: Any) -> str:
+ if isinstance(t, dict):
+ return str(t.get("name") or "")
+ name = getattr(t, "name", None)
+ return str(name) if name else ""
+
+
+def _is_cancelled_error(exc: BaseException) -> bool:
+ import asyncio
+
+ return isinstance(exc, asyncio.CancelledError)
+
+
+def _body_is_aborted(body: dict) -> bool:
+ """Detect cooperative-abort signal in an assembled provider body.
+
+ Cubepi providers normalize aborts into ``stop_reason = "aborted"``
+ on the assistant message (the body's ``stop_reason`` for Anthropic-
+ shaped bodies; for OpenAI bodies the equivalent surfaces via the
+ aborted partial response which carries no terminal finish_reason
+ of its own — handled separately on the agent-side at TurnEnd).
+ """
+ if body.get("stop_reason") == "aborted":
+ return True
+ choices = body.get("choices")
+ if isinstance(choices, list) and choices:
+ first = choices[0]
+ if isinstance(first, dict) and first.get("finish_reason") == "aborted":
+ return True
+ return False
diff --git a/cubepi/tracing/schema.py b/cubepi/tracing/schema.py
new file mode 100644
index 0000000..e622abb
--- /dev/null
+++ b/cubepi/tracing/schema.py
@@ -0,0 +1,155 @@
+"""Field-name constants and pinned semconv version for cubepi tracing.
+
+Align with OpenTelemetry GenAI Semantic Conventions v1.41.0
+(https://opentelemetry.io/docs/specs/semconv/gen-ai/). Anything cubepi-
+specific lives under the ``cubepi.*`` namespace per the OTel-recommended
+vendor-extension pattern.
+"""
+
+from __future__ import annotations
+
+#: Pinned semconv version. Bumping requires auditing for renamed/deprecated
+#: attributes — both Resource and InstrumentationScope advertise this URL.
+SCHEMA_URL = "https://opentelemetry.io/schemas/1.41.0"
+
+# ---------------------------------------------------------------------------
+# OTel GenAI semantic conventions (https://opentelemetry.io/docs/specs/semconv/gen-ai/)
+# ---------------------------------------------------------------------------
+
+# Operation discriminator
+GEN_AI_OPERATION_NAME = "gen_ai.operation.name"
+OP_INVOKE_AGENT = "invoke_agent"
+OP_CHAT = "chat"
+OP_EXECUTE_TOOL = "execute_tool"
+
+# Provider id
+GEN_AI_PROVIDER_NAME = "gen_ai.provider.name"
+
+# Agent identity (process-level lives in Resource; per-run override possible)
+GEN_AI_AGENT_NAME = "gen_ai.agent.name"
+GEN_AI_AGENT_ID = "gen_ai.agent.id"
+GEN_AI_AGENT_DESCRIPTION = "gen_ai.agent.description"
+GEN_AI_AGENT_VERSION = "gen_ai.agent.version"
+
+# Conversation / thread
+GEN_AI_CONVERSATION_ID = "gen_ai.conversation.id"
+
+# Request parameters
+GEN_AI_REQUEST_MODEL = "gen_ai.request.model"
+GEN_AI_REQUEST_MAX_TOKENS = "gen_ai.request.max_tokens"
+GEN_AI_REQUEST_TEMPERATURE = "gen_ai.request.temperature"
+GEN_AI_REQUEST_TOP_P = "gen_ai.request.top_p"
+GEN_AI_REQUEST_TOP_K = "gen_ai.request.top_k"
+GEN_AI_REQUEST_STOP_SEQUENCES = "gen_ai.request.stop_sequences"
+GEN_AI_REQUEST_FREQUENCY_PENALTY = "gen_ai.request.frequency_penalty"
+GEN_AI_REQUEST_PRESENCE_PENALTY = "gen_ai.request.presence_penalty"
+GEN_AI_REQUEST_SEED = "gen_ai.request.seed"
+GEN_AI_REQUEST_STREAM = "gen_ai.request.stream"
+GEN_AI_REQUEST_CHOICE_COUNT = "gen_ai.request.choice.count"
+GEN_AI_OUTPUT_TYPE = "gen_ai.output.type"
+
+# Response metadata
+GEN_AI_RESPONSE_MODEL = "gen_ai.response.model"
+GEN_AI_RESPONSE_ID = "gen_ai.response.id"
+GEN_AI_RESPONSE_FINISH_REASONS = "gen_ai.response.finish_reasons"
+GEN_AI_RESPONSE_TIME_TO_FIRST_CHUNK = "gen_ai.response.time_to_first_chunk"
+
+# Usage / tokens
+GEN_AI_USAGE_INPUT_TOKENS = "gen_ai.usage.input_tokens"
+GEN_AI_USAGE_OUTPUT_TOKENS = "gen_ai.usage.output_tokens"
+GEN_AI_USAGE_REASONING_OUTPUT_TOKENS = "gen_ai.usage.reasoning.output_tokens"
+GEN_AI_USAGE_CACHE_READ_INPUT_TOKENS = "gen_ai.usage.cache_read.input_tokens"
+GEN_AI_USAGE_CACHE_CREATION_INPUT_TOKENS = "gen_ai.usage.cache_creation.input_tokens"
+
+# Tool execution
+GEN_AI_TOOL_NAME = "gen_ai.tool.name"
+GEN_AI_TOOL_CALL_ID = "gen_ai.tool.call.id"
+GEN_AI_TOOL_TYPE = "gen_ai.tool.type"
+GEN_AI_TOOL_DESCRIPTION = "gen_ai.tool.description"
+
+# Network (recommended on CLIENT spans)
+SERVER_ADDRESS = "server.address"
+SERVER_PORT = "server.port"
+
+# Error classification (CR on error)
+ERROR_TYPE = "error.type"
+
+# GenAI-specific exception event name
+EVENT_GEN_AI_EXCEPTION = "gen_ai.client.operation.exception"
+
+# ---------------------------------------------------------------------------
+# cubepi extension attributes
+# ---------------------------------------------------------------------------
+
+# Per-run identity
+CUBEPI_RUN_ID = "cubepi.run_id"
+CUBEPI_THREAD_ID = "cubepi.thread_id"
+
+# Root span helpers
+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_ABORTED = "cubepi.aborted"
+
+# Turn span attributes (cubepi.turn span — no gen_ai.operation.name)
+CUBEPI_TURN_INDEX = "cubepi.turn.index"
+CUBEPI_TURN_STOP_REASON = "cubepi.turn.stop_reason"
+CUBEPI_TURN_TOOL_CALLS_COUNT = "cubepi.turn.tool_calls.count"
+CUBEPI_TURN_TERMINATED_BY_TOOL = "cubepi.turn.terminated_by_tool"
+
+# Chat span — provider-side LLM call
+CUBEPI_LLM_THINKING_LEVEL = "cubepi.llm.thinking_level"
+CUBEPI_LLM_RAW_REQUEST = "cubepi.llm.raw_request"
+CUBEPI_LLM_RAW_RESPONSE = "cubepi.llm.raw_response"
+
+# Tool span
+CUBEPI_TOOL_EXECUTION_MODE = "cubepi.tool.execution_mode"
+CUBEPI_TOOL_IS_ERROR = "cubepi.tool.is_error"
+CUBEPI_TOOL_TERMINATE = "cubepi.tool.terminate"
+CUBEPI_TOOL_BLOCKED_BY_HOOK = "cubepi.tool.blocked_by_hook"
+CUBEPI_TOOL_BLOCK_REASON = "cubepi.tool.block_reason"
+
+# Span names (NOT semconv keys — these are name templates)
+SPAN_NAME_INVOKE_AGENT = "invoke_agent"
+SPAN_NAME_TURN = "cubepi.turn"
+SPAN_NAME_CHAT = "chat"
+SPAN_NAME_EXECUTE_TOOL = "execute_tool"
+
+# Instrumentation scope identity
+SCOPE_NAME = "cubepi.tracing"
+
+
+# ---------------------------------------------------------------------------
+# Provider name mapping (cubepi.Model.provider → gen_ai.provider.name)
+# ---------------------------------------------------------------------------
+
+#: Cubepi providers identify themselves with short strings on
+#: ``Model.provider``. Map to the canonical OTel ``gen_ai.provider.name``
+#: values per the semconv registry. Unknown providers get the raw string
+#: prefixed with ``unknown:`` so observers can spot the gap.
+PROVIDER_NAME_MAP: dict[str, str] = {
+ "anthropic": "anthropic",
+ "openai": "openai",
+ "azure_openai": "azure.ai.openai",
+ "gemini": "gcp.gemini",
+ "vertex_ai": "gcp.vertex_ai",
+ "bedrock": "aws.bedrock",
+ "cohere": "cohere",
+ "mistral": "mistral_ai",
+ "groq": "groq",
+ "xai": "x_ai",
+ "deepseek": "deepseek",
+ "perplexity": "perplexity",
+ "watsonx": "ibm.watsonx.ai",
+ "faux": "faux",
+}
+
+
+def map_provider_name(provider: str) -> str:
+ """Translate cubepi ``Model.provider`` to the canonical
+ ``gen_ai.provider.name`` value.
+
+ Unknown providers get ``unknown:<raw>`` so observers can spot a gap.
+ """
+ return PROVIDER_NAME_MAP.get(provider, f"unknown:{provider}")
diff --git a/cubepi/tracing/tracer.py b/cubepi/tracing/tracer.py
new file mode 100644
index 0000000..276ca95
--- /dev/null
+++ b/cubepi/tracing/tracer.py
@@ -0,0 +1,214 @@
+"""``Tracer`` config class — the user-facing entry point.
+
+Builds an SDK :class:`opentelemetry.sdk.trace.TracerProvider` with a
+pinned schema URL, attaches one ``BatchSpanProcessor`` per exporter,
+and exposes ``attach(agent)`` to wire the cubepi :class:`Recorder` into
+the agent's event stream.
+"""
+
+from __future__ import annotations
+
+import uuid
+from typing import TYPE_CHECKING, Any, Callable
+
+from opentelemetry.sdk.resources import Resource
+from opentelemetry.sdk.trace import TracerProvider
+from opentelemetry.sdk.trace.export import BatchSpanProcessor, SpanExporter
+from opentelemetry.trace import (
+ NonRecordingSpan,
+ SpanContext,
+ TraceFlags,
+ set_span_in_context,
+)
+
+import cubepi
+from cubepi.tracing.schema import SCHEMA_URL, SCOPE_NAME
+
+if TYPE_CHECKING:
+ from cubepi.agent.agent import Agent
+
+
+class Tracer:
+ """Attaches OTel-compatible tracing to a cubepi :class:`Agent`.
+
+ Construct once per process (or per service). Each ``attach(agent)``
+ call wires the cubepi recorder to the agent's event stream and
+ provider listener registry; the returned callable detaches.
+
+ Example
+ -------
+ ::
+
+ from cubepi.tracing import Tracer
+ from cubepi.tracing.exporters import JsonlSpanExporter
+
+ tracer = Tracer(
+ service_name="my-bot",
+ agent_name="coding-agent",
+ exporters=[JsonlSpanExporter(directory="./cubepi-traces")],
+ )
+ detach = tracer.attach(agent)
+ try:
+ ...
+ finally:
+ detach()
+ await tracer.shutdown()
+ """
+
+ def __init__(
+ self,
+ *,
+ service_name: str | None = None,
+ service_version: str | None = None,
+ service_namespace: str | None = None,
+ service_instance_id: str | None = None,
+ deployment_environment: str | None = None,
+ agent_name: str | None = None,
+ agent_id: str | None = None,
+ agent_description: str | None = None,
+ agent_version: str | None = None,
+ exporters: list[SpanExporter] | None = None,
+ record_content: bool = False,
+ resource: Resource | None = None,
+ ) -> None:
+ if record_content:
+ raise NotImplementedError(
+ "record_content=True is Phase 2 of cubepi.tracing. "
+ "Construct with record_content=False (default) for MVP."
+ )
+
+ self._record_content = record_content
+ self._resource = resource or _build_resource(
+ service_name=service_name,
+ service_version=service_version,
+ service_namespace=service_namespace,
+ service_instance_id=service_instance_id,
+ deployment_environment=deployment_environment,
+ agent_name=agent_name,
+ agent_id=agent_id,
+ agent_description=agent_description,
+ agent_version=agent_version,
+ )
+ self._provider = TracerProvider(resource=self._resource)
+ self._processors: list[BatchSpanProcessor] = []
+ for exporter in exporters or []:
+ proc = BatchSpanProcessor(exporter)
+ self._provider.add_span_processor(proc)
+ self._processors.append(proc)
+
+ self._otel_tracer = self._provider.get_tracer(
+ instrumenting_module_name=SCOPE_NAME,
+ instrumenting_library_version=cubepi.__version__
+ if hasattr(cubepi, "__version__")
+ else None,
+ schema_url=SCHEMA_URL,
+ )
+ self._shutdown = False
+
+ # -- public API ---------------------------------------------------
+
+ @property
+ def resource(self) -> Resource:
+ return self._resource
+
+ @property
+ def otel_tracer(self) -> Any:
+ """The underlying ``opentelemetry.trace.Tracer`` instance.
+
+ Exposed so callers can write their own spans alongside the
+ cubepi-generated ones if desired.
+ """
+ return self._otel_tracer
+
+ def attach(self, agent: "Agent") -> Callable[[], None]:
+ """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.
+ """
+ from cubepi.tracing.recorder import Recorder
+
+ recorder = Recorder(self, record_content=self._record_content)
+ return recorder.attach(agent)
+
+ async def force_flush(self, timeout_seconds: float = 30.0) -> bool:
+ """Block until all currently buffered spans are exported.
+
+ Returns ``False`` on timeout.
+ """
+ timeout_millis = int(timeout_seconds * 1000)
+ return self._provider.force_flush(timeout_millis=timeout_millis)
+
+ async def shutdown(self, timeout_seconds: float = 30.0) -> None:
+ """Flush and close all exporters. Tracer is unusable after this."""
+ if self._shutdown:
+ return
+ # SpanProcessor.shutdown is sync; flush first to bound wait.
+ await self.force_flush(timeout_seconds=timeout_seconds)
+ self._provider.shutdown()
+ self._shutdown = True
+
+ async def __aenter__(self) -> "Tracer":
+ return self
+
+ async def __aexit__(self, *exc: Any) -> None:
+ await self.shutdown()
+
+ # -- internals used by Recorder -----------------------------------
+
+ def _make_parent_context(
+ self,
+ *,
+ parent_trace_id: int | None = None,
+ parent_span_id: int | None = None,
+ trace_flags: int = 0x01,
+ ):
+ """Build an OTel ``Context`` that wraps an inbound W3C
+ ``traceparent``. Used by ``run_scope`` to root the cubepi spans
+ under a caller-supplied trace.
+ """
+ if parent_trace_id is None or parent_span_id is None:
+ return None
+ ctx_obj = SpanContext(
+ trace_id=parent_trace_id,
+ span_id=parent_span_id,
+ is_remote=True,
+ trace_flags=TraceFlags(trace_flags),
+ )
+ return set_span_in_context(NonRecordingSpan(ctx_obj))
+
+
+def _build_resource(
+ *,
+ service_name: str | None,
+ service_version: str | None,
+ service_namespace: str | None,
+ service_instance_id: str | None,
+ deployment_environment: str | None,
+ agent_name: str | None,
+ agent_id: str | None,
+ agent_description: str | None,
+ agent_version: str | None,
+) -> Resource:
+ attrs: dict[str, Any] = {}
+ if service_name is not None:
+ attrs["service.name"] = service_name
+ if service_namespace is not None:
+ attrs["service.namespace"] = service_namespace
+ if service_version is not None:
+ attrs["service.version"] = service_version
+ attrs["service.instance.id"] = service_instance_id or str(uuid.uuid4())
+ if deployment_environment is not None:
+ attrs["deployment.environment.name"] = deployment_environment
+ if agent_name is not None:
+ attrs["gen_ai.agent.name"] = agent_name
+ if agent_id is not None:
+ attrs["gen_ai.agent.id"] = agent_id
+ if agent_description is not None:
+ attrs["gen_ai.agent.description"] = agent_description
+ if agent_version is not None:
+ attrs["gen_ai.agent.version"] = agent_version
+ # The SDK adds telemetry.sdk.* automatically.
+ return Resource.create(attrs, schema_url=SCHEMA_URL)
diff --git a/pyproject.toml b/pyproject.toml
index 9534fab..d4a26f6 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -36,6 +36,9 @@ mcp = [
docs = [
"griffe>=0.45",
]
+tracing = [
+ "opentelemetry-sdk>=1.30",
+]
[dependency-groups]
dev = [
diff --git a/tests/tracing/__init__.py b/tests/tracing/__init__.py
new file mode 100644
index 0000000..e69de29
diff --git a/tests/tracing/test_recorder.py b/tests/tracing/test_recorder.py
new file mode 100644
index 0000000..322432a
--- /dev/null
+++ b/tests/tracing/test_recorder.py
@@ -0,0 +1,435 @@
+"""End-to-end tracing tests against FauxProvider.
+
+Each test attaches a Tracer + an in-memory exporter to a fresh Agent,
+runs a scenario, then inspects the captured spans.
+"""
+
+from __future__ import annotations
+
+import asyncio
+from typing import Any
+
+import pytest
+from opentelemetry.sdk.trace import ReadableSpan
+from opentelemetry.sdk.trace.export import SpanExporter, SpanExportResult
+from opentelemetry.trace import SpanKind, StatusCode
+
+from cubepi.agent.agent import Agent
+from cubepi.agent.types import (
+ AgentTool,
+ AgentToolResult,
+ BeforeToolCallResult,
+)
+from cubepi.providers.base import Model, TextContent, ToolCall
+from cubepi.providers.faux import FauxProvider, faux_assistant_message
+from cubepi.tracing import Tracer
+
+
+MODEL = Model(id="faux-1", provider="faux")
+
+
+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
+
+
+async def _build(
+ *,
+ system_prompt: str = "test prompt",
+ tools: list[AgentTool] | None = None,
+ before_tool_call=None,
+) -> tuple[Agent, FauxProvider, InMemoryExporter, Tracer]:
+ provider = FauxProvider()
+ agent = Agent(
+ provider=provider,
+ model=MODEL,
+ system_prompt=system_prompt,
+ tools=tools,
+ before_tool_call=before_tool_call,
+ )
+ exporter = InMemoryExporter()
+ tracer = Tracer(
+ service_name="test-svc",
+ agent_name="test-agent",
+ exporters=[exporter],
+ )
+ tracer.attach(agent)
+ return agent, provider, exporter, tracer
+
+
+def _spans_by_name(exporter: InMemoryExporter) -> dict[str, list[ReadableSpan]]:
+ out: dict[str, list[ReadableSpan]] = {}
+ for s in exporter.spans:
+ out.setdefault(s.name, []).append(s)
+ return out
+
+
+def _attrs(span: ReadableSpan) -> dict[str, Any]:
+ return dict(span.attributes or {})
+
+
+class TestSpanTreeBasic:
+ async def test_simple_run_emits_three_spans(self):
+ agent, provider, exporter, tracer = await _build()
+ provider.append_responses([faux_assistant_message("hello")])
+
+ await agent.prompt("hi")
+ await agent.wait_for_idle()
+ await tracer.shutdown()
+
+ names = sorted(s.name for s in exporter.spans)
+ assert "invoke_agent" in names
+ assert "cubepi.turn" in names
+ assert any(n.startswith("chat ") for n in names)
+ assert len(exporter.spans) == 3
+
+ async def test_root_invoke_agent_attrs(self):
+ agent, provider, exporter, tracer = await _build()
+ provider.append_responses([faux_assistant_message("ok")])
+
+ await agent.prompt("x")
+ await agent.wait_for_idle()
+ await tracer.shutdown()
+
+ roots = [s for s in exporter.spans if s.name == "invoke_agent"]
+ assert len(roots) == 1
+ attrs = _attrs(roots[0])
+ assert attrs["gen_ai.operation.name"] == "invoke_agent"
+ assert attrs["gen_ai.provider.name"] == "faux"
+ assert "cubepi.run_id" in attrs
+ assert "cubepi.agent.system_prompt.sha256" in attrs
+ assert roots[0].kind == SpanKind.INTERNAL
+
+
+class TestChatSpan:
+ async def test_chat_span_is_client_and_carries_gen_ai_attrs(self):
+ agent, provider, exporter, tracer = await _build()
+ provider.append_responses([faux_assistant_message("hi")])
+
+ await agent.prompt("x")
+ await agent.wait_for_idle()
+ await tracer.shutdown()
+
+ chats = [s for s in exporter.spans if s.name.startswith("chat ")]
+ assert len(chats) == 1
+ chat = chats[0]
+ assert chat.kind == SpanKind.CLIENT
+ attrs = _attrs(chat)
+ assert attrs["gen_ai.operation.name"] == "chat"
+ assert attrs["gen_ai.provider.name"] == "faux"
+ assert attrs["gen_ai.request.model"] == MODEL.id
+ assert attrs["gen_ai.request.stream"] is True
+ assert "gen_ai.usage.input_tokens" in attrs
+ assert "gen_ai.usage.output_tokens" in attrs
+ assert attrs["gen_ai.response.finish_reasons"] == ("stop",)
+
+
+class TestTurnSpan:
+ async def test_turn_span_no_operation_name(self):
+ agent, provider, exporter, tracer = await _build()
+ provider.append_responses([faux_assistant_message("ok")])
+
+ await agent.prompt("x")
+ await agent.wait_for_idle()
+ await tracer.shutdown()
+
+ turn = [s for s in exporter.spans if s.name == "cubepi.turn"][0]
+ attrs = _attrs(turn)
+ assert "gen_ai.operation.name" not in attrs
+ assert "gen_ai.workflow.name" not in attrs
+ assert attrs["cubepi.turn.index"] == 0
+ assert attrs["cubepi.turn.stop_reason"] == "stop"
+
+ async def test_multi_turn_indexes_increment(self):
+ from pydantic import BaseModel
+
+ class P(BaseModel):
+ pass
+
+ async def echo(tool_call_id, params, *, signal=None, on_update=None):
+ return AgentToolResult(content=[TextContent(text="done")])
+
+ tool = AgentTool(name="echo", description="echo", parameters=P, execute=echo)
+
+ agent, provider, exporter, tracer = await _build(tools=[tool])
+ provider.append_responses(
+ [
+ faux_assistant_message(
+ [ToolCall(id="t1", name="echo", arguments={})],
+ stop_reason="tool_use",
+ ),
+ faux_assistant_message("done"),
+ ]
+ )
+
+ await agent.prompt("x")
+ await agent.wait_for_idle()
+ await tracer.shutdown()
+
+ turns = sorted(
+ [s for s in exporter.spans if s.name == "cubepi.turn"],
+ key=lambda s: s.start_time or 0,
+ )
+ assert len(turns) == 2
+ assert _attrs(turns[0])["cubepi.turn.index"] == 0
+ assert _attrs(turns[1])["cubepi.turn.index"] == 1
+
+
+class TestExecuteToolSpan:
+ async def test_tool_span_attrs(self):
+ from pydantic import BaseModel
+
+ class P(BaseModel):
+ pass
+
+ async def run(tool_call_id, params, *, signal=None, on_update=None):
+ return AgentToolResult(content=[TextContent(text="done")])
+
+ tool = AgentTool(
+ name="echo",
+ description="echo a thing",
+ parameters=P,
+ execute=run,
+ )
+
+ agent, provider, exporter, tracer = await _build(tools=[tool])
+ provider.append_responses(
+ [
+ faux_assistant_message(
+ [ToolCall(id="t1", name="echo", arguments={})],
+ stop_reason="tool_use",
+ ),
+ faux_assistant_message("done"),
+ ]
+ )
+
+ await agent.prompt("x")
+ await agent.wait_for_idle()
+ await tracer.shutdown()
+
+ tool_spans = [s for s in exporter.spans if s.name.startswith("execute_tool ")]
+ assert len(tool_spans) == 1
+ t = tool_spans[0]
+ assert t.kind == SpanKind.INTERNAL
+ attrs = _attrs(t)
+ assert attrs["gen_ai.operation.name"] == "execute_tool"
+ assert attrs["gen_ai.tool.name"] == "echo"
+ assert attrs["gen_ai.tool.call.id"] == "t1"
+ assert attrs["gen_ai.tool.type"] == "function"
+ # description and execution_mode come from the AgentTool — the
+ # Recorder reads them off the agent's tool registry at exec
+ # start.
+ assert attrs["gen_ai.tool.description"] == "echo a thing"
+ assert attrs["cubepi.tool.execution_mode"] in {"parallel", "sequential"}
+ assert attrs["cubepi.tool.is_error"] is False
+ assert "cubepi.tool.terminate" not in attrs
+
+ async def test_tool_terminate_flag_propagates(self):
+ from pydantic import BaseModel
+
+ class P(BaseModel):
+ pass
+
+ async def run(tool_call_id, params, *, signal=None, on_update=None):
+ return AgentToolResult(content=[TextContent(text="done")], terminate=True)
+
+ tool = AgentTool(name="t", description="t", parameters=P, execute=run)
+
+ agent, provider, exporter, tracer = await _build(tools=[tool])
+ provider.append_responses(
+ [
+ faux_assistant_message(
+ [ToolCall(id="t1", name="t", arguments={})],
+ stop_reason="tool_use",
+ ),
+ ]
+ )
+
+ await agent.prompt("x")
+ await agent.wait_for_idle()
+ await tracer.shutdown()
+
+ t_span = [s for s in exporter.spans if s.name.startswith("execute_tool ")][0]
+ assert _attrs(t_span)["cubepi.tool.terminate"] is True
+ turn = [s for s in exporter.spans if s.name == "cubepi.turn"][0]
+ assert _attrs(turn)["cubepi.turn.terminated_by_tool"] is True
+
+ async def test_tool_blocked_by_hook(self):
+ from pydantic import BaseModel
+
+ class P(BaseModel):
+ pass
+
+ async def run(tool_call_id, params, *, signal=None, on_update=None):
+ return AgentToolResult(content=[TextContent(text="never")])
+
+ async def before(ctx, *, signal=None):
+ return BeforeToolCallResult(block=True, reason="no thanks")
+
+ tool = AgentTool(name="g", description="g", parameters=P, execute=run)
+
+ agent, provider, exporter, tracer = await _build(
+ tools=[tool], before_tool_call=before
+ )
+ provider.append_responses(
+ [
+ faux_assistant_message(
+ [ToolCall(id="t1", name="g", arguments={})],
+ stop_reason="tool_use",
+ ),
+ faux_assistant_message("acknowledged"),
+ ]
+ )
+
+ await agent.prompt("x")
+ await agent.wait_for_idle()
+ await tracer.shutdown()
+
+ t_span = [s for s in exporter.spans if s.name.startswith("execute_tool ")][0]
+ attrs = _attrs(t_span)
+ assert attrs["cubepi.tool.is_error"] is True
+ assert attrs["cubepi.tool.blocked_by_hook"] is True
+ assert attrs["cubepi.tool.block_reason"] == "no thanks"
+ assert t_span.status.status_code == StatusCode.ERROR
+ assert attrs["error.type"] == "cubepi.tool.blocked_by_hook"
+
+
+class TestParentChild:
+ async def test_chat_and_tool_share_turn_parent(self):
+ from pydantic import BaseModel
+
+ class P(BaseModel):
+ pass
+
+ async def run(tool_call_id, params, *, signal=None, on_update=None):
+ return AgentToolResult(content=[TextContent(text="done")])
+
+ tool = AgentTool(name="t", description="t", parameters=P, execute=run)
+
+ agent, provider, exporter, tracer = await _build(tools=[tool])
+ provider.append_responses(
+ [
+ faux_assistant_message(
+ [ToolCall(id="t1", name="t", arguments={})],
+ stop_reason="tool_use",
+ ),
+ faux_assistant_message("done"),
+ ]
+ )
+
+ await agent.prompt("x")
+ await agent.wait_for_idle()
+ await tracer.shutdown()
+
+ trace_ids = {s.context.trace_id for s in exporter.spans}
+ assert len(trace_ids) == 1
+
+ by_name = _spans_by_name(exporter)
+ root = by_name["invoke_agent"][0]
+ assert root.parent is None
+ for turn in by_name["cubepi.turn"]:
+ assert turn.parent is not None
+ assert turn.parent.span_id == root.context.span_id
+ for chat in [s for s in exporter.spans if s.name.startswith("chat ")]:
+ assert chat.parent is not None
+ assert chat.parent.span_id in {
+ t.context.span_id for t in by_name["cubepi.turn"]
+ }
+
+
+class TestErrorAndAbort:
+ async def test_chat_span_records_provider_exception(self):
+ agent, provider, exporter, tracer = await _build()
+
+ async def boom(messages, model, system_prompt, tools):
+ raise RuntimeError("provider boom")
+
+ provider.append_responses([boom])
+
+ await agent.prompt("x")
+ await agent.wait_for_idle()
+ await tracer.shutdown()
+
+ chats = [s for s in exporter.spans if s.name.startswith("chat ")]
+ assert len(chats) == 1
+ chat = chats[0]
+ assert chat.status.status_code == StatusCode.ERROR
+ attrs = _attrs(chat)
+ assert "error.type" in attrs
+ evnames = [e.name for e in chat.events]
+ assert "gen_ai.client.operation.exception" in evnames
+
+ async def test_agent_aborted_marks_cubepi_aborted(self):
+ # Slow chunking so the abort signal lands MID-stream.
+ 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])
+ tracer.attach(agent)
+
+ provider.append_responses([faux_assistant_message("x" * 600)])
+
+ # ``agent.prompt`` blocks until the run finishes, so kick it off
+ # as a background task; abort while it's still streaming.
+ run = asyncio.create_task(agent.prompt("hi"))
+ await asyncio.sleep(0.1)
+ agent.abort()
+ await run
+ await tracer.shutdown()
+
+ root = [s for s in exporter.spans if s.name == "invoke_agent"][0]
+ attrs = _attrs(root)
+ assert attrs.get("cubepi.aborted") is True
+
+
+class TestLifecycle:
+ async def test_shutdown_is_idempotent(self):
+ agent, provider, exporter, tracer = await _build()
+ provider.append_responses([faux_assistant_message("ok")])
+
+ await agent.prompt("x")
+ await agent.wait_for_idle()
+ await tracer.shutdown()
+ await tracer.shutdown()
+
+ async def test_record_content_true_is_not_yet_supported(self):
+ with pytest.raises(NotImplementedError):
+ Tracer(service_name="s", record_content=True)
+
+
+class TestJsonlExporter:
+ async def test_writes_jsonl_files(self, tmp_path):
+ from cubepi.tracing.exporters import JsonlSpanExporter
+
+ provider = FauxProvider()
+ provider.append_responses([faux_assistant_message("ok")])
+ agent = Agent(provider=provider, model=MODEL, system_prompt="s")
+ exporter = JsonlSpanExporter(directory=tmp_path)
+ tracer = Tracer(service_name="t", agent_name="a", exporters=[exporter])
+ tracer.attach(agent)
+
+ await agent.prompt("x")
+ await agent.wait_for_idle()
+ await tracer.shutdown()
+
+ files = list(tmp_path.rglob("*.jsonl"))
+ assert files, "expected at least one jsonl file"
+ lines = []
+ for f in files:
+ lines.extend(line for line in f.read_text().splitlines() if line.strip())
+ import json as _json
+
+ for line in lines:
+ d = _json.loads(line)
+ assert "name" in d
+ assert "context" in d
diff --git a/tests/tracing/test_recorder_coverage.py b/tests/tracing/test_recorder_coverage.py
new file mode 100644
index 0000000..f6990f1
--- /dev/null
+++ b/tests/tracing/test_recorder_coverage.py
@@ -0,0 +1,393 @@
+"""Extra coverage for cubepi.tracing.recorder — pins the contracts
+codex flagged in the round-1 review and exercises the response-body
+shape parsers and error-type derivation paths that aren't covered by
+the FauxProvider end-to-end tests.
+"""
+
+from __future__ import annotations
+
+import asyncio
+from typing import Any
+
+from opentelemetry.sdk.trace import ReadableSpan
+from opentelemetry.sdk.trace.export import SpanExporter, SpanExportResult
+from opentelemetry.trace import StatusCode
+
+from cubepi.agent.agent import Agent
+from cubepi.providers.base import Model
+from cubepi.providers.faux import FauxProvider, faux_assistant_message
+from cubepi.tracing import Tracer
+
+
+MODEL = Model(id="faux-1", provider="faux")
+
+
+class _Capture(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 _attrs(span: ReadableSpan) -> dict[str, Any]:
+ return dict(span.attributes or {})
+
+
+# ---------------------------------------------------------------------------
+# P2-1: every span must carry cubepi.run_id (codex round 1)
+# ---------------------------------------------------------------------------
+
+
+class TestRunIdOnEverySpan:
+ async def test_run_id_propagated_to_all_spans(self):
+ provider = FauxProvider()
+ provider.append_responses([faux_assistant_message("ok")])
+ agent = Agent(provider=provider, model=MODEL, system_prompt="s")
+ exporter = _Capture()
+ tracer = Tracer(service_name="t", agent_name="a", exporters=[exporter])
+ tracer.attach(agent)
+
+ await agent.prompt("x")
+ await agent.wait_for_idle()
+ await tracer.shutdown()
+
+ assert exporter.spans, "expected spans"
+ run_ids = {_attrs(s).get("cubepi.run_id") for s in exporter.spans}
+ assert len(run_ids) == 1
+ assert None not in run_ids
+ # Same run id appears on invoke_agent / cubepi.turn / chat ...
+ assert run_ids.pop() is not None
+
+
+class TestJsonlSharding:
+ async def test_jsonl_shards_all_spans_under_run_file(self, tmp_path):
+ """All spans from one run must end up in the same per-run file —
+ codex flagged that without cubepi.run_id on child spans the
+ JsonlSpanExporter routed them to unknown-run.jsonl."""
+ from cubepi.tracing.exporters import JsonlSpanExporter
+
+ provider = FauxProvider()
+ provider.append_responses([faux_assistant_message("ok")])
+ agent = Agent(provider=provider, model=MODEL, system_prompt="s")
+ exporter = JsonlSpanExporter(directory=tmp_path)
+ tracer = Tracer(service_name="t", agent_name="a", exporters=[exporter])
+ tracer.attach(agent)
+
+ await agent.prompt("x")
+ await agent.wait_for_idle()
+ await tracer.shutdown()
+
+ files = list(tmp_path.rglob("*.jsonl"))
+ assert len(files) == 1, f"expected one file, got {files}"
+ assert "unknown-run" not in files[0].name
+
+
+# ---------------------------------------------------------------------------
+# P2-2: cooperative abort path on chat span (codex round 1)
+# ---------------------------------------------------------------------------
+
+
+class TestChatSpanAbort:
+ async def test_chat_span_marks_aborted_on_cooperative_abort(self):
+ provider = FauxProvider(tokens_per_second=10.0)
+ agent = Agent(provider=provider, model=MODEL, system_prompt="s")
+ exporter = _Capture()
+ tracer = Tracer(service_name="t", agent_name="a", exporters=[exporter])
+ tracer.attach(agent)
+ provider.append_responses([faux_assistant_message("x" * 600)])
+
+ run = asyncio.create_task(agent.prompt("hi"))
+ await asyncio.sleep(0.1)
+ agent.abort()
+ await run
+ await tracer.shutdown()
+
+ chats = [s for s in exporter.spans if s.name.startswith("chat ")]
+ assert len(chats) == 1
+ attrs = _attrs(chats[0])
+ # Cooperative abort: no exception, but body has stop_reason="aborted".
+ assert attrs.get("cubepi.aborted") is True
+ assert attrs.get("error.type") == "cubepi.aborted"
+ # Status remains UNSET — abort is a control signal, not a failure.
+ assert chats[0].status.status_code == StatusCode.UNSET
+
+
+# ---------------------------------------------------------------------------
+# Response body shape parsing — direct unit tests against Recorder helpers
+# ---------------------------------------------------------------------------
+
+
+class _Span:
+ """Lightweight stand-in for an OTel Span — just records set_attribute."""
+
+ def __init__(self) -> None:
+ self.attrs: dict[str, Any] = {}
+
+ def set_attribute(self, key: str, value: Any) -> None:
+ self.attrs[key] = value
+
+
+def _recorder():
+ from cubepi.tracing.recorder import Recorder
+
+ tracer = Tracer(service_name="t", exporters=[])
+ return Recorder(tracer)
+
+
+class TestAnthropicResponseShape:
+ def test_anthropic_usage_reconciles_cache_tokens(self):
+ rec = _recorder()
+ span = _Span()
+ body = {
+ "stop_reason": "end_turn",
+ "model": "claude-test",
+ "id": "msg_1",
+ "usage": {
+ "input_tokens": 100,
+ "output_tokens": 50,
+ "cache_read_input_tokens": 30,
+ "cache_creation_input_tokens": 10,
+ },
+ }
+ rec._record_chat_response_attrs(span, body)
+ # input_tokens = 100 + 30 + 10
+ assert span.attrs["gen_ai.usage.input_tokens"] == 140
+ assert span.attrs["gen_ai.usage.output_tokens"] == 50
+ assert span.attrs["gen_ai.usage.cache_read.input_tokens"] == 30
+ assert span.attrs["gen_ai.usage.cache_creation.input_tokens"] == 10
+ assert span.attrs["gen_ai.response.finish_reasons"] == ["end_turn"]
+ assert span.attrs["gen_ai.response.model"] == "claude-test"
+ assert span.attrs["gen_ai.response.id"] == "msg_1"
+
+
+class TestOpenAIChatResponseShape:
+ def test_openai_chat_usage_and_finish_reason(self):
+ rec = _recorder()
+ span = _Span()
+ body = {
+ "id": "chatcmpl-1",
+ "model": "gpt-test",
+ "object": "chat.completion",
+ "choices": [{"finish_reason": "stop", "message": {"role": "assistant"}}],
+ "usage": {
+ "prompt_tokens": 75,
+ "completion_tokens": 25,
+ "total_tokens": 100,
+ "prompt_tokens_details": {"cached_tokens": 5},
+ },
+ }
+ rec._record_chat_response_attrs(span, body)
+ assert span.attrs["gen_ai.usage.input_tokens"] == 75
+ assert span.attrs["gen_ai.usage.output_tokens"] == 25
+ assert span.attrs["gen_ai.usage.cache_read.input_tokens"] == 5
+ assert span.attrs["gen_ai.response.finish_reasons"] == ["stop"]
+ assert span.attrs["gen_ai.response.id"] == "chatcmpl-1"
+ assert span.attrs["gen_ai.response.model"] == "gpt-test"
+
+
+class TestOpenAIResponsesShape:
+ def test_openai_responses_reasoning_tokens(self):
+ rec = _recorder()
+ span = _Span()
+ body = {
+ "object": "response",
+ "id": "resp_1",
+ "model": "o4-test",
+ "status": "completed",
+ "usage": {
+ "input_tokens": 60,
+ "output_tokens": 40,
+ "input_tokens_details": {"cached_tokens": 20},
+ "output_tokens_details": {"reasoning_tokens": 30},
+ },
+ }
+ rec._record_chat_response_attrs(span, body)
+ assert span.attrs["gen_ai.usage.input_tokens"] == 60
+ assert span.attrs["gen_ai.usage.output_tokens"] == 40
+ assert span.attrs["gen_ai.usage.cache_read.input_tokens"] == 20
+ assert span.attrs["gen_ai.usage.reasoning.output_tokens"] == 30
+ assert span.attrs["gen_ai.response.finish_reasons"] == ["completed"]
+
+
+# ---------------------------------------------------------------------------
+# System-prompt extraction across provider shapes
+# ---------------------------------------------------------------------------
+
+
+class TestSystemPromptExtraction:
+ def test_anthropic_string_system(self):
+ from cubepi.tracing.recorder import _extract_system_prompt
+
+ assert _extract_system_prompt({"system": "hi"}) == "hi"
+
+ def test_anthropic_cached_system_blocks(self):
+ from cubepi.tracing.recorder import _extract_system_prompt
+
+ payload = {
+ "system": [
+ {"type": "text", "text": "hello"},
+ {"type": "text", "text": "world"},
+ ]
+ }
+ assert _extract_system_prompt(payload) == "helloworld"
+
+ def test_faux_system_prompt_key(self):
+ from cubepi.tracing.recorder import _extract_system_prompt
+
+ assert _extract_system_prompt({"system_prompt": "faux"}) == "faux"
+
+ def test_openai_chat_first_system_message(self):
+ from cubepi.tracing.recorder import _extract_system_prompt
+
+ payload = {
+ "messages": [
+ {"role": "system", "content": "be helpful"},
+ {"role": "user", "content": "hi"},
+ ]
+ }
+ assert _extract_system_prompt(payload) == "be helpful"
+
+ def test_openai_responses_developer_role(self):
+ from cubepi.tracing.recorder import _extract_system_prompt
+
+ payload = {
+ "input": [
+ {"role": "developer", "content": "be precise"},
+ {"role": "user", "content": "."},
+ ]
+ }
+ assert _extract_system_prompt(payload) == "be precise"
+
+ def test_no_system_returns_none(self):
+ from cubepi.tracing.recorder import _extract_system_prompt
+
+ assert _extract_system_prompt({}) is None
+ assert _extract_system_prompt({"messages": []}) is None
+ assert _extract_system_prompt({"system": {"unexpected": "shape"}}) is None
+
+
+# ---------------------------------------------------------------------------
+# error.type derivation
+# ---------------------------------------------------------------------------
+
+
+class TestErrorType:
+ def test_cancelled_error(self):
+ from cubepi.tracing.errors import cubepi_error_type_for
+
+ assert cubepi_error_type_for(asyncio.CancelledError()) == "cubepi.aborted"
+
+ def test_timeout(self):
+ from cubepi.tracing.errors import cubepi_error_type_for
+
+ assert cubepi_error_type_for(asyncio.TimeoutError()) == "timeout"
+ assert cubepi_error_type_for(TimeoutError()) == "timeout"
+
+ def test_connection_error(self):
+ from cubepi.tracing.errors import cubepi_error_type_for
+
+ assert cubepi_error_type_for(ConnectionError()) == "connection_error"
+
+ def test_builtin_exception_uses_qualname(self):
+ from cubepi.tracing.errors import cubepi_error_type_for
+
+ assert cubepi_error_type_for(ValueError("x")) == "ValueError"
+
+ def test_module_qualified_class(self):
+ from cubepi.tracing.errors import cubepi_error_type_for
+
+ class CustomErr(Exception):
+ pass
+
+ err = CustomErr()
+ out = cubepi_error_type_for(err)
+ assert out.endswith("CustomErr")
+
+
+# ---------------------------------------------------------------------------
+# Schema URL & provider name mapping
+# ---------------------------------------------------------------------------
+
+
+class TestSchemaConstants:
+ def test_schema_url_pinned(self):
+ from cubepi.tracing.schema import SCHEMA_URL
+
+ assert SCHEMA_URL == "https://opentelemetry.io/schemas/1.41.0"
+
+ def test_provider_name_known(self):
+ from cubepi.tracing.schema import map_provider_name
+
+ assert map_provider_name("anthropic") == "anthropic"
+ assert map_provider_name("azure_openai") == "azure.ai.openai"
+ assert map_provider_name("bedrock") == "aws.bedrock"
+ assert map_provider_name("vertex_ai") == "gcp.vertex_ai"
+
+ def test_provider_name_unknown_prefixed(self):
+ from cubepi.tracing.schema import map_provider_name
+
+ assert map_provider_name("nobody") == "unknown:nobody"
+
+
+# ---------------------------------------------------------------------------
+# Detach lifecycle
+# ---------------------------------------------------------------------------
+
+
+class TestDetach:
+ async def test_detach_unsubscribes(self):
+ provider = FauxProvider()
+ provider.append_responses([faux_assistant_message("a")])
+ agent = Agent(provider=provider, model=MODEL, system_prompt="s")
+ exporter = _Capture()
+ tracer = Tracer(service_name="t", agent_name="a", exporters=[exporter])
+ detach = tracer.attach(agent)
+
+ await agent.prompt("first")
+ await agent.wait_for_idle()
+ await tracer.force_flush()
+ first_count = len(exporter.spans)
+ assert first_count >= 1
+
+ detach()
+ # detach schedules an async unsubscribe task; let it run.
+ await asyncio.sleep(0.05)
+
+ provider.append_responses([faux_assistant_message("b")])
+ await agent.prompt("second")
+ await agent.wait_for_idle()
+ await tracer.shutdown()
+
+ # After detach the recorder must no longer produce new spans.
+ assert len(exporter.spans) == first_count
+
+
+# ---------------------------------------------------------------------------
+# Tracer config edge cases
+# ---------------------------------------------------------------------------
+
+
+class TestTracerConfig:
+ def test_explicit_resource_passes_through(self):
+ from opentelemetry.sdk.resources import Resource
+
+ custom = Resource.create(
+ {"service.name": "explicit"},
+ schema_url="https://opentelemetry.io/schemas/1.41.0",
+ )
+ tracer = Tracer(resource=custom, exporters=[])
+ assert tracer.resource is custom
+
+ async def test_async_context_manager_calls_shutdown(self):
+ exporter = _Capture()
+ async with Tracer(service_name="t", exporters=[exporter]) as t:
+ assert t.resource is not None
+ # No raise — shutdown ran via __aexit__.
diff --git a/uv.lock b/uv.lock
index 4aebc73..940a530 100644
--- a/uv.lock
+++ b/uv.lock
@@ -397,6 +397,9 @@ postgres = [
sqlite = [
{ name = "aiosqlite" },
]
+tracing = [
+ { name = "opentelemetry-sdk" },
+]
[package.dev-dependencies]
dev = [
@@ -420,10 +423,11 @@ requires-dist = [
{ name = "mcp", marker = "extra == 'mcp'", specifier = ">=1.0" },
{ name = "msgpack", marker = "extra == 'postgres'", specifier = ">=1.0" },
{ name = "openai", specifier = ">=2.36.0" },
+ { name = "opentelemetry-sdk", marker = "extra == 'tracing'", specifier = ">=1.30" },
{ name = "pydantic", specifier = ">=2.13.4" },
{ name = "sqlalchemy", marker = "extra == 'postgres'", specifier = ">=2.0" },
]
-provides-extras = ["sqlite", "postgres", "mcp", "docs"]
+provides-extras = ["sqlite", "postgres", "mcp", "docs", "tracing"]
[package.metadata.requires-dev]
dev = [
@@ -603,6 +607,18 @@ wheels = [
{ url = "https://files.pythonhosted.org/packages/5d/13/ad7d7ca3808a898b4612b6fe93cde56b53f3034dcde235acb1f0e1df24c6/idna-3.13-py3-none-any.whl", hash = "sha256:892ea0cde124a99ce773decba204c5552b69c3c67ffd5f232eb7696135bc8bb3", size = 68629, upload-time = "2026-04-22T16:42:40.909Z" },
]
+[[package]]
+name = "importlib-metadata"
+version = "8.7.1"
+source = { registry = "https://pypi.org/simple/" }
+dependencies = [
+ { name = "zipp" },
+]
+sdist = { url = "https://files.pythonhosted.org/packages/f3/49/3b30cad09e7771a4982d9975a8cbf64f00d4a1ececb53297f1d9a7be1b10/importlib_metadata-8.7.1.tar.gz", hash = "sha256:49fef1ae6440c182052f407c8d34a68f72efc36db9ca90dc0113398f2fdde8bb", size = 57107, upload-time = "2025-12-21T10:00:19.278Z" }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/fa/5e/f8e9a1d23b9c20a551a8a02ea3637b4642e22c2626e3a13a9a29cdea99eb/importlib_metadata-8.7.1-py3-none-any.whl", hash = "sha256:5a1f80bf1daa489495071efbb095d75a634cf28a8bc299581244063b53176151", size = 27865, upload-time = "2025-12-21T10:00:18.329Z" },
+]
+
[[package]]
name = "iniconfig"
version = "2.3.0"
@@ -826,6 +842,46 @@ wheels = [
{ url = "https://files.pythonhosted.org/packages/9d/1c/5d43735b2553baae2a5e899dcbcd0670a86930d993184d72ca909bf11c9b/openai-2.36.0-py3-none-any.whl", hash = "sha256:143f6194b548dbc2c921af1f1b03b9f14c85fed8a75b5b516f5bcc11a2a50c63", size = 1302361, upload-time = "2026-05-07T17:33:15.063Z" },
]
+[[package]]
+name = "opentelemetry-api"
+version = "1.41.1"
+source = { registry = "https://pypi.org/simple/" }
+dependencies = [
+ { name = "importlib-metadata" },
+ { name = "typing-extensions" },
+]
+sdist = { url = "https://files.pythonhosted.org/packages/fa/fc/b7564cbef36601aef0d6c9bc01f7badb64be8e862c2e1c3c5c3b43b53e4f/opentelemetry_api-1.41.1.tar.gz", hash = "sha256:0ad1814d73b875f84494387dae86ce0b12c68556331ce6ce8fe789197c949621", size = 71416, upload-time = "2026-04-24T13:15:38.262Z" }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/29/59/3e7118ed140f76b0982ba4321bdaed1997a0473f9720de2d10788a577033/opentelemetry_api-1.41.1-py3-none-any.whl", hash = "sha256:a22df900e75c76dc08440710e51f52f1aa6b451b429298896023e60db5b3139f", size = 69007, upload-time = "2026-04-24T13:15:15.662Z" },
+]
+
+[[package]]
+name = "opentelemetry-sdk"
+version = "1.41.1"
+source = { registry = "https://pypi.org/simple/" }
+dependencies = [
+ { name = "opentelemetry-api" },
+ { name = "opentelemetry-semantic-conventions" },
+ { name = "typing-extensions" },
+]
+sdist = { url = "https://files.pythonhosted.org/packages/58/d0/54ee30dab82fb0acda23d144502771ff76ef8728459c83c3e89ef9fb1825/opentelemetry_sdk-1.41.1.tar.gz", hash = "sha256:724b615e1215b5aeacda0abb8a6a8922c9a1853068948bd0bd225a56d0c792e6", size = 230180, upload-time = "2026-04-24T13:15:50.991Z" }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/b4/e7/a1420b698aad018e1cf60fdbaaccbe49021fb415e2a0d81c242f4c518f54/opentelemetry_sdk-1.41.1-py3-none-any.whl", hash = "sha256:edee379c126c1bce952b0c812b48fe8ff35b30df0eecf17e98afa4d598b7d85d", size = 180213, upload-time = "2026-04-24T13:15:33.767Z" },
+]
+
+[[package]]
+name = "opentelemetry-semantic-conventions"
+version = "0.62b1"
+source = { registry = "https://pypi.org/simple/" }
+dependencies = [
+ { name = "opentelemetry-api" },
+ { name = "typing-extensions" },
+]
+sdist = { url = "https://files.pythonhosted.org/packages/9e/de/911ac9e309052aca1b20b2d5549d3db45d1011e1a610e552c6ccdd1b64f8/opentelemetry_semantic_conventions-0.62b1.tar.gz", hash = "sha256:c5cc6e04a7f8c7cdd30be2ed81499fa4e75bfbd52c9cb70d40af1f9cd3619802", size = 145750, upload-time = "2026-04-24T13:15:52.236Z" }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/eb/a6/83dc2ab6fa397ee66fba04fe2e74bdf7be3b3870005359ceb7689103c058/opentelemetry_semantic_conventions-0.62b1-py3-none-any.whl", hash = "sha256:cf506938103d331fbb78eded0d9788095f7fd59016f2bda813c3324e5a74a93c", size = 231620, upload-time = "2026-04-24T13:15:35.454Z" },
+]
+
[[package]]
name = "packaging"
version = "26.2"
@@ -1421,3 +1477,12 @@ sdist = { url = "https://files.pythonhosted.org/packages/1f/93/041fca8274050e40e
wheels = [
{ url = "https://files.pythonhosted.org/packages/31/a3/5b1562db76a5a488274b2332a97199b32d0442aca0ed193697fd47786316/uvicorn-0.46.0-py3-none-any.whl", hash = "sha256:bbebbcbed972d162afca128605223022bedd345b7bc7855ce66deb31487a9048", size = 70926, upload-time = "2026-04-23T07:15:58.355Z" },
]
+
+[[package]]
+name = "zipp"
+version = "3.23.1"
+source = { registry = "https://pypi.org/simple/" }
+sdist = { url = "https://files.pythonhosted.org/packages/30/21/093488dfc7cc8964ded15ab726fad40f25fd3d788fd741cc1c5a17d78ee8/zipp-3.23.1.tar.gz", hash = "sha256:32120e378d32cd9714ad503c1d024619063ec28aad2248dc6672ad13edfa5110", size = 25965, upload-time = "2026-04-13T23:21:46.6Z" }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/08/8a/0861bec20485572fbddf3dfba2910e38fe249796cb73ecdeb74e07eeb8d3/zipp-3.23.1-py3-none-any.whl", hash = "sha256:0b3596c50a5c700c9cb40ba8d86d9f2cc4807e9bedb06bcdf7fac85633e444dc", size = 10378, upload-time = "2026-04-13T23:21:45.386Z" },
+]