Skip to content

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

feat(trace-cli): filter and display traces by run metadata (--meta / --show-meta) (#125)

Chrisa4432c3c3a65
diff --git a/cubepi/cli/trace/commands.py b/cubepi/cli/trace/commands.py
index 523a3ba..a9d46c7 100644
--- a/cubepi/cli/trace/commands.py
+++ b/cubepi/cli/trace/commands.py
@@ -17,6 +17,13 @@ def register(subparsers: "argparse._SubParsersAction") -> None:
p_ls = trace_sub.add_parser("ls", help="list recent runs")
_add_dir(p_ls)
p_ls.add_argument("-n", type=int, default=20, help="max runs to show")
+ _add_meta(p_ls)
+ p_ls.add_argument(
+ "--show-meta",
+ metavar="KEY[,KEY...]",
+ help="also show these run-metadata keys as columns "
+ "(comma-separated); e.g. --show-meta conversation_id,user_id",
+ )
p_ls.set_defaults(handler=cmd_ls)
p_view = trace_sub.add_parser("view", help="render a run as a tree")
@@ -46,6 +53,7 @@ def register(subparsers: "argparse._SubParsersAction") -> None:
_add_dir(p_stats)
p_stats.add_argument("--by", choices=("model", "tool"), default="model")
p_stats.add_argument("--since", default=None, help="YYYY-MM-DD lower bound")
+ _add_meta(p_stats)
p_stats.set_defaults(handler=cmd_stats)
@@ -57,6 +65,32 @@ def _add_dir(parser: argparse.ArgumentParser) -> None:
)
+def _add_meta(parser: argparse.ArgumentParser) -> None:
+ parser.add_argument(
+ "--meta",
+ action="append",
+ metavar="KEY=VALUE",
+ help="filter to traces whose run metadata matches KEY=VALUE "
+ "(repeatable = AND, exact match); e.g. --meta conversation_id=conv_123",
+ )
+
+
+class _MetaParseError(Exception):
+ """Raised for a malformed --meta KEY=VALUE token."""
+
+
+def _parse_meta(items: list[str] | None) -> dict[str, str]:
+ """Parse repeated ``--meta KEY=VALUE`` tokens into a dict. Raises
+ :class:`_MetaParseError` on a token without ``=`` or an empty key."""
+ out: dict[str, str] = {}
+ for item in items or []:
+ key, sep, value = item.partition("=")
+ if not sep or not key:
+ raise _MetaParseError(f"--meta expects KEY=VALUE, got {item!r}")
+ out[key] = value
+ return out
+
+
def _emit_skipped(skipped: int) -> None:
if skipped:
print(f"({skipped} lines skipped (malformed))")
@@ -67,11 +101,18 @@ def cmd_ls(args: argparse.Namespace) -> int:
if not directory.exists():
print(f"no traces directory at {directory}")
return 1
- runs = loader.list_runs(directory, limit=args.n)
+ try:
+ meta = _parse_meta(args.meta)
+ except _MetaParseError as exc:
+ print(str(exc))
+ return 2
+ runs = loader.list_runs(directory, limit=args.n, meta=meta)
if not runs:
- print(f"no runs found under {directory}")
+ scope = f" matching {meta}" if meta else ""
+ print(f"no runs found under {directory}{scope}")
return 1
- render.render_runs(runs)
+ show_meta = [k.strip() for k in (args.show_meta or "").split(",") if k.strip()]
+ render.render_runs(runs, show_meta=show_meta)
return 0
@@ -125,7 +166,14 @@ def cmd_stats(args: argparse.Namespace) -> int:
if not files:
print(f"no runs found under {directory}")
return 1
+ try:
+ meta = _parse_meta(args.meta)
+ except _MetaParseError as exc:
+ print(str(exc))
+ return 2
spans, skipped = loader.load_run(files)
+ if meta:
+ spans = loader.filter_spans_by_meta(spans, meta)
rows = stats.aggregate(spans, by=args.by)
render.render_stats(rows, by=args.by)
_emit_skipped(skipped)
diff --git a/cubepi/cli/trace/loader.py b/cubepi/cli/trace/loader.py
index af32646..44c3bbd 100644
--- a/cubepi/cli/trace/loader.py
+++ b/cubepi/cli/trace/loader.py
@@ -3,7 +3,7 @@
from __future__ import annotations
import json
-from dataclasses import dataclass
+from dataclasses import dataclass, field
from datetime import datetime, timezone
from pathlib import Path
@@ -13,6 +13,52 @@ from cubepi.tracing import schema
DEFAULT_DIR = Path("./cubepi-traces")
_MIN = datetime.min.replace(tzinfo=timezone.utc)
+# Run-scoped metadata is stamped by the recorder as ``cubepi.metadata.<key>``
+# attributes on the root invoke_agent span (set via
+# ``cubepi.tracing.tracing_context(metadata=...)``).
+_META_PREFIX = "cubepi.metadata."
+
+
+def _root_span(spans: list[Span]) -> Span | None:
+ """The trace's root invoke_agent span (parent-less), else any invoke_agent."""
+ return next(
+ (s for s in spans if s.is_invoke_agent and not s.parent_id), None
+ ) or next((s for s in spans if s.is_invoke_agent), None)
+
+
+def _run_metadata(spans: list[Span]) -> dict[str, str]:
+ """The ``cubepi.metadata.*`` attributes off the trace's root span, with the
+ prefix stripped and values stringified. Empty when none were recorded."""
+ root = _root_span(spans)
+ if root is None:
+ return {}
+ return {
+ k[len(_META_PREFIX) :]: str(v)
+ for k, v in root.attributes.items()
+ if k.startswith(_META_PREFIX)
+ }
+
+
+def _meta_matches(have: dict[str, str], want: dict[str, str]) -> bool:
+ """True iff every ``want`` key/value is present (exact match) in ``have``."""
+ return all(have.get(k) == v for k, v in want.items())
+
+
+def filter_spans_by_meta(spans: list[Span], meta: dict[str, str]) -> list[Span]:
+ """Keep only spans belonging to a trace whose root metadata matches all of
+ ``meta`` (AND, exact). Groups by ``trace_id``; a trace with no root span is
+ dropped when a filter is given. No-op when ``meta`` is empty."""
+ if not meta:
+ return spans
+ by_trace: dict[str | None, list[Span]] = {}
+ for sp in spans:
+ by_trace.setdefault(sp.trace_id, []).append(sp)
+ kept: list[Span] = []
+ for trace_spans in by_trace.values():
+ if _meta_matches(_run_metadata(trace_spans), meta):
+ kept.extend(trace_spans)
+ return kept
+
class RunResolutionError(Exception):
"""Raised when a trace id / path cannot be resolved to any file."""
@@ -85,9 +131,7 @@ def _run_prompt(spans: list[Span]) -> str | None:
successive runs in one thread stay distinguishable. ``None`` when content
isn't recorded or no user text is present.
"""
- root = next(
- (s for s in spans if s.is_invoke_agent and not s.parent_id), None
- ) or next((s for s in spans if s.is_invoke_agent), None)
+ root = _root_span(spans)
candidates = [root] if root is not None else spans
for sp in candidates:
raw = sp.attributes.get(schema.GEN_AI_INPUT_MESSAGES)
@@ -129,14 +173,22 @@ class RunSummary:
has_error: bool
duration_ms: float | None
prompt: str | None
+ metadata: dict[str, str] = field(default_factory=dict)
-def list_runs(directory: Path, limit: int | None = None) -> list[RunSummary]:
+def list_runs(
+ directory: Path,
+ limit: int | None = None,
+ meta: dict[str, str] | None = None,
+) -> list[RunSummary]:
"""Summarize each trace, newest first.
Files are grouped by trace_id (stem), so a trace split across two date
dirs (crossed UTC midnight) is summarized as ONE trace, not two. The
span_count spans the whole trace — parent run plus nested subagent runs.
+
+ ``meta`` filters to traces whose root metadata matches every key/value
+ (AND, exact) — e.g. ``{"conversation_id": "conv_123"}``.
"""
by_trace: dict[str, list[Path]] = {}
for f in directory.glob("*/*.jsonl"):
@@ -146,6 +198,9 @@ def list_runs(directory: Path, limit: int | None = None) -> list[RunSummary]:
spans, _ = load_run(sorted(files))
if not spans:
continue
+ metadata = _run_metadata(spans)
+ if meta and not _meta_matches(metadata, meta):
+ continue
starts = [s.start for s in spans if s.start is not None]
ends = [s.end for s in spans if s.end is not None]
start = min(starts) if starts else None
@@ -161,6 +216,7 @@ def list_runs(directory: Path, limit: int | None = None) -> list[RunSummary]:
has_error=any(s.is_error for s in spans),
duration_ms=duration,
prompt=_run_prompt(spans),
+ metadata=metadata,
)
)
summaries.sort(key=lambda s: s.start or _MIN, reverse=True)
diff --git a/cubepi/cli/trace/render.py b/cubepi/cli/trace/render.py
index 55f9c2c..267bb2d 100644
--- a/cubepi/cli/trace/render.py
+++ b/cubepi/cli/trace/render.py
@@ -127,20 +127,26 @@ def render_tree_to_text(
return console.export_text()
-def render_runs(runs: list[RunSummary]) -> None:
+def render_runs(runs: list[RunSummary], show_meta: list[str] | None = None) -> None:
from rich.table import Table
+ show_meta = show_meta or []
console = _console()
table = Table(title="cubepi runs")
for col in ("started", "trace_id", "spans", "status", "duration"):
table.add_column(col)
+ for key in show_meta:
+ table.add_column(key)
table.add_column("input", max_width=48, no_wrap=True, overflow="ellipsis")
for r in runs:
started = r.start.isoformat() if r.start else "?"
dur = f"{r.duration_ms:.0f}ms" if r.duration_ms is not None else "?"
status = "[red]error[/red]" if r.has_error else "ok"
prompt = " ".join(r.prompt.split()) if r.prompt else "[dim]—[/dim]"
- table.add_row(started, r.trace_id, str(r.span_count), status, dur, prompt)
+ meta_cells = [r.metadata.get(k) or "[dim]—[/dim]" for k in show_meta]
+ table.add_row(
+ started, r.trace_id, str(r.span_count), status, dur, *meta_cells, prompt
+ )
console.print(table)
diff --git a/skills/cubepi-trace/SKILL.md b/skills/cubepi-trace/SKILL.md
index 02e9198..cfdb3a1 100644
--- a/skills/cubepi-trace/SKILL.md
+++ b/skills/cubepi-trace/SKILL.md
@@ -108,6 +108,16 @@ uv run cubepi trace follow <run>
# Aggregate across runs: latency p50/p95, error rate, tokens — by model or tool.
uv run cubepi trace stats --by model
uv run cubepi trace stats --by tool --since 2026-05-20
+
+# Filter by run metadata (cubebox stamps conversation_id / user_id / org_id /
+# workspace_id on the root span). Repeatable = AND, exact match. Works on
+# `ls` and `stats` — find all traces for a conversation, or that user's stats.
+uv run cubepi trace ls --meta conversation_id=conv_123
+uv run cubepi trace ls --meta user_id=usr_9 --meta org_id=org_1
+uv run cubepi trace stats --by model --meta user_id=usr_9
+
+# Show metadata as ls columns (display, not filter):
+uv run cubepi trace ls --show-meta conversation_id,user_id
```
If the CLI view still isn't enough, the files are plain JSONL — one span per
diff --git a/tests/cli/trace/test_commands.py b/tests/cli/trace/test_commands.py
index 7e25851..b595e64 100644
--- a/tests/cli/trace/test_commands.py
+++ b/tests/cli/trace/test_commands.py
@@ -65,3 +65,87 @@ def test_stats_by_model(tmp_path, capsys):
out = capsys.readouterr().out
assert rc == 0
assert "gpt-x" in out
+
+
+def _write_run_with_meta(directory: Path, stem: str, conversation_id: str):
+ f = directory / "2026-05-20" / f"{stem}.jsonl"
+ f.parent.mkdir(parents=True, exist_ok=True)
+ rows = [
+ {
+ "name": "invoke_agent",
+ "context": {"trace_id": f"0x{stem}", "span_id": "0x1"},
+ "parent_id": None,
+ "start_time": "2026-05-20T00:00:00Z",
+ "end_time": "2026-05-20T00:00:02Z",
+ "status": {"status_code": "UNSET"},
+ "attributes": {
+ "cubepi.run_id": stem,
+ "gen_ai.operation.name": "invoke_agent",
+ "cubepi.metadata.conversation_id": conversation_id,
+ },
+ },
+ {
+ "name": "chat gpt-x",
+ "context": {"trace_id": f"0x{stem}", "span_id": "0x2"},
+ "parent_id": "0x1",
+ "start_time": "2026-05-20T00:00:00Z",
+ "end_time": "2026-05-20T00:00:01Z",
+ "status": {"status_code": "UNSET"},
+ "attributes": {
+ "gen_ai.operation.name": "chat",
+ "gen_ai.request.model": "gpt-x",
+ "gen_ai.usage.input_tokens": 10,
+ "gen_ai.usage.output_tokens": 5,
+ },
+ },
+ ]
+ with f.open("w") as fh:
+ for r in rows:
+ fh.write(json.dumps(r) + "\n")
+
+
+def test_ls_meta_bad_format(tmp_path, capsys):
+ _write_run(tmp_path)
+ rc = main(["trace", "ls", "--dir", str(tmp_path), "--meta", "nokey"])
+ out = capsys.readouterr().out
+ assert rc == 2
+ assert "KEY=VALUE" in out
+
+
+def test_ls_meta_no_match(tmp_path, capsys):
+ _write_run(tmp_path) # has no cubepi.metadata.*
+ rc = main(
+ ["trace", "ls", "--dir", str(tmp_path), "--meta", "conversation_id=conv_X"]
+ )
+ out = capsys.readouterr().out
+ assert rc == 1
+ assert "no runs found" in out
+
+
+def test_stats_meta_filters(tmp_path, capsys):
+ _write_run_with_meta(tmp_path, "tA", "conv_A")
+ # matching meta -> the model shows up
+ rc = main(
+ ["trace", "stats", "--dir", str(tmp_path), "--meta", "conversation_id=conv_A"]
+ )
+ out = capsys.readouterr().out
+ assert rc == 0
+ assert "gpt-x" in out
+ # non-matching meta -> filtered out, model absent
+ rc = main(
+ ["trace", "stats", "--dir", str(tmp_path), "--meta", "conversation_id=zzz"]
+ )
+ out = capsys.readouterr().out
+ assert rc == 0
+ assert "gpt-x" not in out
+
+
+def test_ls_show_meta_columns(tmp_path, capsys):
+ _write_run_with_meta(tmp_path, "tA", "conv_A")
+ rc = main(["trace", "ls", "--dir", str(tmp_path), "--show-meta", "conversation_id"])
+ out = capsys.readouterr().out
+ assert rc == 0
+ # rich may ellipsis-truncate the header at narrow widths ("conversation…"),
+ # so assert on a prefix; the value renders in full.
+ assert "conversation" in out # column header (possibly truncated)
+ assert "conv_A" in out # the value
diff --git a/tests/cli/trace/test_loader.py b/tests/cli/trace/test_loader.py
index cdee068..5aeb793 100644
--- a/tests/cli/trace/test_loader.py
+++ b/tests/cli/trace/test_loader.py
@@ -301,3 +301,100 @@ def test_run_prompt_prefers_root_over_subagent_invoke_agent():
)
)
assert _run_prompt([sub, root]) == "root prompt"
+
+
+def test_list_runs_filters_by_meta(tmp_path):
+ f1 = tmp_path / "2026-05-20" / "tA.jsonl"
+ f2 = tmp_path / "2026-05-20" / "tB.jsonl"
+ _write(
+ f1,
+ [
+ _span(
+ "0x1",
+ None,
+ "invoke_agent",
+ "2026-05-20T00:00:00Z",
+ "rA",
+ **{
+ "gen_ai.operation.name": "invoke_agent",
+ "cubepi.metadata.conversation_id": "conv_A",
+ "cubepi.metadata.user_id": "u1",
+ },
+ )
+ ],
+ )
+ _write(
+ f2,
+ [
+ _span(
+ "0x2",
+ None,
+ "invoke_agent",
+ "2026-05-20T00:00:01Z",
+ "rB",
+ **{
+ "gen_ai.operation.name": "invoke_agent",
+ "cubepi.metadata.conversation_id": "conv_B",
+ },
+ )
+ ],
+ )
+ # metadata surfaced on the summary
+ by_id = {r.trace_id: r for r in list_runs(tmp_path)}
+ assert by_id["tA"].metadata == {"conversation_id": "conv_A", "user_id": "u1"}
+ assert by_id["tB"].metadata == {"conversation_id": "conv_B"}
+ # single-key filter
+ assert [
+ r.trace_id for r in list_runs(tmp_path, meta={"conversation_id": "conv_A"})
+ ] == ["tA"]
+ # AND: every key must match
+ assert [
+ r.trace_id
+ for r in list_runs(
+ tmp_path, meta={"conversation_id": "conv_A", "user_id": "u1"}
+ )
+ ] == ["tA"]
+ assert (
+ list_runs(tmp_path, meta={"conversation_id": "conv_A", "user_id": "nope"}) == []
+ )
+ # unknown key matches nothing
+ assert list_runs(tmp_path, meta={"missing": "x"}) == []
+
+
+def test_filter_spans_by_meta():
+ from cubepi.cli.trace.loader import filter_spans_by_meta
+ from cubepi.cli.trace.model import Span
+
+ def sp(trace_id, span_id, parent, name, **attrs):
+ return Span(
+ {
+ "name": name,
+ "context": {"trace_id": trace_id, "span_id": span_id},
+ "parent_id": parent,
+ "start_time": "2026-05-20T00:00:00Z",
+ "end_time": "2026-05-20T00:00:00Z",
+ "status": {"status_code": "UNSET"},
+ "attributes": attrs,
+ }
+ )
+
+ a_root = sp(
+ "0xA",
+ "0x1",
+ None,
+ "invoke_agent",
+ **{"gen_ai.operation.name": "invoke_agent", "cubepi.metadata.user_id": "u1"},
+ )
+ a_chat = sp("0xA", "0x2", "0x1", "chat", **{"gen_ai.operation.name": "chat"})
+ b_root = sp(
+ "0xB",
+ "0x3",
+ None,
+ "invoke_agent",
+ **{"gen_ai.operation.name": "invoke_agent", "cubepi.metadata.user_id": "u2"},
+ )
+ spans = [a_root, a_chat, b_root]
+ kept = filter_spans_by_meta(spans, {"user_id": "u1"})
+ assert {s.span_id for s in kept} == {"0x1", "0x2"}
+ # empty filter is a no-op (same list)
+ assert filter_spans_by_meta(spans, {}) is spans
diff --git a/website/docs/guides/tracing/cli.md b/website/docs/guides/tracing/cli.md
index 1d103e0..084266e 100644
--- a/website/docs/guides/tracing/cli.md
+++ b/website/docs/guides/tracing/cli.md
@@ -34,6 +34,31 @@ cubepi trace ls # newest first; -n N to limit
| `duration` | wall-clock span of the trace |
| `input` | the user's prompt, to identify the run |
+### Filter by run metadata (`--meta`)
+
+If the host stamped run-scoped metadata onto the trace (via
+`tracing_context(metadata=…)` — e.g. cubebox records `conversation_id`,
+`user_id`, `org_id`, `workspace_id` on the root `invoke_agent` span), filter to
+just those traces:
+
+```bash
+cubepi trace ls --meta conversation_id=conv_123
+cubepi trace ls --meta user_id=usr_9 --meta org_id=org_1 # repeatable = AND, exact match
+```
+
+Each `--meta KEY=VALUE` is matched exactly against the trace's root metadata;
+repeating the flag ANDs the conditions.
+
+To **display** metadata values as columns (rather than only filter by them),
+add `--show-meta KEY[,KEY…]`:
+
+```bash
+cubepi trace ls --show-meta conversation_id,user_id
+cubepi trace ls --meta org_id=org_1 --show-meta conversation_id # filter + show
+```
+
+(Or see all of a single trace's metadata with `cubepi trace view <id> -v`.)
+
## `view` — render a trace as a span tree
A trace-id **prefix** is enough (the table truncates ids); an ambiguous prefix
@@ -88,6 +113,15 @@ cubepi trace stats --by model # latency p50/p95, error rate, to
cubepi trace stats --by tool --since 2026-05-20
```
+`stats` also accepts `--meta KEY=VALUE` (same semantics as `ls`) to aggregate
+only the traces that match — e.g. latency / error-rate / tokens for one user or
+conversation:
+
+```bash
+cubepi trace stats --by model --meta user_id=usr_9
+cubepi trace stats --by tool --meta conversation_id=conv_123
+```
+
## Beyond the CLI
The files are plain JSONL — one span per line — so you can parse them directly