Skip to content

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

fix(tracing): address codex review findings from merged PRs #82/#83/#85 (#87)

Chrisd90e869c31a2
diff --git a/cubepi/tracing/meter.py b/cubepi/tracing/meter.py
index 696519a..5684fde 100644
--- a/cubepi/tracing/meter.py
+++ b/cubepi/tracing/meter.py
@@ -30,6 +30,7 @@ import cubepi
from cubepi.tracing.schema import (
GEN_AI_OPERATION_NAME,
GEN_AI_PROVIDER_NAME,
+ GEN_AI_REQUEST_MODEL,
GEN_AI_RESPONSE_MODEL,
OP_CHAT,
OP_EXECUTE_TOOL,
@@ -201,9 +202,22 @@ class Meter:
self._agent_attrs = {}
elif type_name == "tool_execution_start":
self._tool_open_ns[event.tool_call_id] = time.time_ns()
- self._tool_attrs[event.tool_call_id] = {
- GEN_AI_OPERATION_NAME: OP_EXECUTE_TOOL,
- }
+ # Carry the most-recent provider onto tool metrics so
+ # ``execute_tool`` duration observations can be filtered
+ # alongside chat metrics. ``_on_provider_request`` fires
+ # before any tool in a normal run, so its setdefault
+ # loop has nothing to update by then; stamp at creation
+ # time here from the latest chat attrs instead
+ # (codex P2 finding on PR #85).
+ attrs: dict[str, Any] = {GEN_AI_OPERATION_NAME: OP_EXECUTE_TOOL}
+ provider_name = self._chat_attrs.get(GEN_AI_PROVIDER_NAME) or (
+ self._agent_attrs.get(GEN_AI_PROVIDER_NAME)
+ if self._agent_attrs
+ else None
+ )
+ if provider_name is not None:
+ attrs[GEN_AI_PROVIDER_NAME] = provider_name
+ self._tool_attrs[event.tool_call_id] = attrs
elif type_name == "tool_execution_end":
start = self._tool_open_ns.pop(event.tool_call_id, None)
attrs = self._tool_attrs.pop(event.tool_call_id, None)
@@ -217,9 +231,14 @@ class Meter:
provider_name = map_provider_name(model.provider)
self._chat_open_ns = time.time_ns()
self._chat_first_chunk_ns = None
+ # Include gen_ai.request.model so failed/cancelled chat metrics
+ # (where the response body never lands and gen_ai.response.model
+ # cannot be set) can still be grouped by the requested model
+ # (codex P2 finding on PR #85).
self._chat_attrs = {
GEN_AI_OPERATION_NAME: OP_CHAT,
GEN_AI_PROVIDER_NAME: provider_name,
+ GEN_AI_REQUEST_MODEL: model.id,
}
# Stamp the agent + tool attrs with provider too, so all metrics
# from this run can be filtered by provider in one shot.
diff --git a/cubepi/tracing/recorder.py b/cubepi/tracing/recorder.py
index 888148a..a3f3293 100644
--- a/cubepi/tracing/recorder.py
+++ b/cubepi/tracing/recorder.py
@@ -285,6 +285,27 @@ class Recorder:
# invoke_agent
# ------------------------------------------------------------------
+ def _agent_signal_is_set(self) -> bool:
+ """True iff the attached agent's active abort signal is set.
+
+ Used to disambiguate a provider response listener firing as
+ ``(body=None, exc=None)``: that shape can mean either a real
+ cooperative abort (we should mark the chat span aborted) or a
+ provider-side non-abort fallback like
+ ``OpenAIResponsesProvider`` finalizing an incomplete stream
+ (we must NOT mark it aborted).
+ """
+ agent = self._agent
+ if agent is None:
+ return False
+ sig = getattr(agent, "_active_signal", None)
+ if sig is None:
+ return False
+ try:
+ return bool(sig.is_set())
+ except Exception:
+ return False
+
def _sweep_tool_span_tokens(self, run: "_RunState | None") -> None:
"""Drain ``run.tool_span_tokens`` through ``unregister_tool_span``.
@@ -344,6 +365,39 @@ class Recorder:
# that vary per-run set their own value via _ensure_agent_name.
self._run = _RunState(run_id=run_id, agent_span=span)
+ # Seed the transcript from the agent's existing conversation
+ # history. The cubepi agent loop only emits MessageStartEvent
+ # for newly-introduced messages (new prompts in ``run_agent_loop``,
+ # tool_results in ``execute_tool_calls``); the prior history is
+ # NOT replayed. Without this seed, ``Agent.resume()`` /
+ # ``run_agent_loop_continue`` (which adds no new prompt) would
+ # leave ``run.transcript`` empty and the first chat span's
+ # ``gen_ai.input.messages`` would omit the conversation history
+ # that the provider request actually carries. For a normal
+ # ``prompt()`` the pre-run history is also present here — the
+ # new prompt(s) then append via MessageStart, producing the
+ # full chronological context.
+ #
+ # Source: ``Agent.state.messages`` — that's where production
+ # code (e.g. ``_create_context_snapshot``) reads the persisted
+ # conversation from. ``getattr(agent, "messages", …)`` would
+ # return ``None`` on real Agent instances because the
+ # ``messages`` property lives on :class:`AgentState`, not on
+ # :class:`Agent` (codex P2 follow-up on PR #87).
+ if self._agent is not None:
+ history: list[Any] = []
+ try:
+ state = getattr(self._agent, "state", None)
+ state_messages = (
+ getattr(state, "messages", None) if state is not None else None
+ )
+ if state_messages:
+ history = list(state_messages)
+ except Exception:
+ history = []
+ if history:
+ self._run.transcript.extend(history)
+
def _on_agent_end(self, event: AgentEndEvent) -> None:
run = self._run
if run is None:
@@ -587,15 +641,20 @@ class Recorder:
run = self._run
if run is None:
return
- # Append assistant / tool_result messages to the transcript so
- # later chat spans see them in their ``gen_ai.input.messages``.
- # Note: ``output_messages`` accumulation happens at TurnEnd
- # (since it includes the synthesized turn snapshot); here we
- # only update the chronological transcript that drives chat
- # span input.
+ # Append assistant messages to the transcript so later chat
+ # spans see them in their ``gen_ai.input.messages``.
+ #
+ # tool_result messages are intentionally excluded here:
+ # ``execute_tool_calls`` emits both MessageStart AND MessageEnd
+ # for the same tool_result, and ``_on_message_start`` already
+ # appends ToolResultMessage to the transcript. Appending again
+ # here would produce two identical ``tool`` entries in the
+ # next chat span's input messages even though the provider
+ # context contains only one. Assistant messages have no
+ # MessageStart in the cubepi event flow, so they only land
+ # here.
msg = event.message
- msg_role = getattr(msg, "role", None)
- if msg_role in ("assistant", "tool_result"):
+ if getattr(msg, "role", None) == "assistant":
run.transcript.append(msg)
# ------------------------------------------------------------------
@@ -738,7 +797,26 @@ class Recorder:
span.set_attribute(CUBEPI_ABORTED, True)
span.set_attribute(ERROR_TYPE, "cubepi.aborted")
- if exc is None:
+ if exc is None and body is None and self._agent_signal_is_set():
+ # Provider abort branches (anthropic/openai/openai_responses)
+ # return from the stream before assembling a body, so the
+ # response listener is invoked as (None, model, None). The
+ # cooperative-abort marker check above requires a body to
+ # inspect, so without this branch the chat span would close
+ # UNSET — out of sync with the turn/root which TurnEnd
+ # marks aborted. Match the cancellation contract: leave
+ # Status UNSET, set cubepi.aborted + error.type.
+ #
+ # Gate on ``agent._active_signal.is_set()`` so we don't
+ # mistake provider-side non-abort fallbacks for aborts:
+ # OpenAIResponsesProvider, for example, finalizes a
+ # stream that ends without ``response.completed`` by
+ # firing response listeners with body=None / exc=None
+ # — a successful (if incomplete) completion that must
+ # NOT be marked aborted (codex P2 follow-up on PR #87).
+ span.set_attribute(CUBEPI_ABORTED, True)
+ span.set_attribute(ERROR_TYPE, "cubepi.aborted")
+ elif exc is None:
# Healthy completion — leave Status UNSET per OTel guidance.
pass
elif _is_cancelled_error(exc):
diff --git a/tests/tracing/test_content_recording.py b/tests/tracing/test_content_recording.py
index 58ec746..a0b72cf 100644
--- a/tests/tracing/test_content_recording.py
+++ b/tests/tracing/test_content_recording.py
@@ -288,6 +288,75 @@ class TestChatInputIncludesPriorAssistant:
# The assistant message must carry the tool_call part.
asst = next(m for m in inp if m["role"] == "assistant")
assert any(p.get("type") == "tool_call" for p in asst.get("parts", []))
+ # Pin the round-83 codex fix: tool_result must appear exactly
+ # once (it was previously appended both by _on_message_start
+ # and _on_message_end, producing two identical ``tool`` entries
+ # even though the provider context contains only one).
+ assert roles.count("tool") == 1
+
+
+class TestChatInputForContinuedHistory:
+ """For ``Agent.resume()`` and other continuation paths, the cubepi
+ loop intentionally does NOT emit ``MessageStartEvent`` for the
+ pre-existing ``context.messages`` — so without seeding, the
+ recorder's transcript starts empty and the first chat span's
+ ``gen_ai.input.messages`` omits the conversation history that the
+ provider request actually carries.
+
+ Codex P2 finding on PR #83: the recorder must seed the transcript
+ from the agent's existing messages at agent_start.
+ """
+
+ async def test_resume_chat_input_includes_prior_history(self):
+ from cubepi.providers.base import UserMessage as _U
+ from cubepi.providers.base import AssistantMessage as _A
+ from cubepi.providers.base import ToolResultMessage as _TR
+
+ agent, provider, exporter, tracer = await _build(record_content=True)
+ # Pre-load the agent with conversation history via the
+ # production state path — ``agent.state.messages`` is what
+ # ``_create_context_snapshot`` reads from. The recorder must
+ # source its seed from the same place (codex P2 follow-up on
+ # PR #87).
+ agent.state.messages = [
+ _U(content=[TextContent(text="earlier prompt")]),
+ _A(
+ content=[TextContent(text="ok, working on it")],
+ stop_reason="end_turn",
+ ),
+ ]
+ # Now drive a new prompt and check that the FIRST chat span
+ # includes the prior turns in its input. (resume() doesn't
+ # add a new prompt; using prompt() here is equivalent for the
+ # transcript-seeding contract since both code paths leave the
+ # pre-existing history un-emitted.)
+ provider.append_responses([faux_assistant_message("acknowledged")])
+ await agent.prompt("now continue")
+ await agent.wait_for_idle()
+ await tracer.shutdown()
+
+ chats = sorted(
+ [s for s in exporter.spans if s.name.startswith("chat ")],
+ key=lambda s: s.start_time or 0,
+ )
+ assert len(chats) == 1
+ inp = _json_attr(chats[0], "gen_ai.input.messages")
+ roles = [m["role"] for m in inp]
+ # Must carry: earlier user + earlier assistant + new user prompt.
+ assert roles == ["user", "assistant", "user"], (
+ f"first chat span input must include seeded history; got {roles}"
+ )
+ # Earlier user content survived.
+ assert any("earlier prompt" in p.get("content", "") for p in inp[0]["parts"])
+ # Earlier assistant content survived.
+ assert any("ok, working on it" in p.get("content", "") for p in inp[1]["parts"])
+ # New prompt is last.
+ assert any("now continue" in p.get("content", "") for p in inp[2]["parts"])
+
+ # Silence the unused-import linter on the ToolResultMessage
+ # alias — it documents the message shapes this test cares about
+ # even though only User+Assistant are exercised inline.
+ del _TR
class TestRedaction:
diff --git a/tests/tracing/test_meter.py b/tests/tracing/test_meter.py
index 6a50086..eb192ab 100644
--- a/tests/tracing/test_meter.py
+++ b/tests/tracing/test_meter.py
@@ -130,6 +130,88 @@ class TestTimeToFirstChunkMetric:
assert len(ttfc) == 1
+class TestRequestModelOnChatMetrics:
+ async def test_chat_duration_carries_request_model(self):
+ """Every chat metric must carry ``gen_ai.request.model`` so that
+ failed / cancelled requests (no response body, no response.model)
+ can still be grouped by the requested model. Codex P2 finding
+ on PR #85."""
+ provider = FauxProvider()
+ provider.append_responses([faux_assistant_message("ok")])
+ agent = Agent(provider=provider, model=MODEL, system_prompt="s")
+ meter, reader = _build_meter()
+ meter.attach(agent)
+
+ await agent.prompt("hello")
+ await agent.wait_for_idle()
+
+ points = _all_metric_points(reader)
+ chat_durations = [
+ dp
+ for n, dp in points
+ if n == "gen_ai.client.operation.duration"
+ and dict(dp.attributes).get("gen_ai.operation.name") == "chat"
+ ]
+ assert chat_durations
+ for dp in chat_durations:
+ attrs = dict(dp.attributes)
+ assert attrs.get("gen_ai.request.model") == MODEL.id, (
+ f"chat metric missing gen_ai.request.model; got {attrs}"
+ )
+
+
+class TestProviderOnToolMetrics:
+ async def test_tool_duration_carries_provider_name(self):
+ """``execute_tool`` duration observations must carry
+ ``gen_ai.provider.name`` so they can be filtered alongside
+ chat metrics. Tool execution starts AFTER the chat request,
+ so the meter must read the active provider at tool-start time
+ instead of relying on the chat-request stamp loop (which by
+ then has no tool entries to update). Codex P2 finding on PR #85."""
+ from pydantic import BaseModel
+
+ from cubepi.agent.types import AgentTool, AgentToolResult
+ from cubepi.providers.base import TextContent, ToolCall
+
+ class P(BaseModel):
+ pass
+
+ async def run(tool_call_id, params, *, signal=None, on_update=None):
+ return AgentToolResult(content=[TextContent(text="ok")])
+
+ tool = AgentTool(name="t", description="t", parameters=P, execute=run)
+ provider = FauxProvider()
+ provider.append_responses(
+ [
+ faux_assistant_message(
+ [ToolCall(id="c1", name="t", arguments={})],
+ stop_reason="tool_use",
+ ),
+ faux_assistant_message("final"),
+ ]
+ )
+ agent = Agent(provider=provider, model=MODEL, system_prompt="s", tools=[tool])
+ meter, reader = _build_meter()
+ meter.attach(agent)
+
+ await agent.prompt("kick off")
+ await agent.wait_for_idle()
+
+ points = _all_metric_points(reader)
+ tool_durations = [
+ dp
+ for n, dp in points
+ if n == "gen_ai.client.operation.duration"
+ and dict(dp.attributes).get("gen_ai.operation.name") == "execute_tool"
+ ]
+ assert tool_durations
+ for dp in tool_durations:
+ attrs = dict(dp.attributes)
+ assert attrs.get("gen_ai.provider.name") == "faux", (
+ f"execute_tool metric missing gen_ai.provider.name; got {attrs}"
+ )
+
+
class TestNoMetricsWithoutListeners:
async def test_detach_stops_emission(self):
provider = FauxProvider()
diff --git a/tests/tracing/test_recorder.py b/tests/tracing/test_recorder.py
index 7f57d5a..ec9463c 100644
--- a/tests/tracing/test_recorder.py
+++ b/tests/tracing/test_recorder.py
@@ -73,6 +73,18 @@ def _spans_by_name(exporter: InMemoryExporter) -> dict[str, list[ReadableSpan]]:
return out
+def _find_attached_recorder(provider):
+ """Walk a provider's request_listeners to return the cubepi
+ Recorder instance — used by tests that need to drive recorder
+ callbacks directly with synthetic provider events."""
+ from cubepi.tracing.recorder import Recorder
+
+ for cb in getattr(provider, "_request_listeners", []):
+ if hasattr(cb, "__self__") and isinstance(cb.__self__, Recorder):
+ return cb.__self__
+ return None
+
+
def _attrs(span: ReadableSpan) -> dict[str, Any]:
return dict(span.attributes or {})
@@ -390,6 +402,186 @@ class TestErrorAndAbort:
attrs = _attrs(root)
assert attrs.get("cubepi.aborted") is True
+ async def test_chat_span_marks_aborted_when_provider_returns_no_body(self):
+ """Real Anthropic/OpenAI/OpenAI-Responses abort branches return
+ from the stream before assembling a body, so the response
+ listener is called as ``(None, model, None)``. Without an
+ explicit case for that the chat span would close UNSET — out
+ of sync with the turn/root which TurnEnd marks aborted (codex
+ P2 round on PR #82).
+
+ The (None, None) shape is only treated as abort when the
+ agent's ``_active_signal`` is set — otherwise it's a benign
+ provider-side fallback (e.g. OpenAIResponsesProvider
+ finalizing an incomplete stream). See the companion
+ ``test_no_body_without_signal_keeps_chat_unset`` below.
+
+ Drive the recorder's listeners directly with the (None, None)
+ shape — reproducing real provider behaviour without needing
+ the provider to actually cooperate."""
+ import asyncio as _asyncio
+
+ provider = FauxProvider()
+ agent = Agent(provider=provider, model=MODEL, system_prompt="s")
+ exporter = InMemoryExporter()
+ tracer = Tracer(service_name="t", agent_name="a", exporters=[exporter])
+ tracer.attach(agent)
+
+ # First, do a real run so a turn span is open via normal flow.
+ provider.append_responses([faux_assistant_message("warmup")])
+ await agent.prompt("warmup")
+
+ recorder = _find_attached_recorder(provider)
+ assert recorder is not None
+ from cubepi.agent.types import AgentStartEvent, TurnStartEvent
+
+ await recorder._on_agent_event(AgentStartEvent())
+ await recorder._on_agent_event(TurnStartEvent())
+ recorder._on_provider_request({"messages": []}, MODEL)
+ # Simulate that the user called agent.abort() before the
+ # response listener fires.
+ agent._active_signal = _asyncio.Event()
+ agent._active_signal.set()
+ # Provider abort branch -> (body=None, exc=None).
+ recorder._on_provider_response(None, MODEL, None)
+
+ await tracer.shutdown()
+ chats = [s for s in exporter.spans if s.name.startswith("chat ")]
+ assert len(chats) >= 2
+ aborted_chat = chats[-1]
+ attrs = _attrs(aborted_chat)
+ assert attrs.get("cubepi.aborted") is True
+ assert attrs.get("error.type") == "cubepi.aborted"
+ assert aborted_chat.status.status_code == StatusCode.UNSET
+
+ async def test_no_body_without_signal_keeps_chat_unset(self):
+ """``OpenAIResponsesProvider`` finalizes a stream that ends
+ without ``response.completed`` by firing response listeners
+ with ``(body=None, exc=None)`` — a successful (if incomplete)
+ completion. The chat span MUST NOT be marked aborted in that
+ case; only a (None, None) shape coinciding with the agent's
+ abort signal counts as a real abort (codex P2 follow-up on
+ PR #87)."""
+ provider = FauxProvider()
+ agent = Agent(provider=provider, model=MODEL, system_prompt="s")
+ exporter = InMemoryExporter()
+ tracer = Tracer(service_name="t", agent_name="a", exporters=[exporter])
+ tracer.attach(agent)
+
+ provider.append_responses([faux_assistant_message("warmup")])
+ await agent.prompt("warmup")
+
+ recorder = _find_attached_recorder(provider)
+ assert recorder is not None
+ from cubepi.agent.types import AgentStartEvent, TurnStartEvent
+
+ await recorder._on_agent_event(AgentStartEvent())
+ await recorder._on_agent_event(TurnStartEvent())
+ recorder._on_provider_request({"messages": []}, MODEL)
+ # Provider's non-abort fallback path — no signal set.
+ agent._active_signal = None
+ recorder._on_provider_response(None, MODEL, None)
+
+ await tracer.shutdown()
+ chats = [s for s in exporter.spans if s.name.startswith("chat ")]
+ assert len(chats) >= 2
+ fallback_chat = chats[-1]
+ attrs = _attrs(fallback_chat)
+ assert "cubepi.aborted" not in attrs, (
+ "non-abort (None, None) fallback must not be marked aborted"
+ )
+ assert attrs.get("error.type") != "cubepi.aborted"
+ assert fallback_chat.status.status_code == StatusCode.UNSET
+
+
+class TestAgentSignalHelper:
+ """Unit-level coverage for the defensive branches of
+ ``Recorder._agent_signal_is_set`` introduced in PR #87. The
+ main-path branch (signal is set / not set) is already exercised
+ by the abort-handling chat-span tests; here we pin the
+ no-agent and signal-raises edges so codecov accepts the patch."""
+
+ def test_returns_false_when_no_agent_attached(self):
+ from cubepi.tracing.recorder import Recorder
+
+ tracer = Tracer(service_name="t", exporters=[])
+ recorder = Recorder(tracer)
+ # Default: no agent attached.
+ assert recorder._agent_signal_is_set() is False
+
+ def test_returns_false_when_agent_has_no_signal(self):
+ from cubepi.tracing.recorder import Recorder
+
+ tracer = Tracer(service_name="t", exporters=[])
+ recorder = Recorder(tracer)
+
+ class _Bare:
+ pass # no _active_signal attribute
+
+ recorder._agent = _Bare()
+ assert recorder._agent_signal_is_set() is False
+
+ def test_returns_false_when_signal_is_set_raises(self):
+ from cubepi.tracing.recorder import Recorder
+
+ tracer = Tracer(service_name="t", exporters=[])
+ recorder = Recorder(tracer)
+
+ class _Boom:
+ def is_set(self):
+ raise RuntimeError("broken signal")
+
+ class _Agent:
+ _active_signal = _Boom()
+
+ recorder._agent = _Agent()
+ # Exception is swallowed; helper degrades to False rather than
+ # crashing the response-listener callback chain.
+ assert recorder._agent_signal_is_set() is False
+
+
+class TestTranscriptSeedingDefensiveBranches:
+ """The transcript-seeding path on ``_on_agent_start`` reads
+ ``agent.state.messages`` defensively — pin the no-state and
+ raising-state branches so the patch is fully covered."""
+
+ async def test_no_seed_when_agent_has_no_state(self):
+ from cubepi.tracing.recorder import Recorder
+ from cubepi.agent.types import AgentStartEvent
+
+ tracer = Tracer(service_name="t", exporters=[])
+ recorder = Recorder(tracer)
+
+ class _Bare:
+ pass # no `state` attribute
+
+ recorder._agent = _Bare()
+ await recorder._on_agent_event(AgentStartEvent())
+ # _RunState was created (otherwise other handlers crash) but
+ # transcript stays empty.
+ assert recorder._run is not None
+ assert recorder._run.transcript == []
+
+ async def test_seed_handles_exception_in_state_messages(self):
+ from cubepi.tracing.recorder import Recorder
+ from cubepi.agent.types import AgentStartEvent
+
+ tracer = Tracer(service_name="t", exporters=[])
+ recorder = Recorder(tracer)
+
+ class _BoomState:
+ @property
+ def messages(self):
+ raise RuntimeError("state broken")
+
+ class _Agent:
+ state = _BoomState()
+
+ recorder._agent = _Agent()
+ await recorder._on_agent_event(AgentStartEvent())
+ assert recorder._run is not None
+ assert recorder._run.transcript == []
+
class TestLifecycle:
async def test_shutdown_is_idempotent(self):