CubeLoop — a Pythonic, async-native agent harness core designed for high performance, readability, and production-grade persistence.
Python agent-frameworkagent-harnessagent-runtimeagentic-aiai-agentsai-frameworkanthropicharnessharness-engineeringharness-frameworklanggraphlanggraph-alternativellmmcpopenaipi-agentpi-agent-corepythonpython-agent
feat(tracing): add Tracer/Meter.attached(agent) async context managers (#90)
Chrisfa89c78280e7
diff --git a/cubepi/tracing/meter.py b/cubepi/tracing/meter.pyindex 7125ae6..1bfe950 100644--- a/cubepi/tracing/meter.py+++ b/cubepi/tracing/meter.py@@ -16,9 +16,10 @@ Histograms emitted (per OTel GenAI semconv):from __future__ import annotations+import contextlibimport timefrom dataclasses import dataclass, field-from typing import TYPE_CHECKING, Any, Callable+from typing import TYPE_CHECKING, Any, AsyncIterator, Callablefrom opentelemetry.sdk.metrics import MeterProviderfrom opentelemetry.sdk.metrics.export import (@@ -200,6 +201,35 @@ class Meter:self._provider.shutdown()self._shutdown = True+ @contextlib.asynccontextmanager+ async def attached(self, agent: "Agent") -> AsyncIterator["Meter"]:+ """RAII wrapper around :meth:`attach`.++ ``async with`` enters by attaching the per-attach state, exits+ by calling the detach callable returned from :meth:`attach`.+ Mirrors :meth:`Tracer.attached` — use both for the cleanest+ end-to-end shutdown:++ ::++ async with (+ Tracer(...) as tracer,+ Meter(resource=tracer.resource, ...) as meter,+ tracer.attached(agent),+ meter.attached(agent),+ ):+ await agent.prompt("...")+ # auto: detach both + shutdown both+ """+ detach = self.attach(agent)+ try:+ yield self+ finally:+ try:+ detach()+ except Exception:+ pass+async def __aenter__(self) -> "Meter":return selfdiff --git a/cubepi/tracing/tracer.py b/cubepi/tracing/tracer.pyindex 8d5d1b2..9a96e92 100644--- a/cubepi/tracing/tracer.py+++ b/cubepi/tracing/tracer.py@@ -8,8 +8,9 @@ the agent's event stream.from __future__ import annotations+import contextlibimport uuid-from typing import TYPE_CHECKING, Any, Callable+from typing import TYPE_CHECKING, Any, AsyncIterator, Callablefrom opentelemetry.sdk.resources import Resourcefrom opentelemetry.sdk.trace import TracerProvider@@ -209,6 +210,56 @@ class Tracer:self._provider.shutdown()self._shutdown = True+ @contextlib.asynccontextmanager+ async def attached(self, agent: "Agent") -> AsyncIterator["Tracer"]:+ """RAII wrapper around :meth:`attach`.++ ``async with`` enters by attaching the recorder, exits by+ running detach and (in an async context) awaiting its returned+ flush ``Task``. Equivalent to::++ detach = tracer.attach(agent)+ try:+ ...+ finally:+ result = detach()+ if result is not None: # async context: it's a Task+ await result++ Use this instead of the bare ``attach`` / ``finally: detach()``+ pattern when you want the cleanup tied to a single ``async+ with`` block. Combines with :class:`Tracer`'s own context+ manager:++ ::++ async with Tracer(...) as tracer, tracer.attached(agent):+ await agent.prompt("...")+ # auto: detach (closes cancelled spans) + shutdown (flush + close)+ """+ import sys++ detach = self.attach(agent)+ try:+ yield self+ finally:+ result = detach()+ if result is not None and hasattr(result, "__await__"):+ # Surface flush failures to the caller when the body+ # didn't raise — matches what ``await detach()`` would+ # do manually, so users don't continue past the block+ # believing spans were exported when they weren't.+ # When the body did raise, suppress flush errors so+ # the original (more diagnostic) exception isn't+ # masked by a cleanup failure (codex review on PR #90).+ if sys.exc_info()[1] is None:+ await result+ else:+ try:+ await result+ except BaseException:+ pass+async def __aenter__(self) -> "Tracer":return selfdiff --git a/tests/tracing/test_meter.py b/tests/tracing/test_meter.pyindex 029142a..ee37023 100644--- a/tests/tracing/test_meter.py+++ b/tests/tracing/test_meter.py@@ -269,6 +269,68 @@ class TestConcurrentAgents:)+class TestAttachedContextManager:+ """``Meter.attached(agent)`` mirrors ``Tracer.attached`` — RAII+ wrapper that detaches on exit."""++ async def test_basic_usage(self):+ provider = FauxProvider()+ provider.append_responses([faux_assistant_message("ok")])+ agent = Agent(provider=provider, model=MODEL, system_prompt="s")+ meter, reader = _build_meter()++ async with meter.attached(agent):+ await agent.prompt("hi")+ await agent.wait_for_idle()++ points = _all_metric_points(reader)+ durations = _by_name(points, "gen_ai.client.operation.duration")+ assert len(durations) >= 2 # chat + invoke_agent++ async def test_exception_inside_block_still_detaches(self):+ provider = FauxProvider()+ agent = Agent(provider=provider, model=MODEL, system_prompt="s")+ meter, _reader = _build_meter()+ try:+ async with meter.attached(agent):+ raise RuntimeError("boom")+ except RuntimeError:+ pass+ # Re-attach must not pile up duplicate listeners.+ async with meter.attached(agent):+ pass+++class TestAttachedDefensiveBranches:+ """``Meter.attached`` swallows any exception raised by the detach+ callable so that an aborted run cleanup doesn't propagate over a+ healthy body return — covers the defensive branch."""++ async def test_swallows_detach_exception(self):+ provider = FauxProvider()+ provider.append_responses([faux_assistant_message("ok")])+ agent = Agent(provider=provider, model=MODEL, system_prompt="s")+ meter, _reader = _build_meter()++ # Patch attach to return a detach that raises.+ original_attach = meter.attach++ def _attach_with_bad_detach(_agent):+ real_detach = original_attach(_agent)++ def _bad_detach():+ real_detach()+ raise RuntimeError("detach boom")++ return _bad_detach++ meter.attach = _attach_with_bad_detach # type: ignore[method-assign]+ # Body completes; detach raises; helper must swallow.+ async with meter.attached(agent):+ pass # no body work needed+ # If we got here, the swallow worked.++class TestNoMetricsWithoutListeners:async def test_detach_stops_emission(self):provider = FauxProvider()diff --git a/tests/tracing/test_recorder.py b/tests/tracing/test_recorder.pyindex e3020f0..0721fe9 100644--- a/tests/tracing/test_recorder.py+++ b/tests/tracing/test_recorder.py@@ -779,6 +779,142 @@ class TestTranscriptSeedingDefensiveBranches:assert recorder._run.transcript == []+class TestAttachedContextManager:+ """``Tracer.attached(agent)`` is the RAII wrapper around+ ``attach`` / ``detach``. Pin: the body runs with the recorder+ attached, the exit path runs the same cleanup as a manual+ ``detach()`` call (closes any cancelled-run spans, schedules and+ awaits the flush), and the next attach on the same agent doesn't+ pile up handlers."""++ async def test_basic_usage(self):+ provider = FauxProvider()+ agent = Agent(provider=provider, model=MODEL, system_prompt="s")+ exporter = InMemoryExporter()+ tracer = Tracer(service_name="t", agent_name="a", exporters=[exporter])+ provider.append_responses([faux_assistant_message("ok")])++ async with tracer.attached(agent):+ await agent.prompt("hi")+ await agent.wait_for_idle()++ # After the block, spans have been flushed.+ names = {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)++ async def test_cancellation_inside_block_still_closes_spans(self):+ provider = FauxProvider(tokens_per_second=10.0)+ agent = Agent(provider=provider, model=MODEL, system_prompt="s")+ exporter = InMemoryExporter()+ tracer = Tracer(service_name="t", agent_name="a", exporters=[exporter])+ provider.append_responses([faux_assistant_message("x" * 400)])++ async with tracer.attached(agent):+ run = asyncio.create_task(agent.prompt("hi"))+ await asyncio.sleep(0.05)+ run.cancel()+ try:+ await run+ except asyncio.CancelledError:+ pass+ # The async exit ran detach + awaited flush.+ names = {s.name for s in exporter.spans}+ assert "invoke_agent" in names, (+ f"cancelled run's invoke_agent span did not export; got {names}"+ )+ # Each open-at-cancel span carries cubepi.aborted.+ for span in exporter.spans:+ if span.name == "invoke_agent" or span.name == "cubepi.turn":+ attrs = _attrs(span)+ assert attrs.get("cubepi.aborted") is True++ async def test_exception_inside_block_still_detaches(self):+ provider = FauxProvider()+ agent = Agent(provider=provider, model=MODEL, system_prompt="s")+ tracer = Tracer(service_name="t", agent_name="a", exporters=[])++ try:+ async with tracer.attached(agent):+ raise RuntimeError("boom")+ except RuntimeError:+ pass+ # Exception propagated; the recorder must be detached so it+ # can be attached again to a different agent without piling up+ # subscriptions on the original.+ async with tracer.attached(agent):+ pass # no-op; should not error or warn++ async def test_flush_exception_surfaces_when_body_ok(self):+ """If the post-block flush fails and the body itself did NOT+ raise, the exception must surface to the caller — same as+ what ``await detach()`` would do manually. Otherwise users+ continue past the block thinking spans landed (codex P2 on+ PR #90)."""+ provider = FauxProvider()+ agent = Agent(provider=provider, model=MODEL, system_prompt="s")+ tracer = Tracer(service_name="t", agent_name="a", exporters=[])+ provider.append_responses([faux_assistant_message("ok")])++ sentinel = RuntimeError("flush exploded")++ async def _bad_flush(*_a, **_kw):+ raise sentinel++ # Patch the underlying force_flush to fail.+ import cubepi.tracing.tracer as _t_mod++ original = tracer.force_flush+ tracer.force_flush = _bad_flush # type: ignore[method-assign]+ try:+ with __import__("pytest").raises(RuntimeError, match="flush exploded"):+ async with tracer.attached(agent):+ await agent.prompt("hi")+ await agent.wait_for_idle()+ finally:+ tracer.force_flush = original # type: ignore[method-assign]+ del _t_mod++ async def test_flush_exception_suppressed_when_body_raises(self):+ """When the body raised, the flush failure must NOT mask the+ original exception — the body's exception is the real+ problem. Matches the standard contextlib pattern."""+ provider = FauxProvider()+ agent = Agent(provider=provider, model=MODEL, system_prompt="s")+ tracer = Tracer(service_name="t", agent_name="a", exporters=[])++ async def _bad_flush(*_a, **_kw):+ raise RuntimeError("flush exploded")++ tracer.force_flush = _bad_flush # type: ignore[method-assign]+ try:+ with __import__("pytest").raises(ValueError, match="body"):+ async with tracer.attached(agent):+ raise ValueError("body")+ finally:+ pass++ async def test_combined_with_tracer_async_with(self):+ """The intended top-level idiom — Tracer + attached in one+ ``async with`` line.+ """+ provider = FauxProvider()+ agent = Agent(provider=provider, model=MODEL, system_prompt="s")+ provider.append_responses([faux_assistant_message("ok")])+ exporter = InMemoryExporter()++ async with (+ Tracer(service_name="t", agent_name="a", exporters=[exporter]) as tracer,+ tracer.attached(agent),+ ):+ await agent.prompt("x")+ await agent.wait_for_idle()+ # Tracer is shut down; further use raises.+ assert tracer._shutdown is True+ assert exporter.spans++class TestLifecycle:async def test_shutdown_is_idempotent(self):agent, provider, exporter, tracer = await _build()