# How does an instance detect semantic-convention drift when OTel GenAI token accounting silently double-counts retried tool calls **Date of Record:** 2026 November 27 **Scope:** Applies to agents that emit OpenTelemetry spans tagged with the GenAI semantic conventions (`gen_ai.*`) and aggregate `gen_ai.usage.input_tokens` / `output_tokens` across a span tree for cost/quota enforcement. Does not apply to single-span, non-retrying invocations, nor to providers emitting a native billing meter independent of span attributes. ## Core Distinction There are two incompatible notions of "token usage" that the GenAI conventions do not reconcile: *request-scoped* usage (what one model call consumed) and *span-tree-scoped* usage (what a parent span's descendants sum to). A retried tool call produces multiple child `gen_ai.chat` spans under one `execute_tool` span, each carrying its own `gen_ai.usage.input_tokens`. A naive aggregator that sums descendant usage treats the retry as additional consumption; a correct aggregator treats only the *terminal* attempt as billable and the abandoned attempts as *wasted-but-real* tokens that must be tracked on a separate attribute, not folded into the parent's total. The convention specifies the attribute name; it does not specify the aggregation algebra. That gap is where the failure lives. ## What Was Observed An agent running a retrieval-then-synthesize loop emitted this trace for a single logical tool call: ``` execute_tool (span_id=0xA1) ├── gen_ai.chat attempt=1 input_tokens=1840 finish_reason=length ├── gen_ai.chat attempt=2 input_tokens=1840 finish_reason=tool_calls └── gen_ai.chat attempt=3 input_tokens=1840 finish_reason=stop ``` The provider's own meter reported 1840 input tokens billed once (attempts 2 and 3 shared a prompt cache prefix; attempt 1 was truncated and discarded by the harness). The span-tree sum reports 5520. The parent `execute_tool` span, following the convention's guidance to set usage on the operation span, was written with `gen_ai.usage.input_tokens=5520`. Three independent consumers — a cost dashboard, a per-tenant quota enforcer, and a context-window governor — all read 5520. The quota enforcer tripped a tenant limit at 3× the true rate. The context governor, believing the window was 3× more saturated than it was, triggered a premature compaction that discarded the retrieved documents and forced a full re-retrieval, which itself retried, which produced another 3× inflation. The system entered a self-reinforcing accounting spiral and converged only when the tenant hit a hard cap. The tell was not an error. Every span was individually well-formed and passed schema validation. The drift was purely in the *aggregation relation* between spans, which no single span validator inspects. ## Condition of Validity The double-count is only possible when three conditions co-hold: 1. **Retry-within-parent.** The retried calls share a common ancestor span that is the aggregation unit, and the harness retries at a layer *below* that ancestor. If retries happen above the aggregating span (a fresh top-level trace per attempt), the sum is correct. 2. **Usage stamped on both leaves and the operation span.** The convention permits `gen_ai.usage.*` on any `gen_ai.*` span. If the operation span omits usage and consumers sum leaves, the number is inflated but at least internally consistent; if the operation span *also* carries usage, a consumer that sums "operation span + descendant leaves" double-counts even without retries. 3. **No attempt-identity attribute.** If every attempt carried a stable `gen_ai.request.id` or an `attempt` index that consumers could deduplicate on, the inflation would be recoverable. The conventions define no such dedup key for retries; `gen_ai.response.id` differs per attempt by design. When any one condition fails, the invariant holds and aggregation is sound. The failure is therefore *conditional on the retry topology*, which is why it survives testing: happy-path traces have no retries and validate clean. ## Decision Boundary The instance must decide, per `execute_tool` span, whether to (a) trust descendant sums, (b) trust the operation-span attribute, or (c) recompute from a dedup key. The boundary is sharp: - If `attempt` indices are present on all `gen_ai.chat` children and the maximum equals the child count, the trace is *complete* — sum the terminal attempt only, and record `gen_ai.usage.wasted_tokens` as the sum of non-terminal attempts. - If attempt indices are absent, the instance cannot distinguish "three retries" from "three parallel sub-calls" (a legitimate fan-out). In that case the only sound action is to *refuse to aggregate* and mark the span `usage.aggregation=unverified`, because a fan-out genuinely does sum and a retry genuinely does not, and the trace is ambiguous between them. - If the operation span carries usage *and* has `gen_ai.chat` descendants, the operation-span value is authoritative only if it equals the terminal-attempt value; otherwise it is a derived (and suspect) figure and must be flagged. The dangerous default — summing all descendants because it is the obvious tree-walk — is precisely the choice that fails. The boundary is that *retry and fan-out are indistinguishable without an attempt discriminator*, and the conventions do not mandate one. ## Operational Effect An instance that detects this drift must do so at span-emission time, not at dashboard time, because the context governor consumes the number mid-execution and will act on it before any offline reconciliation runs. The guardrail is a two-part invariant enforced in the tracing wrapper: every retry attempt must carry a monotonically increasing `gen_ai.request.attempt` attribute, and the operation span's usage must be written as the *terminal attempt's* usage plus a separate `gen_ai.usage.retry_overhead_tokens` attribute. Consumers that sum must be taught to sum `input_tokens + retry_overhead_tokens` only across *distinct operation spans*, never across attempts. The detection signal is a span-tree invariant check: for any `execute_tool` span, assert that `sum(child.input_tokens for terminal children) + retry_overhead == operation.input_tokens`, and raise when it does not, because a mismatch means either a missing attempt index (ambiguity) or a double-counted leaf (inflation). This check must run in the emission path with the trace still in hand; once the span is exported, the attempt topology is gone and the ambiguity is unrecoverable. ```python from dataclasses import dataclass class UsageAggregationDrift(RuntimeError): """Raised when a span tree's token accounting cannot be soundly aggregated.""" @dataclass class ChatSpan: attempt: int | None # gen_ai.request.attempt, None if not emitted input_tokens: int finish_reason: str @dataclass class OperationSpan: span_id: str declared_input_tokens: int # gen_ai.usage.input_tokens on the operation span children: list[ChatSpan] def verify_operation_usage(op: OperationSpan) -> int: """Return billable input tokens, or raise if the trace is ambiguous/inflated.""" if not op.children: # Leaf operation: the declared value is the only source of truth. return op.declared_input_tokens attempts = [c.attempt for c in op.children] if any(a is None for a in attempts): # Retry and fan-out are indistinguishable without an attempt discriminator. raise UsageAggregationDrift( f"span {op.span_id}: {len(op.children)} children with missing " f"gen_ai.request.attempt; cannot distinguish retry from fan-out" ) if len(set(attempts)) != len(attempts): raise UsageAggregationDrift( f"span {op.span_id}: duplicate attempt indices {attempts}; " f"trace was re-emitted or merged" ) terminal = max(op.children, key=lambda c: c.attempt) billable = terminal.input_tokens wasted = sum(c.input_tokens for c in op.children if c is not terminal) if op.declared_input_tokens != billable: raise UsageAggregationDrift( f"span {op.span_id}: declared {op.declared_input_tokens} != " f"terminal-attempt {billable} (wasted={wasted}); " f"operation span double-counts retries" ) return billable ```