# In what scenarios must an instance reconcile OpenTelemetry GenAI span accounting against the tool-call fan-out it actually executed, rather than trusting the emitted `gen_ai.usage.*` counters? **Date of Record:** 2026 November 21 **Scope:** Applies to any agent runtime that emits OpenTelemetry GenAI semantic-convention spans (`gen_ai.operation.name`, `gen_ai.usage.input_tokens`, `gen_ai.usage.output_tokens`, `gen_ai.tool.name`, `gen_ai.tool.call.id`) across multi-turn tool-use loops where a single logical agent invocation fans out into N child tool spans. Does not apply to single-shot completion calls with no tool fan-out, nor to batch offline evaluation where spans are not correlated into a trace. ## Core Distinction The GenAI semantic conventions describe *per-span* token accounting: each `gen_ai.chat` span carries the `gen_ai.usage.input_tokens` and `gen_ai.usage.output_tokens` reported by the model provider for *that* completion. They deliberately do **not** define an aggregate invariant tying a parent agent span's token totals to the sum of its child tool-call spans. The convention is a vocabulary, not a ledger. The failure mode is treating the vocabulary as a ledger. An operator (or an automated cost/guardrail reconciler) computes "tokens consumed by this agent run" by summing `gen_ai.usage.*` across every span in the trace subtree, and compares that against a budget or against the provider's billing statement. Under tool fan-out these two numbers diverge for a structural reason: **the same input context is re-counted once per model turn, and each model turn re-sends the entire accumulated conversation** — but the *tool result* content that inflates the next turn's `input_tokens` is generated by a child span that itself reports zero tokens (tools don't consume LLM tokens). The trace's summed token count is therefore not a function of the trace's span count; it is a function of conversation length × turn count, a quantity no single span attribute records. ## What Was Observed A representative trace from a research agent executing a 7-turn tool loop: - Parent `gen_ai.agent` span: `gen_ai.usage.input_tokens` absent (agents aren't model calls), `gen_ai.usage.output_tokens` absent. - Seven child `gen_ai.chat` spans, one per model turn. Turn *k*'s `input_tokens` ≈ turn *k−1*'s `input_tokens` + turn *k−1*'s `output_tokens` + size of the tool result injected between them. - Six `gen_ai.tool` spans (one chat turn produced no tool call), each with `gen_ai.tool.name` and `gen_ai.tool.call.id`, and **no** `gen_ai.usage.*` attributes — correctly, since tools are not model invocations. The reconciler summed `input_tokens` across the seven chat spans and got 41,200. The provider's billing for the same window reported 41,200 — *they matched*. The divergence appeared one layer up: the reconciler then asserted "41,200 tokens for 7 model turns ⇒ ~5,885 tokens/turn, under the 8k per-turn budget ⇒ healthy." But the *final* turn alone consumed 11,900 input tokens, exceeding the per-turn context budget. The sum was correct; the *derived per-turn figure* was a mean over a monotonically growing sequence, and the mean masked a tail that had already breached the context limit. The agent had been silently truncating tool results (a client-side guard) to stay under the limit — which is why the sum looked bounded while the *semantic* content of the tool results was being dropped. The trace showed healthy token totals and a 100% tool-call success rate; the agent had in fact discarded the content of its last three tool results and answered from stale context. The tell was not in any single span. It was in the ratio between `gen_ai.usage.output_tokens` on the chat span immediately preceding a tool call and the *absence* of a corresponding growth in the following turn's `input_tokens` delta. Turn 5 output 1,100 tokens (a large tool-argument payload). Turn 6's `input_tokens` grew by only 400 over turn 5's total. The 1,100-token tool call had produced a tool result that *should* have added ~thousands of tokens; only 400 arrived. The truncation guard had fired and emitted no span event. ## Condition of Validity The summed-token invariant `Σ gen_ai.usage.input_tokens over chat spans == provider-billed input tokens` holds **only when** every model turn is represented by exactly one `gen_ai.chat` span in the trace and no retries, streaming re-connections, or client-side truncation occur between the provider's count and the span's recorded count. It breaks under three concrete conditions, all of which are the *normal* operating mode of a tool-using agent: 1. **Retry duplication.** A `gen_ai.chat` span that retries on a 429 emits one span but the provider bills two completions. Or the runtime emits two spans for one logical turn. Either way the sum double-counts or under-counts. 2. **Truncation invisibility.** Client-side context-window management (dropping old turns, truncating tool results, summarizing history) mutates the input *after* the previous turn's `output_tokens` were recorded but *before* the next turn's `input_tokens` are measured. The delta between consecutive turns is therefore not reconstructable from span attributes alone — the mutation has no span. 3. **Fan-in ambiguity.** Parallel tool calls (a single chat turn emitting three `gen_ai.tool` spans) share one preceding `gen_ai.chat` span. There is no per-tool token attribution, because the convention doesn't define one — the model produced all three tool calls in one output, and their individual "cost" is undefined. ## Decision Boundary An instance must **reconcile against the tool-call fan-out graph**, not the token sum, when *any* of the following is true: - The trace contains ≥1 `gen_ai.tool` span whose `gen_ai.tool.call.id` does not have a matching tool result reflected in the next chat span's input growth (i.e., the truncation check above fails). - Consecutive `gen_ai.chat` spans show an input-token delta inconsistent with the prior turn's `output_tokens` plus the byte-size of the intervening tool result (allow a tokenizer-ratio tolerance band; a delta below the band means content was dropped). - The mean per-turn input token count is within 20% of the configured context limit — the mean is a lagging indicator and the tail is what breaches. An instance may **trust the summed `gen_ai.usage.*` counters directly** only when the loop is single-turn (no tool spans), or when every intervening tool result's size is recorded as a span attribute and the per-turn delta reconciles within tolerance. In the absence of that, the token sum is a *billing* figure, not a *context-health* figure, and must not be used to certify that the agent saw what it was supposed to see. ## Operational Effect The guardrail is a **turn-delta reconciliation** emitted as a span event on the parent agent span: for each consecutive chat-span pair, compute `expected_input_growth = prior_output_tokens + tool_result_tokens` and compare against `observed_input_growth`. A shortfall beyond tolerance raises a truncation event and marks the run's context as degraded. This converts an invisible silent-truncation failure into a trace-visible one, and it bounds the class of "agent answered from stale context while reporting 100% tool success" incidents. The token counters remain the billing source of truth; the delta reconciliation becomes the *context-integrity* source of truth. They are different invariants over the same spans, and conflating them is the failure. ```python class GenAiSpanReconciliationError(RuntimeError): """Raised when a trace's GenAI span token accounting cannot certify that the agent actually observed its tool results.""" # Tokenizer-ratio tolerance: observed input growth may fall below # (prior output + tool result tokens) by at most this fraction before # we declare silent truncation. TRUNCATION_TOLERANCE = 0.15 def reconcile_turn_deltas(chat_spans: list[dict], tool_results: dict[str, int]) -> None: """ chat_spans: ordered list of dicts with keys 'gen_ai.usage.input_tokens', 'gen_ai.usage.output_tokens', 'tool_call_ids' (list of gen_ai.tool.call.id emitted by this turn) tool_results: map gen_ai.tool.call.id -> token count of the tool result injected before the NEXT chat turn. Raises GenAiSpanReconciliationError if any turn's input growth is inconsistent with the prior turn's output plus intervening tool results. """ for i in range(1, len(chat_spans)): prev = chat_spans[i - 1] cur = chat_spans[i] tool_tokens = sum(tool_results.get(cid, 0) for cid in prev["tool_call_ids"]) expected_growth = prev["gen_ai.usage.output_tokens"] + tool_tokens observed_growth = ( cur["gen_ai.usage.input_tokens"] - prev["gen_ai.usage.input_tokens"] ) if expected_growth == 0: continue shortfall_ratio = (expected_growth - observed_growth) / expected_growth if shortfall_ratio > TRUNCATION_TOLERANCE: raise GenAiSpanReconciliationError( f"Turn {i}: expected input growth ~{expected_growth} tokens " f"(prior output {prev['gen_ai.usage.output_tokens']} + " f"{tool_tokens} tool-result tokens) but observed only " f"{observed_growth}. Shortfall {shortfall_ratio:.0%} exceeds " f"tolerance {TRUNCATION_TOLERANCE:.0%}; agent likely answered " f"from stale context. Tool call ids in prior turn: " f"{prev['tool_call_ids']}." ) def certify_run(chat_spans: list[dict], tool_results: dict[str, int], context_limit: int) -> bool: if not chat_spans: raise GenAiSpanReconciliationError("Empty trace: no gen_ai.chat spans.") reconcile_turn_deltas(chat_spans, tool_results) tail_input = chat_spans[-1]["gen_ai.usage.input_tokens"] if tail_input > 0.80 * context_limit: raise GenAiSpanReconciliationError( f"Final-turn input {tail_input} exceeds 80% of context limit " f"{context_limit}; mean-based health check would mask this tail." ) return True ```