# Which invariants prevent token-accounting drift in OpenTelemetry GenAI agent spans when tool-call subtrees are re-emitted after retry **Date of Record:** 2026 November 30 **Scope:** Applies to agent runtimes that emit OpenTelemetry GenAI spans (`gen_ai.*` semantic conventions) for LLM calls and tool invocations, where a retry, resume, or checkpoint-replay causes a previously-emitted span subtree to be re-emitted under a new parent. Does not cover single-shot, non-retried inference calls, nor transport-level retries that are deduplicated before span creation. ## Core Distinction The GenAI semantic conventions treat `gen_ai.usage.input_tokens` and `gen_ai.usage.output_tokens` as **per-span, per-attempt facts**, while downstream cost aggregators, budget enforcers, and rate governors treat them as **per-logical-operation facts**. These two readings diverge the moment a span subtree is re-emitted. The convention does not specify a reconciliation key; it specifies attributes. The invariant that must be enforced outside the convention is: *token usage is attributed exactly once per `(trace_id, logical_step_id)` tuple, regardless of how many physical spans carry it.* The failure is not double-counting in the naive sense. It is **subtree re-emission under a fresh `span_id` but a preserved `gen_ai.operation.name` and preserved usage attributes**, which produces internally consistent spans that an aggregator cannot distinguish from a genuine second LLM call. The telemetry is not corrupt; it is *ambiguous by construction*. ## What Was Observed An agent executing a three-tool plan (`search` → `fetch` → `summarize`) hit a `DeadlineExceeded` on the `fetch` tool span at T+42s. The orchestrator's retry policy re-entered the step, creating a new child span `fetch` (new `span_id`, same `gen_ai.operation.name="execute_tool"`, same `gen_ai.tool.name="fetch"`) parented to the *same* agent span. The original `fetch` span was ended with `status.code=ERROR` but retained its `gen_ai.usage.*` attributes from a partial token stream (the tool had an internal LLM-backed summarizer that emitted 1,180 input / 340 output tokens before timing out). The retried `fetch` succeeded and emitted 1,190 input / 355 output tokens. Both spans landed in the collector. The budget governor, which summed `gen_ai.usage.input_tokens` over all spans where `gen_ai.operation.name` matched an allowlist, charged 2,370 input tokens for a step whose true cost was ~1,190. The agent's remaining-budget estimate dropped below its self-imposed floor, and it aborted the `summarize` step — a **telemetry-induced execution divergence**: the observability layer's accounting error caused the agent to terminate a plan that was, in fact, within budget. A second variant surfaced on checkpoint-resume. The agent persisted a checkpoint at the step boundary and, on process restart, replayed from the checkpoint. The replay re-emitted the *entire* prior span subtree under a new trace root (the checkpoint did not carry `trace_id`/`span_id` linkage, only the logical step list). The aggregator saw two complete traces with identical `gen_ai.operation.name` sequences and summed both. Budget depletion was 2× the true value, and the agent entered a permanent abort state on every subsequent resume. The common signature: **usage attributes are correct per span; the aggregation key is wrong.** ## Condition of Validity The exactly-once token invariant holds only when at least one of the following is true for every re-emitted span: 1. The re-emitted span carries a stable `gen_ai.agent.step_id` (or equivalent custom attribute) that is identical across attempts, and the aggregator deduplicates on `(trace_id, step_id)` selecting the **terminal** attempt (the one whose `status.code != ERROR` or whose `end_time` is latest). 2. The retried span is emitted under a *new* `trace_id` and the aggregator is trace-scoped, so the error attempt in the prior trace is excluded by construction. 3. The retry is represented as an OTel **event** (`span.add_event("retry", ...)`) on the parent rather than a new child span, so there is exactly one usage-bearing span per logical step. The invariant is **violated** when: the agent emits a new child span per retry attempt, preserves `gen_ai.operation.name` and `gen_ai.tool.name`, does *not* preserve a logical step identifier, and the aggregator keys on operation name alone. This is the default behavior of most naive instrumentation wrappers and is exactly what the semantic conventions permit, because they define attributes, not identity. ## Decision Boundary The boundary is a single question the runtime must answer at span-emission time: > *Is the current attempt a re-execution of a logical step that has already emitted usage, and does the aggregator have a key to distinguish attempts from distinct steps?* If **yes to re-execution and no to a distinguishing key**, the runtime MUST either (a) suppress `gen_ai.usage.*` on the superseded attempt (emit `gen_ai.usage.input_tokens` only on the terminal attempt, and mark the failed attempt with `status.code=ERROR` and *no* usage attributes), or (b) attach a monotonic `gen_ai.agent.attempt` integer and a stable `gen_ai.agent.step_id`, and require the aggregator to `argmax(attempt)` per `step_id`. Option (a) loses the partial-token truth; option (b) preserves it at the cost of aggregator complexity. There is no third option that keeps both naive aggregation and per-attempt truth. For checkpoint-resume, the boundary is stricter: the checkpoint MUST carry `trace_id` and the parent `span_id` of the in-flight step, so the resumed runtime can either continue the same trace (link via `SpanContext`) or emit a `span.add_link()` to the pre-checkpoint span. A checkpoint that carries only logical state and not telemetry linkage guarantees the 2× drift on every resume. ## Operational Effect The consequence is not merely inflated dashboards. Because agents increasingly read their own telemetry to make budget and termination decisions, token-accounting drift becomes a **control-loop input error**. The agent's belief about remaining budget is a function of its own span emissions; if re-emission inflates that belief negatively, the agent aborts valid plans (false budget exhaustion). If an aggregator deduplicates aggressively on `gen_ai.operation.name` without attempt awareness, it can *under*-count genuine repeated calls (e.g., a legitimate loop calling `search` five times), producing false budget surplus and runaway execution. The guardrail is a two-part invariant, enforced at emission and at aggregation: - **Emission invariant:** every usage-bearing span carries `(gen_ai.agent.step_id, gen_ai.agent.attempt)`; superseded attempts are marked `status.code=ERROR` and, if the aggregator cannot be trusted to `argmax`, have usage attributes stripped. - **Aggregation invariant:** token sums are computed as `sum over step_id of usage(argmax_attempt(step_id))`, never as `sum over spans`. The following predicate encodes the emission-side check and refuses to emit a usage-bearing span that would violate the exactly-once invariant under a naive aggregator. ```python from dataclasses import dataclass, field from typing import Optional class TokenAccountingInvariantError(RuntimeError): """Raised when a span emission would make token usage ambiguous under naive aggregation.""" pass @dataclass class GenAISpanEmission: trace_id: str span_id: str operation_name: str # gen_ai.operation.name tool_name: Optional[str] # gen_ai.tool.name step_id: Optional[str] # gen_ai.agent.step_id (custom, required for retries) attempt: Optional[int] # gen_ai.agent.attempt (custom, required for retries) status_code: str # "OK" | "ERROR" input_tokens: Optional[int] # gen_ai.usage.input_tokens output_tokens: Optional[int] # gen_ai.usage.output_tokens @dataclass class EmissionLedger: # (trace_id, step_id) -> list of attempts already emitted seen: dict = field(default_factory=dict) def record(self, e: GenAISpanEmission, aggregator_is_attempt_aware: bool) -> None: carries_usage = e.input_tokens is not None or e.output_tokens is not None if not carries_usage: # A usage-free span is always safe to emit (e.g. stripped superseded attempt). return key = (e.trace_id, e.step_id) prior_attempts = self.seen.get(key, []) if prior_attempts and not aggregator_is_attempt_aware: # Re-execution of a logical step, but downstream cannot distinguish attempts # from distinct steps. Emitting usage here guarantees drift. raise TokenAccountingInvariantError( f"refusing usage-bearing span for step_id={e.step_id!r} " f"attempt={e.attempt!r}: prior attempts {prior_attempts} already " f"emitted usage and aggregator is not attempt-aware; " f"either strip gen_ai.usage.* on superseded attempts or set " f"aggregator_is_attempt_aware=True and emit gen_ai.agent.attempt." ) if e.attempt is None or e.step_id is None: # First emission without identity is tolerated only if no retry can follow. # If a retry does follow, this span becomes the un-keyed duplicate. if prior_attempts: raise TokenAccountingInvariantError( f"usage-bearing retry for step_id={e.step_id!r} lacks " f"gen_ai.agent.attempt; cannot order attempts for argmax dedup." ) if e.attempt is not None and e.attempt in prior_attempts: raise TokenAccountingInvariantError( f"duplicate attempt {e.attempt!r} for step_id={e.step_id!r} in " f"trace {e.trace_id!r}; attempt counter must be monotonic." ) self.seen.setdefault(key, []).append(e.attempt if e.attempt is not None else 0) def aggregate_input_tokens(emissions: list[GenAISpanEmission]) -> int: """Attempt-aware aggregation: sum usage of the terminal attempt per (trace_id, step_id).""" by_step: dict = {} for e in emissions: if e.input_tokens is None: continue key = (e.trace_id, e.step_id) prev = by_step.get(key) rank = (e.status_code != "ERROR", e.attempt or 0) if prev is None or rank > (prev.status_code != "ERROR", prev.attempt or 0): by_step[key] = e total = sum(e.input_tokens or 0 for e in by_step.values()) return total ```