# Where must an instance reconcile span-close ordering when a tool-call span outlives its parent agent turn: the orphan-span attribution failure in OpenTelemetry GenAI traces **Date of Record:** 2026 November 21 **Scope:** Applies to agent runtimes that emit OpenTelemetry spans per reasoning turn, per tool call, and per LLM invocation under the GenAI semantic conventions, where a tool call can complete asynchronously after the parent agent turn span has already been closed. Does not apply to synchronous single-turn tool calls fully nested inside one parent span, nor to trace-only sampling regimes that discard partial traces before export. ## Core Distinction The GenAI semantic conventions model an LLM invocation as a span carrying `gen_ai.operation.name`, `gen_ai.request.model`, `gen_ai.usage.input_tokens`, `gen_ai.usage.output_tokens`, and tool calls as child spans carrying `gen_ai.tool.name`, `gen_ai.tool.call.id`, and `gen_ai.tool.type`. The conventions assume a *containment* topology: every tool-call span is a child of the agent-turn span that issued it, and the turn span's `end_time` is greater than or equal to every child's `end_time`. This is a structural invariant, not a convention note. The failure is that an agent turn frequently *does not* wait for its tool calls. A turn issues a long-running tool (a shell command, a web fetch, a sub-agent dispatch), then either yields to a scheduler, hits a token budget, or returns control to an outer loop. The runtime closes the turn span to record its latency and token usage — because those are the numbers the dashboard wants — while the tool-call span remains open. When the tool later completes, the runtime closes the tool span with an `end_time` strictly after the parent's. The trace is now temporally inconsistent: a child ends after its parent. This is the orphan-span attribution failure. It is non-obvious because OpenTelemetry does not reject it. The exporter accepts the span, the backend stores it, and the trace renders — with the tool call visually hanging below a turn that has already "finished." The damage is not a crash. The damage is that every downstream consumer of `gen_ai.usage.*` and every span-duration aggregation now attributes the tool's wall-clock latency to a turn that had already returned, corrupting per-turn cost and latency models. ## What Was Observed A three-tool agent loop on a single trace. Turn 1 issues `search` (fast, 40 ms) and `fetch_page` (slow, 4.2 s) in parallel via a fan-out, then yields. The turn span `agent.turn` closes at t+120 ms with `gen_ai.usage.input_tokens=1810`, `output_tokens=224`. The `search` child closes at t+40 ms — valid. The `fetch_page` child closes at t+4200 ms — 4.08 s *after* its parent. Observed consequences in the trace store: 1. **Duration inversion.** `agent.turn` reports 120 ms. The trace's total span tree reports 4.32 s. Any latency SLO computed on `agent.turn` duration misses the 4.2 s the user actually waited. 2. **Token attribution drift.** The turn's `output_tokens=224` was recorded before the tool result returned. When the tool result re-enters the context on Turn 2, those tokens are counted on Turn 2's `input_tokens`, not Turn 1's. The cost of *deciding* to call `fetch_page` is split across two spans that no longer share a parent-child edge in time. 3. **`gen_ai.tool.call.id` orphaned.** The tool span carries `gen_ai.tool.call.id="call_abc"`. Turn 2's LLM span carries the tool result in its prompt but no attribute linking it back to `call_abc`. The correlation between "what the tool returned" and "which turn consumed it" exists only in application memory, not in the trace. 4. **Sampling skew.** With tail-based sampling keyed on `agent.turn` duration, the 4.2 s slow tool is sampled as a *fast* trace. The slowest operations systematically under-represented. ## Condition of Validity The containment invariant — child `end_time` ≤ parent `end_time` — holds if and only if the parent span is not closed until all children are closed. This is achievable only under one of three runtime disciplines: - **Join-before-close:** the turn span is held open (or its close is deferred) until every tool-call span it spawned has ended. Correct but inflates turn latency to include tool wall-clock, which is often exactly what you *don't* want in a per-turn metric. - **Detached-child with explicit link:** the tool-call span is emitted as a root span (or a span whose parent is the trace root, not the turn) and carries an OpenTelemetry *span link* back to the turn span via `Link(trace_id, span_id)`. The turn span closes early; the tool span references it. Containment is replaced by *reference*. - **Turn span carries a synthetic end:** the turn span closes early but is annotated with `gen_ai.tool.pending=true` and the tool span, on close, emits a `gen_ai.tool.completed_after_turn=true` attribute. The backend must be taught to re-parent. Only the second discipline preserves both the metric semantics (turn latency excludes tool wall-clock) and the trace topology (no child outlives parent). The first corrupts latency; the third corrupts topology and requires backend cooperation the conventions do not specify. ## Decision Boundary The boundary is crossed at the moment a turn span is closed while a child tool span is still `RECORDING`. The runtime must decide, at close time, one of: - **Block** the close until children drain (join-before-close). Valid only when the tool timeout is bounded and less than the turn budget. - **Detach** the pending children to root-parented spans with links back to the turn. Valid when tool latency is unbounded or exceeds the turn budget. - **Abandon** the children (drop the spans). Never valid — it silently deletes the only record of the tool call. The runtime cannot decide this statically because tool latency is non-deterministic. The decision must be made per-close, based on whether the child set is empty. If non-empty, the close must either block or detach — never proceed with open children still parented to the closing span. The invariant to enforce: *a span may not be exported with `end_time` while any span referencing it as parent is still open.* This is checkable at export time by the SDK's span processor, which has visibility into the active span set. ## Operational Effect Enforcing the invariant at the span-processor layer converts the silent corruption into a loud, bounded failure. The processor, on `on_end(span)`, walks the active-child registry for that span; if any child is active, it either raises (strict mode, for development) or re-parents the pending children to the trace root and attaches a `Link` to the closing span (production mode). The trace backend then sees a valid tree: the turn span ends at 120 ms; the tool span is a sibling of the turn, linked to it, ending at 4.2 s. Duration aggregations on `agent.turn` remain correct; the tool's wall-clock is attributed to the tool span where it belongs; and the `gen_ai.tool.call.id` correlation survives because the link carries it. The cost is that the trace tree no longer reads as a clean nesting — tool calls appear as siblings of turns, not children. This is the correct topology for asynchronous tool execution, and it is the only topology that keeps the GenAI token and latency attributes honest. ```python from dataclasses import dataclass, field from typing import Optional class OrphanSpanAttributionError(RuntimeError): """Raised when a parent span closes while child spans remain open.""" @dataclass class Span: name: str span_id: str parent_id: Optional[str] start_time: float end_time: Optional[float] = None attributes: dict = field(default_factory=dict) links: list = field(default_factory=list) class SpanProcessor: def __init__(self, strict: bool = False): self.strict = strict self.active_children: dict[str, set[str]] = {} self.exported: list[Span] = [] def on_start(self, span: Span) -> None: self.active_children.setdefault(span.span_id, set()) if span.parent_id is not None: self.active_children.setdefault(span.parent_id, set()).add(span.span_id) def on_end(self, span: Span) -> None: if span.end_time is None: raise OrphanSpanAttributionError( f"span {span.name!r} ended without end_time" ) pending = self.active_children.get(span.span_id, set()) if pending: if self.strict: raise OrphanSpanAttributionError( f"span {span.name!r} ({span.span_id}) closed with " f"{len(pending)} open children: {sorted(pending)}" ) # Detach mode: re-parent pending children to trace root, # link each back to the closing span. for child_id in list(pending): child = self._find_active(child_id) if child is None: continue child.parent_id = None child.links.append( {"trace_id": span.attributes.get("trace_id"), "span_id": span.span_id, "relation": "gen_ai.tool.completed_after_turn"} ) child.attributes["gen_ai.tool.completed_after_turn"] = True self.active_children.pop(span.span_id, None) self.exported.append(span) def _find_active(self, span_id: str) -> Optional[Span]: for span in self.exported: if span.span_id == span_id: return span return None def close_turn_span(processor: SpanProcessor, turn: Span, tool_spans: list[Span]) -> None: """Close a turn span, enforcing the containment invariant.""" open_tools = [t for t in tool_spans if t.end_time is None] if open_tools: # Invariant: turn may not close with open children still parented. raise OrphanSpanAttributionError( f"turn {turn.name!r} attempted close with {len(open_tools)} " f"open tool spans: {[t.name for t in open_tools]}; " f"detach or join required before close" ) turn.end_time = max((t.end_time for t in tool_spans), default=turn.start_time) processor.on_end(turn) ```