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(cli): linear-interp percentiles, null-safe token sums, ordered cross-file follow, non-dict line skip
xf gongdac21dfbe65d
diff --git a/cubepi/cli/trace/follow.py b/cubepi/cli/trace/follow.pyindex 8109080..f4af38e 100644--- a/cubepi/cli/trace/follow.py+++ b/cubepi/cli/trace/follow.py@@ -38,10 +38,14 @@ def iter_new_spans(path: Path, state: dict[str, Any]):if not line:continuetry:- yield Span(json.loads(line))+ obj = json.loads(line)except json.JSONDecodeError:state["skipped"] = state.get("skipped", 0) + 1continue+ if not isinstance(obj, dict):+ state["skipped"] = state.get("skipped", 0) + 1+ continue+ yield Span(obj)def is_run_complete(span: Span) -> bool:@@ -76,17 +80,22 @@ def follow_run(last_activity = time.monotonic()try:while True:- saw_any = False- done = False+ # Collect this poll's new spans across all files, then print in+ # end-time order so a cross-midnight run (old + new date file both+ # with backlog) stays chronological.+ batch: list[Span] = []for path in resolve_files():state = states.setdefault(path, {"offset": 0, "buffer": "", "skipped": 0})- for span in iter_new_spans(path, state):- print(format_event(span), flush=True)- saw_any = True- if is_run_complete(span):- done = True+ batch.extend(iter_new_spans(path, state))+ batch.sort(key=lambda s: s.sort_end)+ saw_any = bool(batch)+ done = False+ for span in batch:+ print(format_event(span), flush=True)+ if is_run_complete(span):+ done = Trueif done:breaknow = time.monotonic()diff --git a/cubepi/cli/trace/loader.py b/cubepi/cli/trace/loader.pyindex 54907dd..b63c84a 100644--- a/cubepi/cli/trace/loader.py+++ b/cubepi/cli/trace/loader.py@@ -51,9 +51,14 @@ def load_run(files: list[Path]) -> tuple[list[Span], int]:if not line:continuetry:- spans.append(Span(json.loads(line)))+ obj = json.loads(line)except json.JSONDecodeError:skipped += 1+ continue+ if not isinstance(obj, dict):+ skipped += 1+ continue+ spans.append(Span(obj))spans.sort(key=lambda s: s.sort_start)return spans, skippeddiff --git a/cubepi/cli/trace/model.py b/cubepi/cli/trace/model.pyindex 2da2fce..cdc7024 100644--- a/cubepi/cli/trace/model.py+++ b/cubepi/cli/trace/model.py@@ -108,6 +108,11 @@ class Span:"""start_time, or epoch when missing — for stable ordering."""return self.start or _EPOCH+ @property+ def sort_end(self) -> datetime:+ """end_time (falling back to start, then epoch) — completion order."""+ return self.end or self.start or _EPOCH+@dataclassclass TreeNode:diff --git a/cubepi/cli/trace/stats.py b/cubepi/cli/trace/stats.pyindex 040807e..9401ac2 100644--- a/cubepi/cli/trace/stats.py+++ b/cubepi/cli/trace/stats.py@@ -27,8 +27,14 @@ class StatRow: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]+ if len(vals) == 1:+ return vals[0]+ # Linear interpolation between closest ranks (so p50 of [100, 300] is 200).+ rank = (p / 100.0) * (len(vals) - 1)+ lo = int(rank)+ hi = min(lo + 1, len(vals) - 1)+ frac = rank - lo+ return vals[lo] + (vals[hi] - vals[lo]) * fracdef aggregate(spans: list[Span], by: str) -> list[StatRow]:@@ -70,10 +76,11 @@ def aggregate(spans: list[Span], by: str) -> list[StatRow]:row.aborted += 1if 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))+ # `or 0` guards against the attr being present but JSON null.+ row.input_tokens += int(a.get(schema.GEN_AI_USAGE_INPUT_TOKENS) or 0)+ row.output_tokens += int(a.get(schema.GEN_AI_USAGE_OUTPUT_TOKENS) or 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))+ a.get(schema.GEN_AI_USAGE_CACHE_READ_INPUT_TOKENS) or 0+ ) + int(a.get(schema.GEN_AI_USAGE_CACHE_CREATION_INPUT_TOKENS) or 0)return sorted(rows.values(), key=lambda r: r.count, reverse=True)diff --git a/tests/cli/trace/test_loader.py b/tests/cli/trace/test_loader.pyindex d8d25e2..0a4931f 100644--- a/tests/cli/trace/test_loader.py+++ b/tests/cli/trace/test_loader.py@@ -70,6 +70,21 @@ def test_load_run_skips_malformed(tmp_path):assert skipped == 1+def test_load_run_skips_non_dict_json(tmp_path):+ f = tmp_path / "2026-05-20" / "r1.jsonl"+ f.parent.mkdir(parents=True)+ with f.open("w") as fh:+ fh.write("null\n") # valid JSON, but not a span object+ fh.write("[1, 2]\n") # valid JSON array, not a span object+ fh.write(+ json.dumps(_span("0x1", None, "invoke_agent", "2026-05-20T00:00:00Z", "r1"))+ + "\n"+ )+ spans, skipped = load_run([f])+ assert len(spans) == 1+ assert skipped == 2++def test_list_runs(tmp_path):f = tmp_path / "2026-05-20" / "r1.jsonl"_write(diff --git a/tests/cli/trace/test_stats.py b/tests/cli/trace/test_stats.pyindex 4d6a23d..f7ffcf7 100644--- a/tests/cli/trace/test_stats.py+++ b/tests/cli/trace/test_stats.py@@ -55,6 +55,34 @@ def test_aggregate_by_model_tokens():assert row.error_rate == 0.0+def test_percentile_interpolates_median():+ spans = [_chat("gpt-x", 1, 1, 100), _chat("gpt-x", 1, 1, 300)]+ row = aggregate(spans, by="model")[0]+ assert row.percentile(50) == 200.0+++def test_null_token_attr_does_not_crash():+ sp = Span(+ {+ "name": "chat",+ "context": {"trace_id": "0xt", "span_id": "0x1"},+ "parent_id": "0x0",+ "start_time": "2026-05-20T00:00:00Z",+ "end_time": "2026-05-20T00:00:00.1Z",+ "status": {"status_code": "UNSET"},+ "attributes": {+ "gen_ai.operation.name": "chat",+ "gen_ai.request.model": "gpt-x",+ "gen_ai.usage.input_tokens": None,+ "gen_ai.usage.output_tokens": 5,+ },+ }+ )+ row = aggregate([sp], by="model")[0]+ assert row.input_tokens == 0+ assert row.output_tokens == 5++def test_aggregate_by_tool_no_tokens_counts_aborts():spans = [_tool("read", 50), _tool("read", 150, aborted=True)]rows = aggregate(spans, by="tool")