# Which invariants prevent OpenTelemetry GenAI span trees from silently dropping tool-call causality during agent turn fan-out **Date of Record:** 2026 November 25 **Scope:** Applies to agents emitting OpenTelemetry GenAI semantic-convention spans (`gen_ai.operation.name`, `gen_ai.tool.name`, `gen_ai.agent.*`, tool-call and agent-turn spans) where a single logical turn fans out into concurrent tool invocations whose spans are parented by a shared turn span. Does not apply to single-threaded synchronous tool loops with strictly serial execution, nor to tracing that uses only non-GenAI custom attributes. ## Core Distinction The failure is not "missing spans." It is **causal misattribution under fan-out**: the span tree remains structurally valid and every span is exported, yet the *parent-child edge* that should bind a tool result to the specific model turn that requested it is either (a) collapsed onto a single turn span, or (b) re-parented to whichever tool span the exporter's context happened to be holding when a non-deterministic tool returned. The observable symptom is a trace that looks complete — no orphans, no `dropped_spans` — but where a downstream replay or verifier reconstructing "which tool output fed which reasoning step" produces a different causal graph than the agent actually executed. The invariant that matters: **a tool-call span's parent MUST be the specific `gen_ai.operation.name=chat` (or `agent.turn`) span whose request message carries the corresponding tool-call ID, and the span's `gen_ai.tool.call.id` MUST equal the `tool_calls[].id` emitted by the model in that parent's completion.** When this holds, the span tree is a faithful DAG of the agent's reasoning. When it does not, the tree is a *plausible but wrong* DAG — the most dangerous kind of telemetry defect, because it passes schema validation and lulls auditors. ## What Was Observed An agent turn issues a model call that returns three tool calls in one assistant message (`tool_calls: [{id: "call_a"}, {id: "call_b"}, {id: "call_c"}]`). The runtime fans out: it spawns three concurrent async tasks, each of which opens a `gen_ai.operation.name=execute_tool` span. Because the runtime propagates OTel context via a contextvar (task-local, not inherited unless explicitly copied), the three tool spans do not all inherit the turn span's `SpanContext`. Two failure traces were observed: 1. **Loss of parent via contextvar reset.** The fan-out used `asyncio.gather` with tasks created *after* the turn span was detached (the turn span was ended when the model call returned, before tool execution began). The three tool spans attached to the *root* span. The trace now reads: root → tool_a, tool_b, tool_c, with no `chat` parent. A reconstructor cannot tell whether these tools were requested by the turn or by some earlier turn — the causal edge is gone even though every span exists. 2. **Cross-wiring under non-deterministic completion order.** Tool `call_b` returned first and, in a shared mutable "current tool context," the runtime wrote `call_b`'s result. When `call_a` finished second, its span was created using the *mutable* context pointer, so `call_a`'s span got `gen_ai.tool.call.id=call_b`. The exported spans had correct names but swapped call IDs. A replay that maps `tool.call.id → tool result` now attributes `call_b`'s output to `call_a`'s reasoning step. The model's subsequent reasoning, which depended on `call_a`'s actual output, is recorded as having depended on `call_b`'s. In both cases the span tree passed the OTel GenAI schema check: required attributes present, `trace_id` consistent, no orphan spans flagged. The defect is invisible to schema validation because the schema constrains *attribute presence and type*, not the *referential integrity between a parent's completion payload and a child's call ID*. ## Condition of Validity The invariant holds only under these conditions, and fails silently outside them: - **The turn span must remain the active parent for the entire duration of all tool calls it requested.** This means the turn span cannot be ended at model-response boundary; it must be closed after all descendant tool spans terminate. If the runtime treats the model call as the turn (ending the span on response), fan-out necessarily orphans tool spans. - **Context propagation must be explicit and per-task, not via a shared mutable pointer.** The call ID must be captured *at the moment the model response is parsed* and passed as an immutable parameter into each tool task; it must never be read from a shared "current call" variable at span-creation time. - **Concurrent completion order must not influence span attributes.** Because tool completion is non-deterministic (network, sandbox latency), any code path where span attributes depend on completion order violates the invariant. ## Decision Boundary The decision is between two span-modeling strategies at the fan-out point, and the boundary is *whether the turn span outlives its tool children*: - If the runtime can guarantee the turn span stays open across fan-out (structural parent + immutable per-task call ID), use the nested model: `turn → {tool_a, tool_b, tool_c}`, each child carrying its own `gen_ai.tool.call.id` as an immutable attribute. - If the runtime *cannot* keep the turn span open (e.g., the model call and tool execution are in separate processes, or the turn span is closed for latency accounting), then the nested model is invalid and you MUST fall back to a **link-based model**: tool spans carry `SpanLink` back to the turn span plus the call ID as a first-class attribute, and the reconstructor MUST join on `(turn.span_id, tool.call.id)` rather than on parent pointers. The failure occurs precisely when a system *uses the nested model but cannot satisfy its parent-lifetime precondition* — it emits a tree that looks nested but is not causally nested. ## Operational Effect Downstream, a verification replay that reconstructs the agent's causal graph from spans will diverge from the agent's actual execution trace. This is not a cosmetic tracing bug: in systems where the span tree is the audit substrate (safety review, incident reconstruction, or a verifier agent cross-checking a peer's tool use), a misattributed call ID means the auditor attributes an output to the wrong reasoning step. In the worst case, a tool that returned a poisoned or injected result is recorded as feeding a *different* step than the one it actually poisoned, so post-hoc injection analysis misses the injection entirely. The guardrail is to assert, at span-close time, that every tool span's `gen_ai.tool.call.id` appears in its parent turn span's recorded completion `tool_calls[].id` set, and to fail the emit (not silently export) when it does not. ```python from dataclasses import dataclass, field from typing import Optional class SpanCausalityViolation(RuntimeError): """Raised when a tool-call span's parent/call-id edge is not causally valid.""" pass @dataclass class TurnSpan: span_id: str requested_call_ids: set[str] = field(default_factory=set) closed: bool = False @dataclass class ToolSpan: span_id: str parent_span_id: Optional[str] tool_call_id: str def validate_tool_span_causality(turn: TurnSpan, tool: ToolSpan) -> None: """Enforce the invariant: tool span must be parented by the turn that requested its call ID, and that call ID must be in the turn's completion.""" if turn.closed: raise SpanCausalityViolation( f"turn {turn.span_id} closed before tool {tool.tool_call_id} " "reported; parent edge lost (orphaned fan-out)" ) if tool.parent_span_id != turn.span_id: raise SpanCausalityViolation( f"tool {tool.tool_call_id} parented to {tool.parent_span_id}, " f"expected turn {turn.span_id} (contextvar reset / cross-wire)" ) if tool.tool_call_id not in turn.requested_call_ids: raise SpanCausalityViolation( f"tool {tool.tool_call_id} not present in turn {turn.span_id} " f"completion tool_calls {sorted(turn.requested_call_ids)} " "(call-id swap under non-deterministic completion order)" ) def emit_fanout(turn: TurnSpan, tools: list[ToolSpan]) -> None: for t in tools: validate_tool_span_causality(turn, t) # only reached if every child edge is causally faithful ```