# Where must an instance reconcile OTel GenAI span attributes when a tool-call span is emitted before its parent model-invocation span closes **Date of Record:** 2026 December 1 **Scope:** Applies to agents that emit OpenTelemetry GenAI semantic-convention spans (`gen_ai.operation.name`, `gen_ai.tool.name`, `gen_ai.usage.input_tokens`, `gen_ai.request.model`, `gen_ai.response.finish_reasons`) where tool execution is nested inside a model-invocation turn and spans are exported asynchronously. Does not apply to batch/offline evaluation traces with no live parent, nor to pure LLM-gateway proxies that only proxy a single completion. ## Core Distinction The GenAI semantic conventions treat a model invocation and a tool call as two distinct operations with distinct attribute namespaces, but they do not mandate emission order. In a real agent loop the tool call is *logically* a child of the model invocation that requested it, yet it executes and finishes *before* the model invocation span closes—because the model invocation's turn is not complete until the tool result is fed back and the next completion is produced. This creates a structural inversion: a child span (`gen_ai.operation.name = "execute_tool"`) is finalized and exported while its parent (`gen_ai.operation.name = "chat"`) is still open, still accumulating `gen_ai.usage.*` counters, and still has an unknown `gen_ai.response.finish_reasons`. The distinction that matters operationally is between **attribute finality** and **span lifecycle**. Most tracing backends assume a span's attributes are immutable once the span ends. The GenAI conventions silently violate that assumption for the parent: the parent's token usage and finish reason are only knowable after the child tool result returns. Any consumer that reads the parent span at child-export time observes a *half-populated* parent—and if the collector batches the child and parent into the same export window, the child's `trace_id`/`parent_span_id` linkage resolves against a parent record whose usage fields are zero or absent. ## What Was Observed A multi-turn agent using a function-calling loop emitted spans in this order for a single user request: 1. `chat` span opened (`gen_ai.operation.name=chat`, `gen_ai.request.model=gpt-4o`, no usage yet). 2. Completion returned a tool call; `execute_tool` span opened as child of (1). 3. Tool ran, `execute_tool` span closed with `gen_ai.tool.name=search_docs`, `gen_ai.tool.call.id=call_abc`. 4. Tool result appended to messages; second completion requested on the *same* `chat` span (the loop reused the parent). 5. `chat` span closed with `gen_ai.usage.input_tokens=4120`, `gen_ai.usage.output_tokens=290`, `gen_ai.response.finish_reasons=["tool_calls","stop"]`. The failure surfaced downstream: the trace backend's span-aggregation job computed "tokens attributable to tool calls" by joining `execute_tool` children to their parent `chat` usage. Because the child was indexed in export batch N and the parent's final usage landed in batch N+1 (the parent closed ~800ms later), the join ran against the batch-N snapshot of the parent. Result: every tool call in that trace was attributed `input_tokens=0`, and the per-tool cost dashboard undercounted by the full prompt size on every loop iteration. The trace *looked* complete—no missing spans, no orphan warnings—because the linkage IDs were correct. Only the usage attribution was silently wrong. A second, sharper symptom appeared under concurrent turns: when two `chat` spans shared a reused HTTP connection and the exporter flushed by batch size rather than by span end, a child `execute_tool` span occasionally arrived at the collector *before* its parent `chat` span had been created in the backend's index. The backend accepted the child, buffered it, and on parent arrival linked it—but the buffered child had already been through the aggregation job once with a null parent, producing a transient double-count that a later reconciliation pass could not distinguish from a genuine orphan. The invariant that was violated: **a GenAI parent span's usage attributes are not final at any point before `span.end()`, and no child of that span may be aggregated against the parent's usage until the parent has ended.** Nothing in the semantic conventions states this, because the conventions describe attribute *names*, not emission *ordering*. ## Condition of Validity The failure is bounded and predictable. It occurs only when all of the following hold: - The agent reuses a single model-invocation span across multiple completion round-trips (the "loop on one span" pattern), rather than opening a fresh `chat` span per completion. - Tool execution is nested as a child of that reused span. - The exporter is batch-based (OTLP batch processor, default `max_export_batch_size=512`, `scheduled_delay=5000ms`) so that a fast child and a slow parent can land in different export batches. - A downstream consumer performs a usage-attribution join keyed on parent span identity rather than on span-end timestamps. It does **not** occur when each completion gets its own `chat` span (the child then belongs to a span that closes before the next turn opens), nor when the collector exports synchronously per span end, nor when the consumer joins on `gen_ai.usage.*` read only from spans whose `end_time` is present in the same batch. The loop-on-one-span pattern is the trigger; batch export is the amplifier. ## Decision Boundary The correct architectural choice is not "always open a new span per completion" (that inflates trace cardinality and breaks the natural parent-child grouping of a single user turn). The boundary is: **if you reuse a model-invocation span across tool round-trips, you must not let any consumer observe its usage before `end()`.** Two admissible resolutions: 1. **Defer child export until parent end.** Buffer `execute_tool` spans in-process and flush them only when the enclosing `chat` span ends, so child and parent share an export batch and the parent's usage is final at join time. Cost: memory held for the duration of the turn; unacceptable for long-running loops exceeding the buffer bound. 2. **Emit usage on a terminal child, not the reused parent.** Keep the reused `chat` span for structural grouping but attach final `gen_ai.usage.*` to a synthetic terminal span (or to the last completion's own span) that closes *after* all tool children, and have consumers join on that terminal span. This decouples "grouping identity" from "usage finality." The invalid middle ground—reused parent carrying live-mutating usage while children export independently—is exactly what produces the silent zero-attribution. If neither resolution is implemented, the agent must at minimum stamp `execute_tool` children with the parent's `gen_ai.usage.*` *as known at child close* and mark them `usage.partial=true`, so consumers do not mistake a snapshot for a total. ## Operational Effect The practical consequence is that GenAI trace *completeness* and GenAI trace *correctness* diverge. A trace can have every span, every correct `trace_id`, every correct `parent_span_id`, and still report per-tool token cost as zero, because the join resolved against a parent snapshot taken before the parent's usage attributes were written. Cost dashboards, budget-enforcement loops that read trace usage to decide whether to continue a turn, and any auditor replaying traces to verify token accounting will all read the wrong number—and will read it *consistently*, so the error does not announce itself as an anomaly. The guardrail is to treat `gen_ai.usage.*` on a reused model-invocation span as non-final until `end_time` is set, and to reject any attribution join that reads usage from a span whose `end_time` is absent from the same batch as its children. ```python from dataclasses import dataclass, field from typing import Optional class UsageAttributionError(RuntimeError): """Raised when a tool-call span is attributed against a non-final parent usage snapshot.""" @dataclass class GenAISpan: span_id: str parent_span_id: Optional[str] operation: str # "chat" | "execute_tool" end_time: Optional[float] = None # None while span is open usage_input_tokens: Optional[int] = None usage_output_tokens: Optional[int] = None partial_usage: bool = False def is_final(self) -> bool: return self.end_time is not None and not self.partial_usage def attribute_tool_usage(child: GenAISpan, parent: GenAISpan) -> int: """Return input tokens attributable to a tool call, or fail loudly if parent usage is not final.""" if child.operation != "execute_tool": raise UsageAttributionError(f"expected execute_tool child, got {child.operation!r}") if parent.operation != "chat": raise UsageAttributionError(f"expected chat parent, got {parent.operation!r}") if child.parent_span_id != parent.span_id: raise UsageAttributionError( f"span linkage mismatch: child.parent={child.parent_span_id} parent.span={parent.span_id}" ) if not parent.is_final(): raise UsageAttributionError( f"parent {parent.span_id} usage not final " f"(end_time={parent.end_time}, partial={parent.partial_usage}); " f"refusing to attribute child {child.span_id} against a live snapshot" ) if parent.usage_input_tokens is None: raise UsageAttributionError(f"parent {parent.span_id} ended without gen_ai.usage.input_tokens") return parent.usage_input_tokens # Trigger trace: reused chat span, child closes first, batch splits parent/child. chat = GenAISpan(span_id="s1", parent_span_id=None, operation="chat") tool = GenAISpan(span_id="s2", parent_span_id="s1", operation="execute_tool", end_time=100.0, usage_input_tokens=0) # parent still open at child-export time: try: attribute_tool_usage(tool, chat) except UsageAttributionError as e: # Correct behavior: fail instead of silently attributing 0 tokens. print("blocked:", e) # Resolution path: parent ends with final usage. chat.end_time = 900.0 chat.usage_input_tokens = 4120 chat.usage_output_tokens = 290 assert attribute_tool_usage(tool, chat) == 4120 ```