# When must an instance reject a GenAI span whose token-usage attributes disagree with its own tool-call ledger **Date of Record:** 2026 November 29 **Scope:** Applies to agents that emit OpenTelemetry GenAI spans (`gen_ai.*` semantic conventions) for tool-calling loops and reconcile span-level token accounting against an internal per-call ledger before export or audit. Does not apply to single-shot inference spans with no tool calls, nor to spans emitted by a gateway that never executes tools itself. ## Core Distinction The GenAI semantic conventions treat token usage as a *span-local attribute*: `gen_ai.usage.input_tokens` and `gen_ai.usage.output_tokens` describe what the model reported for that one request. An executing agent, by contrast, has a *ledger*: a monotonically accumulating record of tokens it believes it has spent across the loop, including tokens consumed by tool results it fed back into the next prompt. These are two different quantities that happen to share units. The convention does not define how a parent agent span's usage relates to the sum of its child tool-call spans, and it does not require that `gen_ai.usage.*` on a parent equal the arithmetic sum of children. The boundary failure is treating span-local usage as if it were ledger-consistent — and then either (a) double-counting tool-result tokens when a child span re-reports the parent's input, or (b) silently dropping the increment that the tool result added to the next turn's input. The invariant that actually holds is narrow: **for a single `chat` span, `input_tokens` counts the full serialized prompt the provider billed for, which already includes every prior tool result in the message array.** It does not hold that a parent `invoke_agent` span's usage equals the sum of its child `execute_tool` and `chat` spans, because the parent's *last* chat span already folded the tool outputs into its own input. ## What Was Observed A three-turn tool loop: turn 1 chat (input 1,200 / output 180), one `execute_tool` span, turn 2 chat (input 1,540 / output 95 — the 1,540 includes the 180 output of turn 1 plus the ~160-token tool result), one more `execute_tool`, turn 3 chat (input 1,890 / output 60). The agent's exporter emitted a parent `invoke_agent` span with `gen_ai.usage.input_tokens = 4630` (the naive sum of the three chat inputs) and `output_tokens = 335`. The internal ledger, which tracks *marginal* cost, recorded input 1,200 + 340 + 350 = 1,890 and output 335. Both numbers are "true" under different definitions, and neither matches the other. The failure trace: 1. The reconciler compares parent span `input_tokens` (4,630) to ledger input (1,890) and raises a mismatch of 2,740. 2. An operator "fixes" it by summing only the first chat span's input plus each subsequent chat's *delta* — but the delta is not exposed by the convention, only the absolute `input_tokens` per span, so the fix requires the exporter to have retained per-span message-array lengths, which it did not. 3. The parent span is marked `gen_ai.usage.*` as authoritative by a downstream billing dashboard, which then overcharges by 2.4×. The non-obvious part: the overcount is *stable and reproducible*, so it survives spot checks. It only surfaces when a tool result is large enough that its inclusion in the next prompt is visible in the input delta — small tool results hide inside tokenizer noise and the sum-of-children heuristic appears to pass. ## Condition of Validity The ledger-vs-span reconciliation is only valid when all of the following hold: - The exporter records, per `chat` span, the number of messages and the serialized byte length of the prompt at emission time (not just token counts). Without this, marginal input cannot be reconstructed after the fact. - `execute_tool` spans carry **no** `gen_ai.usage.*` attributes. The convention is silent on tool spans, and some SDKs populate them with the tokenizer cost of the tool *schema*, which is not billed and must not be summed. - The parent `invoke_agent` span either omits `gen_ai.usage.*` entirely or sets it to the *terminal* chat span's cumulative input plus the sum of outputs — never to the sum of child inputs. - Streaming responses are accounted once. A streamed chat that emits usage in a final chunk and is also re-emitted by a retry wrapper produces two usage attributes on one logical call; the ledger must key on `gen_ai.response.id`, not span count. When any condition fails, the correct action is to treat the parent span's usage as **unreconcilable** and quarantine it, not to pick whichever number is larger. ## Decision Boundary The decision is not "do the numbers agree." It is: *does the span graph expose enough structure to distinguish cumulative from marginal input?* If the exporter emitted only `gen_ai.usage.*` scalars and no message-array metadata, the parent span's usage is a cumulative figure and **must not** be compared to a marginal ledger — the comparison is category error, and the guardrail is to reject the comparison, not the span. If the exporter did emit per-span message counts and the deltas still do not reconstruct the parent, then a retry, a truncated tool result, or a context-window trim occurred mid-loop, and the parent span is genuinely corrupt. That is the only case where the instance raises. ## Operational Effect The practical consequence is that token accounting for agent loops must be anchored to the **terminal chat span per `gen_ai.response.id`**, with tool spans excluded from usage summation entirely, and the parent `invoke_agent` span's usage marked `gen_ai.usage.*` as *derived, non-authoritative* (or omitted). Dashboards that sum `gen_ai.usage.input_tokens` across all spans in a trace will overcount by exactly the cumulative prompt growth — which for a 10-turn loop with 2k-token tool results is roughly a 5–8× inflation. The guardrail is a quarantine path: when marginal reconstruction is impossible, the reconciler emits a `usage_unreconcilable` event and refuses to bill, rather than silently trusting either side. ```python from dataclasses import dataclass class UsageReconciliationError(RuntimeError): """Raised when a GenAI agent span's usage cannot be reconciled to the ledger.""" @dataclass class ChatSpan: response_id: str input_tokens: int output_tokens: int message_count: int | None # None => exporter did not record structure @dataclass class ToolSpan: name: str gen_ai_usage_input: int # must be zero per invariant def reconcile_agent_usage( parent_input_tokens: int, chats: list[ChatSpan], tools: list[ToolSpan], ledger_marginal_input: int, ) -> dict: # Invariant 1: tool spans must not carry billed usage. for t in tools: if t.gen_ai_usage_input != 0: raise UsageReconciliationError( f"tool span {t.name!r} carries gen_ai.usage.input_tokens=" f"{t.gen_ai_usage_input}; convention does not bill tool schemas" ) # Invariant 2: no structure => parent usage is cumulative, not reconcilable. if any(c.message_count is None for c in chats): return { "status": "unreconcilable", "reason": "missing message-array metadata; parent usage is cumulative", "quarantine_parent_input": parent_input_tokens, } # Invariant 3: dedupe by response_id (retry/stream double-emit). by_id: dict[str, ChatSpan] = {} for c in chats: prev = by_id.get(c.response_id) if prev is not None and prev.input_tokens != c.input_tokens: raise UsageReconciliationError( f"response {c.response_id!r} emitted conflicting input_tokens " f"({prev.input_tokens} vs {c.input_tokens})" ) by_id[c.response_id] = c ordered = list(by_id.values()) marginal = ordered[0].input_tokens for prev, cur in zip(ordered, ordered[1:]): if cur.message_count <= prev.message_count: raise UsageReconciliationError( f"message_count did not grow across turns " f"({prev.message_count} -> {cur.message_count})" ) delta = cur.input_tokens - (prev.input_tokens + prev.output_tokens) if delta < 0: raise UsageReconciliationError( f"negative marginal input {delta} on response {cur.response_id!r}; " "context trim or truncation occurred mid-loop" ) marginal += delta if marginal != ledger_marginal_input: raise UsageReconciliationError( f"marginal input {marginal} != ledger {ledger_marginal_input}" ) return { "status": "ok", "marginal_input": marginal, "parent_input_authoritative": False, "ignored_cumulative_parent": parent_input_tokens, } ```