# Which invariants prevent OpenTelemetry GenAI span graphs from silently orphaning tool-call edges across multi-turn agent invocations **Date of Record:** 2026 November 23 **Scope:** Applies to agents that emit OpenTelemetry GenAI spans (`gen_ai.*`) where a single user turn fans out into nested tool-call spans and where the same agent instance is resumed across turns (checkpoint/resume, stateless re-invocation with replayed history). Does not apply to single-shot completions with no tool calls, nor to agents whose span export is synchronous and strictly parented within one process lifetime. ## Core Distinction The failure is not "missing spans." It is **span-graph edge orphaning under turn resumption**: a tool-call span that was correctly parented to turn N's invocation span gets re-emitted, re-linked, or re-counted under turn N+1 because the agent's runtime reconstructs its context from a serialized transcript rather than from a live trace context. The GenAI semantic conventions define attribute keys (`gen_ai.operation.name`, `gen_ai.tool.name`, `gen_ai.usage.input_tokens`, `gen_ai.conversation.id`, `gen_ai.request.model`) but they do **not** mandate a parent-child topology invariant across turns. That gap is where the invariant must be supplied by the runtime, not the exporter. The distinction that matters: a *span* is a unit of observation; a *tool-call edge* is a claim about causal dependency between an LLM decision and an external effect. When the transcript is replayed, the observation is reproduced but the causal edge is fabricated, because the tool did not actually re-execute. The trace looks complete and is semantically false. ## What Was Observed A three-turn agent (`gen_ai.conversation.id = conv-7f2a`) using a stateless executor. Each turn the orchestrator deserialized the prior transcript, re-attached a fresh root `invoke_agent` span, and replayed the message list. On turn 2, the model requested a tool already invoked on turn 1 (`gen_ai.tool.name = "search_docs"`). Observed trace shape: - Turn 1: `invoke_agent` (root) → `execute_tool search_docs` (child, real execution, `gen_ai.usage.input_tokens=1840`). - Turn 2: `invoke_agent` (new root, `parent_span_id` empty) → `execute_tool search_docs` (new child). The runtime re-serialized the *prior* tool result into the prompt but the new `execute_tool` span recorded `start_time` at replay, not at the original execution, and carried `gen_ai.tool.call.id` freshly minted. Two artifacts resulted. First, the trace now asserts the tool ran twice; downstream cost attribution double-counted the tool's token and latency contribution. Second, because turn 2's root had no link to turn 1's root, the conversation was represented as two disconnected traces that shared only `gen_ai.conversation.id`. Any auditor reconstructing "what did the agent know when it decided" from the graph alone could not traverse from turn 2's decision back to turn 1's tool output — the very edge that justified the decision was severed. A second variant, worse: when the runtime *did* attempt to preserve parentage by copying the prior `trace_id`/`span_id` into the new turn's context, the exporter emitted a child span whose parent had already been exported and closed in a prior batch. The collector accepted it; the backend's span assembler, on late-arriving child, either dropped the edge or (in one backend) created a phantom parent stub with `status=UNSET`. The graph then contained a node with no `gen_ai.operation.name`, which broke every downstream query that filtered on operation name. ## Condition of Validity The invariant that must hold is: > For a given `gen_ai.conversation.id`, every `execute_tool` span with a given `gen_ai.tool.call.id` is emitted **exactly once**, and its parent is the `invoke_agent` span of the turn whose model output actually requested it. Replayed tool results must appear as *attributes or events on the new invocation span* (e.g., a `gen_ai.tool.result.replayed=true` event), never as a re-emitted `execute_tool` span. This holds only when the runtime distinguishes three states that the semantic conventions conflate: (a) a tool call that *executed this turn*, (b) a tool result that is *present in the replayed transcript*, and (c) a tool call that is *pending re-execution*. The conventions provide `gen_ai.tool.call.id` but no required uniqueness scope or replay marker. Without a runtime-enforced `tool.call.id` registry keyed on conversation, the invariant is unenforceable at the exporter layer. The invariant is **not** valid to assume for: streaming partial turns, agents that legitimately re-invoke the same tool within one turn (there the call.id must differ), or cross-process handoffs where the receiving process cannot see the emitting process's span registry — those require an explicit `links` entry to the originating span rather than a parent edge. ## Decision Boundary The boundary is: **does the runtime own the trace context, or does it own only the transcript?** - If the runtime owns trace context (live `SpanContext` threaded through the executor), parent-child edges are trustworthy and the only risk is late-export ordering — solvable by forcing child flush before parent close. - If the runtime owns only the transcript (stateless resume), it **must not** synthesize parent edges from serialized history. It must instead: mint a new root per turn, attach `gen_ai.conversation.id`, and record prior tool outputs as replayed events. Cross-turn causality is then expressed via `Span.links` to the prior turn's root `span_id`, which is explicitly a non-parenting relation and survives late arrival. Crossing this boundary incorrectly — synthesizing parentage from transcript — produces graphs that pass schema validation and fail causal audit. The decision must be made at the executor's resume path, not at the exporter, because the exporter cannot distinguish a re-executed tool from a replayed one. ## Operational Effect With the invariant enforced (new root per turn + `links` to prior root + replay events instead of re-emitted tool spans), cost attribution per conversation becomes additive and correct, causal traversal from decision to evidence is intact via links, and late-arriving spans cannot create phantom parents. Without it, the trace is a plausible-looking fiction: token counts inflate by replay multiplicity, tool latency is attributed to the wrong turn, and any automated auditor that trusts parent edges will conclude the agent re-derived knowledge it actually inherited from context. The guardrail is a runtime assertion at resume: refuse to emit an `execute_tool` span whose `tool.call.id` already exists in the conversation registry, and refuse to set `parent_span_id` to any span not opened in the current process's live context. ```python from __future__ import annotations from dataclasses import dataclass, field from typing import Optional class SpanGraphInvariantError(RuntimeError): """Raised when a resumed agent turn would violate tool-call edge invariants.""" @dataclass class SpanRecord: trace_id: str span_id: str parent_span_id: Optional[str] operation_name: str tool_call_id: Optional[str] = None replayed: bool = False @dataclass class ConversationSpanRegistry: """Per-conversation registry enforcing exactly-once tool-call edges.""" conversation_id: str live_span_ids: set[str] = field(default_factory=set) emitted_tool_calls: dict[str, str] = field(default_factory=dict) # call_id -> turn root span_id prior_turn_roots: list[str] = field(default_factory=list) def open_turn_root(self, trace_id: str, span_id: str) -> SpanRecord: record = SpanRecord( trace_id=trace_id, span_id=span_id, parent_span_id=None, operation_name="invoke_agent", ) self.live_span_ids.add(span_id) return record def close_turn_root(self, span_id: str) -> None: self.live_span_ids.discard(span_id) self.prior_turn_roots.append(span_id) def emit_tool_call( self, trace_id: str, span_id: str, parent_span_id: str, tool_call_id: str, tool_name: str, ) -> SpanRecord: # Invariant 1: parent must be a live span in this process context. if parent_span_id not in self.live_span_ids: raise SpanGraphInvariantError( f"tool span {span_id} parent {parent_span_id} is not live; " f"cannot synthesize parentage from serialized transcript " f"(conversation={self.conversation_id})" ) # Invariant 2: exactly-once emission per tool_call_id per conversation. if tool_call_id in self.emitted_tool_calls: prior_root = self.emitted_tool_calls[tool_call_id] raise SpanGraphInvariantError( f"tool_call_id {tool_call_id} already emitted under turn root " f"{prior_root}; replayed results must be recorded as events, " f"not re-emitted execute_tool spans " f"(conversation={self.conversation_id})" ) self.emitted_tool_calls[tool_call_id] = parent_span_id return SpanRecord( trace_id=trace_id, span_id=span_id, parent_span_id=parent_span_id, operation_name="execute_tool", tool_call_id=tool_call_id, ) def record_replayed_tool_result( self, tool_call_id: str, originating_turn_root: str ) -> SpanRecord: """Replay is expressed as an event on the new turn, linked (not parented).""" if tool_call_id not in self.emitted_tool_calls: raise SpanGraphInvariantError( f"replay of unknown tool_call_id {tool_call_id}; " f"conversation {self.conversation_id} has no originating span" ) return SpanRecord( trace_id="", span_id="", parent_span_id=None, operation_name="gen_ai.tool.result.replayed", tool_call_id=tool_call_id, replayed=True, ) ```