Skip to content

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

fix(tracing): gate raw diagnostics behind content opt-in

Cue106ab6dd6ad7
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 9e7b9d3..1cdc2d3 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -15,10 +15,15 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
turn, chat, and tool spans end with `cubepi.run.outcome="suspended"`; observer
failures cannot hide the terminal event, cancellation still propagates, and
`respond()` opens a distinct correlated activation trace.
-- **Raw provider error details now follow the content-recording opt-in.** With
- `record_content=False`, traces retain typed error classification and ERROR
- status but use bounded generic descriptions and omit exception messages and
- stack traces. `record_content=True` preserves the prior diagnostic detail.
+- **Raw tracing diagnostics now follow the content-recording opt-in.** With
+ `record_content=False`, provider, turn, one-shot, and MCP spans retain typed
+ error classification and ERROR status but use bounded generic descriptions
+ and omit exception messages and stack traces. Stream logs retain structural
+ timing/size fields while omitting tool-argument previews and raw error text.
+ `record_content=True` preserves the prior diagnostic detail for failures.
+- **One-shot cancellation now matches Agent and MCP cancellation semantics.** It
+ records `cubepi.aborted=true` with status UNSET and does not emit an exception
+ event, because cancellation is a control signal rather than a failure.
## [0.13.3] - 2026-08-02
diff --git a/cubepi/mcp/_tracing.py b/cubepi/mcp/_tracing.py
index 57f75cd..0c798e4 100644
--- a/cubepi/mcp/_tracing.py
+++ b/cubepi/mcp/_tracing.py
@@ -65,18 +65,17 @@ except ImportError: # pragma: no cover — exercised only without the extra.
# multiple agents (each attach pushes a token; each detach pops just
# its own entry) and supports detaches in any order without clearing
# routing for the still-attached agents.
-_provider_stack: list[tuple[object, Any]] = []
+_provider_stack: list[tuple[object, Any, bool]] = []
-def register_provider(provider: Any) -> object:
- """Push ``provider`` onto the routing stack as the preferred source
- for MCP spans. Returns an opaque token that
- :func:`unregister_provider` uses to remove this exact entry.
+def register_provider(provider: Any, *, record_content: bool = False) -> object:
+ """Push ``provider`` and its content policy onto the routing stack.
- Called by :meth:`cubepi.tracing.Tracer.attach`.
+ Returns an opaque token that :func:`unregister_provider` uses to remove
+ this exact entry. Called by :meth:`cubepi.tracing.Tracer.attach`.
"""
token = object()
- _provider_stack.append((token, provider))
+ _provider_stack.append((token, provider, record_content))
return token
@@ -93,26 +92,28 @@ def unregister_provider(token: object | None = None) -> None:
if token is None:
_provider_stack.pop()
return
- for i, (t, _p) in enumerate(_provider_stack):
+ for i, (t, _p, _record_content) in enumerate(_provider_stack):
if t is token:
_provider_stack.pop(i)
return
-def _get_tracer(scope_name: str) -> Any:
- """Resolve the tracer to use for emitting an MCP span.
-
- Prefers the most recently-registered provider over OTel's global
- default (which is a no-op unless the user separately called
- ``set_tracer_provider``).
- """
+def _get_tracer_route(scope_name: str) -> tuple[Any, bool]:
+ """Resolve the tracer and content policy for an MCP span."""
if _provider_stack:
- return _provider_stack[-1][1].get_tracer(scope_name)
- return _otel_trace.get_tracer(scope_name)
+ _token, provider, record_content = _provider_stack[-1]
+ return provider.get_tracer(scope_name), record_content
+ return _otel_trace.get_tracer(scope_name), False
+
+
+def _get_tracer(scope_name: str) -> Any:
+ """Resolve the tracer to use for emitting an MCP span."""
+ tracer, _record_content = _get_tracer_route(scope_name)
+ return tracer
# When the cubepi Recorder opens an ``execute_tool`` span, it publishes
-# ``(span, owning_provider)`` here so an MCP tool call running inside
+# ``(span, owning_provider, record_content)`` here so an MCP tool call running inside
# the AgentTool body can make its CLIENT span a child of this span
# (rather than starting an orphan root trace — recorder doesn't bother
# installing ``execute_tool`` as the OTel current span; see
@@ -122,7 +123,7 @@ def _get_tracer(scope_name: str) -> Any:
#
# Lookup uses a per-task ``ContextVar`` holding a STACK of opaque
# handles (outermost first, innermost last), with the actual
-# ``(span, provider)`` payload stored in a module-level
+# ``(span, provider, record_content)`` payload stored in a module-level
# ``_active_entries`` dict. The dict is the source of truth for which
# handles are still live; the contextvar stack records nesting order
# per task.
@@ -148,16 +149,21 @@ def _get_tracer(scope_name: str) -> Any:
# is found. Dead handles linger only in a task's local stack tuple and
# are GC'd when that task ends; ``_active_entries`` stays bounded by
# live registrations.
-_active_entries: dict[object, tuple[Any, Any]] = {}
+_active_entries: dict[object, tuple[Any, Any, bool]] = {}
_handle_stack: contextvars.ContextVar[tuple[object, ...]] = contextvars.ContextVar(
"_cubepi_mcp_tool_handle_stack", default=()
)
+_record_content_context: contextvars.ContextVar[bool] = contextvars.ContextVar(
+ "_cubepi_mcp_record_content", default=False
+)
def register_tool_span(
tool_call_id: str,
span: Any,
provider: Any = None,
+ *,
+ record_content: bool = False,
) -> tuple[object, contextvars.Token[tuple[object, ...]]]:
"""Publish ``span`` (and its owning ``provider``) as the current
``execute_tool`` parent for the calling task.
@@ -173,7 +179,7 @@ def register_tool_span(
"""
del tool_call_id
handle = object()
- _active_entries[handle] = (span, provider)
+ _active_entries[handle] = (span, provider, record_content)
cv_token = _handle_stack.set(_handle_stack.get() + (handle,))
return (handle, cv_token)
@@ -205,9 +211,10 @@ def unregister_tool_span(
pass
-def _get_tool_span_entry() -> tuple[Any, Any] | None:
- """Return the (span, provider) entry for the current task, or
- ``None`` when no live ``execute_tool`` is in scope.
+def _get_tool_span_entry() -> tuple[Any, Any, bool] | None:
+ """Return the active span, provider, and content policy for this task.
+
+ Returns ``None`` when no live ``execute_tool`` is in scope.
Walks the per-task handle stack inner→outer and returns the first
handle whose payload is still live in ``_active_entries``. A nested
@@ -287,16 +294,19 @@ async def mcp_client_span(
del parent_tool_call_id
entry = _get_tool_span_entry()
if entry is not None:
- parent_span, parent_provider = entry
+ parent_span, parent_provider, record_content = entry
parent_context = _otel_trace.set_span_in_context(parent_span)
- tracer = (
- parent_provider.get_tracer(_SCOPE_NAME)
- if parent_provider is not None
- else _get_tracer(_SCOPE_NAME)
- )
+ if parent_provider is not None:
+ tracer = parent_provider.get_tracer(_SCOPE_NAME)
+ else:
+ tracer, _fallback_record_content = _get_tracer_route(_SCOPE_NAME)
else:
parent_context = None
tracer = _get_tracer(_SCOPE_NAME)
+ # Without an execute_tool parent there is no task-scoped owner.
+ # The provider stack is process-global, so borrowing its content flag
+ # could leak details from a different concurrent Tracer. Fail closed.
+ record_content = False
attrs: dict[str, Any] = {
_MCP_METHOD_NAME: method,
_GEN_AI_OPERATION_NAME: "execute_tool",
@@ -318,35 +328,48 @@ async def mcp_client_span(
attributes=attrs,
context=parent_context,
)
+ content_token = _record_content_context.set(record_content)
try:
- # Disable use_span's default record_exception / set_status_on_exception
- # so we are the single source of the exception event and ERROR
- # status — otherwise OTel would auto-record on context exit AND
- # this ``except`` block would record again, double-counting.
- with _otel_trace.use_span(
- span,
- record_exception=False,
- set_status_on_exception=False,
- ):
- yield span
- except BaseException as exc:
try:
- error_type = _error_type_for(exc)
- span.set_attribute(_ERROR_TYPE, error_type)
- # Cancellation is a control signal, not a failure — match the
- # convention from the chat / turn / invoke_agent spans: leave
- # Status UNSET and mark cubepi.aborted=true, do NOT record an
- # exception event.
- if error_type == "cubepi.aborted":
- span.set_attribute("cubepi.aborted", True)
- else:
- span.set_status(Status(StatusCode.ERROR, str(exc)[:256]))
- span.record_exception(exc)
- finally:
+ # Disable use_span's default record_exception / set_status_on_exception
+ # so we are the single source of the exception event and ERROR
+ # status — otherwise OTel would auto-record on context exit AND
+ # this ``except`` block would record again, double-counting.
+ with _otel_trace.use_span(
+ span,
+ record_exception=False,
+ set_status_on_exception=False,
+ ):
+ yield span
+ except BaseException as exc:
+ try:
+ error_type = _error_type_for(exc)
+ span.set_attribute(_ERROR_TYPE, error_type)
+ # Cancellation is a control signal, not a failure — match the
+ # convention from the chat / turn / invoke_agent spans: leave
+ # Status UNSET and mark cubepi.aborted=true, do NOT record an
+ # exception event.
+ if error_type == "cubepi.aborted":
+ span.set_attribute("cubepi.aborted", True)
+ else:
+ description = (
+ str(exc)[:256] if record_content else "mcp client error"
+ )
+ span.set_status(Status(StatusCode.ERROR, description))
+ if record_content:
+ span.record_exception(exc)
+ else:
+ span.add_event(
+ "exception",
+ attributes={"exception.type": type(exc).__name__},
+ )
+ finally:
+ span.end()
+ raise
+ else:
span.end()
- raise
- else:
- span.end()
+ finally:
+ _record_content_context.reset(content_token)
def mark_span_mcp_error(span: Any, message: str) -> None:
@@ -362,7 +385,10 @@ def mark_span_mcp_error(span: Any, message: str) -> None:
"""
if span is None or not _OTEL_AVAILABLE:
return
- span.set_status(Status(StatusCode.ERROR, message[:256]))
+ description = (
+ message[:256] if _record_content_context.get() else "mcp protocol error"
+ )
+ span.set_status(Status(StatusCode.ERROR, description))
span.set_attribute(_ERROR_TYPE, "mcp.is_error")
diff --git a/cubepi/tracing/recorder.py b/cubepi/tracing/recorder.py
index b9f49a9..280213c 100644
--- a/cubepi/tracing/recorder.py
+++ b/cubepi/tracing/recorder.py
@@ -585,7 +585,7 @@ class Recorder:
entry = _mcp_tracing._get_tool_span_entry()
if entry is not None:
- tool_span, _tool_provider = entry
+ tool_span, _tool_provider, _record_content = entry
parent_ctx = trace.set_span_in_context(tool_span)
except ImportError: # pragma: no cover — mcp module always present
parent_ctx = None
@@ -845,7 +845,7 @@ class Recorder:
# cubepi.aborted on the invoke_agent root.
if stop_reason == "error":
err_msg = (
- getattr(msg, "error_message", None) or "model error"
+ (getattr(msg, "error_message", None) or "model error")
if self._record_content
else "model error"
)
@@ -907,6 +907,7 @@ class Recorder:
event.tool_call_id,
span,
provider=self._tracer._provider,
+ record_content=self._record_content,
)
run.tool_span_tokens[event.tool_call_id] = cv_token
except ImportError: # pragma: no cover — mcp module always present
@@ -1170,9 +1171,10 @@ class Recorder:
"ci": ci,
"chars": len(delta),
"accumulated": run.stream_tool_accumulated[ci],
- "preview": delta[:60],
}
)
+ if self._record_content:
+ rec["preview"] = delta[:60]
elif event.type == "toolcall_end":
id_, name, args_str = "", "", ""
@@ -1188,15 +1190,20 @@ class Recorder:
"id": id_,
"name": name,
"args_chars": total,
- "args_preview": args_str[:80],
}
)
+ if self._record_content:
+ rec["args_preview"] = args_str[:80]
elif event.type in ("text_delta", "thinking_delta"):
rec["chars"] = len(event.delta or "")
elif event.type == "error":
- rec["error_message"] = event.error_message or ""
+ rec["error_message"] = (
+ (event.error_message or "provider error")
+ if self._record_content
+ else "provider error"
+ )
try:
run.stream_file.write(json.dumps(rec) + "\n") # type: ignore[union-attr]
diff --git a/cubepi/tracing/tracer.py b/cubepi/tracing/tracer.py
index c6e2f47..a5969a2 100644
--- a/cubepi/tracing/tracer.py
+++ b/cubepi/tracing/tracer.py
@@ -289,7 +289,10 @@ class Tracer:
from cubepi.mcp import _tracing as mcp_tracing
assert mcp_tracing is not None
- mcp_token = mcp_tracing.register_provider(self._provider)
+ mcp_token = mcp_tracing.register_provider(
+ self._provider,
+ record_content=self._record_content,
+ )
except ImportError: # pragma: no cover — mcp module always present
pass
except BaseException:
@@ -612,9 +615,18 @@ class Tracer:
root_span.set_attribute(CUBEPI_ABORTED, True)
root_span.set_attribute(ERROR_TYPE, "cubepi.aborted")
else:
- root_span.set_status(Status(StatusCode.ERROR, str(_exc)[:256]))
+ description = str(_exc)[:256] if do_record else "oneshot error"
+ root_span.set_status(Status(StatusCode.ERROR, description))
root_span.set_attribute(ERROR_TYPE, type(_exc).__name__)
- root_span.record_exception(_exc)
+ if do_record:
+ root_span.record_exception(_exc)
+ else:
+ root_span.add_event(
+ "exception",
+ attributes={
+ "exception.type": type(_exc).__name__,
+ },
+ )
except Exception: # pragma: no cover — defensive
pass
raise
diff --git a/dev/plans/2026-08-04-tracing-hitl-suspension.md b/dev/plans/2026-08-04-tracing-hitl-suspension.md
index 8dd88fd..ae324de 100644
--- a/dev/plans/2026-08-04-tracing-hitl-suspension.md
+++ b/dev/plans/2026-08-04-tracing-hitl-suspension.md
@@ -49,9 +49,12 @@ OpenTelemetry SDK, pytest, Ruff, mypy, uv.
- Sweep tool-span registrations, close stream state, and clear the active run.
- Move assistant output accumulation to `MessageEndEvent` so suspension before
`TurnEndEvent` still records the partial output.
-- Do not change `_close_open_spans()` cancellation semantics.
+- Do not change `_close_open_spans()` cancellation semantics; make one-shot
+ cancellation match the same aborted-without-exception-event contract.
- When `record_content=False`, preserve typed ERROR classification while using
- generic status descriptions and omitting exception messages/stack traces.
+ generic status descriptions and omitting exception messages/stack traces from
+ provider, turn, one-shot, and MCP spans; keep stream telemetry structural by
+ omitting raw argument/error previews.
## Task 4: Document the lifecycle contract
diff --git a/dev/specs/2026-08-04-tracing-hitl-suspension.md b/dev/specs/2026-08-04-tracing-hitl-suspension.md
index 5ff148e..b7d1bfe 100644
--- a/dev/specs/2026-08-04-tracing-hitl-suspension.md
+++ b/dev/specs/2026-08-04-tracing-hitl-suspension.md
@@ -33,12 +33,15 @@ left the old `_RunState` retained in that task's context.
cancellation priority.
- Clear the pending-request snapshot on every owning activation failure/exit and
avoid unhandled `HitlDetached` future warnings.
-- Preserve the existing run cancellation cleanup and classification.
+- Preserve run cancellation cleanup and classification; align one-shot
+ cancellation with Agent/MCP semantics by recording aborted control flow
+ without an exception event.
- Remove tool-span and MCP-provider registrations during normal tracing detach.
- Count the assistant tool-call message as partial activation output.
- Keep tracing observational: recorder failures must not affect the agent.
-- Keep raw provider error messages and stack traces behind `record_content=True`;
- privacy-default traces retain only typed error classification.
+- Keep raw provider, turn, one-shot, MCP, and stream-log diagnostics behind
+ `record_content=True`; privacy-default traces retain only typed error
+ classification and structural stream timing/size evidence.
## Non-goals
diff --git a/tests/tracing/test_attach_atomicity.py b/tests/tracing/test_attach_atomicity.py
index 0319d05..5100225 100644
--- a/tests/tracing/test_attach_atomicity.py
+++ b/tests/tracing/test_attach_atomicity.py
@@ -73,7 +73,7 @@ async def test_tracer_attach_unwinds_recorder_on_mcp_register_failure(monkeypatc
try:
import cubepi.mcp._tracing as mcp_tracing
- def _boom(_provider): # noqa: ANN001, ANN202
+ def _boom(_provider, **_kwargs): # noqa: ANN001, ANN202
raise RuntimeError("register_provider failed")
monkeypatch.setattr(mcp_tracing, "register_provider", _boom)
@@ -129,7 +129,7 @@ async def test_tracer_attach_cleanup_swallows_recorder_detach_error(monkeypatch)
import cubepi.mcp._tracing as mcp_tracing
- def _boom(_provider): # noqa: ANN001, ANN202
+ def _boom(_provider, **_kwargs): # noqa: ANN001, ANN202
raise RuntimeError("register_provider failed")
monkeypatch.setattr(mcp_tracing, "register_provider", _boom)
diff --git a/tests/tracing/test_content_recording.py b/tests/tracing/test_content_recording.py
index 1b67c48..ae251d4 100644
--- a/tests/tracing/test_content_recording.py
+++ b/tests/tracing/test_content_recording.py
@@ -122,6 +122,30 @@ class TestContentDisabled:
for event in span.events:
assert secret not in repr(dict(event.attributes or {}))
+ async def test_turn_error_message_is_private_when_record_content_false(self):
+ secret = "Authorization: Bearer TURNSECRET"
+ agent, provider, exporter, tracer = await _build(record_content=False)
+ provider.append_responses(
+ [
+ faux_assistant_message(
+ "oops",
+ stop_reason="error",
+ error_message=secret,
+ )
+ ]
+ )
+
+ await agent.prompt("private prompt")
+ await agent.wait_for_idle()
+ await tracer.shutdown()
+
+ turn = next(span for span in exporter.spans if span.name == "cubepi.turn")
+ assert turn.status.status_code.name == "ERROR"
+ assert turn.status.description == "model error"
+ assert secret not in repr(dict(turn.attributes or {}))
+ for event in turn.events:
+ assert secret not in repr(dict(event.attributes or {}))
+
class TestRootContent:
async def test_invoke_agent_records_input_output_system(self):
diff --git a/tests/tracing/test_mcp_spans.py b/tests/tracing/test_mcp_spans.py
index ff834fa..3eefe30 100644
--- a/tests/tracing/test_mcp_spans.py
+++ b/tests/tracing/test_mcp_spans.py
@@ -11,6 +11,7 @@ from __future__ import annotations
import asyncio
from typing import Any
+import pytest
from opentelemetry import trace as _trace
from opentelemetry.sdk.resources import Resource
from opentelemetry.sdk.trace import ReadableSpan, TracerProvider
@@ -245,6 +246,26 @@ class TestMCPIsErrorResponse:
attrs = _attrs(span)
assert attrs["error.type"] == "mcp.is_error"
+ async def test_protocol_error_message_is_private_by_default(self, monkeypatch):
+ from cubepi.mcp._tracing import mark_span_mcp_error, mcp_client_span
+
+ provider, exporter = _make_provider()
+ _patch_mcp_trace(monkeypatch, provider)
+ secret = "Authorization: Bearer MCPPROTOCOLSECRET"
+
+ async with mcp_client_span(
+ method="tools/call",
+ tool_name="search",
+ ) as span:
+ mark_span_mcp_error(span, secret)
+
+ captured = next(s for s in exporter.spans if s.name.startswith("tools/call "))
+ assert captured.status.status_code == StatusCode.ERROR
+ assert captured.status.description == "mcp protocol error"
+ assert secret not in repr(dict(captured.attributes or {}))
+ for event in captured.events:
+ assert secret not in repr(dict(event.attributes or {}))
+
async def test_iserror_false_keeps_span_unset(self, monkeypatch):
provider, exporter = _make_provider()
_patch_mcp_trace(monkeypatch, provider)
@@ -437,6 +458,160 @@ class TestTracerProviderRouting:
assert client_span.parent is not None
assert client_span.parent.span_id == tool_ctx.span_id
+ async def test_mcp_exception_is_private_without_content_opt_in(self):
+ from cubepi.agent.agent import Agent
+ from cubepi.providers.base import ToolCall
+ from cubepi.providers.faux import FauxProvider, faux_assistant_message
+ from cubepi.tracing import Tracer
+
+ secret = "Authorization: Bearer MCPSECRET"
+ exporter = _CaptureExporter()
+
+ async def call_remote(name, args):
+ raise RuntimeError(secret)
+
+ mcp_tool = make_mcp_agent_tool(
+ name="search",
+ description="search",
+ input_schema={
+ "type": "object",
+ "properties": {"q": {"type": "string"}},
+ },
+ call_remote=call_remote,
+ )
+ provider = FauxProvider(provider_id="faux")
+ provider.append_responses(
+ [
+ faux_assistant_message(
+ [ToolCall(id="tc1", name="search", arguments={"q": "x"})],
+ stop_reason="tool_use",
+ ),
+ faux_assistant_message("done"),
+ ]
+ )
+ agent = Agent(
+ model=provider.model("faux-1"),
+ system_prompt="s",
+ tools=[mcp_tool],
+ )
+ tracer = Tracer(
+ service_name="t",
+ agent_name="a",
+ exporters=[exporter],
+ record_content=False,
+ )
+ detach = tracer.attach(agent)
+ try:
+ await agent.prompt("go")
+ await agent.wait_for_idle()
+ finally:
+ detach()
+ await tracer.shutdown()
+
+ span = next(s for s in exporter.spans if s.name.startswith("tools/call "))
+ assert span.status.status_code == StatusCode.ERROR
+ assert span.status.description == "mcp client error"
+ assert secret not in repr(dict(span.attributes or {}))
+ exception_event = next(
+ event for event in span.events if event.name == "exception"
+ )
+ assert exception_event.attributes["exception.type"] == "RuntimeError"
+ for event in span.events:
+ assert secret not in repr(dict(event.attributes or {}))
+
+ async def test_mcp_exception_details_remain_available_with_content_opt_in(self):
+ from cubepi.agent.agent import Agent
+ from cubepi.providers.base import ToolCall
+ from cubepi.providers.faux import FauxProvider, faux_assistant_message
+ from cubepi.tracing import Tracer
+
+ secret = "diagnostic mcp failure"
+ exporter = _CaptureExporter()
+
+ async def call_remote(name, args):
+ raise RuntimeError(secret)
+
+ mcp_tool = make_mcp_agent_tool(
+ name="search",
+ description="search",
+ input_schema={
+ "type": "object",
+ "properties": {"q": {"type": "string"}},
+ },
+ call_remote=call_remote,
+ )
+ provider = FauxProvider(provider_id="faux")
+ provider.append_responses(
+ [
+ faux_assistant_message(
+ [ToolCall(id="tc1", name="search", arguments={"q": "x"})],
+ stop_reason="tool_use",
+ ),
+ faux_assistant_message("done"),
+ ]
+ )
+ agent = Agent(
+ model=provider.model("faux-1"),
+ system_prompt="s",
+ tools=[mcp_tool],
+ )
+ tracer = Tracer(
+ service_name="t",
+ agent_name="a",
+ exporters=[exporter],
+ record_content=True,
+ )
+ detach = tracer.attach(agent)
+ try:
+ await agent.prompt("go")
+ await agent.wait_for_idle()
+ finally:
+ detach()
+ await tracer.shutdown()
+
+ span = next(s for s in exporter.spans if s.name.startswith("tools/call "))
+ assert secret in (span.status.description or "")
+ assert any(
+ secret in repr(dict(event.attributes or {})) for event in span.events
+ )
+
+ async def test_unparented_mcp_exception_fails_closed_with_opted_in_tracer(self):
+ """Without a tool-span owner, the global provider stack cannot prove
+ which concurrent Tracer owns the call, so content must stay disabled."""
+ from cubepi.agent.agent import Agent
+ from cubepi.mcp._tracing import mcp_client_span
+ from cubepi.providers.faux import FauxProvider
+ from cubepi.tracing import Tracer
+
+ secret = "Authorization: Bearer UNPARENTEDMCPSECRET"
+ exporter = _CaptureExporter()
+ provider = FauxProvider(provider_id="faux")
+ agent = Agent(model=provider.model("faux-1"), system_prompt="s")
+ tracer = Tracer(
+ service_name="t",
+ agent_name="a",
+ exporters=[exporter],
+ record_content=True,
+ )
+ detach = tracer.attach(agent)
+ try:
+ with pytest.raises(RuntimeError, match="UNPARENTEDMCPSECRET"):
+ async with mcp_client_span(
+ method="connect",
+ server_address="example.com",
+ ):
+ raise RuntimeError(secret)
+ finally:
+ detach()
+ await tracer.shutdown()
+
+ span = next(s for s in exporter.spans if s.name == "connect")
+ assert span.status.status_code == StatusCode.ERROR
+ assert span.status.description == "mcp client error"
+ event = next(event for event in span.events if event.name == "exception")
+ assert dict(event.attributes or {}) == {"exception.type": "RuntimeError"}
+ assert secret not in repr(dict(span.attributes or {}))
+
async def test_two_attaches_detach_one_keeps_other_routing(self):
"""When a Tracer is attached to two agents and one is detached,
the remaining agent's MCP spans must still land in the Tracer's
@@ -1004,7 +1179,11 @@ class TestMCPSpanParentage:
)
try:
# Innermost lookup is the inner tool while it is live.
- assert mcp_tracing._get_tool_span_entry() == ("span-inner", "prov-inner")
+ assert mcp_tracing._get_tool_span_entry() == (
+ "span-inner",
+ "prov-inner",
+ False,
+ )
async def _end_inner() -> None:
mcp_tracing.unregister_tool_span(tok_inner)
@@ -1013,7 +1192,11 @@ class TestMCPSpanParentage:
await _asyncio.create_task(_end_inner())
# Must fall back to the OUTER tool, not None.
- assert mcp_tracing._get_tool_span_entry() == ("span-outer", "prov-outer")
+ assert mcp_tracing._get_tool_span_entry() == (
+ "span-outer",
+ "prov-outer",
+ False,
+ )
finally:
mcp_tracing.unregister_tool_span(tok_outer)
diff --git a/tests/tracing/test_oneshot.py b/tests/tracing/test_oneshot.py
index 9ba27a2..179bacd 100644
--- a/tests/tracing/test_oneshot.py
+++ b/tests/tracing/test_oneshot.py
@@ -264,14 +264,15 @@ async def test_oneshot_generate_error_event_raises_and_marks_root() -> None:
provider = FauxProvider(provider_id="faux")
tracer, exporter = _make_tracer()
+ secret = "Authorization: Bearer ONESHOTSECRET"
error_stream = MessageStream()
- error_stream.push(StreamEvent(type="error", error_message="boom"))
+ error_stream.push(StreamEvent(type="error", error_message=secret))
error_stream.set_result(
- AssistantMessage(content=[], stop_reason="error", error_message="boom")
+ AssistantMessage(content=[], stop_reason="error", error_message=secret)
)
with patch.object(provider, "stream", new=AsyncMock(return_value=error_stream)):
- with pytest.raises(RuntimeError, match="boom"):
+ with pytest.raises(RuntimeError, match="ONESHOTSECRET"):
async with tracer.oneshot(model=provider.model(MODEL.id)) as session:
await session.generate(
system="sys",
@@ -286,8 +287,46 @@ async def test_oneshot_generate_error_event_raises_and_marks_root() -> None:
assert len(roots) == 1
root = roots[0]
assert root.status.status_code == StatusCode.ERROR
+ assert root.status.description == "oneshot error"
attrs = dict(root.attributes or {})
assert attrs.get("error.type") == "RuntimeError"
+ assert secret not in repr(attrs)
+ for event in root.events:
+ assert secret not in repr(dict(event.attributes or {}))
+
+
+async def test_oneshot_error_details_remain_available_with_content_opt_in() -> None:
+ from opentelemetry.trace import StatusCode
+ from unittest.mock import AsyncMock, patch
+
+ provider = FauxProvider(provider_id="faux")
+ tracer, exporter = _make_tracer(record_content=True)
+ diagnostic = "diagnostic oneshot failure"
+
+ error_stream = MessageStream()
+ error_stream.push(StreamEvent(type="error", error_message=diagnostic))
+ error_stream.set_result(
+ AssistantMessage(content=[], stop_reason="error", error_message=diagnostic)
+ )
+ with patch.object(provider, "stream", new=AsyncMock(return_value=error_stream)):
+ with pytest.raises(RuntimeError, match="diagnostic oneshot failure"):
+ async with tracer.oneshot(model=provider.model(MODEL.id)) as session:
+ await session.generate(
+ system="sys",
+ messages=[UserMessage(content=[TextContent(text="q")])],
+ max_output_tokens=10,
+ )
+
+ await tracer.force_flush()
+ await tracer.shutdown()
+
+ root = next(s for s in exporter.spans if s.name == "invoke_agent")
+ assert root.status.status_code == StatusCode.ERROR
+ assert diagnostic in (root.status.description or "")
+ assert any(
+ diagnostic in repr(dict(event.attributes or {})) for event in root.events
+ )
@pytest.mark.asyncio
@@ -598,9 +637,11 @@ async def test_oneshot_cancelled_generate_closes_chat_span() -> None:
# matching the agent path's contract.
roots = [s for s in exporter.spans if s.name == "invoke_agent"]
assert len(roots) == 1
- attrs = dict(roots[0].attributes or {})
+ root = roots[0]
+ attrs = dict(root.attributes or {})
assert attrs.get("cubepi.aborted") is True
assert attrs.get("error.type") == "cubepi.aborted"
+ assert not any(event.name == "exception" for event in root.events)
@pytest.mark.asyncio
diff --git a/tests/tracing/test_recorder_coverage.py b/tests/tracing/test_recorder_coverage.py
index 7c54c48..7dc3301 100644
--- a/tests/tracing/test_recorder_coverage.py
+++ b/tests/tracing/test_recorder_coverage.py
@@ -483,12 +483,16 @@ class TestStreamRecording:
assert len(files) == 1
files[0].read_text() # raises if file handle leaked
- async def test_stream_toolcall_events_recorded(self, tmp_path):
- """toolcall_start / toolcall_delta / toolcall_end events reach the stream file."""
+ async def test_stream_toolcall_events_hide_arguments_without_content_opt_in(
+ self, tmp_path
+ ):
+ """Stream timing stays available without persisting tool arguments."""
from pydantic import BaseModel
+ secret = "Bearer STREAMSECRET"
+
class P(BaseModel):
- pass
+ authorization: str
async def noop(tool_call_id: str, params: P, *, signal=None, on_update=None):
return AgentToolResult(content=[TextContent(text="done")])
@@ -498,7 +502,13 @@ class TestStreamRecording:
provider.append_responses(
[
faux_assistant_message(
- [ToolCall(id="tc1", name="noop", arguments={"x": 1})],
+ [
+ ToolCall(
+ id="tc1",
+ name="noop",
+ arguments={"authorization": secret},
+ )
+ ],
stop_reason="tool_use",
),
faux_assistant_message("all done"),
@@ -520,17 +530,22 @@ class TestStreamRecording:
files = list(tmp_path.glob("*.stream.jsonl"))
assert len(files) == 1
- events = [
- json.loads(line) for line in files[0].read_text().splitlines() if line
- ]
+ raw_stream = files[0].read_text()
+ assert secret not in raw_stream
+ events = [json.loads(line) for line in raw_stream.splitlines() if line]
types = [e["type"] for e in events]
assert "toolcall_start" in types
assert "toolcall_delta" in types
assert "toolcall_end" in types
- # toolcall_end should carry accumulated arg char count
+ # Structural telemetry remains, but argument deltas/previews are content.
+ delta_ev = next(e for e in events if e["type"] == "toolcall_delta")
+ assert "chars" in delta_ev
+ assert "accumulated" in delta_ev
+ assert "preview" not in delta_ev
end_ev = next(e for e in events if e["type"] == "toolcall_end")
assert "args_chars" in end_ev
assert end_ev["args_chars"] > 0
+ assert "args_preview" not in end_ev
async def test_no_stream_file_without_record_stream(self, tmp_path):
"""Default (record_stream=False) must not create any stream file."""
@@ -585,6 +600,7 @@ class TestStreamRecording:
service_name="t",
agent_name="a",
exporters=[],
+ record_content=True,
record_stream=True,
stream_dir=tmp_path,
)
@@ -602,7 +618,40 @@ class TestStreamRecording:
types = [e["type"] for e in events]
assert "error" in types
err_ev = next(e for e in events if e["type"] == "error")
- assert "error_message" in err_ev
+ assert err_ev["error_message"] == "boom"
+
+ async def test_stream_error_hides_message_without_content_opt_in(self, tmp_path):
+ secret = "Authorization: Bearer STREAMSECRET"
+ provider = FauxProvider(provider_id="faux")
+ provider.append_responses(
+ [
+ faux_assistant_message(
+ "oops",
+ stop_reason="error",
+ error_message=secret,
+ )
+ ]
+ )
+ agent = Agent(model=provider.model(MODEL.id), system_prompt="s")
+ tracer = Tracer(
+ service_name="t",
+ agent_name="a",
+ exporters=[],
+ record_stream=True,
+ stream_dir=tmp_path,
+ )
+ tracer.attach(agent)
+
+ await agent.prompt("x")
+ await agent.wait_for_idle()
+ await tracer.shutdown()
+
+ stream_file = next(tmp_path.glob("*.stream.jsonl"))
+ raw_stream = stream_file.read_text()
+ assert secret not in raw_stream
+ events = [json.loads(line) for line in raw_stream.splitlines() if line]
+ err_ev = next(e for e in events if e["type"] == "error")
+ assert err_ev["error_message"] == "provider error"
async def test_stream_write_exception_swallowed(self, tmp_path):
"""If the stream file write raises, _write_stream_event swallows it silently."""
diff --git a/website/docs/guides/tracing/content-recording.md b/website/docs/guides/tracing/content-recording.md
index a469c95..f6da04f 100644
--- a/website/docs/guides/tracing/content-recording.md
+++ b/website/docs/guides/tracing/content-recording.md
@@ -7,10 +7,11 @@ sidebar_position: 4
# Recording Prompts, Responses, and Tool Payloads
By default CubePi's tracing emits structural attributes only — operation
-names, models, token counts, finish reasons, durations. **No prompt content,
-no model output, no tool arguments or results leave the process.** This is
-deliberate: many agent setups handle PII, customer data, or trade-secret
-prompts that don't belong in a third-party observability backend.
+names, models, token counts, finish reasons, durations, and typed error classes.
+**No prompt content, model output, tool arguments/results, raw exception text,
+or exception stack traces leave the process.** This is deliberate: many agent
+setups handle PII, customer data, or trade-secret prompts that don't belong in
+a third-party observability backend.
When you _do_ want content captured — for offline evaluation, debugging a
flaky tool call, or building a labelled dataset — opt in explicitly with
@@ -38,6 +39,10 @@ attributes per the OTel GenAI semconv:
| `chat <model>` | `gen_ai.system_instructions`, `gen_ai.input.messages`, `gen_ai.tool.definitions`, `cubepi.llm.raw_request`, `cubepi.llm.raw_response` |
| `execute_tool <tool_name>` | `gen_ai.tool.call.arguments`, `gen_ai.tool.call.result` |
+Developer-authored agent and tool descriptions are treated as operational
+metadata and are exported regardless of `record_content`; do not place secrets
+or per-request user data in description strings.
+
The `chat` span's `gen_ai.input.messages` contains the **full chronological
context** the provider request actually carried — including prior assistant
turns and tool results — not just the new user prompt. This matters for
@@ -131,8 +136,10 @@ tracer = Tracer(
`record_stream` writes `<stream_dir>/<run_id>.stream.jsonl` (one JSON line per
`StreamEvent`). Every line carries `t` (elapsed seconds from run start) and
-`type`. Tool-call lines also include `ci` (content index), `id`, `name`, delta
-sizes, and argument previews:
+`type`. Tool-call lines also include structural fields such as `ci` (content
+index), `id`, `name`, delta sizes, and accumulated argument length. When
+`record_content=True`, they additionally include argument previews, and error
+events include the raw provider error message:
```json
{"t": 5.873, "type": "toolcall_start", "ci": 1, "id": "toolu_...", "name": "show_widget"}
@@ -144,8 +151,11 @@ This makes it straightforward to confirm whether argument chunks ever arrived, o
whether the same event fired twice (e.g. a provider that sends `finish_reason`
twice produces two `toolcall_end` lines for the same `ci`).
-`record_stream` is independent of `record_content` — turn it on only in debugging
-sessions. Files can grow large for long-running, tool-heavy agents.
+`record_stream` is independent of `record_content`: it can retain structural
+chunk timing and size evidence without content recording. Raw tool-argument
+previews and raw error messages still require `record_content=True`. Turn stream
+recording on only in debugging sessions; files can grow large for long-running,
+tool-heavy agents.
## Auditing what's recorded
diff --git a/website/docs/guides/tracing/getting-started.md b/website/docs/guides/tracing/getting-started.md
index b44a30c..457c9dc 100644
--- a/website/docs/guides/tracing/getting-started.md
+++ b/website/docs/guides/tracing/getting-started.md
@@ -137,21 +137,23 @@ instrumented MCP server can continue the trace.
The recorder treats cancellation as a control signal, not a failure:
-- `agent.abort()` mid-stream → spans close with `cubepi.aborted=true` and
- `error.type=cubepi.aborted`, **status UNSET** (per OTel guidance — cancellation
- isn't an error).
+- `agent.abort()` or a cancelled one-shot call → affected spans close with
+ `cubepi.aborted=true` and `error.type=cubepi.aborted`, **status UNSET**, and no
+ exception event (per OTel guidance — cancellation isn't an error).
- `agent.detach()` at a durable HITL prompt → open spans close with
`cubepi.run.outcome=suspended` and no aborted/error classification. A later
`respond()` is a new activation trace; correlate the two with metadata such as
a host run or conversation ID.
-- A provider raising → chat/turn/root close with **status ERROR**, an
- `exception` event on the chat span, and `error.type` derived from the
- exception class (`timeout`, `connection_error`, fully-qualified class name, …).
- With the default `record_content=False`, the status description is generic and
- the event contains only `exception.type`; raw exception messages and stack
- traces are included only when content recording is explicitly enabled.
-- An MCP `tools/call` returning `isError=true` → CLIENT span closes
- ERROR + `error.type=mcp.is_error`.
+- A provider or one-shot call raising → affected spans close with **status
+ ERROR** and `error.type` derived from the exception class (`timeout`,
+ `connection_error`, fully-qualified class name, …). With the default
+ `record_content=False`, status descriptions are generic and exception events
+ contain only `exception.type`; raw exception messages and stack traces are
+ included only when content recording is explicitly enabled.
+- An MCP transport raising follows the same privacy rule on its CLIENT span. An
+ MCP `tools/call` returning `isError=true` closes the CLIENT span with ERROR +
+ `error.type=mcp.is_error`; its status description is also generic unless
+ content recording is enabled.
In every case, `detach()` and `tracer.shutdown()` close any span the activation
left open, so cancelled and suspended runs remain visible in your backend rather
@@ -185,8 +187,9 @@ Optional, opt-in via `Tracer(record_content=True)`:
`gen_ai.input.messages`, `gen_ai.output.messages`, `gen_ai.system_instructions`,
`gen_ai.tool.definitions`, `gen_ai.tool.call.arguments`,
`gen_ai.tool.call.result`, `cubepi.llm.raw_request`,
-`cubepi.llm.raw_response`, provider exception messages, and provider exception
-stack traces. See [Content & Redaction](./content-recording).
+`cubepi.llm.raw_response`, provider/MCP/one-shot exception messages and stack
+traces, and stream-log tool-argument/error previews. See
+[Content & Redaction](./content-recording).
## Multiple agents, one process