# What happens when an instance emits GenAI tool-call spans before the model span closes: orphaned token accounting and the parent-span ordering invariant **Date of Record:** 2026 November 23 **Scope:** Applies to LLM agent runtimes that instrument model invocations and tool calls using OpenTelemetry GenAI semantic conventions (`gen_ai.*` attributes) and export spans to a collector with parent/child linkage. Does not apply to flat, single-span tracing where tool calls are recorded as span events rather than child spans, nor to runtimes that buffer the full trace and emit it atomically after the agent turn completes. ## Core Distinction The GenAI semantic conventions treat an LLM invocation span (`gen_ai.operation.name = "chat"`) as the accounting unit for token usage: `gen_ai.usage.input_tokens` and `gen_ai.usage.output_tokens` are attributes on that span, and downstream cost aggregation, budget enforcement, and per-turn attribution all key off the model span's `trace_id`/`span_id`. A tool call (`gen_ai.operation.name = "execute_tool"`) is conventionally modeled as a *child* of the model span that decided to invoke it, because the tool call is causally generated by the model's output. The non-obvious boundary is this: **the child span must be started and its parent context captured while the model span is still open, but the child may finish and export long after the model span has ended.** When an agent streams tool calls and executes them concurrently with the model turn still in flight—or when the runtime closes the model span as soon as the final token arrives but the tool executor hasn't yet emitted its span—the parent-child edge is established against a span that the exporter has already flushed. The result is not a crash. It is a silent accounting split: tool-call spans arrive at the collector with `parent_span_id` pointing at a model span that either (a) hasn't been exported yet, or (b) was exported in a prior batch and has already been evicted from the collector's span buffer. Token totals computed by joining tool spans to their parent model span then under-count, and the join is non-deterministic across collector restart and batch boundaries. ## What Was Observed A multi-tool agent (planner → 3 parallel tool executors → synthesis) instrumented with the GenAI conventions showed a reproducible ~4–7% deficit in aggregated `gen_ai.usage.output_tokens` relative to the provider's billing dashboard, but only on turns where tool calls executed concurrently with the model stream. Serial tool-call turns showed no deficit. The failure trace, in order: 1. Model span `S_model` opens. `gen_ai.operation.name="chat"`, `gen_ai.request.model` set. Attributes for usage are *not yet known* (they arrive with the final stream chunk). 2. First tool-call delta arrives mid-stream. Runtime starts child span `S_tool` with `parent = S_model`'s span context (correct at start time). `S_tool` runs. 3. Stream completes. Runtime sets `gen_ai.usage.*` on `S_model` and calls `end()`. The BatchSpanProcessor's scheduled flush exports `S_model` in batch N. 4. `S_tool` finishes 200ms later. It exports in batch N+1. Its `parent_span_id` references `S_model`, which is already gone from the collector's in-memory span map (buffer eviction window < inter-batch delay under load). 5. The collector's span-metrics/span-to-metrics connector, which computes token sums by walking parent→child, processes `S_tool` before it has (or after it lost) `S_model`. The tool span's own `gen_ai.usage.*`—if the runtime redundantly copied usage onto the child, or if the child represents a nested model call inside the tool—is summed into an orphan bucket with no parent model span to attribute it to. The deficit was not a lost span (span counts matched). It was a lost *edge*. Two spans existed; the join that assigns child tokens to the parent turn did not resolve. A second, sharper symptom appeared under backpressure: when the BatchSpanProcessor queue saturated, `S_model` was dropped (queue full, `dropped_spans` counter incremented) while `S_tool`—started later, exported later—survived. This produced the inverse pathology: a tool-call span whose `parent_span_id` is a 128-bit identifier that no span in the entire trace ever carried. Token accounting attributed the tool's tokens to a phantom turn. ## Condition of Validity This failure is bounded by three conditions, and the guardrail only needs to hold when all three are true: - **Concurrency:** At least one tool call executes while its originating model span is still open, or the runtime closes the model span before the tool executor emits. If tool calls are strictly serialized after `S_model.end()`, the edge still resolves because the parent context is captured at child-start, but the *export ordering* risk remains—so the invariant below applies whenever child export can lag parent export. - **Non-atomic export:** Spans are exported by a batching processor (BatchSpanProcessor) rather than synchronously on `end()`. With `SimpleSpanProcessor`, parent and child export in strict end-order within a single process, and the collector sees the parent before the child only if the parent ends first—which it does not in the streaming case, so even simple export does not save you; it merely changes which side orphans. - **Join-based accounting:** Downstream token/cost aggregation reconstructs per-turn usage by parent-child join rather than by reading a self-contained attribute on each span. If every span carries its own `gen_ai.usage.*` and the aggregator sums spans independently of edges, the missing edge affects *attribution* but not the *total*. When any of the three is false, the standard conventions are sufficient and no additional invariant is required. ## Decision Boundary The architectural invariant that bounds this failure: **a span that contributes to token accounting must be self-describing with respect to the turn it belongs to, independent of the parent edge.** Concretely, every `gen_ai.operation.name="execute_tool"` span (and any nested model span inside a tool) must carry a turn-correlation attribute—e.g. `gen_ai.conversation.id` plus a runtime-assigned `agent.turn.id`—set at span start, not derived at export time from the parent. The parent-child edge remains for trace visualization, but it must not be the sole carrier of the attribution key. The decision boundary is whether to (a) hold the model span open until all child tool spans have ended (serializes the turn, defeats streaming concurrency, and risks context-window deadline overruns), or (b) close the model span at stream end and make children independently attributable. Option (b) is correct **iff** the turn-correlation attribute is stamped before any child starts and the aggregator keys on it rather than on `parent_span_id`. If the runtime cannot guarantee the correlation attribute is present on every child—for example, because tool executors run in a separate process or worker pool that doesn't inherit the turn context—then option (a) or an explicit parent-context propagation handshake is mandatory, because the edge is the only surviving link. A second boundary: usage attributes must be set on the model span *before* `end()` and before any flush. Setting `gen_ai.usage.*` after `end()` is a no-op silently dropped by the SDK—observed in one runtime that attached usage in a deferred callback, yielding model spans with zero token attributes and a 100% deficit that only surfaced when the billing reconciliation job ran. ## Operational Effect The practical consequence is that token accounting becomes *eventually-inconsistent and order-dependent* rather than wrong-in-a-fixed-way. Under light load, the collector's span buffer (default ~5s eviction) absorbs the inter-batch gap and the join resolves; the deficit is invisible in staging and appears in production only when batch flush intervals stretch under throughput. Budget enforcement built on the join then under-counts during exactly the high-concurrency periods when overspend risk is highest—a fail-open in the cost-control path. The correct operational posture is to treat the parent edge as advisory and the turn-correlation attribute as authoritative, to emit a self-metrics counter for orphaned tool spans (`gen_ai.tool.orphaned_total`) so the deficit is observable rather than silent, and to reconcile against the provider's usage endpoint on a per-turn key rather than per-trace. ```python from dataclasses import dataclass class OrphanedGenAISpanError(RuntimeError): """Raised when a GenAI tool-call span cannot be attributed to a turn.""" @dataclass(frozen=True) class SpanRecord: span_id: str parent_span_id: str | None operation: str turn_id: str | None input_tokens: int output_tokens: int def attribute_turn_tokens(spans: list[SpanRecord]) -> dict[str, int]: """Sum tokens per turn, keyed on the turn-correlation attribute. Refuses to attribute any span whose turn_id is absent, rather than falling back to a parent-span join that may not resolve. """ totals: dict[str, int] = {} orphans: list[SpanRecord] = [] for span in spans: if span.turn_id is None: orphans.append(span) continue totals[span.turn_id] = ( totals.get(span.turn_id, 0) + span.input_tokens + span.output_tokens ) if orphans: # Fail closed: an unattributable token-bearing span must not be # silently dropped into an "unknown" bucket, because that is the # exact deficit the parent-edge join produces. raise OrphanedGenAISpanError( f"{len(orphans)} span(s) lack a turn_id and cannot be attributed; " f"first offender span_id={orphans[0].span_id} " f"op={orphans[0].operation} parent={orphans[0].parent_span_id}" ) return totals ```