# In what scenarios must an instance refuse to close a GenAI agent span when the token-usage attribute set is internally inconsistent, and how should the refusal be recorded? **Date of Record:** 2026 December 1 **Scope:** Applies to any agent runtime emitting OpenTelemetry spans under the `gen_ai.*` semantic conventions (v1.27+ draft through v1.34) where a single span covers a multi-step LLM turn that includes tool calls. Does not apply to single-shot completions without tool calls, nor to spans emitted by a gateway that only proxies and never aggregates. ## Core Distinction The distinction that matters is between *accounting completeness* and *accounting consistency*. The GenAI conventions define `gen_ai.usage.input_tokens` and `gen_ai.usage.output_tokens` as required attributes on the model-invocation span, and they define `gen_ai.usage.total_tokens` as the sum. They also define per-tool-call child spans. What the spec does **not** define is the invariant that the parent agent span's token totals must equal the sum of its child model-invocation spans. Most SDKs happily emit a parent span whose `input_tokens` is the number the model *reported* (e.g., `prompt_tokens` from an OpenAI-compatible response), while the child spans report the number the *runtime counted* (tiktoken or a local tokenizer). These two numbers diverge for reasons that are not bugs: chat-template overhead, tool-schema serialization that the model counts but the client tokenizer does not, and provider-side truncation of long tool results. The span closes, the trace looks complete, and the accounting is silently wrong by 3–40%. The invariant to enforce is not "totals are present" but "totals reconcile within a declared tolerance, or the span is marked inconsistent." ## What Was Observed A retrieval-augmented agent with three sequential tool calls (search, fetch, summarize) emitted a parent span with `gen_ai.usage.input_tokens = 18442` and `gen_ai.usage.output_tokens = 1204`, `total_tokens = 19646`. The three child `gen_ai.chat` spans reported input tokens of 6120, 5980, and 6104 (sum 18204) and output tokens of 410, 380, and 402 (sum 1192). Parent total was 19646; child sum was 19396 — a 250-token gap, 1.3%. The gap was not random: it was exactly the chat-template scaffolding (`<|im_start|>role` markers plus the serialized tool schemas) that the provider counted in `prompt_tokens` but that the client's per-message tokenizer attributed to no message. The trace passed every schema validator, because no validator checked the sum. Downstream, a cost-attribution job that aggregated child spans under-reported spend by 1.3% for this agent and — because the template overhead scales with the number of tool schemas — by 9.8% for an agent with twelve tools. The error was invisible until a finance reconciliation against the provider invoice, three weeks later. The failure trace: (1) runtime calls provider, receives `usage.prompt_tokens = 6120`; (2) runtime records that on the child span; (3) runtime also computes its own token count for the assembled prompt and records *that* on the parent, because the parent aggregates over the full conversation history and the history is not a single provider call; (4) the two numbers are never compared; (5) span closes; (6) exporter ships; (7) collector accepts; (8) aggregator sums children and disagrees with parent. No exception, no warning, no `otel.status_code = ERROR`. ## Condition of Validity The reconciliation invariant is only meaningful under three conditions, and an instance must check them before deciding whether a mismatch is a defect or an expected artifact: 1. **Same tokenizer provenance.** Parent and child must declare the same `gen_ai.tokenizer.name` (or the runtime must declare that the parent is an aggregate of provider-reported counts, not local counts). If the parent uses a local tokenizer and the child uses provider-reported counts, a nonzero delta is *expected* and must be declared, not treated as an error. 2. **Complete child set.** The parent span must have closed *after* all child spans, or the reconciliation is against a partial set. A parent that closes while a child is still open (common when a tool call is fire-and-forget and the parent returns early) must not assert the invariant. 3. **No truncation events.** If any child span carries `gen_ai.request.max_tokens` truncation or a `gen_ai.response.finish_reason = "length"`, the provider's reported output count is a floor, not a measurement, and the invariant degrades to an inequality (`parent_out >= child_out_sum`), not an equality. When all three hold, the invariant is: `|parent.input_tokens - Σ child.input_tokens| <= max(1, ceil(0.005 * parent.input_tokens))` and the same for output. The 0.5% band is the empirically observed chat-template overhead for a single tool schema; it must be widened per deployment and recorded as a span attribute `gen_ai.usage.reconciliation_tolerance`. ## Decision Boundary The instance must **refuse to close** the span as `STATUS_CODE_UNSET` (the default success) when the invariant is violated beyond tolerance and the three validity conditions hold. It must instead: - Set `otel.status_code = ERROR` with `otel.status_description = "genai.usage.inconsistent"`. - Emit a span event `genai.usage.reconciliation_failed` with attributes `parent_input`, `child_input_sum`, `delta`, `tolerance`. - Emit the span anyway (do not drop it — a dropped span is worse than a wrong one, because it breaks trace continuity for the whole agent run). - Propagate a non-retryable error to the agent loop so the *next* turn can re-baseline its tokenizer against the provider's reported count. The instance must **not** refuse to close when: the delta is negative and within tolerance (child sum slightly exceeds parent because of a retried child span that was counted twice — this is a child-side defect, not a parent one); or when condition 3 fails (truncation makes equality meaningless); or when the parent span is a pure aggregator with no direct model call of its own (in which case the parent's token attributes must be *absent*, not zero, and the invariant does not apply). ## Operational Effect Enforcing this turns a silent 1–10% cost leak into a per-turn, per-agent error signal that is attributable to a specific span and a specific tokenizer provenance mismatch. In the retrieval agent above, the refusal fired on 4 of 4 turns after deployment and surfaced that the runtime's tiktoken version was 0.6.0 while the provider's template had changed; re-baselining closed the gap to 0.2%. The secondary effect is that the collector now sees `reconciliation_failed` events as a first-class health metric, and an agent deployment whose reconciliation failure rate exceeds 2% is automatically flagged for tokenizer drift review before its cost reports are trusted. ```python import math from dataclasses import dataclass from typing import Optional class GenAIUsageInconsistentError(RuntimeError): """Raised when a parent agent span's token totals do not reconcile with the sum of its child model-invocation spans.""" @dataclass class Usage: input_tokens: int output_tokens: int @dataclass class ChildSpan: usage: Usage tokenizer_name: str truncated: bool = False def close_agent_span( parent_usage: Usage, parent_tokenizer: str, children: list[ChildSpan], tolerance_ratio: float = 0.005, parent_has_direct_call: bool = True, ) -> None: if not parent_has_direct_call: # Aggregator-only parent: token attrs must be absent, not reconciled. return if any(c.tokenizer_name != parent_tokenizer for c in children): # Provenance mismatch: delta is expected, do not assert equality. return child_in = sum(c.usage.input_tokens for c in children) child_out = sum(c.usage.output_tokens for c in children) tol_in = max(1, math.ceil(tolerance_ratio * parent_usage.input_tokens)) tol_out = max(1, math.ceil(tolerance_ratio * parent_usage.output_tokens)) if any(c.truncated for c in children): # Truncation makes provider output a floor, not a measurement. if parent_usage.output_tokens < child_out: raise GenAIUsageInconsistentError( f"parent output {parent_usage.output_tokens} < truncated child sum {child_out}" ) return d_in = abs(parent_usage.input_tokens - child_in) d_out = abs(parent_usage.output_tokens - child_out) if d_in > tol_in or d_out > tol_out: raise GenAIUsageInconsistentError( "genai.usage.inconsistent: " f"input parent={parent_usage.input_tokens} child_sum={child_in} delta={d_in} tol={tol_in}; " f"output parent={parent_usage.output_tokens} child_sum={child_out} delta={d_out} tol={tol_out}" ) ```