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): gate root attribution by model, not listener identity
xf gong64f3e64723ca
diff --git a/cubepi/middleware/base.py b/cubepi/middleware/base.pyindex f955312..24f8f3b 100644--- a/cubepi/middleware/base.py+++ b/cubepi/middleware/base.py@@ -12,7 +12,7 @@ from cubepi.agent.types import (BeforeToolCallContext,BeforeToolCallResult,)-from cubepi.providers.base import AssistantMessage, Message, Provider+from cubepi.providers.base import AssistantMessage, Message, Model, Providerfrom cubepi.types import JsonObject, StructuredObject@@ -90,15 +90,25 @@ class Middleware:) -> list[Message] | None:raise NotImplementedError- def providers(self) -> Iterable[Provider]:- """Return any extra LLM providers this middleware drives directly.-- Some middlewares (e.g. ``CompactionMiddleware``) make their own LLM- calls outside the agent's main provider. Returning those providers- here lets ``cubepi.tracing.Recorder`` wire its listeners so the- resulting calls show up in the trace tree alongside the agent's own- chat spans. Default is empty — middlewares that do not call any- LLM directly need not override.+ def extra_llm_calls(self) -> Iterable[tuple[Provider, Model]]:+ """Declare LLM calls this middleware drives outside the agent's main+ provider/model.++ Each pair is ``(provider, model)``. ``cubepi.tracing.Recorder`` uses+ these to:++ * Subscribe listeners on any provider the recorder isn't already+ watching, so the resulting calls show up in the trace tree+ alongside the agent's own chat spans.+ * Identify middleware-owned calls by ``(model.provider, model.id)``+ so they don't overwrite the root ``invoke_agent`` span's+ attribution (provider name, system prompt hash, tool list). This+ model-based gate is what handles the common "reuse one provider+ client, swap the model" pattern — listener identity alone would+ attribute the middleware's first call to the agent.++ Default is empty — middlewares that do not call any LLM directly+ need not override."""return ()diff --git a/cubepi/middleware/compaction/__init__.py b/cubepi/middleware/compaction/__init__.pyindex f654d6a..3246fd9 100644--- a/cubepi/middleware/compaction/__init__.py+++ b/cubepi/middleware/compaction/__init__.py@@ -133,12 +133,14 @@ class CompactionMiddleware(Middleware):ctx.extra["compaction_until_msg_index"] = new_boundaryreturn _compressed_view(messages, new_state, new_boundary)- def providers(self) -> tuple[Provider, ...]:- # Surface the summary provider so ``cubepi.tracing.Recorder`` can- # wire its listeners — without this the summarizer's LLM call is- # invisible to the trace, even though the rest of the turn is- # recorded.- return (self._summary_provider,)+ def extra_llm_calls(self) -> tuple[tuple[Provider, Model], ...]:+ # Surface (provider, model) so ``cubepi.tracing.Recorder`` can both+ # subscribe its listeners (the summarizer's chat span lands in the+ # trace) AND identify the summary call by model — important when+ # ``summary_provider`` is the same instance as the agent's main+ # provider, which is the common "reuse the client, swap the model"+ # pattern.+ return ((self._summary_provider, self._summary_model),)__all__ = [diff --git a/cubepi/tracing/recorder.py b/cubepi/tracing/recorder.pyindex caa42e1..eb2f249 100644--- a/cubepi/tracing/recorder.py+++ b/cubepi/tracing/recorder.py@@ -218,6 +218,14 @@ class Recorder:# ``_close_open_spans`` (the latter covers cancelled runs that# never emit AgentEndEvent).self._active_run_token: Any | None = None+ # ``(model.provider, model.id)`` tuples for LLM calls a middleware+ # owns (e.g. ``CompactionMiddleware``'s summarizer). When the+ # provider listener fires with one of these models we keep the+ # chat span but skip the root ``invoke_agent`` attribution writes+ # so the run stays attributed to the agent's own provider /+ # system prompt / tools. Model-based gating works even when the+ # middleware shares the agent's main provider instance.+ self._extra_call_models: set[tuple[str, str]] = set()# ------------------------------------------------------------------# Attach / detach@@ -234,26 +242,10 @@ class Recorder:provider = getattr(agent, "_provider", None) or getattr(agent, "provider", None)provider_detachers: list[Callable[[], None]] = []- def _subscribe(p: Any, *, is_main: bool) -> None:+ def _subscribe(p: Any) -> None:if not isinstance(p, BaseProvider):return- # 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_request(self._on_provider_request))provider_detachers.append(p.subscribe_chunk(self._on_provider_chunk))provider_detachers.append(p.subscribe_response(self._on_provider_response))@@ -262,24 +254,29 @@ 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, 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- # silently bypassing it. ``Middleware.providers()`` returns- # an empty iterable by default, so middlewares that don't- # touch an LLM directly cost nothing here.+ _subscribe(provider)+ # Middlewares may drive their own LLM calls (e.g.+ # ``CompactionMiddleware``'s summarizer). For each declared+ # (provider, model) pair: (a) subscribe the provider if we+ # aren't already, so those calls show up in the trace tree;+ # (b) record the model identity in ``_extra_call_models`` so+ # ``_on_provider_request`` knows to skip the root-attribution+ # write — gating by listener identity alone would fail when+ # the middleware shares the agent's main provider instance+ # ("reuse the client, swap the model"), since both calls+ # would arrive on the same listener.seen: set[int] = {id(provider)} if provider is not None else set()for mw in getattr(agent, "_middleware", []) or []:try:- extra = list(mw.providers())+ extra = list(mw.extra_llm_calls())except Exception:extra = []- for p in extra:+ for p, m in extra:+ self._extra_call_models.add((m.provider, m.id))if id(p) in seen:continueseen.add(id(p))- _subscribe(p, is_main=False)+ _subscribe(p)except BaseException:for d in provider_detachers:try:@@ -904,15 +901,7 @@ class Recorder:# Provider listeners — drive the chat span lifetime# ------------------------------------------------------------------- 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:+ def _on_provider_request(self, payload: dict, model: "Model") -> None:run = self._runif run is None or run.turn_span is None:return@@ -959,6 +948,17 @@ class Recorder:):attrs[CUBEPI_LLM_THINKING_LEVEL] = payload["reasoning"]["effort"]+ # Root ``invoke_agent`` span carries attribution for the agent+ # invocation as a whole — provider name, system prompt hash, tool+ # list. Middleware-driven LLM calls (e.g. the compaction+ # summarizer) must NOT overwrite those, otherwise a single+ # ``transform_context`` call that fires before the main model+ # would mis-attribute the whole run. ``_extra_call_models`` is+ # populated in ``attach`` from ``Middleware.extra_llm_calls()`` —+ # if the incoming model matches, skip the root writes. Gating by+ # model rather than listener identity is what handles the+ # shared-provider case ("reuse the client, swap the model").+ attribute_root = (model.provider, model.id) not in self._extra_call_modelsif attribute_root:# System prompt sha256 on root agent span (once per run).self._maybe_record_system_prompt_hash(payload, run)diff --git a/tests/tracing/test_recorder.py b/tests/tracing/test_recorder.pyindex fd5e972..8df1113 100644--- a/tests/tracing/test_recorder.py+++ b/tests/tracing/test_recorder.py@@ -577,43 +577,90 @@ class TestMiddlewareProviders: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+ async def test_shared_provider_still_protected_by_model_gate(self):+ # When ``summary_provider`` IS the agent's main provider (a common+ # "reuse the client, swap the model" pattern), listener-identity+ # dedupe would route the summarizer through the main listener and+ # let it clobber the root attribution. The fix gates on the model,+ # not the listener — this regression test pins that contract.+ from cubepi.checkpointer.memory import MemoryCheckpointer+ from cubepi.middleware.compaction import CompactionMiddleware+ from cubepi.providers.base import UserMessage- 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")+ shared = FauxProvider()+ agent_model = Model(id="agent-1", provider="faux-main")+ summary_model = Model(id="summary-1", provider="faux-summary")+ mw = CompactionMiddleware(+ summary_provider=shared,+ summary_model=summary_model,+ max_tokens_before_compact=1,+ keep_recent_messages=1,+ max_summary_tokens=128,+ min_compact_messages=2,+ )+ cp = MemoryCheckpointer()+ thread_id = "t-shared-provider"+ await cp.append(+ thread_id,+ [+ UserMessage(content=[TextContent(text="first")]),+ faux_assistant_message("first reply"),+ UserMessage(content=[TextContent(text="second")]),+ faux_assistant_message("second reply"),+ ],+ )++ agent = Agent(+ provider=shared,+ model=agent_model,+ system_prompt="agent system prompt — kept on root",+ middleware=[mw],+ checkpointer=cp,+ thread_id=thread_id,+ )+ exporter = InMemoryExporter()+ tracer = Tracer(+ service_name="test-svc",+ agent_name="test-agent",+ exporters=[exporter],+ )+ tracer.attach(agent)++ shared.append_responses(+ [+ faux_assistant_message("a brief summary"), # summarizer first+ faux_assistant_message("ok"), # then agent+ ]+ )++ await agent.prompt("third")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.+ # Despite the summarizer firing first on the shared listener, the+ # root must stay attributed to the agent's own provider (the+ # ``unknown:`` prefix is just ``map_provider_name`` canonicalising+ # the unfamiliar test label — what matters is it's the agent's+ # ``faux-main``, not the summarizer's ``faux-summary``).+ assert _attrs(root)["gen_ai.provider.name"].endswith("faux-main")++ def test_middleware_extra_llm_calls_default_is_empty(self):+ # ``Middleware.extra_llm_calls()`` 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()) == []+ assert list(Middleware().extra_llm_calls()) == []- 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.+ async def test_middleware_extra_llm_calls_raising_is_swallowed(self):+ # If a middleware's ``extra_llm_calls()`` 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 Middlewareclass _BoomMiddleware(Middleware):- def providers(self):+ def extra_llm_calls(self):raise RuntimeError("boom")provider = FauxProvider()