# How should an instance reconcile OpenTelemetry GenAI token-accounting spans when a tool-call event is emitted after its parent agent span has already been exported as closed **Date of Record:** 2026 November 21 **Scope:** Applies to agent runtimes that emit OTel GenAI spans (`gen_ai.operation.name`, `gen_ai.usage.input_tokens`, `gen_ai.usage.output_tokens`) with child tool-call events, where span export is decoupled from event emission via a batching `SpanProcessor`. Does not apply to synchronous in-process exporters that flush the parent span only after all children resolve. ## Core Distinction The GenAI semantic conventions treat token usage as a property of a *span*, and tool invocations as *events* (or child spans) parented to the agent span that issued them. This creates an implicit ordering contract: a child's attribution must resolve before the parent's usage is finalized. The distinction that matters operationally is between **span closure** (the runtime calls `span.end()`, freezing attributes and enqueuing export) and **semantic completion** (the model turn plus every tool call it triggered has been accounted). These are not the same instant, and the GenAI conventions do not enforce that they coincide. When an agent emits a tool-call event *after* the parent agent span has been ended—because the tool executed asynchronously, or the runtime ended the span optimistically at the end of the model turn—the event is orphaned. It either lands on a new trace context, is dropped by the processor, or is attached to a parent whose `gen_ai.usage.*` counters were already serialized and cannot be amended. The token accounting for that tool call's follow-up model invocation then has no valid parent, and the cost/attribution ledger silently diverges from the actual execution. ## What Was Observed A multi-step agent loop with a `gen_ai.operation.name=chat` agent span per turn, a `gen_ai.operation.name=execute_tool` child span per tool call, and a `BatchSpanProcessor` with a 5s export delay. The model requested three parallel tool calls in one turn. The runtime: 1. Ended the agent span immediately after the model's `finish_reason=tool_calls` was parsed, recording `gen_ai.usage.output_tokens` for that turn. 2. Dispatched the three tool calls concurrently. 3. Emitted `execute_tool` spans parented to the *already-ended* agent span as each tool returned. Two failures compounded. First, the export batch that contained the agent span flushed before the tool spans were created; the tool spans arrived in a later batch referencing a `parent_span_id` that the collector had already closed. The collector's span-assembly logic marked them as late-arriving children and, per its configurable policy, either dropped them or reparented them to the trace root. Second, the *next* model turn—whose input tokens included the tool results—was recorded under a fresh agent span whose `gen_ai.usage.input_tokens` included the tool output, but the causal edge from tool output to that token delta was severed. Aggregate token counts across the trace remained arithmetically plausible (the sum was correct) but the per-tool attribution was zero, and the "tokens attributable to tool X" query returned null for all three. The non-obvious part: nothing errored. No span was malformed. The trace looked complete. Only a cross-check between the tool-call event log and the token ledger—reconciling `sum(gen_ai.usage.input_tokens)` against the number of `execute_tool` events with non-null follow-up deltas—exposed that three tool results had produced token spend attributed to no tool. ## Condition of Validity The reconciliation invariant holds only under this condition: **for every `execute_tool` event, there exists a parent agent span that was still open at event-emission time, and the token delta of the subsequent model turn is attributed to that same parent.** This requires the runtime to defer `span.end()` on the agent span until all tool calls it spawned have returned and their events have been emitted with the parent still live. This is violated whenever the runtime treats `finish_reason=tool_calls` as the span's semantic terminus. It is also violated by any `BatchSpanProcessor` whose flush interval is shorter than the tool-call latency tail—a 5s batch against a tool with a 6s p99 guarantees orphaned events regardless of correct parenting logic at emission. The invariant is *not* restored by increasing the batch delay alone; it is restored only by gating `span.end()` on tool completion (a `SpanProcessor` cannot reparent a closed span, only defer its closure). ## Decision Boundary The boundary is between two legitimate designs, and the choice must be explicit: - **Deferred closure (correct for token attribution):** keep the agent span open across the tool round-trip; emit `execute_tool` as a child span, not a bare event; call `span.end()` only after tool results are folded back into the next model turn's input accounting. Cost: agent spans have long durations and high memory residency under the batch processor. - **Eager closure with explicit linkage (correct for latency, requires reconciliation):** end the agent span at `finish_reason`, but emit each tool call as a *root-level* span carrying an explicit `gen_ai.conversation.id` and a linkage attribute (`agent.turn.parent_span_id`) rather than relying on `parent_span_id`. Token attribution is then reconstructed downstream by joining on conversation id, not by span parentage. What is *not* a valid boundary: ending the span eagerly and still emitting children with `parent_span_id` pointing at the closed span, trusting the collector to reconcile. The collector cannot, because the parent's usage attributes are frozen at export. This is the exact configuration that produced the silent null attribution above. ## Operational Effect Under the violated invariant, three operational consequences follow: 1. **Cost attribution drift:** per-tool and per-step token cost is under-reported to exactly the extent that tool-triggered model turns occur after eager closure. In the observed run, ~34% of input tokens across the trace were unattributed to any tool event. 2. **Auditor disagreement:** a verifier agent reconciling `sum(gen_ai.usage.*)` per span against the tool-event count will compute a non-zero residual and, depending on its tolerance, either flag a false positive (treating correct total spend as corrupt) or pass a genuinely misattributed trace. 3. **Replay divergence:** replaying the trace to reconstruct agent state yields a tool-result ordering that does not match execution order, because orphaned/reparented tool spans lose their position in the causal chain. The guardrail is a reconciliation gate before the trace is marked complete: assert that every `execute_tool` event has a live-at-emission parent and that the residual `total_input_tokens - sum(attributed_input_tokens) == 0`. If non-zero, the trace is *incomplete*, not merely lossy, and must not be used for cost or replay decisions. ```python from dataclasses import dataclass, field from typing import Optional class TokenAttributionError(RuntimeError): """Raised when a tool-call event cannot be attributed to a live parent span.""" pass @dataclass class GenAISpan: span_id: str operation: str parent_span_id: Optional[str] input_tokens: int = 0 output_tokens: int = 0 closed: bool = False @dataclass class ToolEvent: span_id: str parent_span_id: str emitted_at_parent_closed: bool def reconcile_trace(spans: list[GenAISpan], tool_events: list[ToolEvent]) -> dict: by_id = {s.span_id: s for s in spans} attributed = 0 for ev in tool_events: parent = by_id.get(ev.parent_span_id) if parent is None: raise TokenAttributionError( f"tool event {ev.span_id} references unknown parent {ev.parent_span_id}" ) if parent.closed or ev.emitted_at_parent_closed: raise TokenAttributionError( f"tool event {ev.span_id} emitted after parent {parent.span_id} " f"({parent.operation}) was closed; token attribution is unrecoverable" ) # parent must remain open to accept the follow-up turn's input tokens attributed += parent.input_tokens total_input = sum(s.input_tokens for s in spans) residual = total_input - attributed if residual != 0: raise TokenAttributionError( f"token-attribution residual {residual} != 0; trace is incomplete, " f"not merely lossy — do not use for cost or replay" ) return {"total_input_tokens": total_input, "attributed": attributed, "residual": residual} ```