Skip to content

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

feat(tracing): add best-effort trace() scope helper

xf gong6c31b5123e01
diff --git a/cubepi/tracing/__init__.py b/cubepi/tracing/__init__.py
index 007288c..8ce311e 100644
--- a/cubepi/tracing/__init__.py
+++ b/cubepi/tracing/__init__.py
@@ -22,6 +22,7 @@ __all__ = [
"Meter",
"SCHEMA_URL",
"Tracer",
+ "trace",
"tracing_context",
]
@@ -30,7 +31,7 @@ if TYPE_CHECKING: # pragma: no cover
from cubepi.tracing.exporters import JsonlSpanExporter
from cubepi.tracing.meter import Meter
from cubepi.tracing.schema import SCHEMA_URL
- from cubepi.tracing.tracer import Tracer
+ from cubepi.tracing.tracer import Tracer, trace
_LAZY = {
"tracing_context": ("cubepi.tracing.context", "tracing_context"),
@@ -38,6 +39,7 @@ _LAZY = {
"Meter": ("cubepi.tracing.meter", "Meter"),
"SCHEMA_URL": ("cubepi.tracing.schema", "SCHEMA_URL"),
"Tracer": ("cubepi.tracing.tracer", "Tracer"),
+ "trace": ("cubepi.tracing.tracer", "trace"),
}
diff --git a/cubepi/tracing/tracer.py b/cubepi/tracing/tracer.py
index bdf7d2a..07b959a 100644
--- a/cubepi/tracing/tracer.py
+++ b/cubepi/tracing/tracer.py
@@ -10,6 +10,7 @@ from __future__ import annotations
import atexit
import contextlib
+import logging
import uuid
from typing import TYPE_CHECKING, Any, AsyncIterator, Callable
@@ -379,3 +380,66 @@ def _build_resource(
attrs["gen_ai.agent.version"] = agent_version
# The SDK adds telemetry.sdk.* automatically.
return Resource.create(attrs, schema_url=SCHEMA_URL)
+
+
+async def trace(
+ tracer: "Tracer | None",
+ agent: "Agent",
+) -> AsyncIterator[None]:
+ """Best-effort tracing scope for one agent run.
+
+ Attaches ``tracer`` to ``agent`` on enter and detaches + flushes its
+ buffered spans on exit. Every tracing fault — a failed attach, detach, or
+ flush — is logged and swallowed, so tracing can never break or fail the
+ work inside the ``async with`` block. Passing ``tracer=None`` makes the
+ block a no-op, which lets callers gate tracing on config without branching
+ at the call site.
+
+ This does **not** shut the tracer down: the tracer is reusable across runs,
+ so build it once (e.g. per process) and call ``await tracer.shutdown()``
+ when the owning process stops.
+
+ Unlike :meth:`Tracer.attached`, which surfaces flush failures to the caller,
+ this helper swallows them — use it when tracing is auxiliary to the work and
+ must never affect its outcome.
+
+ Example
+ -------
+ ::
+
+ async with trace(tracer, agent):
+ await agent.prompt("...")
+ """
+ if tracer is None:
+ yield
+ return
+
+ detach: "Callable[[], Any] | None" = None
+ try:
+ detach = tracer.attach(agent)
+ except Exception as exc: # noqa: BLE001 — tracing must never break the run
+ _log_tracing_warning("attach failed; running untraced", exc)
+ detach = None
+
+ try:
+ yield
+ finally:
+ if detach is not None:
+ try:
+ result = detach()
+ # In an async context ``detach()`` returns a flush Task; await
+ # it so this run's spans are exported before the block exits.
+ if result is not None and hasattr(result, "__await__"):
+ await result
+ except Exception as exc: # noqa: BLE001 — flush/detach must never break the run
+ _log_tracing_warning("detach/flush failed", exc)
+
+
+def _log_tracing_warning(message: str, exc: BaseException) -> None:
+ """Log a swallowed tracing fault via stdlib ``logging`` — cubepi does not
+ depend on loguru. Hosts that use loguru can intercept stdlib logging to
+ route these records through it."""
+ logging.getLogger("cubepi.tracing").warning(
+ "cubepi tracing: %s", message, exc_info=exc
+ )
diff --git a/tests/tracing/test_trace_scope.py b/tests/tracing/test_trace_scope.py
new file mode 100644
index 0000000..254247b
--- /dev/null
+++ b/tests/tracing/test_trace_scope.py
@@ -0,0 +1,114 @@
+"""The ``trace`` best-effort scope helper.
+
+``trace(tracer, agent)`` is a context manager that attaches the tracer on
+enter and detaches + flushes on exit, swallowing every tracing fault so that
+tracing can never break or fail the wrapped work. ``tracer=None`` is a no-op.
+These tests pin that contract: attach/detach lifecycle on the happy path, and
+silent fallback on attach / flush failures.
+"""
+
+from __future__ import annotations
+
+from opentelemetry.sdk.trace.export import SpanExporter, SpanExportResult
+
+from cubepi.agent.agent import Agent
+from cubepi.providers.base import Model
+from cubepi.providers.faux import FauxProvider
+from cubepi.tracing import Tracer, trace
+
+MODEL = Model(id="faux-1", provider="faux")
+
+
+class _NullExporter(SpanExporter):
+ def export(self, spans): # noqa: ANN001
+ return SpanExportResult.SUCCESS
+
+ def shutdown(self) -> None:
+ pass
+
+ def force_flush(self, timeout_millis: int = 30_000) -> bool:
+ return True
+
+
+def _build() -> tuple[Agent, FauxProvider, Tracer]:
+ provider = FauxProvider()
+ agent = Agent(provider=provider, model=MODEL, system_prompt="t")
+ tracer = Tracer(
+ service_name="t",
+ agent_name="t",
+ exporters=[_NullExporter()],
+ atexit_flush=False,
+ )
+ return agent, provider, tracer
+
+
+async def test_trace_none_is_noop():
+ agent, _provider, tracer = _build()
+ try:
+ ran = False
+ async with trace(None, agent):
+ ran = True
+ assert ran
+ assert agent._listeners == [], (
+ "no listeners should be attached when tracer is None"
+ )
+ finally:
+ await tracer.shutdown()
+
+
+async def test_trace_attaches_within_scope_and_detaches_after():
+ agent, provider, tracer = _build()
+ try:
+ assert agent._listeners == []
+ async with trace(tracer, agent):
+ assert len(agent._listeners) == 1, (
+ "recorder should be attached inside the scope"
+ )
+ assert len(provider._request_listeners) == 1
+ assert len(provider._chunk_listeners) == 1
+ assert len(provider._response_listeners) == 1
+ assert agent._listeners == [], "recorder should be detached after the scope"
+ assert provider._request_listeners == []
+ assert provider._chunk_listeners == []
+ assert provider._response_listeners == []
+ finally:
+ await tracer.shutdown()
+
+
+async def test_trace_swallows_attach_failure(monkeypatch):
+ agent, _provider, tracer = _build()
+ try:
+
+ def _boom(_listener): # noqa: ANN202
+ raise RuntimeError("attach boom")
+
+ monkeypatch.setattr(agent, "subscribe", _boom)
+
+ ran = False
+ async with trace(tracer, agent): # must not raise
+ ran = True
+ assert ran, "body must run even when attach fails"
+ finally:
+ await tracer.shutdown()
+
+
+async def test_trace_swallows_flush_failure(monkeypatch):
+ agent, provider, tracer = _build()
+ try:
+
+ async def _boom_flush(*_args, **_kwargs): # noqa: ANN202
+ raise RuntimeError("flush boom")
+
+ monkeypatch.setattr(tracer, "force_flush", _boom_flush)
+
+ ran = False
+ async with trace(tracer, agent):
+ ran = True
+ assert ran, "body must run even when flush fails on exit"
+ # Synchronous detach still ran before the flush failure.
+ assert agent._listeners == []
+ assert provider._request_listeners == []
+ finally:
+ # Restore the real force_flush so shutdown() can clean up.
+ monkeypatch.undo()
+ await tracer.shutdown()