# Where must an instance reconcile GenAI span token accounting when a tool-call child span terminates after its parent agent span has already been exported **Date of Record:** 2026 November 26 **Scope:** Applies to agents instrumented with OpenTelemetry GenAI semantic conventions (`gen_ai.*`) where tool invocations are emitted as child spans under an agent invocation span, and where span export is asynchronous and non-ordered. Does not apply to synchronous in-process exporters that flush strictly in span-close order, nor to batch pipelines that buffer entire traces before export. ## Core Distinction The GenAI semantic conventions treat `gen_ai.usage.input_tokens` and `gen_ai.usage.output_tokens` as attributes of the *invocation* span — the LLM call. Tool-call spans carry `gen_ai.tool.name`, `gen_ai.tool.call.id`, and result attributes, but no token usage of their own. The operational trap is the assumption that a parent agent span's token totals can be finalized at parent close. They cannot, because a tool-call child span may close *after* the parent has already been closed and exported — the agent hands off to a tool, the tool outlives the model's turn boundary (streaming result, deferred callback, retry), and the exporter flushes the parent on its own close event. The invariant that must hold is: **the sum of token usage attributed to a trace must equal the sum over all `gen_ai` invocation spans in that trace, regardless of export ordering.** When a child span closes post-parent-export, any aggregation done at the parent's close event is permanently short by that child's contribution — and there is no later event to correct it, because the parent is already in the backend. This is not a batching bug or a clock-skew problem. It is a semantic mismatch between "span lifetime" (parent closes when the agent's turn ends) and "accounting lifetime" (the trace's token total is only knowable when the last descendant closes). The GenAI conventions do not specify a reconciliation point, and most SDK auto-instrumentation finalizes parent attributes at `on_end`, which fires before the late child. ## What Was Observed A retrieval-augmented agent emitted, per turn: one `invoke_agent` span, one or more `chat` spans (the LLM calls), and one `execute_tool` span per tool call. Under normal latency the tool span closed inside the parent's turn and the parent's `gen_ai.usage.*` attributes, computed by summing child `chat` spans at parent close, were correct. Under a specific trigger — a tool call whose backend latency exceeded the agent's turn timeout, causing the agent to close its span and return a "pending" status while the tool continued — the following trace shape appeared: 1. `execute_tool` span opened, `gen_ai.tool.call.id` set, no usage attributes (correct per convention). 2. Agent turn timed out; `invoke_agent` span closed and exported with `gen_ai.usage.input_tokens = 4120`, `output_tokens = 890` — the totals of the two `chat` spans that had completed. 3. 1.4 s later the tool returned; `execute_tool` span closed and exported. 4. The agent, on receiving the tool result, issued a third `chat` call whose `gen_ai.usage` (input 4310, output 210) was recorded on a *new* `chat` span parented to the already-closed `invoke_agent` span. The backend received three spans for the trace. The parent's usage attributes (4120/890) did not include the third `chat` (4310/210), because that span did not exist at parent close. The trace-level token total computed by summing `gen_ai.usage` over all spans was 4120+890+4310+210 = 9530, but any dashboard or cost-attribution job that reads the *agent* span's attributes saw 5010 — a 47% undercount. The third `chat` span arrived with a `parent_span_id` pointing at a span the backend had already indexed as closed; some backends silently re-parent it to the trace root, others drop it, and neither surfaces an error. The failure is silent: no span is marked error, no attribute signals truncation, and the parent's `gen_ai.usage` looks plausible. The only detectable signature is a `chat` span whose `parent_span_id` references a span with an earlier `end_time` than the child's `start_time` — a temporal impossibility that no convention currently forbids. ## Condition of Validity The reconciliation requirement binds only when all three hold: 1. **Asynchronous tool execution outlives the agent turn.** If tool calls are synchronous and the agent blocks until the tool returns, the parent cannot close before the child, and parent-close aggregation is safe. 2. **Parent attributes are finalized at `on_end`.** If the exporter or processor defers parent attribute computation until trace completion (e.g., a `SpanProcessor` that buffers by `trace_id` and computes totals at `on_end` of the last span), the late child is included. The failure requires eager finalization. 3. **Token usage is attributed to invocation spans, not to the agent span.** The conventions place `gen_ai.usage.*` on `chat` spans; any design that copies or sums them onto the agent span at close inherits the ordering hazard. If consumers aggregate from `chat` spans directly (summing `gen_ai.usage.input_tokens` over all spans with `gen_ai.operation.name = chat`), the parent's stale total is irrelevant and the failure disappears. When (1) or (2) is false, or when (3) is avoided by consumer-side aggregation, no correction is needed. The boundary is precisely the intersection: eager parent finalization × asynchronous tool lifetime × parent-carried usage totals. ## Decision Boundary The architect must choose, at instrumentation time, between two mutually exclusive policies: - **Eager finalization (parent carries totals):** acceptable only if the agent guarantees that no descendant span can outlive the parent. This requires the agent to either block on every tool call or to explicitly mark the parent span as "open for late children" and have the exporter hold it. The latter is not expressible in the current GenAI conventions — there is no `gen_ai.span.finalized` flag — so in practice eager finalization is safe only for synchronous tool execution. - **Deferred finalization (consumer aggregates):** the parent span carries no usage totals; cost and token dashboards sum `gen_ai.usage.*` across all `chat` spans keyed by `trace_id`. This is order-independent and correct under arbitrary tool latency, but it moves the accounting burden to every consumer and breaks any downstream system that expects usage on the agent span. The decision boundary is the tool-latency distribution relative to the agent turn timeout. If `P(tool_latency > turn_timeout)` is non-zero — which it is for any agent with a timeout at all — eager finalization is incorrect for the tail. The only sound default is deferred finalization with a reconciliation pass that detects `chat` spans arriving after their parent's `end_time` and either re-parents them to the trace root or flags the trace for recomputation. ## Operational Effect Agents that finalize usage at parent close and run tools asynchronously will undercount tokens on every trace where a tool outlives the turn — typically the slowest, most expensive traces (large retrievals, long code execution, retried external APIs), which are exactly the ones cost attribution cares about most. The error is one-directional (always an undercount, never an overcount) and grows with the number of post-timeout turns, so it inflates apparent efficiency and hides the cost of the agent's worst-performing path. Because the late `chat` span is still exported, the raw data to correct the total exists in the backend; the failure is purely in *where the total is read from*, not in whether it was recorded. The guardrail is a reconciliation invariant enforced at the collector or query layer: for each `trace_id`, assert that no `chat` span has `start_time` greater than the `end_time` of any span it is parented to, and recompute agent-level totals as the sum over `chat` spans rather than trusting the parent's `gen_ai.usage.*` attributes. Without that invariant, the undercount is undetectable from the agent span alone. ```python from dataclasses import dataclass from typing import Iterable, Optional class TokenAccountingDivergence(RuntimeError): """Raised when a chat span's usage cannot be reconciled into its parent agent span.""" @dataclass(frozen=True) class Span: span_id: str parent_span_id: Optional[str] operation: str # e.g. "invoke_agent", "chat", "execute_tool" start_time_ns: int end_time_ns: int input_tokens: int = 0 output_tokens: int = 0 def reconcile_trace(spans: Iterable[Span]) -> dict: """ Enforce the ordering invariant: no chat span may start after its parent agent span has ended. Returns trace-level token totals summed over chat spans, independent of export order. """ by_id = {s.span_id: s for s in spans} chat_spans = [s for s in spans if s.operation == "chat"] for chat in chat_spans: parent = by_id.get(chat.parent_span_id) if chat.parent_span_id else None if parent is None: continue if chat.start_time_ns > parent.end_time_ns: raise TokenAccountingDivergence( f"chat span {chat.span_id} started at {chat.start_time_ns} " f"after parent {parent.span_id} ended at {parent.end_time_ns}; " f"parent-carried gen_ai.usage is short by " f"{chat.input_tokens}/{chat.output_tokens} tokens" ) return { "input_tokens": sum(s.input_tokens for s in chat_spans), "output_tokens": sum(s.output_tokens for s in chat_spans), "chat_span_count": len(chat_spans), } ```