Skip to content

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

feat(cli): trace loader — discovery, cross-midnight merge, malformed skip

xf gong00ae1ac59cac
diff --git a/cubepi/cli/trace/loader.py b/cubepi/cli/trace/loader.py
new file mode 100644
index 0000000..04aae9c
--- /dev/null
+++ b/cubepi/cli/trace/loader.py
@@ -0,0 +1,102 @@
+"""Discover trace files, resolve a run id to file(s), read spans."""
+from __future__ import annotations
+
+import json
+from dataclasses import dataclass
+from datetime import datetime, timezone
+from pathlib import Path
+
+from cubepi.cli.trace.model import Span
+
+DEFAULT_DIR = Path("./cubepi-traces")
+_MIN = datetime.min.replace(tzinfo=timezone.utc)
+
+
+class RunResolutionError(Exception):
+ """Raised when a run id / path cannot be resolved to any file."""
+
+
+def resolve_run(arg: str, directory: Path) -> list[Path]:
+ """Resolve a CLI argument to one or more JSONL files.
+
+ A ``.jsonl`` path is used directly. Otherwise ``arg`` is a run id and we
+ glob ``<dir>/*/{run_id}.jsonl`` across date subdirs — a run that crosses
+ UTC midnight is split across date dirs, so ALL matches are returned and
+ later merged. Zero matches is an error.
+ """
+ path = Path(arg)
+ if path.suffix == ".jsonl" and path.is_file():
+ return [path]
+ matches = sorted(directory.glob(f"*/{arg}.jsonl"))
+ if not matches:
+ raise RunResolutionError(
+ f"no trace file for run {arg!r} under {directory} "
+ f"(try `cubepi trace ls`)"
+ )
+ return matches
+
+
+def load_run(files: list[Path]) -> tuple[list[Span], int]:
+ """Read all spans from the given files; return (spans, skipped_count).
+
+ Malformed lines are skipped and tallied, never fatal. Spans are returned
+ sorted by start time so a merged cross-midnight run reads in order.
+ """
+ spans: list[Span] = []
+ skipped = 0
+ for f in files:
+ with f.open(encoding="utf-8") as fh:
+ for line in fh:
+ line = line.strip()
+ if not line:
+ continue
+ try:
+ spans.append(Span(json.loads(line)))
+ except json.JSONDecodeError:
+ skipped += 1
+ spans.sort(key=lambda s: s.sort_start)
+ return spans, skipped
+
+
+@dataclass
+class RunSummary:
+ run_id: str
+ files: list[Path]
+ start: datetime | None
+ span_count: int
+ has_error: bool
+ duration_ms: float | None
+
+
+def list_runs(directory: Path, limit: int | None = None) -> list[RunSummary]:
+ """Summarize each run, newest first.
+
+ Files are grouped by run_id (stem), so a run split across two date dirs
+ (crossed UTC midnight) is summarized as ONE run, not two.
+ """
+ by_run: dict[str, list[Path]] = {}
+ for f in directory.glob("*/*.jsonl"):
+ by_run.setdefault(f.stem, []).append(f)
+ summaries: list[RunSummary] = []
+ for run_id, files in by_run.items():
+ spans, _ = load_run(sorted(files))
+ if not spans:
+ 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
+ duration = None
+ if start is not None and ends:
+ duration = (max(ends) - start).total_seconds() * 1000.0
+ summaries.append(
+ RunSummary(
+ run_id=run_id,
+ files=sorted(files),
+ start=start,
+ span_count=len(spans),
+ has_error=any(s.is_error for s in spans),
+ duration_ms=duration,
+ )
+ )
+ summaries.sort(key=lambda s: s.start or _MIN, reverse=True)
+ return summaries[:limit] if limit else summaries
diff --git a/tests/cli/trace/test_loader.py b/tests/cli/trace/test_loader.py
new file mode 100644
index 0000000..d34fe0d
--- /dev/null
+++ b/tests/cli/trace/test_loader.py
@@ -0,0 +1,88 @@
+from __future__ import annotations
+
+import json
+from pathlib import Path
+
+import pytest
+
+from cubepi.cli.trace.loader import (
+ RunResolutionError,
+ list_runs,
+ load_run,
+ resolve_run,
+)
+
+
+def _span(span_id, parent_id, name, start, run_id, **attrs):
+ return {
+ "name": name,
+ "context": {"trace_id": "0xt", "span_id": span_id},
+ "parent_id": parent_id,
+ "start_time": start,
+ "end_time": start,
+ "status": {"status_code": "UNSET"},
+ "attributes": {"cubepi.run_id": run_id, **attrs},
+ }
+
+
+def _write(path: Path, spans: list[dict]) -> None:
+ path.parent.mkdir(parents=True, exist_ok=True)
+ with path.open("w") as f:
+ for sp in spans:
+ f.write(json.dumps(sp) + "\n")
+
+
+def test_resolve_by_path(tmp_path):
+ f = tmp_path / "a.jsonl"
+ _write(f, [_span("0x1", None, "invoke_agent", "2026-05-20T00:00:00Z", "r1")])
+ assert resolve_run(str(f), tmp_path) == [f]
+
+
+def test_resolve_by_run_id_merges_cross_midnight(tmp_path):
+ f1 = tmp_path / "2026-05-19" / "r1.jsonl"
+ f2 = tmp_path / "2026-05-20" / "r1.jsonl"
+ _write(f1, [_span("0x1", None, "invoke_agent", "2026-05-19T23:59:59Z", "r1")])
+ _write(f2, [_span("0x2", "0x1", "chat", "2026-05-20T00:00:01Z", "r1")])
+ resolved = resolve_run("r1", tmp_path)
+ assert sorted(resolved) == sorted([f1, f2])
+
+
+def test_resolve_zero_match_errors(tmp_path):
+ with pytest.raises(RunResolutionError):
+ resolve_run("missing", tmp_path)
+
+
+def test_load_run_skips_malformed(tmp_path):
+ f = tmp_path / "2026-05-20" / "r1.jsonl"
+ f.parent.mkdir(parents=True)
+ with f.open("w") as fh:
+ fh.write(json.dumps(_span("0x1", None, "invoke_agent",
+ "2026-05-20T00:00:00Z", "r1")) + "\n")
+ fh.write("{ not json\n")
+ fh.write(json.dumps(_span("0x2", "0x1", "chat",
+ "2026-05-20T00:00:00.1Z", "r1")) + "\n")
+ spans, skipped = load_run([f])
+ assert len(spans) == 2
+ assert skipped == 1
+
+
+def test_list_runs(tmp_path):
+ f = tmp_path / "2026-05-20" / "r1.jsonl"
+ _write(f, [
+ _span("0x1", None, "invoke_agent", "2026-05-20T00:00:00Z", "r1"),
+ _span("0x2", "0x1", "chat", "2026-05-20T00:00:00.1Z", "r1"),
+ ])
+ runs = list_runs(tmp_path)
+ assert len(runs) == 1
+ assert runs[0].run_id == "r1"
+ assert runs[0].span_count == 2
+
+
+def test_list_runs_merges_cross_midnight(tmp_path):
+ f1 = tmp_path / "2026-05-19" / "r1.jsonl"
+ f2 = tmp_path / "2026-05-20" / "r1.jsonl"
+ _write(f1, [_span("0x1", None, "invoke_agent", "2026-05-19T23:59:59Z", "r1")])
+ _write(f2, [_span("0x2", "0x1", "chat", "2026-05-20T00:00:01Z", "r1")])
+ runs = list_runs(tmp_path)
+ assert len(runs) == 1 # one run, not two
+ assert runs[0].span_count == 2