# Where must an instance reconcile OpenTelemetry GenAI token accounting when a tool-call span closes before the model span that spawned it **Date of Record:** 2026 December 3 **Scope:** Applies to agent runtimes that emit OpenTelemetry spans per the GenAI semantic conventions (`gen_ai.*`) and aggregate token usage across a multi-span turn where tool-call child spans may terminate before their parent inference span. Does not apply to single-shot completion logging or to billing reconciliation performed outside the trace pipeline. ## Core Distinction The GenAI semantic conventions define `gen_ai.usage.input_tokens` and `gen_ai.usage.output_tokens` as attributes of the *inference* span (`gen_ai.operation.name = chat` or `text_completion`). They do not define a token attribute for the tool-execution span (`gen_ai.operation.name = execute_tool`). The failure mode here is not a missing attribute; it is a **temporal ordering violation** between span closure and usage attribution. In a ReAct-style loop, the model emits a tool call, the runtime executes the tool as a child span, and the tool span ends when the tool returns. The model span that *requested* the tool does not end until the model has consumed the tool result and produced its next response—or until the turn terminates. Because OpenTelemetry spans are immutable once ended, any usage accumulated *after* a child span closes cannot be attached to that child. If the runtime attributes tokens to the span that was "active" at emission time, and the tool span has already closed, the tokens get attributed to the wrong span or dropped entirely. The invariant at stake: **every token counted by the provider must be recoverable from exactly one closed span, and that span's `gen_ai.operation.name` must match the operation that actually consumed the tokens.** ## What Was Observed A three-step agent turn running against a provider that reports usage per completion: 1. `chat` span A opens. Model returns a tool-call directive. Provider reports `input_tokens=1820, output_tokens=64` (the 64 includes the serialized tool-call arguments). 2. `execute_tool` span B opens as a child of A. Tool runs for 340 ms. Span B closes with no usage attributes. 3. `chat` span A *continues*—the model span is still open because the runtime is treating the whole turn as one logical inference. The tool result is fed back, the model produces a final answer, provider reports `input_tokens=2410, output_tokens=210`. 4. Span A closes. The runtime writes `gen_ai.usage.input_tokens=2410, gen_ai.usage.output_tokens=210` onto A. The first completion's 1820+64 tokens are **silently absent from the trace**. The trace shows one chat span with 2410 input tokens. A downstream cost aggregator summing `gen_ai.usage.*` across spans reports 2410 input tokens against a provider invoice of 4230. The gap is 43% of billed input, and it is invisible because the span that should have carried it (A) was overwritten by the second completion's usage, and the span that was open when the first completion arrived (B) had already closed. A second, subtler variant: if the runtime instead opens a *new* chat span for each completion (correct per the conventions), but the tool span B is parented to the *first* chat span A1, then B's `parent_span_id` points at A1 while the tool result is consumed by A2. Trace topology now shows the tool hanging off a span that never saw its output, and any auditor reconstructing "which inference saw this tool result" resolves it incorrectly. ## Condition of Validity The convention-compliant model is: **one chat span per provider completion**, with usage attributes written on that span at close, and tool spans parented to the chat span whose completion *requested* the tool. Under this model the invariant holds: sum of `gen_ai.usage.input_tokens` over all `chat` spans in a trace equals provider-billed input for the turn. The invariant breaks whenever any of the following hold: - The runtime batches multiple completions into a single span (as above) and overwrites rather than accumulates usage. - The runtime writes usage at emission time to the currently-active span, which may be a tool span that does not accept `gen_ai.usage.*` under the conventions (and thus is dropped by strict exporters or rejected by schema validation). - The runtime emits usage on the tool span anyway, and a downstream aggregator that filters on `gen_ai.operation.name = chat` misses it. - A tool span is reparented (e.g., by an async context manager that captures the span context at task creation) so its `parent_span_id` diverges from the chat span that consumed its result. ## Decision Boundary The boundary is **span-closure ordering vs. usage-emission ordering**. Usage for a completion is only knowable after the completion returns; the span for that completion must therefore remain open until usage is written and then close. A tool span that opens and closes *within* that window is fine only if it is a child of the correct chat span and carries no usage. The decision rule: - If a completion's usage arrives while a tool span is the active span, the runtime MUST NOT write usage to the tool span. It MUST route usage to the chat span that owns the completion. - If a single logical turn spans multiple completions, the runtime MUST emit one chat span per completion, each carrying its own `gen_ai.usage.*`, and MUST NOT merge them. - If the runtime cannot guarantee one-span-per-completion (e.g., streaming with usage reported only at stream end), it MUST buffer usage and write it at the chat span's close, and it MUST ensure no tool span is a child of a chat span whose usage was already written by a prior completion. Violating any of these yields a trace whose per-span usage does not sum to billed usage, and the error is not detectable from the trace alone—it requires cross-referencing the provider invoice or a separate usage ledger. ## Operational Effect Downstream consumers that trust the trace as a billing or budget source will under-count. In the observed case, 43% of input tokens vanished. Agent runtimes that enforce a token budget by summing `gen_ai.usage.input_tokens` over the trace will over-run the budget before the trace signals exhaustion, because the trace lags the true count. Auditors reconstructing "what did this tool call cost" get zero, because the tool span has no usage and its parent chat span's usage is attributed to a different completion. The guardrail is a **usage reconciliation check at trace close**: sum `gen_ai.usage.input_tokens` and `gen_ai.usage.output_tokens` across all `chat` spans, compare to the provider-reported turn total (carried in a separate ledger or in a `gen_ai.usage.total_tokens` on a turn-level span), and raise if they diverge beyond a tolerance. This catches the overwrite case, the dropped case, and the misrouted case with one check. ```python from dataclasses import dataclass, field from typing import Optional class UsageReconciliationError(RuntimeError): """Raised when per-span GenAI usage does not reconcile to the provider turn total.""" @dataclass class Span: span_id: str parent_span_id: Optional[str] operation_name: str # "chat", "execute_tool", etc. input_tokens: int = 0 output_tokens: int = 0 closed: bool = False @dataclass class Turn: spans: list = field(default_factory=list) provider_input_tokens: int = 0 provider_output_tokens: int = 0 def write_usage(span: Span, input_tokens: int, output_tokens: int) -> None: if span.operation_name != "chat": raise UsageReconciliationError( f"refusing to write gen_ai.usage.* to non-chat span " f"{span.span_id} (op={span.operation_name})" ) if span.closed: raise UsageReconciliationError( f"span {span.span_id} already closed; usage cannot be attributed" ) if span.input_tokens or span.output_tokens: raise UsageReconciliationError( f"span {span.span_id} already carries usage " f"({span.input_tokens}/{span.output_tokens}); " f"multiple completions must not share a chat span" ) span.input_tokens = input_tokens span.output_tokens = output_tokens def reconcile_turn(turn: Turn, tolerance: int = 0) -> None: chat_input = sum(s.input_tokens for s in turn.spans if s.operation_name == "chat") chat_output = sum(s.output_tokens for s in turn.spans if s.operation_name == "chat") if abs(chat_input - turn.provider_input_tokens) > tolerance: raise UsageReconciliationError( f"input token mismatch: spans={chat_input} provider={turn.provider_input_tokens}" ) if abs(chat_output - turn.provider_output_tokens) > tolerance: raise UsageReconciliationError( f"output token mismatch: spans={chat_output} provider={turn.provider_output_tokens}" ) # Every tool span must be parented to a chat span that exists in the turn. chat_ids = {s.span_id for s in turn.spans if s.operation_name == "chat"} for s in turn.spans: if s.operation_name == "execute_tool" and s.parent_span_id not in chat_ids: raise UsageReconciliationError( f"tool span {s.span_id} parented to {s.parent_span_id}, " f"which is not a chat span in this turn" ) ```