Skip to content

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

fix(tracing): make Tracer/Recorder attach atomic (#102)

Chris3a1d67753f31
diff --git a/cubepi/tracing/recorder.py b/cubepi/tracing/recorder.py
index 364363f..850cafe 100644
--- a/cubepi/tracing/recorder.py
+++ b/cubepi/tracing/recorder.py
@@ -203,14 +203,32 @@ class Recorder:
# 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)
- )
+ # Attach must be all-or-nothing: if a later subscription raises, unwind
+ # the ones already registered (incl. the agent listener) and re-raise,
+ # so a failed attach() leaves no dangling listeners. The caller never
+ # gets a ``detach`` callable on this path, so we cannot defer cleanup.
+ try:
+ 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)
+ )
+ except BaseException:
+ for d in provider_detachers:
+ try:
+ d()
+ except Exception:
+ pass
+ try:
+ unsub_agent()
+ except Exception:
+ pass
+ raise
def _sync_detach() -> None:
"""All synchronous cleanup: unsubscribe + close any spans
diff --git a/cubepi/tracing/tracer.py b/cubepi/tracing/tracer.py
index 6ed0cdf..bdf7d2a 100644
--- a/cubepi/tracing/tracer.py
+++ b/cubepi/tracing/tracer.py
@@ -185,6 +185,10 @@ class Tracer:
# removes this attach's registration — multiple attaches of the
# same Tracer to different agents must not clobber each other
# (see codex round-6 review on PR #86).
+ #
+ # Keep attach all-or-nothing: if MCP registration fails for any reason
+ # other than the optional module being absent, undo the recorder attach
+ # before re-raising so we don't leak its subscriptions.
mcp_token: object | None = None
try:
from cubepi.mcp import _tracing as mcp_tracing
@@ -192,6 +196,12 @@ class Tracer:
mcp_token = mcp_tracing.register_provider(self._provider)
except ImportError: # pragma: no cover — mcp module always present
mcp_tracing = None
+ except BaseException:
+ try:
+ recorder_detach()
+ except Exception:
+ pass
+ raise
def detach():
# Forward the recorder's detach return — when called from
diff --git a/tests/tracing/test_attach_atomicity.py b/tests/tracing/test_attach_atomicity.py
new file mode 100644
index 0000000..b01cb16
--- /dev/null
+++ b/tests/tracing/test_attach_atomicity.py
@@ -0,0 +1,140 @@
+"""Attach atomicity: a failed ``Tracer.attach`` / ``Recorder.attach`` must
+leave no dangling listener subscriptions behind.
+
+``attach`` wires several subscriptions (agent event listener + three provider
+listeners, then an MCP provider registration). If any step raises partway, the
+subscriptions registered before it would otherwise leak — the caller never
+receives a ``detach`` callable, so it cannot clean them up. These tests pin the
+contract: attach is all-or-nothing.
+"""
+
+from __future__ import annotations
+
+import pytest
+
+from cubepi.agent.agent import Agent
+from cubepi.providers.base import Model
+from cubepi.providers.faux import FauxProvider
+from cubepi.tracing import Tracer
+
+MODEL = Model(id="faux-1", provider="faux")
+
+
+def _build_unattached() -> tuple[Agent, FauxProvider, Tracer]:
+ from opentelemetry.sdk.trace.export import SpanExporter, SpanExportResult
+
+ 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
+
+ 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
+
+
+def _assert_no_listeners(agent: Agent, provider: FauxProvider) -> None:
+ assert agent._listeners == [], "agent event listener leaked after failed attach"
+ assert provider._request_listeners == [], "provider request listener leaked"
+ assert provider._chunk_listeners == [], "provider chunk listener leaked"
+ assert provider._response_listeners == [], "provider response listener leaked"
+
+
+async def test_recorder_attach_unwinds_on_partial_provider_subscription_failure():
+ agent, provider, tracer = _build_unattached()
+ try:
+ # subscribe_request succeeds, subscribe_chunk blows up midway.
+ def _boom(cb): # noqa: ANN001, ANN202
+ raise RuntimeError("subscribe_chunk failed")
+
+ provider.subscribe_chunk = _boom # type: ignore[method-assign]
+
+ with pytest.raises(RuntimeError, match="subscribe_chunk failed"):
+ tracer.attach(agent)
+
+ _assert_no_listeners(agent, provider)
+ finally:
+ await tracer.shutdown()
+
+
+async def test_tracer_attach_unwinds_recorder_on_mcp_register_failure(monkeypatch):
+ agent, provider, tracer = _build_unattached()
+ try:
+ import cubepi.mcp._tracing as mcp_tracing
+
+ def _boom(_provider): # noqa: ANN001, ANN202
+ raise RuntimeError("register_provider failed")
+
+ monkeypatch.setattr(mcp_tracing, "register_provider", _boom)
+
+ with pytest.raises(RuntimeError, match="register_provider failed"):
+ tracer.attach(agent)
+
+ _assert_no_listeners(agent, provider)
+ finally:
+ await tracer.shutdown()
+
+
+async def test_recorder_attach_cleanup_swallows_detacher_errors(monkeypatch):
+ """Unwind itself must be fault-tolerant: a detach callable raising during
+ cleanup is swallowed so the ORIGINAL subscription error is what surfaces."""
+ agent, provider, tracer = _build_unattached()
+ try:
+
+ def _raising_detacher(): # noqa: ANN202
+ raise RuntimeError("detacher boom")
+
+ def _raising_unsub(): # noqa: ANN202
+ raise RuntimeError("unsub boom")
+
+ # subscribe_request "succeeds" but hands back a detacher that blows up
+ # during unwind; the agent unsubscribe also blows up.
+ monkeypatch.setattr(provider, "subscribe_request", lambda cb: _raising_detacher)
+ monkeypatch.setattr(agent, "subscribe", lambda listener: _raising_unsub)
+
+ def _boom_chunk(cb): # noqa: ANN001, ANN202
+ raise RuntimeError("subscribe_chunk failed")
+
+ monkeypatch.setattr(provider, "subscribe_chunk", _boom_chunk)
+
+ with pytest.raises(RuntimeError, match="subscribe_chunk failed"):
+ tracer.attach(agent)
+ finally:
+ await tracer.shutdown()
+
+
+async def test_tracer_attach_cleanup_swallows_recorder_detach_error(monkeypatch):
+ """If MCP registration fails AND the recorder's own detach raises during
+ unwind, the original register error must still surface."""
+ agent, provider, tracer = _build_unattached()
+ try:
+
+ def _raising_unsub(): # noqa: ANN202
+ raise RuntimeError("unsub boom")
+
+ # recorder.attach succeeds, but its detach will raise (agent unsub
+ # raises inside the recorder's synchronous cleanup).
+ monkeypatch.setattr(agent, "subscribe", lambda listener: _raising_unsub)
+
+ import cubepi.mcp._tracing as mcp_tracing
+
+ def _boom(_provider): # noqa: ANN001, ANN202
+ raise RuntimeError("register_provider failed")
+
+ monkeypatch.setattr(mcp_tracing, "register_provider", _boom)
+
+ with pytest.raises(RuntimeError, match="register_provider failed"):
+ tracer.attach(agent)
+ finally:
+ await tracer.shutdown()