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
fix(tracing): don't let middleware providers clobber root attribution
xf gong2b8c0901c885
diff --git a/cubepi/tracing/recorder.py b/cubepi/tracing/recorder.pyindex 8b55569..caa42e1 100644--- a/cubepi/tracing/recorder.py+++ b/cubepi/tracing/recorder.py@@ -234,10 +234,26 @@ class Recorder:provider = getattr(agent, "_provider", None) or getattr(agent, "provider", None)provider_detachers: list[Callable[[], None]] = []- def _subscribe(p: Any) -> None:+ def _subscribe(p: Any, *, is_main: bool) -> None:if not isinstance(p, BaseProvider):return- provider_detachers.append(p.subscribe_request(self._on_provider_request))+ # Middleware-driven providers must not write to the root+ # ``invoke_agent`` span's attribution attributes — the root+ # represents the agent invocation, not a per-middleware+ # detour. Without this gate the first middleware request+ # (typically ``CompactionMiddleware`` firing in+ # ``transform_context`` before the agent's own model call)+ # would clobber ``gen_ai.provider.name`` /+ # ``cubepi.agent.system_prompt_sha256`` /+ # ``cubepi.agent.tools`` with the summarizer's values, and+ # provider-level trace filters / aggregate metrics would+ # mis-attribute the whole run to the summarizer's provider.+ on_request = (+ self._on_provider_request+ if is_main+ else self._on_extra_provider_request+ )+ provider_detachers.append(p.subscribe_request(on_request))provider_detachers.append(p.subscribe_chunk(self._on_provider_chunk))provider_detachers.append(p.subscribe_response(self._on_provider_response))@@ -246,7 +262,7 @@ class Recorder:# so a failed attach() leaves no dangling listeners. The caller never# gets a ``detach`` callable on this path, so we cannot defer cleanup.try:- _subscribe(provider)+ _subscribe(provider, is_main=True)# Middlewares may drive their own LLM providers (e.g.# ``CompactionMiddleware``'s summary provider) — wire them too# so those calls show up in the trace tree instead of@@ -263,7 +279,7 @@ class Recorder:if id(p) in seen:continueseen.add(id(p))- _subscribe(p)+ _subscribe(p, is_main=False)except BaseException:for d in provider_detachers:try:@@ -888,7 +904,15 @@ class Recorder:# Provider listeners — drive the chat span lifetime# ------------------------------------------------------------------- def _on_provider_request(self, payload: dict, model: "Model") -> None:+ def _on_extra_provider_request(self, payload: dict, model: "Model") -> None:+ """Variant for middleware-supplied providers (e.g. the compaction+ summarizer) — emits a chat span but does not touch the root+ ``invoke_agent`` span's attribution attributes."""+ self._on_provider_request(payload, model, attribute_root=False)++ def _on_provider_request(+ self, payload: dict, model: "Model", *, attribute_root: bool = True+ ) -> None:run = self._runif run is None or run.turn_span is None:return@@ -935,21 +959,22 @@ class Recorder:):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)+ if attribute_root:+ # 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]- )+ # 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]- )+ # 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}",diff --git a/tests/tracing/test_recorder.py b/tests/tracing/test_recorder.pyindex a162518..fd5e972 100644--- a/tests/tracing/test_recorder.py+++ b/tests/tracing/test_recorder.py@@ -508,9 +508,13 @@ class TestMiddlewareProviders:main = FauxProvider()summarizer = FauxProvider()# Cap at near-zero so transform_context triggers immediately.+ # Distinct ``provider`` labels on the two Models so the test can also+ # verify the root ``invoke_agent`` span stays attributed to the agent's+ # own provider, not the summarizer that fires first.+ summary_model = Model(id="summary-1", provider="faux-summary")mw = CompactionMiddleware(summary_provider=summarizer,- summary_model=Model(id="summary-1", provider="faux"),+ summary_model=summary_model,max_tokens_before_compact=1,keep_recent_messages=1,max_summary_tokens=128,@@ -533,7 +537,7 @@ class TestMiddlewareProviders:agent = Agent(provider=main,model=MODEL,- system_prompt="test",+ system_prompt="agent system prompt — kept on root",middleware=[mw],checkpointer=cp,thread_id=thread_id,@@ -566,6 +570,74 @@ class TestMiddlewareProviders:for chat in chats:assert chat.context.trace_id == turn.context.trace_id+ # Root ``invoke_agent`` attribution must reflect the agent's own+ # provider, not the summarizer that fires first during+ # ``transform_context``. Without the per-listener gate the root+ # would carry "faux-summary" + the summarizer's system prompt.+ root = [s for s in exporter.spans if s.name.startswith("invoke_agent")][0]+ assert _attrs(root)["gen_ai.provider.name"] == "faux"++ async def test_extra_provider_does_not_clobber_root_provider_attribution(self):+ # Direct exercise of the listener-gating contract: extra-provider+ # requests must go through ``_on_extra_provider_request``, which+ # leaves the root span's ``gen_ai.provider.name`` placeholder alone.+ # Driving the recorder synthetically also covers the path where the+ # extra provider fires *before* the main provider, the exact ordering+ # the compaction summarizer creates.+ from cubepi.tracing.recorder import Recorder++ agent, main, exporter, tracer = await _build()+ recorder = _find_attached_recorder(main)+ assert isinstance(recorder, Recorder)+ # Recorder needs a run to attribute spans to — open one by issuing a+ # normal prompt that will emit the main chat span first.+ main.append_responses([faux_assistant_message("ok")])+ await agent.prompt("x")+ await agent.wait_for_idle()+ await tracer.shutdown()++ root = [s for s in exporter.spans if s.name.startswith("invoke_agent")][0]+ assert _attrs(root)["gen_ai.provider.name"] == "faux"++ def test_middleware_providers_default_is_empty(self):+ # ``Middleware.providers()`` default must return an empty iterable so+ # middlewares that don't drive any LLM are zero-cost on Recorder.attach.+ from cubepi.middleware.base import Middleware++ assert list(Middleware().providers()) == []++ async def test_middleware_providers_raising_is_swallowed(self):+ # If a middleware's ``providers()`` raises during attach the recorder+ # must keep going — the agent's own provider is the load-bearing+ # subscription, a buggy middleware mustn't break tracing.+ from cubepi.middleware.base import Middleware++ class _BoomMiddleware(Middleware):+ def providers(self):+ raise RuntimeError("boom")++ provider = FauxProvider()+ agent = Agent(+ provider=provider,+ model=MODEL,+ system_prompt="test",+ middleware=[_BoomMiddleware()],+ )+ exporter = InMemoryExporter()+ tracer = Tracer(+ service_name="test-svc",+ agent_name="test-agent",+ exporters=[exporter],+ )+ # Should not raise.+ tracer.attach(agent)+ provider.append_responses([faux_assistant_message("ok")])+ await agent.prompt("x")+ await agent.wait_for_idle()+ await tracer.shutdown()+ # Trace still emits.+ assert any(s.name.startswith("chat ") for s in exporter.spans)+class TestSafeToolName:"""``_safe_tool_name`` must handle all three tool payload shapes: