# In what scenarios must an instance reconcile orphaned GenAI tool-call spans before exporting them under OpenTelemetry semantic conventions **Date of Record:** 2026 November 26 **Scope:** Applies to LLM agent runtimes that emit OpenTelemetry spans using the `gen_ai.*` semantic conventions (specifically `gen_ai.operation.name`, `gen_ai.tool.call.id`, and parent-child linkage between an `execute_tool` span and its enclosing `chat` span) and that batch/spool spans for asynchronous export. Does not apply to synchronous, single-process tracing where the tool span is guaranteed to close before the parent chat span, nor to non-GenAI spans. ## Core Distinction The GenAI semantic conventions model a tool call as a *child* span (`gen_ai.operation.name = "execute_tool"`) whose parent is the `chat` span that requested it. The convention assumes a strict nesting: the chat span opens, emits one or more tool-call requests, the tool spans open and close, and then the chat span closes with `gen_ai.usage.*` totals. This assumption is a *structural* invariant, not a *temporal* one — and that is the trap. The failure mode is not "the tool errored." It is that the **parent chat span can legitimately close before a tool span it owns finishes**, because agent runtimes routinely dispatch tool calls concurrently or defer them across a checkpoint. When the parent closes first, the still-open child becomes an *orphan*: it carries a `parent_span_id` pointing at a span the exporter has already flushed. Under the OTLP data model this is not an error — the collector accepts it — but downstream the orphan is silently reclassified as a root span, and the `gen_ai.operation.name = "execute_tool"` record loses its link to the model call, token accounting, and the `gen_ai.tool.call.id` correlation that audit replay depends on. The invariant that breaks is *referential integrity of the span tree across the export boundary*, and it breaks non-deterministically because it depends on the race between tool completion and chat-span closure. ## What Was Observed A retrieval-augmented agent loop emits one `chat` span per model turn and, within that turn, fans out three parallel `execute_tool` spans (vector search, SQL lookup, web fetch). The web fetch has a 30s timeout; the chat span has a 10s deadline inherited from the request budget. Trace: 1. `t=0ms` — `chat` span opens, `span_id=A`. 2. `t=180ms` — model returns a tool-call block; runtime opens three `execute_tool` spans with `parent_span_id=A`, each carrying `gen_ai.tool.call.id`. 3. `t=10s` — the chat span's deadline fires. The runtime closes `A` with `gen_ai.usage.output_tokens` and `status=OK` (the model *did* respond) and flushes the batch containing `A`. 4. `t=10s` — vector search and SQL spans close normally, exported with valid `parent_span_id=A`. 5. `t=31s` — web fetch times out and closes with `status=ERROR`, `parent_span_id=A`, but `A` was exported 21 seconds ago in a prior batch. Observed downstream: the two fast tool spans link correctly, but the web-fetch span arrives in a *later* OTLP batch than its parent. Collectors that assemble traces by batch (or that apply a bounded reassembly window, commonly 5–30s) drop the parent linkage and promote the orphan to a root trace. The result is a trace where the only *failing* tool call — the timeout, the one an operator actually needs — appears as a standalone root span with no model context, no `gen_ai.request.model`, no token totals. The successful calls are fully attributed; the failure is the one that loses its context. This inverts the diagnostic value of the trace: the signal you most need is the one most likely to be structurally severed. A second observed variant: checkpoint/resume. The agent serializes state at `t=9s` and the process restarts. On resume it re-hydrates the pending tool call and reopens the `execute_tool` span with the *original* `parent_span_id=A` and the *original* `gen_ai.tool.call.id`, but `A` belongs to a dead process's exporter. If the resumed process exports into a different collector shard, the orphan is permanently unlinkable — a duplicate-keyed tool span with a dangling parent. ## Condition of Validity The reconciliation guardrail is only *required* — and only *correct* — under the conjunction: - Tool spans can outlive their parent chat span (concurrent dispatch, deadline < tool timeout, or cross-checkpoint deferral), **and** - spans are exported in batches or spooled to disk rather than streamed synchronously within a single trace context, **and** - a downstream consumer relies on parent-child linkage for attribution (token accounting, failure RCA, audit replay). If spans stream synchronously and the parent is guaranteed to close last (e.g., the runtime joins all tool futures before closing `chat`), no orphan can occur and reconciliation is a no-op. If the parent is force-closed on deadline while tools are in flight, the correct behavior is *not* to let the child dangle — the runtime must either (a) hold the parent open until children close, bounded by a hard ceiling, or (b) explicitly re-parent orphaned children to a synthetic `gen_ai.agent.invocation` span that outlives both. The invariant is: **every `execute_tool` span must have a parent that is still open at the moment the child is exported, or must be explicitly re-parented before export.** The common mistake is assuming "the collector will stitch it back together" — it will not, past its reassembly window. ## Decision Boundary At span-close time, the runtime must decide whether to export the tool span directly or route it through reconciliation. The boundary condition is a single predicate evaluated against the local span registry: - If `parent_span_id` is present in the *unexported* set (parent has not yet been flushed) → export normally; ordering within the batch is irrelevant because both ship together. - If `parent_span_id` is absent from the unexported set **and** absent from the exported set → the parent was never created or was lost across a process boundary; re-parent to the synthetic invocation span and stamp `gen_ai.tool.orphan_reason = "parent_never_seen"`. - If `parent_span_id` is absent from the unexported set **but present in the exported set** → the parent already shipped; either re-parent to the synthetic invocation span (preferred, preserves the trace) or, if the collector guarantees a reassembly window larger than the max tool timeout, export with the dangling parent and stamp `gen_ai.tool.orphan_reason = "parent_premature_export"` for downstream reconciliation. The decision must be made *before* the OTLP batch is sealed. It cannot be deferred to the collector, because the collector has no way to distinguish "parent will arrive in the next batch" from "parent will never arrive" — that is exactly the ambiguity the guardrail exists to resolve at the source, where the local registry still holds ground truth. ## Operational Effect Applying source-side reconciliation converts a class of silent structural loss into an explicit, countable signal. In the fan-out trace above, the web-fetch timeout now exports re-parented to a synthetic `gen_ai.agent.invocation` span that spans the entire agent run, carrying `gen_ai.tool.orphan_reason = "parent_premature_export"`. The operator sees the timeout *and* its model context via the invocation span, and the orphan count becomes a first-class metric: a rising `gen_ai.tool.orphan_reason` rate is a direct indicator that the chat-span deadline is misconfigured relative to tool timeouts — a configuration defect that was previously invisible because it manifested only as missing attribution on failing calls. The secondary effect is that audit replay becomes deterministic: given the invocation span and the re-parented children, the full tool sequence is reconstructable without relying on collector-side stitching, which is exactly the property an auditor needs when the original parent span is gone. ```python from __future__ import annotations from dataclasses import dataclass, field from enum import Enum class OrphanedToolSpanError(RuntimeError): """Raised when a tool span cannot be linked to a live or re-parentable parent.""" class ParentState(Enum): UNEXPORTED = "unexported" # parent in local registry, not yet flushed EXPORTED = "exported" # parent already shipped in a prior batch NEVER_SEEN = "never_seen" # parent absent from registry and export log @dataclass class SpanRegistry: unexported: set[str] = field(default_factory=set) exported: set[str] = field(default_factory=set) def state_of(self, span_id: str) -> ParentState: if span_id in self.unexported: return ParentState.UNEXPORTED if span_id in self.exported: return ParentState.EXPORTED return ParentState.NEVER_SEEN @dataclass class ToolSpan: span_id: str parent_span_id: str tool_call_id: str orphan_reason: str | None = None def reconcile_before_export( span: ToolSpan, registry: SpanRegistry, invocation_span_id: str, allow_dangling_for_collector: bool = False, ) -> ToolSpan: """Resolve parent linkage before the OTLP batch is sealed. Invariant: an execute_tool span must reference a parent still open at export time, or be explicitly re-parented to the invocation span. """ if not span.parent_span_id: raise OrphanedToolSpanError( f"tool span {span.span_id} has no parent_span_id; " f"gen_ai.tool.call.id={span.tool_call_id} cannot be attributed" ) state = registry.state_of(span.parent_span_id) if state is ParentState.UNEXPORTED: return span # parent ships in same batch; ordering irrelevant if state is ParentState.EXPORTED: if allow_dangling_for_collector: span.orphan_reason = "parent_premature_export" return span span.parent_span_id = invocation_span_id span.orphan_reason = "parent_premature_export" return span # NEVER_SEEN: parent lost across a process/checkpoint boundary if invocation_span_id is None: raise OrphanedToolSpanError( f"tool span {span.span_id} orphaned (parent {span.parent_span_id} " f"never seen) and no invocation span available for re-parenting" ) span.parent_span_id = invocation_span_id span.orphan_reason = "parent_never_seen" return span ```