Tracing and Observability for AI Systems › Building the Span Tree and Reconstructing Execution
Language AI HandbookAll chapters Let's make this concrete. We will build a minimal in-memory tracer that produces spans with the fields above, then reconstruct the tree and compute derived views. Everything is deterministic: fixed timestamps and fixed inputs, so results are reproducible and the chapter's numbers never depend on wall-clock time or randomness.
The fixtures use fixed identifiers and timestamps. This lets us check the derived timings without waiting for operations to run or depending on the speed of the machine.
PythonIn [6]Expand
from __future__ import annotations
import json
import uuid
from dataclasses import asdict, dataclass, field
from typing import Any, Optional
# Deterministic span IDs so the chapter is reproducible.
def make_id(prefix: str, n: int) -> str:
return f"{prefix}-{n:04d}"The span class keeps descriptive attributes separate from content fields. Export policy applies to both. The fixture uses integer milliseconds. A deployed service can use a monotonic clock to measure elapsed time within a process. The helper to_record returns an in-memory dictionary that includes payload and error fields. Arbitrary attribute values can require explicit serialization. Use an allowlisted exporter for persisted records, as shown below.
PythonIn [7]Expand
@dataclass
class Span:
trace_id: str
span_id: str
parent_span_id: Optional[str]
name: str
kind: str # chain | llm | retriever | embedding | reranker | tool
start_ms: int
end_ms: int
attributes: dict[str, Any] = field(default_factory=dict)
payload: dict[str, Any] = field(
default_factory=dict
) # sensitive; retention-controlled
status: str = "ok" # ok | error
error_message: Optional[str] = None
@property
def duration_ms(self) -> int:
return self.end_ms - self.start_ms
def to_record(self) -> dict[str, Any]:
return asdict(self)A Trace groups spans sharing a trace ID. The helpers read parent pointers from a flat list and assume this fixture contains one root. A deployed store can index the spans by trace ID and the children by parent ID so the tree can be assembled after spans arrive. Use the trace ID together with the span ID when joining records from different traces.
PythonIn [8]Expand
@dataclass
class Trace:
trace_id: str
spans: list[Span] = field(default_factory=list)
def root(self) -> Span:
roots = [s for s in self.spans if s.parent_span_id is None]
assert len(roots) == 1, "a trace must have exactly one root"
return roots[0]
def children(self, span_id: str) -> list[Span]:
return [s for s in self.spans if s.parent_span_id == span_id]
def by_id(self) -> dict[str, Span]:
return {s.span_id: s for s in self.spans}A worked example: a RAG-with-tool request
Consider a single user request that runs a small RAG pipeline:
- A root
chainspan wraps the whole request. - An
embeddingspan embeds the user query. - A
retrieverspan queries the vector index and returns three candidates. - A
rerankerspan rescores the candidates. - An
llmspan generates an answer from the top context. - A mock
toolspan looks up a fictional balance after the first generation requests it. - A second
llmspan incorporates the mock tool result.
Notice that steps 2 through 7 form a serial pipeline: each step waits for the previous one. This is the simplest possible control flow, which makes it the right first example, but keep in mind that the whole point of the tree representation is to handle the harder case where some of these steps could run in parallel. The diagnostic questions a reviewer asks of this trace are: Was the balance looked up for the right account? Did the first generation correctly decide that a tool was needed? Did the second generation use the tool result faithfully? Each of those questions maps to a specific span, which is the payoff of the structure.
Let's construct it with explicit, plausible timings so the critical path is interesting. The two LLM calls dominate latency; the retriever and reranker are fast; the tool call has network latency.
PythonIn [9]Expand
def build_example_trace() -> Trace:
tid = "trace-0001"
spans = [
Span(
tid,
make_id("s", 1),
None,
"rag_agent.run",
"chain",
0,
1420,
attributes={"route": "rag_with_tool", "tenant": "acme"},
),
Span(
tid,
make_id("s", 2),
make_id("s", 1),
"embed_query",
"embedding",
10,
45,
attributes={"model": "embed-v3", "dim": 384},
),
Span(
tid,
make_id("s", 3),
make_id("s", 1),
"vector_search",
"retriever",
50,
140,
attributes={
"index": "kb-2025-01",
"top_k": 3,
"doc_ids": ["d17", "d42", "d09"],
"scores": [0.81, 0.77, 0.74],
},
),
Span(
tid,
make_id("s", 4),
make_id("s", 1),
"rerank",
"reranker",
145,
210,
attributes={"model": "rerank-v2", "kept": ["d42", "d17"]},
),
Span(
tid,
make_id("s", 5),
make_id("s", 1),
"generate_answer",
"llm",
215,
900,
attributes={
"model": "gen-large",
"prompt_tokens": 910,
"completion_tokens": 120,
"temperature": 0.0,
},
payload={
"prompt": "Context: [d42...] Question: What is my balance?"
},
),
Span(
tid,
make_id("s", 6),
make_id("s", 1),
"tool.get_balance",
"tool",
905,
1150,
attributes={"tool": "get_balance", "status_code": 200},
payload={"result": "balance=1250.00 USD"},
),
Span(
tid,
make_id("s", 7),
make_id("s", 1),
"generate_final",
"llm",
1155,
1420,
attributes={
"model": "gen-large",
"prompt_tokens": 1040,
"completion_tokens": 60,
"temperature": 0.0,
},
payload={
"prompt": "Tool result: balance=1250.00. Answer the user."
},
),
]
return Trace(tid, spans)
example_trace = build_example_trace()Each row shows one operation with its parent, kind, and duration. The first child starts 10 ms after the root, and there are five 5 ms gaps between children. The final child ends with the root. The fixture leaves those gaps unattributed. In a real trace, add instrumentation around a recurring gap if you need to identify what ran there.
ConsoleOut [10]Expand
span parent kind start end dur rag_agent.run None chain 0 1420 1420 embed_query s-0001 embedding 10 45 35 vector_search s-0001 retriever 50 140 90 rerank s-0001 reranker 145 210 65 generate_answer s-0001 llm 215 900 685 tool.get_balance s-0001 tool 905 1150 245 generate_final s-0001 llm 1155 1420 265
The output shows the seven spans of one request. The root rag_agent.run spans from 0 to 1,420 ms. The child intervals account for 1,385 ms, leaving 35 ms without a child span. The fixture does not label that time, so we keep it as unattributed.
Reconstructing the tree and rendering it
The renderer follows the recorded parent pointers to print an indented span hierarchy. The nesting shows the recorded parent relationships. It can help you locate an operation before consulting timing or dependency evidence.
PythonIn [11]Expand
def render_tree(trace: Trace) -> list[str]:
lines = []
root = trace.root()
def walk(span: Span, depth: int) -> None:
indent = " " * depth
lines.append(f"{indent}{span.name} [{span.kind}] {span.duration_ms}ms")
for child in sorted(
trace.children(span.span_id), key=lambda s: s.start_ms
):
walk(child, depth + 1)
walk(root, 0)
return linesConsoleOut [12]Expand
rag_agent.run [chain] 1420ms embed_query [embedding] 35ms vector_search [retriever] 90ms rerank [reranker] 65ms generate_answer [llm] 685ms tool.get_balance [tool] 245ms generate_final [llm] 265ms
The tree shows the recorded parent relationships. All six operations are direct children of the root. The fixture defines their execution order separately. A deeper trace can represent a tool with child operations. This recursive renderer assumes an acyclic structure and is limited by Python’s recursion depth. A production renderer can use an explicit stack and cap the depth displayed.
Computing latency and the critical path
For this serial fixture, group the six immediate child durations by span kind. Each duration already includes any nested work, so this view counts immediate children only. With overlapping siblings, the category sums measure recorded span time and can exceed elapsed request time.
PythonIn [13]Expand
kind_totals_ms = {}
for span in example_trace.children(example_trace.root().span_id):
kind_totals_ms[span.kind] = (
kind_totals_ms.get(span.kind, 0) + span.duration_ms
)
kind_labels = sorted(kind_totals_ms)
kind_values_ms = [kind_totals_ms[kind] for kind in kind_labels]
kind_bar_labels = [f"{duration} ms" for duration in kind_values_ms]ConsoleOut [14]Expand
embedding 35 ms llm 950 ms reranker 65 ms retriever 90 ms tool 245 ms
The two model calls dominate, with the tool and retrieval spans contributing modest amounts. The figure makes that ordering visual at a glance.
VisualizationOut [15]Expand

The root interval contains all six child intervals. The labeled rows preserve their offsets, which makes gaps and nesting visible.
PythonIn [16]Expand
timeline_spans = example_trace.spans
timeline_names = [span.name for span in timeline_spans]
timeline_starts = [span.start_ms for span in timeline_spans]
timeline_durations = [span.duration_ms for span in timeline_spans]
timeline_root = timeline_names[0]VisualizationOut [17]Expand

The root duration measures wall-clock time from the request's start to its end. The six children in this fixture are sequential by construction. They occupy 1,385 ms of the 1,420 ms root interval. The remaining 35 ms consist of a 10 ms leading interval and five 5 ms intervals between children.
PythonIn [18]Expand
root = example_trace.root()
children = example_trace.children(root.span_id)
totals = {}
for span in children:
totals[span.kind] = totals.get(span.kind, 0) + span.duration_ms
assert all(
left.end_ms <= right.start_ms for left, right in zip(children, children[1:])
)
assert (
root.start_ms <= children[0].start_ms <= children[-1].end_ms <= root.end_ms
)
recorded_ms = sum(totals.values())
print("Root latency (ms):", root.duration_ms)
print("Child durations by kind (ms):", totals)
print("Unattributed interval (ms):", root.duration_ms - recorded_ms)ConsoleOut [18]Expand
Root latency (ms): 1420
Child durations by kind (ms): {'embedding': 35, 'retriever': 90, 'reranker': 65, 'llm': 950, 'tool': 245}
Unattributed interval (ms): 35The two generation calls occupy 950 ms in total. In this serial fixture they form part of the blocking sequence. The second generation waits for the tool result, so moving it earlier would change the request's behavior.
A critical path is the longest duration-weighted chain in a dependency graph. Parent spans generally include child time. Summing durations down a parent-child chain therefore counts nested time more than once, and timestamp overlap alone cannot reveal which operation a later step waited for. Use causally justified edges and include necessary queue or coordination work when you need to compute the path. For example, two independent calls that start together and take 700 ms and 250 ms require 700 ms before a join that waits for both. If the join depends only on the shorter call, its dependency chain is different even when the calls' intervals are identical.
Document the clock assumptions and the location of first-token events. Overlapping siblings can make the sum of their durations exceed elapsed time. Uninstrumented gaps can instead make the sum smaller. Label which measurement you are presenting so readers can distinguish elapsed time from aggregated span durations or a computed critical path.
Comments
Add to the conversation
A question, a correction, or an example from your own work.
No comments yet. Be the first to share your thoughts!