Skip to content

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

feat(cli): Span model + (trace_id,span_id) tree builder with orphan marking

xf gong466cc0d62386
diff --git a/cubepi/cli/trace/model.py b/cubepi/cli/trace/model.py
new file mode 100644
index 0000000..7e65ba0
--- /dev/null
+++ b/cubepi/cli/trace/model.py
@@ -0,0 +1,143 @@
+"""Span wrapper + tree building over OTLP/JSON span dicts."""
+from __future__ import annotations
+
+from dataclasses import dataclass, field
+from datetime import datetime, timezone
+from typing import Any
+
+from cubepi.tracing import schema
+
+_EPOCH = datetime(1970, 1, 1, tzinfo=timezone.utc)
+
+
+def _parse_ts(value: str | None) -> datetime | None:
+ if not value:
+ return None
+ return datetime.fromisoformat(value.replace("Z", "+00:00"))
+
+
+@dataclass
+class Span:
+ """Thin typed view over one OTLP/JSON span dict."""
+
+ raw: dict[str, Any]
+
+ @property
+ def _ctx(self) -> dict[str, Any]:
+ return self.raw.get("context") or {}
+
+ @property
+ def span_id(self) -> str | None:
+ return self._ctx.get("span_id")
+
+ @property
+ def trace_id(self) -> str | None:
+ return self._ctx.get("trace_id")
+
+ @property
+ def parent_id(self) -> str | None:
+ return self.raw.get("parent_id")
+
+ @property
+ def name(self) -> str:
+ return self.raw.get("name", "")
+
+ @property
+ def attributes(self) -> dict[str, Any]:
+ return self.raw.get("attributes") or {}
+
+ @property
+ def start(self) -> datetime | None:
+ return _parse_ts(self.raw.get("start_time"))
+
+ @property
+ def end(self) -> datetime | None:
+ return _parse_ts(self.raw.get("end_time"))
+
+ @property
+ def duration_ms(self) -> float | None:
+ s, e = self.start, self.end
+ if s is None or e is None:
+ return None
+ return (e - s).total_seconds() * 1000.0
+
+ @property
+ def status_code(self) -> str:
+ return (self.raw.get("status") or {}).get("status_code", "UNSET")
+
+ @property
+ def is_error(self) -> bool:
+ return self.status_code == "ERROR"
+
+ @property
+ def is_aborted(self) -> bool:
+ # The recorder sets a boolean cubepi.aborted attribute (and also an
+ # error.type="cubepi.aborted" string). The boolean is the canonical
+ # signal; OTel status stays UNSET for aborts, so don't gate on status.
+ return self.attributes.get(schema.CUBEPI_ABORTED) is True
+
+ @property
+ def run_id(self) -> str | None:
+ return self.attributes.get(schema.CUBEPI_RUN_ID)
+
+ @property
+ def operation(self) -> str | None:
+ """gen_ai.operation.name — the reliable span classifier.
+
+ Span *names* carry suffixes ("chat <model>", "execute_tool <tool>"),
+ so classify on this attribute, not on ``name``. The cubepi.turn span
+ has no operation name.
+ """
+ return self.attributes.get(schema.GEN_AI_OPERATION_NAME)
+
+ @property
+ def is_chat(self) -> bool:
+ return self.operation == schema.OP_CHAT
+
+ @property
+ def is_tool(self) -> bool:
+ return self.operation == schema.OP_EXECUTE_TOOL
+
+ @property
+ def is_invoke_agent(self) -> bool:
+ return self.operation == schema.OP_INVOKE_AGENT
+
+ @property
+ def sort_start(self) -> datetime:
+ """start_time, or epoch when missing — for stable ordering."""
+ return self.start or _EPOCH
+
+
+@dataclass
+class TreeNode:
+ span: Span
+ children: list["TreeNode"] = field(default_factory=list)
+ orphan: bool = False
+
+
+def build_forest(spans: list[Span]) -> list[TreeNode]:
+ """Build a parent→child forest keyed on (trace_id, span_id).
+
+ Spans whose parent_id is not present become roots; if they *had* a
+ parent_id, they are flagged ``orphan``.
+ """
+ nodes: dict[tuple[str | None, str | None], TreeNode] = {
+ (sp.trace_id, sp.span_id): TreeNode(span=sp) for sp in spans
+ }
+ roots: list[TreeNode] = []
+ for (trace_id, _), node in nodes.items():
+ parent_id = node.span.parent_id
+ parent = nodes.get((trace_id, parent_id)) if parent_id else None
+ if parent is not None:
+ parent.children.append(node)
+ else:
+ node.orphan = parent_id is not None
+ roots.append(node)
+ _sort(roots)
+ return roots
+
+
+def _sort(nodes: list[TreeNode]) -> None:
+ nodes.sort(key=lambda n: n.span.sort_start)
+ for n in nodes:
+ _sort(n.children)
diff --git a/tests/cli/trace/test_model.py b/tests/cli/trace/test_model.py
new file mode 100644
index 0000000..e355103
--- /dev/null
+++ b/tests/cli/trace/test_model.py
@@ -0,0 +1,70 @@
+from __future__ import annotations
+
+from cubepi.cli.trace.model import Span, build_forest
+
+
+def _raw(span_id, parent_id, name, start, end=None, status="UNSET", attrs=None):
+ return {
+ "name": name,
+ "context": {"trace_id": "0xtrace", "span_id": span_id},
+ "parent_id": parent_id,
+ "start_time": start,
+ "end_time": end,
+ "status": {"status_code": status},
+ "attributes": attrs or {},
+ }
+
+
+def test_span_fields_and_duration():
+ sp = Span(_raw("0x1", None, "invoke_agent",
+ "2026-05-20T00:00:00.000000Z", "2026-05-20T00:00:01.500000Z",
+ attrs={"cubepi.run_id": "run-1"}))
+ assert sp.span_id == "0x1"
+ assert sp.parent_id is None
+ assert sp.name == "invoke_agent"
+ assert sp.run_id == "run-1"
+ assert sp.duration_ms == 1500.0
+ assert sp.is_error is False
+
+
+def test_error_and_abort_distinct():
+ err = Span(_raw("0x2", "0x1", "chat gpt-x", "2026-05-20T00:00:00Z",
+ "2026-05-20T00:00:00.1Z", status="ERROR",
+ attrs={"gen_ai.operation.name": "chat"}))
+ aborted = Span(_raw("0x3", "0x1", "chat gpt-x", "2026-05-20T00:00:00Z",
+ "2026-05-20T00:00:00.1Z",
+ attrs={"gen_ai.operation.name": "chat",
+ "cubepi.aborted": True,
+ "error.type": "cubepi.aborted"}))
+ assert err.is_error is True and err.is_aborted is False
+ assert aborted.is_error is False and aborted.is_aborted is True
+
+
+def test_operation_classification():
+ chat = Span(_raw("0x4", "0x1", "chat gpt-x", "2026-05-20T00:00:00Z",
+ attrs={"gen_ai.operation.name": "chat"}))
+ tool = Span(_raw("0x5", "0x1", "execute_tool read", "2026-05-20T00:00:00Z",
+ attrs={"gen_ai.operation.name": "execute_tool"}))
+ agent = Span(_raw("0x6", None, "invoke_agent", "2026-05-20T00:00:00Z",
+ attrs={"gen_ai.operation.name": "invoke_agent"}))
+ assert chat.is_chat and not chat.is_tool
+ assert tool.is_tool and not tool.is_chat
+ assert agent.is_invoke_agent
+
+
+def test_build_forest_orders_children_and_marks_orphans():
+ # Children written before parent (real exporter order).
+ spans = [
+ Span(_raw("0xb", "0xa", "chat", "2026-05-20T00:00:00.2Z")),
+ Span(_raw("0xc", "0xa", "execute_tool", "2026-05-20T00:00:00.1Z")),
+ Span(_raw("0xa", None, "invoke_agent", "2026-05-20T00:00:00.0Z")),
+ Span(_raw("0xz", "0xMISSING", "chat", "2026-05-20T00:00:00.3Z")),
+ ]
+ roots = build_forest(spans)
+ # invoke_agent root + one orphan whose parent is absent.
+ names = sorted(r.span.name for r in roots)
+ assert names == ["chat", "invoke_agent"]
+ root = next(r for r in roots if r.span.name == "invoke_agent")
+ assert [c.span.name for c in root.children] == ["execute_tool", "chat"]
+ orphan = next(r for r in roots if r.span.name == "chat")
+ assert orphan.orphan is True