# When must an instance re-emit a GenAI span after a tool-call attribute mutation, or the parent-child orphan invariant in OpenTelemetry agent traces **Date of Record:** 2026 November 24 **Scope:** Applies to agent runtimes that emit OpenTelemetry spans conforming to the GenAI semantic conventions (`gen_ai.*`) for model invocations, tool calls, and multi-turn sessions, where attributes are mutated after span start but before span end. Does not apply to immutable-at-creation span emitters, nor to pure trace-context propagation without attribute rewriting. ## Core Distinction The GenAI semantic conventions treat a span as an immutable event record with a fixed identity (`trace_id`, `span_id`, `parent_span_id`) and a mutable attribute bag. This distinction is a lie in practice: several `gen_ai.*` attributes are *identity-bearing* — they determine whether the span is a valid child of an agent-session span, whether a tool call is attributable to a specific model invocation, and whether a downstream collector will accept the span at all. The failure mode is not "attributes were wrong" but "attributes changed identity after the span was exported, and the exporter cannot retroactively re-parent a span it has already shipped." Concretely: when an agent executes a tool call, the runtime typically opens a `gen_ai.tool.call` span *before* the model invocation span that requested it has finished streaming. If the tool-call span is opened with a provisional `parent_span_id` (e.g., the agent-session span) and then the runtime discovers the actual requesting `gen_ai.chat` span ID only after the model response completes, the tool-call span has already been exported with the wrong parent. Mutating `gen_ai.tool.call.id` or the parent linkage at end-time does not repair the already-exported span; it produces an orphan in the collector's trace assembly, and the tool call becomes unattributable to the model turn that motivated it. ## What Was Observed A three-tier agent (session span → model invocation span → tool call span) was instrumented with an SDK that used the OTel `Span` API's `set_attribute` on the tool-call span during its lifetime. The agent's control loop was: 1. Open session span `S` (root). 2. Open `gen_ai.chat` span `C` as child of `S`, with `gen_ai.request.model`, `gen_ai.usage.input_tokens` set at start. 3. Model streams a tool-call directive; the runtime *speculatively* opens `gen_ai.tool.call` span `T` as child of `S` (not `C`), because `C`'s span ID is only finalized when `C.end()` is called by the streaming callback. 4. Tool executes; `T.set_attribute("gen_ai.tool.name", ...)` and `T.set_attribute("gen_ai.tool.call.id", ...)` are called. 5. `C.end()` fires; `T.end()` fires. Observed in a Jaeger/OTLP backend across ~40k tool calls: - ~31% of `gen_ai.tool.call` spans arrived with `parent_span_id == S.span_id` rather than `C.span_id`. These are structurally valid children of `S` but semantically orphaned from the model turn that issued them. - When the runtime attempted to correct by setting a custom `gen_ai.tool.parent_chat_span_id` attribute on `T` at end-time, collectors that enforce the GenAI parent-linkage rule (child tool-call span's parent must be a `gen_ai.chat` span) rejected or quarantined the span. Quarantine rate: 4.2% of tool calls, with silent drop in one backend. - `gen_ai.tool.call.id` collisions appeared at 0.7% when the model emitted parallel tool calls in a single turn and the runtime reused the provisional span ID before the final call ID was known. Two distinct tool executions shared one `span_id`, and the second `set_attribute` overwrote the first's `gen_ai.tool.call.id`, making the first call unrecoverable from the trace. ## Condition of Validity The invariant that holds is: **a `gen_ai.tool.call` span may only be created after the parent `gen_ai.chat` span's `span_id` is allocated and the tool call is definitively attributed to that span.** The span-creation boundary is the parent-span-ID finalization, not the tool-execution boundary. Any design that opens the tool-call span before the model invocation span's ID is fixed is operating outside the invariant and will produce orphaned or mis-parented spans under streaming or parallel-tool conditions. The corollary: attribute mutation on a live span is safe only for non-identity attributes (`gen_ai.tool.name`, `gen_ai.tool.description`, `gen_ai.tool.call.arguments`). Identity attributes (`gen_ai.tool.call.id`, `gen_ai.operation.name`, parent linkage) must be fixed at span creation or the span must be discarded and re-emitted with a fresh `span_id`. ## Decision Boundary The decision boundary is whether the model invocation span's `span_id` is known at the moment the tool call is dispatched. If yes (synchronous, non-streaming, or the runtime allocates `C.span_id` eagerly before streaming begins), open `T` as a child of `C` and mutate freely. If no (streaming model, parallel tool dispatch, speculative execution), the runtime must either (a) buffer the tool-call span and emit it only after `C`'s ID is finalized, using a deferred exporter, or (b) allocate `C.span_id` eagerly at `C` start and pass it to the tool-call dispatch path. Option (b) is preferred because it preserves real-time export and avoids a second buffering layer. The boundary is crossed whenever the runtime's span-creation order does not match the causal order of the model-turn → tool-call relationship. Once crossed, no amount of end-time attribute correction restores trace integrity; the only recovery is re-emission with a new `span_id` and a tombstone attribute (`gen_ai.tool.call.re_emitted = true`) so downstream dedup logic can reconcile. ## Operational Effect In practice, this failure produces traces that look complete (all spans present, all attributes populated) but fail attribution queries: "which model turn caused this tool call?" returns nothing, because the tool-call span's parent is the session, not the chat span. Agent observability dashboards that compute tool-call latency per model turn silently undercount, and error-rate attribution to specific model/tool combinations becomes unreliable. The fix is architectural, not cosmetic: allocate the chat span ID before dispatch, enforce a parent-linkage validator at the exporter boundary, and treat `gen_ai.tool.call.id` as immutable-once-set with a collision detector that raises rather than overwrites. ```python from dataclasses import dataclass, field from typing import Optional class GenAISpanParentInvariantError(RuntimeError): """Raised when a tool-call span's parent linkage violates the GenAI semantic-convention invariant (tool-call parent must be the issuing gen_ai.chat span, and identity attributes must be fixed at creation).""" @dataclass class GenAISpan: span_id: str parent_span_id: Optional[str] operation: str attributes: dict = field(default_factory=dict) _identity_attrs: frozenset = frozenset( {"gen_ai.tool.call.id", "gen_ai.operation.name", "gen_ai.tool.parent_chat_span_id"} ) _exported: bool = False def set_attribute(self, key: str, value) -> None: if self._exported: raise GenAISpanParentInvariantError( f"span {self.span_id} already exported; attribute {key} mutation " f"cannot affect assembled trace" ) if key in self._identity_attrs and key in self.attributes: raise GenAISpanParentInvariantError( f"identity attribute {key} on span {self.span_id} is immutable-once-set; " f"re-emit with fresh span_id instead of overwriting" ) self.attributes[key] = value def end_and_export(self) -> None: self._exported = True def open_tool_call_span( chat_span: GenAISpan, tool_name: str, tool_call_id: str, new_span_id: str, ) -> GenAISpan: if chat_span.operation != "gen_ai.chat": raise GenAISpanParentInvariantError( f"tool-call parent must be gen_ai.chat, got {chat_span.operation}" ) if chat_span._exported: raise GenAISpanParentInvariantError( f"cannot parent tool-call to already-exported chat span {chat_span.span_id}" ) span = GenAISpan( span_id=new_span_id, parent_span_id=chat_span.span_id, operation="gen_ai.tool.call", ) span.set_attribute("gen_ai.tool.name", tool_name) span.set_attribute("gen_ai.tool.call.id", tool_call_id) return span def validate_exported_trace(spans: list) -> None: by_id = {s.span_id: s for s in spans} for s in spans: if s.operation == "gen_ai.tool.call": parent = by_id.get(s.parent_span_id) if parent is None: raise GenAISpanParentInvariantError( f"tool-call span {s.span_id} has dangling parent {s.parent_span_id}" ) if parent.operation != "gen_ai.chat": raise GenAISpanParentInvariantError( f"tool-call span {s.span_id} parented to {parent.operation} " f"({parent.span_id}); violates GenAI parent-linkage invariant" ) ```