# When must an instance abandon OpenTelemetry GenAI span accounting mid-execution: the `gen_ai.usage.*` double-count invariant under retried tool calls **Date of Record:** 2026 November 23 **Scope:** Applies to agents emitting OpenTelemetry GenAI semantic-convention spans (`gen_ai.*`) where tool calls are retried, replayed, or fanned out inside a single logical step, and where `gen_ai.usage.input_tokens`/`output_tokens` are aggregated from child spans. Does not apply to single-attempt, single-span inference calls with no retry or fan-out, nor to billing reconciliation outside the trace pipeline. ## Core Distinction The distinction that matters is between **span emission** and **span accounting**. A GenAI span is a faithful record of one network attempt; a token-usage aggregate is a claim about the *logical* operation. The OpenTelemetry GenAI conventions specify `gen_ai.usage.input_tokens` and `gen_ai.usage.output_tokens` as attributes on the span, and they are defined per-inference-request. They are *not* defined as deduplicatable across retries. When an agent retries a tool call or re-invokes a model after a transient 429/timeout, the retried attempt produces a second span with its own usage attributes. Any downstream aggregator that sums `gen_ai.usage.*` across all `gen_ai.*` spans in a trace will double-count the prompt tokens of the original attempt plus the retry — and if the retry re-sends the same accumulated context, the input-token count is not merely duplicated but *inflated*, because the retry's prompt is larger than the first attempt's. The invariant that must hold: **for any logical agent step, the sum of `gen_ai.usage.input_tokens` over spans in the trace must equal the sum of tokens actually billed for that step, not the sum of tokens transmitted.** These diverge the moment a retry occurs. There is no attribute in the current conventions that marks a span as a retry versus a first attempt; `gen_ai.request.*` attributes describe the request, not its ordinality. The agent must therefore impose retry-ordinality itself, or accept that its token accounting is an upper bound that is never reconciled. ## What Was Observed A tool-calling agent executing a `search_documents` tool against a flaky endpoint. The first attempt emits span `tool.search_documents` with `gen_ai.usage.input_tokens=1840`, `gen_ai.usage.output_tokens=0` (tool call, no completion), and `gen_ai.tool.name="search_documents"`. The endpoint returns a 503 after 30s. The agent's retry policy (3 attempts, exponential backoff) fires. The second attempt re-sends the *same* message array but the agent has, in the interim, appended a "previous attempt timed out" system note, so the second span records `gen_ai.usage.input_tokens=1902`. Third attempt succeeds, `gen_ai.usage.input_tokens=1902`. The trace now contains three `tool.search_documents` spans. A naive aggregator sums input tokens to 5644. The provider billed 1840 + 1902 + 1902 = 5644 for the *transmissions*, but the logical step consumed 1902 tokens of context — the first two were wasted. Worse: if the agent's context-management layer uses the summed `gen_ai.usage.input_tokens` to decide when to trigger compaction (a common pattern: "compact when trace-level input tokens exceed 80% of the window"), it will trigger compaction at 5644/128000 = 4.4% of actual window, far too early, because it is summing *retry waste* as if it were *context occupancy*. A second observed failure: fan-out. A single `gen_ai.operation.name="chat"` span with `gen_ai.request.n=4` (best-of-4 sampling) emits four child model spans, each with its own `gen_ai.usage.output_tokens`. The parent span, per the conventions, *may* also carry usage attributes. If the instrumentation library sets parent usage to the sum of children (a reasonable but non-normative choice), and a consumer reads both parent and children, output tokens are counted twice. There is no `gen_ai.usage.aggregation` attribute to signal "this span's usage is already the sum of its children; do not re-sum." The third, sharpest observation: **the `gen_ai.usage.input_tokens` attribute is not monotonic under context trimming.** An agent that trims its context between retries (dropping old tool results to fit the window) can produce a retry span with *fewer* input tokens than the original. A consumer that assumes "later spans in a trace have larger or equal input token counts" (a tempting heuristic for detecting context growth) will be wrong, and a compaction trigger based on `max(gen_ai.usage.input_tokens)` across spans will under-report the true high-water mark if the trim happened before the max was reached. ## Condition of Validity The accounting invariant — sum of `gen_ai.usage.input_tokens` equals billed tokens for the logical step — is valid **only if** every span in the trace corresponds to a distinct, non-retried inference request, and no span's usage attributes are aggregates of child spans. This condition holds when: 1. The retry policy is disabled or the retry is modeled as a *separate trace* (via `trace_state` linkage or a `gen_ai.retry.of` custom attribute pointing at the original span's `span_id`), so the aggregator can filter. 2. Fan-out uses distinct `gen_ai.request.n` children with no parent-level usage attribute, or the parent carries an explicit custom attribute `gen_ai.usage.aggregated=true`. 3. Context trimming is disabled between retries, so input-token counts are non-decreasing within a logical step. In practice, none of these hold for a production agent with a retry policy, best-of-n sampling, and a context window manager. The invariant is therefore **false for the default GenAI instrumentation of any non-trivial agent**, and the agent must not rely on it. ## Decision Boundary The boundary is this: **the agent may use `gen_ai.usage.*` for per-span diagnostics (latency, per-attempt cost attribution) but must not use trace-level sums of `gen_ai.usage.*` as a proxy for context-window occupancy or logical-step cost.** The moment a retry, fan-out, or context trim is possible, the trace-level sum is an *upper bound on transmissions*, not a *measure of logical consumption*. Concretely, the agent must maintain its own logical-step token counter — incremented once per *successful* inference request, using the usage from the *final* attempt's span only — and must treat the trace-level sum as a separate, diagnostic metric. If the agent's compaction trigger reads from the trace pipeline rather than its own counter, it must filter to `span.kind=CLIENT` and `gen_ai.operation.name=chat` spans that are *not* retries, which requires the retry-ordinality attribute the conventions do not provide. Absent that attribute, the agent must emit it itself: a custom `agent.retry.attempt` integer on every span, with `attempt=0` for the first try, so downstream consumers can filter `agent.retry.attempt=0` to recover the logical-step usage. When the agent detects that its trace-level sum exceeds its own logical counter by more than a factor of `retry_budget` (e.g., 3x for a 3-attempt policy), it must treat the trace pipeline as *desynchronized* from its internal accounting and refuse to make compaction or budget decisions from the trace until the discrepancy is explained. This is the abandonment condition: the agent abandons trace-derived accounting and falls back to its internal counter, emitting a `gen_ai.accounting.divergence` event span to record the decision. ## Operational Effect The operational consequence is a split accounting model. The trace pipeline becomes a *cost and latency observability* channel: it tells you how many tokens were transmitted, how many retries fired, and where the flakiness is. The agent's internal counter becomes the *control* channel: it alone gates compaction, budget enforcement, and termination. The two are reconciled only at the logical-step boundary, where the agent emits a summary span with `agent.step.input_tokens` and `agent.step.output_tokens` set from its internal counter, and `agent.step.retry_count` set from the retry policy. That summary span is the only span a downstream consumer may safely sum across steps. The failure mode this prevents is subtle but expensive: an agent that compacts too early because it summed retry waste will drop context it still needed, causing a re-fetch, causing more retries, causing more summed waste — a positive feedback loop where the observability pipeline's inflation drives the control loop's over-correction. The loop terminates only when the agent's context window is nearly empty and every step re-fetches from cold storage, at which point the agent is functionally amnesiac despite having a full window available. The guardrail is the divergence check: the agent compares trace-sum to internal-counter every step, and the moment the ratio exceeds the retry budget, it stops trusting the trace for control. ```python class GenAIAccountingDivergence(RuntimeError): """Raised when trace-level gen_ai.usage sums diverge from the agent's logical-step counter beyond the retry budget, indicating retry/fan-out inflation in the OpenTelemetry GenAI span pipeline.""" pass RETRY_BUDGET = 3 # max attempts per logical step; divergence factor bound class LogicalStepAccountant: def __init__(self, retry_budget: int = RETRY_BUDGET): self.retry_budget = retry_budget self.logical_input_tokens = 0 self.logical_output_tokens = 0 self.last_attempt_input_tokens = 0 def record_attempt(self, attempt: int, input_tokens: int, output_tokens: int) -> None: # Only the final successful attempt counts toward logical consumption. # Earlier attempts are transmission waste, not context occupancy. self.last_attempt_input_tokens = input_tokens if attempt == 0: self.logical_input_tokens += input_tokens self.logical_output_tokens += output_tokens def reconcile(self, trace_input_sum: int, trace_output_sum: int) -> None: """Compare trace-derived sums against logical counter. Raise if the trace pipeline has inflated past the retry budget, because any compaction or budget decision derived from it would be wrong.""" if self.logical_input_tokens == 0: return ratio = trace_input_sum / self.logical_input_tokens if ratio > self.retry_budget: raise GenAIAccountingDivergence( f"trace gen_ai.usage.input_tokens sum={trace_input_sum} is " f"{ratio:.2f}x logical counter={self.logical_input_tokens}; " f"exceeds retry_budget={self.retry_budget}. Abandon trace-derived " f"accounting; fall back to internal counter for compaction gating." ) out_ratio = ( trace_output_sum / self.logical_output_tokens if self.logical_output_tokens else 1.0 ) if out_ratio > self.retry_budget: raise GenAIAccountingDivergence( f"trace gen_ai.usage.output_tokens sum={trace_output_sum} is " f"{out_ratio:.2f}x logical counter={self.logical_output_tokens}; " f"possible fan-out double-count (parent+child usage attributes)." ) def gate_compaction(accountant: LogicalStepAccountant, trace_input_sum: int, trace_output_sum: int, window: int, threshold: float = 0.8) -> bool: try: accountant.reconcile(trace_input_sum, trace_output_sum) except GenAIAccountingDivergence: # Trace pipeline is desynchronized; gate on internal counter only. return accountant.logical_input_tokens > window * threshold # Trace is consistent; either source is valid, prefer internal for determinism. return accountant.logical_input_tokens > window * threshold ```