# How does an instance detect token accounting divergence when OpenTelemetry GenAI span attributes are aggregated across a tool-call fan-out? **Date of Record:** 2026 November 22 **Scope:** Applies to agent runtimes that emit OpenTelemetry spans conforming to the GenAI semantic conventions (`gen_ai.usage.input_tokens`, `gen_ai.usage.output_tokens`, `gen_ai.operation.name`, `gen_ai.tool.name`) and that reconcile those spans against a parent agent span for billing, budget enforcement, or loop-termination decisions. Does not apply to single-shot inference calls with no tool fan-out, nor to runtimes that bypass OTel and account tokens at the process boundary. ## Core Distinction The GenAI semantic conventions define per-span token attributes as *local* to the operation that span represents. They do not define an aggregation invariant across a parent-child span tree. A parent agent span that fans out to N tool-call spans will therefore observe a token sum that is neither the sum of children (children may not carry usage attributes at all, since tool execution itself consumes no model tokens) nor the parent's own usage (which reflects only the reasoning turns the parent model performed). The failure is not that the numbers are wrong individually—each span is correct in isolation—but that a naive reconciler treats the tree as a conservation system where `parent.usage ≥ Σ children.usage`, an invariant the spec never promises. The non-obvious boundary: **the parent span's `input_tokens` is re-counted on every reasoning turn that re-sends accumulated context, so parent usage grows super-linearly with fan-out width while child spans report zero usage, and the two are not additive.** ## What Was Observed An agent executing a 12-tool fan-out (parallel file reads feeding a synthesis step) emitted the following span tree under a single `gen_ai.operation.name=invoke_agent` parent: - Parent span: `gen_ai.usage.input_tokens=48,210`, `gen_ai.usage.output_tokens=3,102`. - Twelve child spans with `gen_ai.operation.name=execute_tool`, `gen_ai.tool.name=read_file`, each carrying **no** `gen_ai.usage.*` attributes (correct per convention—tool execution is not a model call). - A nested span per tool turn: `gen_ai.operation.name=chat`, each reporting `input_tokens` in the 3,000–4,500 range as the growing context window was re-submitted. The reconciler summed all `chat` span input tokens and got 44,900. It compared this to the parent's `48,210` and flagged a divergence of 3,310 tokens as "unaccounted," triggering a budget-halt. The 3,310 was the parent's own final synthesis turn, whose `chat` child span had not yet been exported when the reconciler ran—a **span export ordering race**, not a leak. On a second run the divergence reversed sign: the reconciler summed children to 49,100, exceeding the parent by 890, because the parent span's usage was populated at span-close from a cached counter that had not incorporated the last tool turn's re-count. The invariant that actually holds is *per-turn*, not *per-tree*: each `chat` span's `input_tokens` equals the tokenized length of the exact message array submitted on that turn. There is no tree-level conservation law. Any reconciler that assumes `parent.input_tokens == Σ chat.input_tokens` will fire spuriously on every fan-out wider than one, and will fire in both directions depending on export timing. ## Condition of Validity The per-turn accounting is only trustworthy when all of the following hold: 1. Every model call emits exactly one `chat` span, and that span is a descendant of the agent span it belongs to (parent-child linkage via `trace_id`/`span_id`, not just shared `trace_id`). 2. The `chat` span's `input_tokens` is sampled from the provider response's `usage` object, not estimated by a local tokenizer. Local tokenizers diverge from provider counts by 1–4% on tool-call-heavy prompts because serialized tool schemas are tokenized differently than the model's internal template. 3. The reconciler waits for the trace to be *closed* (root span ended AND all children exported) before summing. OpenTelemetry's `BatchSpanProcessor` does not guarantee child-before-parent export ordering; a reconciler reading the collector mid-flight sees partial trees. 4. Tool-call spans carry `gen_ai.tool.name` and `gen_ai.tool.call.id` so that the fan-out width is reconstructible independent of token counts. When any condition fails, the observed divergence is an artifact of the accounting method, not of the agent's behavior, and must be classified as `INDETERMINATE` rather than `OVER_BUDGET` or `UNDER_BUDGET`. ## Decision Boundary The reconciler must branch on **trace closure state** before branching on token totals: - If the root span has not ended, or any child span referenced in the fan-out is absent from the exported set, the correct action is to *defer* reconciliation, not to compare partial sums. A partial sum is guaranteed to under-count and will falsely pass budget checks while the agent is still spending. - If the trace is closed and `Σ chat.input_tokens > parent.input_tokens`, this indicates the parent's cached counter missed a turn—trust the sum of `chat` spans, because each is sampled from a provider response and is the finer-grained ground truth. - If the trace is closed and `Σ chat.input_tokens < parent.input_tokens`, this indicates a `chat` span was dropped (sampling, exporter backpressure, or a tool turn that called the model through a path that did not emit a span). This is the dangerous case: the agent spent tokens that the reconciler cannot see, and budget enforcement based on child sums will under-report. Escalate to `ACCOUNTING_GAP`. - Only when the trace is closed AND the sums agree within the provider's reported rounding tolerance (±1 token per span) may the reconciler treat the parent total as authoritative. The boundary is not a threshold on the divergence magnitude. A 50-token gap on a closed trace is a dropped span and matters; a 3,000-token gap on an open trace is expected in-flight behavior and must be ignored. ## Operational Effect Runtimes that reconcile on partial traces exhibit two failure signatures: premature budget halts (false `OVER_BUDGET` during fan-out) and silent budget overruns (partial sums passing while the agent continues spending). Both are eliminated by gating reconciliation on root-span closure and by preferring the sum of `chat` spans over the parent attribute once closure is confirmed. The parent span's `gen_ai.usage.*` should be treated as a *convenience cache*, not a source of truth, precisely because it is populated at span-close from a counter that may lag the last turn. Downstream billing systems that ingest only the parent span will systematically under-charge fan-out-heavy agents; billing must ingest leaf `chat` spans and deduplicate by `span_id`. ```python from dataclasses import dataclass class TokenAccountingDivergence(RuntimeError): """Raised when GenAI span token aggregation cannot be reconciled.""" pass @dataclass class SpanRecord: span_id: str parent_id: str | None operation: str # "invoke_agent" | "chat" | "execute_tool" input_tokens: int | None ended: bool def reconcile_agent_tokens( root: SpanRecord, spans: list[SpanRecord], rounding_tolerance: int = 1, ) -> int: """ Returns authoritative input-token count for an agent trace. Raises TokenAccountingDivergence when the trace is not safe to reconcile. """ if not root.ended: raise TokenAccountingDivergence( f"root span {root.span_id} not closed; partial sums are invalid" ) children = [s for s in spans if s.parent_id is not None] open_children = [s for s in children if not s.ended] if open_children: raise TokenAccountingDivergence( f"{len(open_children)} child span(s) still open under " f"{root.span_id}; defer reconciliation" ) chat_spans = [s for s in spans if s.operation == "chat"] if not chat_spans: raise TokenAccountingDivergence( f"no chat spans under {root.span_id}; cannot reconstruct usage" ) missing = [s for s in chat_spans if s.input_tokens is None] if missing: raise TokenAccountingDivergence( f"{len(missing)} chat span(s) lack gen_ai.usage.input_tokens" ) child_sum = sum(s.input_tokens for s in chat_spans) # type: ignore[arg-type] parent_total = root.input_tokens or 0 if child_sum > parent_total + rounding_tolerance: # parent counter lagged; leaf spans are ground truth return child_sum if child_sum < parent_total - rounding_tolerance: raise TokenAccountingDivergence( f"ACCOUNTING_GAP: chat spans sum to {child_sum} but parent " f"reports {parent_total}; {parent_total - child_sum} tokens " f"are unobserved (dropped span or bypassed model call)" ) return parent_total ```