Skip to content

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

feat(cli): trace stats aggregation by model/tool

xf gongc3dce62e2082
diff --git a/cubepi/cli/trace/stats.py b/cubepi/cli/trace/stats.py
new file mode 100644
index 0000000..aa086a3
--- /dev/null
+++ b/cubepi/cli/trace/stats.py
@@ -0,0 +1,80 @@
+"""Aggregate spans by model or tool."""
+from __future__ import annotations
+
+from dataclasses import dataclass
+
+from cubepi.cli.trace.model import Span
+from cubepi.tracing import schema
+
+
+@dataclass
+class StatRow:
+ key: str
+ count: int
+ durations_ms: list[float]
+ errors: int
+ aborted: int
+ input_tokens: int | None = None
+ output_tokens: int | None = None
+ cache_tokens: int | None = None
+
+ @property
+ def error_rate(self) -> float:
+ return self.errors / self.count if self.count else 0.0
+
+ def percentile(self, p: float) -> float | None:
+ vals = sorted(d for d in self.durations_ms if d is not None)
+ if not vals:
+ return None
+ idx = min(len(vals) - 1, int(round((p / 100.0) * (len(vals) - 1))))
+ return vals[idx]
+
+
+def aggregate(spans: list[Span], by: str) -> list[StatRow]:
+ """Group spans by model (``chat`` spans) or tool (``execute_tool`` spans).
+
+ ``by='model'`` includes token totals; ``by='tool'`` leaves token fields
+ None — tokens live on chat spans, not tool spans.
+ """
+ want_tokens = by == "model"
+ key_attr = (
+ schema.GEN_AI_REQUEST_MODEL if by == "model" else schema.GEN_AI_TOOL_NAME
+ )
+ rows: dict[str, StatRow] = {}
+ for sp in spans:
+ # Classify on gen_ai.operation.name, not span name (names carry
+ # "<model>"/"<tool>" suffixes).
+ if by == "model" and not sp.is_chat:
+ continue
+ if by == "tool" and not sp.is_tool:
+ continue
+ key = str(sp.attributes.get(key_attr, "<unknown>"))
+ row = rows.get(key)
+ if row is None:
+ row = StatRow(
+ key=key,
+ count=0,
+ durations_ms=[],
+ errors=0,
+ aborted=0,
+ input_tokens=0 if want_tokens else None,
+ output_tokens=0 if want_tokens else None,
+ cache_tokens=0 if want_tokens else None,
+ )
+ rows[key] = row
+ row.count += 1
+ if sp.duration_ms is not None:
+ row.durations_ms.append(sp.duration_ms)
+ if sp.is_error:
+ row.errors += 1
+ if sp.is_aborted:
+ row.aborted += 1
+ if want_tokens:
+ a = sp.attributes
+ row.input_tokens += int(a.get(schema.GEN_AI_USAGE_INPUT_TOKENS, 0))
+ row.output_tokens += int(a.get(schema.GEN_AI_USAGE_OUTPUT_TOKENS, 0))
+ # Cache total = read + creation (both are cache-related input tokens).
+ row.cache_tokens += int(
+ a.get(schema.GEN_AI_USAGE_CACHE_READ_INPUT_TOKENS, 0)
+ ) + int(a.get(schema.GEN_AI_USAGE_CACHE_CREATION_INPUT_TOKENS, 0))
+ return sorted(rows.values(), key=lambda r: r.count, reverse=True)
diff --git a/tests/cli/trace/test_stats.py b/tests/cli/trace/test_stats.py
new file mode 100644
index 0000000..ec54e62
--- /dev/null
+++ b/tests/cli/trace/test_stats.py
@@ -0,0 +1,62 @@
+from __future__ import annotations
+
+from cubepi.cli.trace.model import Span
+from cubepi.cli.trace.stats import aggregate
+
+
+def _chat(model, in_tok, out_tok, dur_ms, error=False):
+ end = f"2026-05-20T00:00:{dur_ms / 1000:09.6f}Z"
+ return Span({
+ "name": "chat",
+ "context": {"trace_id": "0xt", "span_id": "0x1"},
+ "parent_id": "0x0",
+ "start_time": "2026-05-20T00:00:00.000000Z",
+ "end_time": end,
+ "status": {"status_code": "ERROR" if error else "UNSET"},
+ "attributes": {
+ "gen_ai.operation.name": "chat",
+ "gen_ai.request.model": model,
+ "gen_ai.usage.input_tokens": in_tok,
+ "gen_ai.usage.output_tokens": out_tok,
+ },
+ })
+
+
+def _tool(name, dur_ms, aborted=False):
+ end = f"2026-05-20T00:00:{dur_ms / 1000:09.6f}Z"
+ attrs = {"gen_ai.operation.name": "execute_tool", "gen_ai.tool.name": name}
+ if aborted:
+ attrs["cubepi.aborted"] = True
+ attrs["error.type"] = "cubepi.aborted"
+ return Span({
+ "name": "execute_tool",
+ "context": {"trace_id": "0xt", "span_id": "0x2"},
+ "parent_id": "0x0",
+ "start_time": "2026-05-20T00:00:00.000000Z",
+ "end_time": end,
+ "status": {"status_code": "UNSET"},
+ "attributes": attrs,
+ })
+
+
+def test_aggregate_by_model_tokens():
+ spans = [_chat("gpt-x", 10, 5, 100), _chat("gpt-x", 20, 7, 300)]
+ rows = aggregate(spans, by="model")
+ assert len(rows) == 1
+ row = rows[0]
+ assert row.key == "gpt-x"
+ assert row.count == 2
+ assert row.input_tokens == 30
+ assert row.output_tokens == 12
+ assert row.error_rate == 0.0
+
+
+def test_aggregate_by_tool_no_tokens_counts_aborts():
+ spans = [_tool("read", 50), _tool("read", 150, aborted=True)]
+ rows = aggregate(spans, by="tool")
+ assert len(rows) == 1
+ row = rows[0]
+ assert row.key == "read"
+ assert row.count == 2
+ assert row.input_tokens is None # tools have no token columns
+ assert row.aborted == 1