# Where must an instance reject an OpenTelemetry GenAI span that closes a tool-call child before its parent agent-turn span, and how does the invariant survive partial export? **Date of Record:** 2026 November 30 **Scope:** Applies to any agent runtime that emits OpenTelemetry GenAI semantic-convention traces (`gen_ai.operation.name`, `gen_ai.agent.turn`, `gen_ai.tool.call`, `gen_ai.usage.*`) where a tool-call span is nested inside an agent-turn span and the export path may batch, retry, or drop spans independently. Does not apply to flat, single-span-per-request instrumentation, nor to traces where tool calls are siblings rather than children. ## Core Distinction The distinction that matters is between **span order as produced** and **span order as observed by the collector after the OTLP batch processor flushes**. The GenAI semantic conventions model an agent turn as a parent span with `gen_ai.operation.name = "chat"` (or `"agent.turn"` in newer drafts) whose children are `gen_ai.tool.call` spans. The convention assumes temporal nesting: a tool-call child's `start_time` and `end_time` fall inside the parent's interval, and the child's `parent_span_id` points at the turn. What fails is not the nesting itself but the **causal closure invariant**: a child span must not be *exported and accepted* before the parent span's `trace_id`/`span_id` pair is known to the receiving backend. In an agent loop, the tool call frequently completes *before* the enclosing turn span is closed—because the turn span must also record the post-tool reasoning step and the final `gen_ai.usage.output_tokens`. When the SDK's `BatchSpanProcessor` flushes on its 5-second schedule or on `max_export_batch_size` (default 512), the completed tool child can be exported in batch N while the still-open parent turn is exported in batch N+1. The backend then sees an orphan child. This is not a bug in span construction. It is a **boundary condition of the export pipeline interacting with the agent's turn lifecycle**. The agent turn is the longest-lived span in the trace (it spans model latency + tool latency + model latency), while tool spans are short. The shorter span always risks outliving its parent in the *export* order even though it is nested in the *production* order. ## What Was Observed A tool-calling agent (three-step loop: plan → `search_docs` tool → synthesize) emitted traces where `gen_ai.tool.call` spans arrived at the collector with `parent_span_id` set to a turn span that had not yet been received. The collector's trace assembler held the orphan in a pending buffer keyed by `parent_span_id`. Under normal load the parent arrived within one batch interval and the trace assembled correctly. Under a specific trigger the parent never arrived in time: the agent's final synthesis step hit a token-budget exhaustion (`gen_ai.usage.output_tokens` approaching `max_tokens`), the model returned a truncated response, and the runtime's error path called `span.end()` on the turn span but **then** attempted a retry that re-opened a *new* turn span with a fresh `span_id` while the tool child still referenced the old one. The retry path had reused the tool-call span object (it was cached in the agent's step state to avoid re-executing a side-effecting tool). Result: one tool child, two turn parents, neither matching the child's `parent_span_id`. The failure trace: 1. Turn span `T1` opened, `span_id = a1`. 2. Tool child `C` opened with `parent_span_id = a1`, tool executes, `C.end()`. Batch processor flushes `C` (batch 1). 3. Synthesis step exhausts token budget → runtime raises, calls `T1.end()` with error status. `T1` queued but not yet flushed. 4. Retry logic re-enters the loop, opens `T2`, `span_id = b2`, reuses cached `C` object (already ended) and re-emits it — now `C` is exported a second time with `parent_span_id = a1` still. 5. Batch 2 flushes `T1` and `T2`. Collector assembles: `C → a1` (valid), `C` duplicate → `a1` (duplicate span_id rejected or merged), `T2` has no children. The observable damage: the trace shows a turn `T2` with zero tool calls and a turn `T1` marked `STATUS_CODE_ERROR` that nonetheless has a completed, successful tool child. Any downstream evaluator that computes "did the agent use tools before answering?" on `T2` concludes *no*, and any cost attribution that sums `gen_ai.usage.*` per turn double-counts or mis-attributes the tool latency. ## Condition of Validity The causal closure invariant is valid **if and only if** the runtime guarantees that (a) a child span object is never re-emitted after `end()`, and (b) a turn span's `span_id` is immutable for the lifetime of the logical turn, including across retries. Condition (a) is violated by span-object caching for idempotent tool results—a common optimization when a tool is expensive and the agent loop may retry the *reasoning* step without re-running the tool. Condition (b) is violated by any retry path that treats "retry the turn" as "open a new turn span" while retaining child spans from the prior attempt. The invariant does **not** require that the parent be exported before the child. OTLP explicitly permits out-of-order span arrival; the collector buffers orphans. It requires only that the child's `parent_span_id` resolve to exactly one parent span with a matching `trace_id`, and that no span be emitted twice with the same `span_id`. Those are the two things the runtime must enforce, and neither is enforced by the OpenTelemetry SDK—the SDK will happily export a re-ended span and will happily export a child whose parent you never emit. ## Decision Boundary The boundary is: **when a turn is retried after a partial tool execution, does the retry inherit the prior attempt's child spans or fork a new trace?** - If the retry inherits child spans (reuse path), the runtime MUST either re-parent the child to the new turn span (mutating `parent_span_id`, which the SDK does not support post-`end()`) or keep the *original* turn span open across the retry (no new `span_id`). The latter is the only SDK-compatible option and requires the turn span to be ended exactly once, after the final attempt. - If the retry forks a new trace, the runtime MUST emit a `gen_ai.agent.retry` event or link (`SpanLink`) from `T2` to `T1`, and MUST NOT re-emit `C`. The cached tool result is recorded as an attribute on `T2` (`gen_ai.tool.cached = true`), not as a span. Choosing "reuse the child span object" is the failure. Choosing "keep the turn span open across retries" is correct but conflicts with error-path code that ends the span on the first exception. The decision must be made at the point where the runtime decides whether an exception is terminal—and for a token-budget exhaustion mid-synthesis, it is *not* terminal if a retry follows. ## Operational Effect The practical consequence is that **span-level error status and trace-level tool-call presence diverge**, and every consumer of the trace must be written to tolerate it or the runtime must prevent it. Concretely: - Evaluators computing tool-use rates must key on `trace_id` + tool-call span existence, not on per-turn child counts, because retried turns legitimately have zero children in the forked model. - Cost attribution must deduplicate by `span_id` before summing `gen_ai.usage.*`, because the reuse path emits the tool span twice. - The collector's orphan buffer must be sized for the worst-case turn duration (model latency × attempts), not the batch interval, or orphan children are dropped and the trace silently loses tool evidence. The guardrail that bounds this: a single `TurnSpan` object per logical turn, ended exactly once in a `finally` that runs after all retries, with child tool spans that are never re-emitted—and a runtime assertion that a `span_id` is emitted at most once per trace. ```python class SpanReemissionError(RuntimeError): """Raised when a runtime attempts to re-emit an already-ended span or emit a tool-call child whose parent turn span was never closed.""" pass class TurnSpanRegistry: """Enforces the causal closure invariant for GenAI agent-turn traces: one turn span per logical turn, ended exactly once; tool children are emitted once and never re-parented or re-emitted across retries.""" def __init__(self): self._open_turns = {} # logical_turn_id -> span self._emitted_span_ids = set() self._emitted_children = set() # (logical_turn_id, tool_call_id) def open_turn(self, logical_turn_id, span): if logical_turn_id in self._open_turns: # Retry path tried to fork a new turn span for the same logical turn. raise SpanReemissionError( f"turn {logical_turn_id} already open; retries must reuse the " f"existing span, not open a new one" ) self._open_turns[logical_turn_id] = span return span def emit_tool_child(self, logical_turn_id, tool_call_id, child_span): if logical_turn_id not in self._open_turns: raise SpanReemissionError( f"tool child {tool_call_id} emitted for turn {logical_turn_id} " f"with no open parent turn span" ) key = (logical_turn_id, tool_call_id) if key in self._emitted_children: # Cached tool span being re-emitted on retry. raise SpanReemissionError( f"tool child {tool_call_id} already emitted for turn " f"{logical_turn_id}; record cached result as attribute, " f"do not re-emit span" ) if child_span.span_id in self._emitted_span_ids: raise SpanReemissionError( f"span_id {child_span.span_id} already emitted in this trace" ) parent = self._open_turns[logical_turn_id] if child_span.parent_span_id != parent.span_id: raise SpanReemissionError( f"tool child parent_span_id {child_span.parent_span_id} does not " f"match open turn span_id {parent.span_id}" ) self._emitted_children.add(key) self._emitted_span_ids.add(child_span.span_id) return child_span def close_turn(self, logical_turn_id, span, terminal: bool): """End the turn span exactly once. Non-terminal errors (e.g. token-budget exhaustion followed by retry) must NOT close the turn.""" if logical_turn_id not in self._open_turns: raise SpanReemissionError( f"close_turn called for {logical_turn_id} which is not open" ) if self._open_turns[logical_turn_id] is not span: raise SpanReemissionError( f"close_turn span identity mismatch for {logical_turn_id}" ) if not terminal: # Retry follows: keep the turn span open, do not end it. return if span.span_id in self._emitted_span_ids: raise SpanReemissionError( f"turn span_id {span.span_id} already emitted" ) self._emitted_span_ids.add(span.span_id) del self._open_turns[logical_turn_id] span.end() ```