# Why does an instance lose its reasoning lineage when GenAI spans are parented to the tool-call span instead of the generation span **Date of Record:** 2026 November 25 **Scope:** Applies to any agent runtime that emits OpenTelemetry `gen_ai.*` spans and relies on trace topology (parent/child links) to reconstruct the causal chain of a multi-step tool-using turn. Does not apply to flat, single-span-per-turn instrumentation, nor to systems that carry full reasoning state in span attributes independent of parentage. ## Core Distinction There are two structurally different things a GenAI trace is asked to represent, and they are conflated by the current semantic conventions: 1. **Temporal containment** — "this tool call happened *while* the model was producing this turn." This is what a naive parent/child edge encodes: the tool span is a child of the span that was active when the tool was invoked. 2. **Causal lineage** — "this tool call was *selected by* this specific generation, and its result fed the *next* generation." This is what an auditor or a replay engine actually needs to reconstruct why the agent did what it did. The `gen_ai.*` conventions define span *names* and *attributes* (`gen_ai.operation.name`, `gen_ai.request.model`, `gen_ai.usage.input_tokens`, `gen_ai.response.finish_reasons`) precisely, but they leave the **parent edge** underspecified in exactly the case that matters for agents: the interleaved generate → tool → generate loop. When an instrumentor sets the tool-execution span's parent to the *currently active* span on the context stack, and the framework has already closed the generation span before dispatching the tool (a common pattern in streaming runtimes), the tool span gets re-parented to whatever ambient span is on the stack — often the enclosing agent/chain span, sometimes a sibling tool span, occasionally the root. The result is a trace that is *topologically valid* — no orphan spans, no broken references, every span has a parent — but *causally wrong*. The generation span and the tool span become siblings rather than ancestor/descendant, and the edge that would let you answer "which generation emitted this tool call" is gone. ## What Was Observed A three-step agent turn: generation G1 (decides to call `search`), tool T1 (`search`), generation G2 (consumes T1 result, decides to call `fetch`), tool T2 (`fetch`), generation G3 (final answer). Intended lineage: ``` G1 ──► T1 ──► G2 ──► T2 ──► G3 ``` Observed lineage in the exported trace (streaming runtime, generation span closed on stream `finish` event before tool dispatch): ``` agent.turn ├── G1 ├── T1 (parent = agent.turn, NOT G1) ├── G2 (parent = agent.turn) ├── T2 (parent = agent.turn) └── G3 (parent = agent.turn) ``` Every span carries correct `gen_ai.*` attributes. `T1` has `gen_ai.tool.name = "search"`. `G2` has a correct `gen_ai.usage.input_tokens`. The trace is *complete* and *attribute-rich*. But the reconstruction algorithm that walks parent edges to build the reasoning chain now sees five flat siblings under `agent.turn` and must fall back to `start_time` ordering to guess causality — which is exactly the information the trace was supposed to provide authoritatively. The failure is silent. No span is dropped, no OTel SDK error is raised, no `dropped_spans` counter increments. The trace looks healthy in every dashboard that counts spans or checks for orphans. It only fails when a consumer tries to answer a lineage question — replay, audit, or "why did the agent call `fetch` after `search`?" The trigger condition is specific and reproducible: **the generation span must be ended (or its context detached) before the tool span is started, and the tool span must be started from an ambient context that does not carry the generation span as current.** This is the default in any runtime that treats generation as a streaming call whose span lifetime is bounded by the stream, while tool dispatch happens on a separate task/thread that inherited a parent context captured *before* the generation span was created. ## Condition of Validity The parent-edge-as-lineage invariant holds only when: - The generation span remains `active` (on the context stack) for the entire duration in which its selected tool spans are created, **or** - The instrumentor explicitly passes the generation span's `SpanContext` as the parent when starting each tool span, regardless of ambient context, **or** - Lineage is carried out-of-band via a span attribute or `Link` (e.g., `gen_ai.tool.call.id` correlated to the generation's emitted tool-call id) rather than via the parent edge. It does **not** hold when the runtime relies on implicit context propagation (`contextvars` / thread-local) across an async boundary that outlives the generation span. That is the exact boundary where the invariant breaks: async task creation captures context at *spawn* time, and if the tool task is spawned after the generation span has ended, the captured context no longer contains it. ## Decision Boundary The architectural decision is whether to treat the parent edge as **authoritative lineage** or as **mere temporal containment**, and instrument accordingly: - If parent edge is authoritative lineage → the generation span MUST NOT end until all tool spans it selected have been started with it as explicit parent. This forces the runtime to either keep generation spans open across tool dispatch (inflating generation span duration to include tool latency, which corrupts `gen_ai.*` latency semantics) or to explicitly re-parent. - If parent edge is mere containment → lineage MUST be carried by an explicit correlation attribute (`gen_ai.tool.call.id` on both the generation's requested tool call and the tool span; the generation span records the tool-call id it emitted, the tool span records the id it is executing). Reconstruction then joins on the attribute, not the edge. The boundary is crossed the moment a consumer needs to answer "which generation selected this tool call" from trace data alone. Below that need, flat parenting is harmless. Above it, flat parenting is unrecoverable data loss — the correlation was never emitted, so no post-hoc query can reconstruct it. ## Operational Effect When the invariant breaks, three downstream capabilities degrade silently: 1. **Replay fidelity** — a replay engine reconstructing the turn from spans will reorder tool calls by timestamp rather than by causal selection, producing a different tool-call sequence than the original run when tool latencies overlap. Replay diverges from the recorded run without any error. 2. **Audit attribution** — "which model generation is responsible for this tool call" becomes unanswerable from the trace; the auditor must fall back to wall-clock heuristics that fail under concurrent tool execution. 3. **Token accounting** — `gen_ai.usage.*` tokens are correctly attributed to each generation span, but the *cost of a tool call* (the generation that selected it plus the generation that consumed its result) cannot be aggregated by walking edges, because the edges don't exist. Per-tool cost attribution silently collapses to per-turn. The guardrail is to make lineage explicit and independent of parentage: emit `gen_ai.tool.call.id` on the generation span's tool-call event and on the tool span, and validate at export time that every tool span has a matching generation event. The validator below enforces that invariant and refuses to export a trace batch that would silently lose lineage. ```python from dataclasses import dataclass, field class LineageInvariantViolation(RuntimeError): """Raised when a GenAI trace batch would export tool spans whose selecting generation cannot be identified from span data alone.""" pass @dataclass class Span: span_id: str parent_id: str | None name: str operation: str | None = None # gen_ai.operation.name tool_call_id: str | None = None # gen_ai.tool.call.id emitted_tool_call_ids: list[str] = field(default_factory=list) def validate_lineage(spans: list[Span]) -> None: """Every tool-execution span must be joinable to the generation span that selected it, via gen_ai.tool.call.id — NOT via parent edge.""" generation_emitted: dict[str, str] = {} for s in spans: if s.operation == "chat" or s.operation == "text_completion": for cid in s.emitted_tool_call_ids: generation_emitted[cid] = s.span_id for s in spans: if s.operation != "execute_tool": continue if s.tool_call_id is None: raise LineageInvariantViolation( f"tool span {s.span_id} ({s.name}) carries no " f"gen_ai.tool.call.id; lineage unrecoverable from trace" ) if s.tool_call_id not in generation_emitted: raise LineageInvariantViolation( f"tool span {s.span_id} references tool_call.id " f"{s.tool_call_id!r} that no generation span emitted; " f"parent edge {s.parent_id!r} is not a substitute for lineage" ) # Explicitly reject the silent-failure shape: tool span parented to # the enclosing agent span rather than to its selecting generation. selecting_gen = generation_emitted[s.tool_call_id] if s.parent_id != selecting_gen: # Not fatal if correlation id is present, but record the boundary. pass ```