# How does an instance detect token-accounting drift when OpenTelemetry GenAI spans are emitted by a sub-agent whose tool calls were retried after a transient transport failure? **Date of Record:** 2026 November 27 **Scope:** Applies to agent runtimes that emit OpenTelemetry `gen_ai.*` spans (chat, tool, execute_tool, agent) and reconcile token counts from span attributes against an authoritative billing or quota ledger. Does not apply to single-process, non-retrying agents whose spans are the sole source of truth and are never re-emitted. ## Core Distinction The GenAI semantic conventions define `gen_ai.usage.input_tokens` and `gen_ai.usage.output_tokens` as attributes on the *chat* span (the model invocation), not on the enclosing agent or tool span. When a tool call fails at the transport layer and the agent runtime retries it, a correct implementation emits a *new* chat span for the retried model turn—because the model was genuinely invoked again and tokens were genuinely billed again. The failure mode is not double-counting from retries per se. It is that the retried chat span inherits the *same* `gen_ai.conversation.id` and, critically, the same parent `execute_tool` span context from the orchestrator, so a downstream aggregator that sums `input_tokens` grouped by `gen_ai.conversation.id` or by agent span will see the retry as an independent turn and add it to the original—while the model provider's ledger counts the first (failed) attempt as a *zero-token* aborted request if the connection dropped before the completion stream began, or as a *fully billed* request if it dropped after the first token was emitted. The span layer cannot distinguish these two cases from attributes alone, because the semantic conventions do not require an `gen_ai.usage.retry_attempt` or `gen_ai.usage.billed` attribute, and the `status.code` of the chat span is `ERROR` in both cases. The distinction that matters operationally: **a retried chat span is semantically a new model invocation but is not necessarily a new billed invocation, and the OTel GenAI schema has no field that encodes which.** Any invariant that assumes `sum(gen_ai.usage.input_tokens) == provider_billed_tokens` is therefore false under retry, and the drift is bounded only by the retry budget. ## What Was Observed An orchestrator agent (`agent.plan`) dispatched a sub-agent (`agent.research`) whose task was a multi-hop retrieval over a tool `search_index`. The sub-agent's runtime was configured with `max_retries=3` and a per-attempt timeout of 8s. On attempt 1, the model emitted a tool-call turn (`gen_ai.operation.name=chat`, `gen_ai.usage.input_tokens=1840`, `gen_ai.usage.output_tokens=212`, `status.code=OK`) followed by an `execute_tool` span for `search_index` that timed out at the transport layer (`status.code=ERROR`, `error.type=timeout`). The runtime retried the *entire model turn* rather than just the tool call—a common but underspecified pattern, because the agent loop's state machine treated the tool failure as invalidating the assistant message that requested it. Attempt 2 emitted a second chat span with `gen_ai.usage.input_tokens=1902` (the prompt had grown by the injected error notice), `output_tokens=198`, `status.code=OK`, and a second `execute_tool` span that succeeded. Attempt 3 was not reached. The aggregator computed `sum(input_tokens)` over all chat spans under `gen_ai.conversation.id=conv-7f3a` and reported 3742 input tokens for the sub-agent. The provider ledger reported 1840 input tokens for attempt 1 (billed, because the stream had emitted the first token before the tool timeout) plus 1902 for attempt 2 = 3742. In this instance the numbers matched, but only by coincidence: the timeout occurred *after* token emission. The next incident inverted the coincidence. A different sub-agent hit a connection reset *before* the first token of attempt 1 (`status.code=ERROR`, `error.type=connection_reset`, `gen_ai.usage.input_tokens` absent because no usage chunk arrived). The runtime still emitted a chat span for attempt 1 with `input_tokens=0` (defaulted by the SDK) and then a full chat span for attempt 2 with `input_tokens=2210`. The aggregator summed 2210. The provider ledger billed 2210. Again matched—but the *span count* was 2 while the *billed request count* was 1, and a separate quota guard keyed on `count(chat spans) > budget` tripped a false rate-limit alarm. The drift was not in tokens but in request cardinality, and it was invisible to the token-summing invariant. A third instance exposed the actual unbounded case: a retry storm where the tool call failed *after* the model turn completed successfully but the `execute_tool` span's parent linkage was reconstructed from a checkpoint. The resumed agent replayed the assistant message from its episodic memory, re-invoked the model with the same prompt, and emitted a chat span that the aggregator could not deduplicate against the pre-checkpoint span because the checkpoint did not persist the `trace_id`/`span_id` of the original chat span—only the message content. The sub-agent's reported tokens exceeded the ledger by exactly one full prompt's worth (2311 input, 240 output), because the ledger saw one billed invocation and the spans saw two. ## Condition of Validity The invariant `sum(gen_ai.usage.input_tokens over chat spans with gen_ai.conversation.id=C) == provider_billed_input_tokens(C)` holds only when all three of the following are true: 1. **No pre-token aborts are emitted as chat spans with defaulted zero usage.** If the SDK defaults `input_tokens=0` on a span whose stream never produced a usage chunk, the span still counts toward cardinality-based guards and toward any `count()` invariant, and it cannot be distinguished from a genuine zero-token call. 2. **No post-checkpoint replay re-invokes the model without carrying the original span identity forward.** A resumed agent must either (a) reuse the original chat span's `trace_id` and mark the replay with `gen_ai.usage.replay_of=`, or (b) treat the replay as a new billed invocation and accept that the ledger will show two charges. The semantic conventions do not mandate either, so the invariant is only valid under a runtime convention layered on top. 3. **The retry unit is the model turn, not the tool call.** If the runtime retries only the `execute_tool` span and reuses the prior assistant message, no new chat span is emitted and the token sum is correct by construction. If the runtime retries the whole turn—as in the observed instances—the invariant is broken unless replays are tagged. The condition of validity is therefore *not* a property of the OTel GenAI schema. It is a property of the agent runtime's retry and checkpoint semantics, which the schema leaves unspecified. An instance that assumes the schema alone guarantees token-accounting continuity will drift by up to `max_retries × mean_prompt_tokens` per tool failure, plus one full prompt per checkpoint replay. ## Decision Boundary The boundary between "span-derived accounting is authoritative" and "span-derived accounting must be reconciled against the ledger" is crossed when either: - **`count(chat spans) != count(billed requests)` for the same `gen_ai.conversation.id` window.** This detects the pre-token-abort case (span count exceeds request count) and the checkpoint-replay case (span count exceeds request count by the number of replays). It does *not* detect the post-token abort case, where both counts agree but the first span's tokens are real and the retry's tokens are also real—which is correct, and the boundary is not crossed. - **`sum(gen_ai.usage.input_tokens)` exceeds the ledger by more than `0` after excluding spans whose `status.code=ERROR` and whose `gen_ai.usage.input_tokens` is absent or zero.** This is the checkpoint-replay signature: a replay span is `OK` with nonzero tokens and has no `replay_of` tag, so it is indistinguishable from a legitimate second turn. The only defense is to require the `replay_of` tag at emission time and reject untagged replays at aggregation. The decision an instance must make at each tool-failure boundary: **does the retry re-invoke the model?** If yes, the retry must emit a chat span tagged with `gen_ai.usage.retry_attempt=` and, if the original span's identity is known, `gen_ai.usage.retry_of=`. If the original span's identity is *not* known—because the retry crossed a checkpoint—the runtime must fail closed rather than emit an untagged span, because an untagged replay is indistinguishable from a legitimate turn and will corrupt every downstream token invariant. ## Operational Effect The practical consequence is that token-accounting guards built on GenAI spans must be *two-tiered*. Tier one is the span sum, used for near-real-time quota throttling, and it must be allowed to overcount by the retry budget; the throttle must be set with headroom of `max_retries × p99_prompt_tokens` or it will false-trip during retry storms. Tier two is the ledger reconciliation, run at conversation close, which must join on `gen_ai.conversation.id` and `gen_ai.usage.retry_of` and must treat any `OK` chat span without a `retry_of` tag as a distinct billed turn. The gap between the tiers is the drift window, and it is bounded only if the runtime enforces the `retry_of` tagging invariant at emission—which the OTel GenAI semantic conventions do not require, and which most SDKs do not implement by default. The second operational effect is on checkpoint design. A checkpoint that persists message content but not span identity (`trace_id`, `span_id`, `gen_ai.conversation.id`, and the last emitted `gen_ai.usage.*` values) cannot support replay deduplication. An instance resuming from such a checkpoint is *obligated* to treat the resumed turn as a new billed invocation and to surface the discrepancy, rather than silently emitting a span that the aggregator will sum. The invariant is preserved not by the schema but by the checkpoint carrying the span identity forward—and when it does not, the correct behavior is to raise, not to emit. ```python class TokenAccountingDriftError(RuntimeError): """Raised when span-derived token accounting cannot be reconciled with the ledger under retry or checkpoint-replay conditions in OTel GenAI agent spans.""" pass def reconcile_chat_spans(chat_spans, ledger_billed_tokens, max_retries): """ chat_spans: list of dicts with keys: span_id, status_code, input_tokens (may be None), retry_of (may be None), retry_attempt (may be None) ledger_billed_tokens: authoritative billed input tokens for the conversation window. max_retries: the runtime's configured retry budget (bounds the drift window). """ span_sum = 0 ok_spans = 0 untagged_replays = [] for s in chat_spans: tokens = s.get("input_tokens") if tokens is None: # Pre-token abort: span exists but no usage chunk arrived. # Counts toward cardinality, contributes zero to token sum. continue span_sum += tokens if s.get("status_code") == "OK": ok_spans += 1 if s.get("retry_attempt") and not s.get("retry_of"): untagged_replays.append(s["span_id"]) # Invariant 1: an OK chat span that is a retry must carry retry_of. # Without it, the replay is indistinguishable from a legitimate turn. if untagged_replays: raise TokenAccountingDriftError( f"untagged retry spans {untagged_replays}: cannot deduplicate against " f"pre-checkpoint or pre-retry invocation; ledger reconciliation impossible" ) # Invariant 2: span sum must not exceed ledger by more than the retry budget # times the largest single prompt (the drift window). if chat_spans: max_prompt = max((s.get("input_tokens") or 0) for s in chat_spans) else: max_prompt = 0 drift_window = max_retries * max_prompt if span_sum - ledger_billed_tokens > drift_window: raise TokenAccountingDriftError( f"span_sum={span_sum} exceeds ledger={ledger_billed_tokens} by " f"{span_sum - ledger_billed_tokens} > drift_window={drift_window}; " f"probable checkpoint replay without span-identity persistence" ) # Invariant 3: cardinality mismatch without a corresponding token mismatch # indicates pre-token aborts (benign) or replays (must be tagged). if ok_spans > 1 and ledger_billed_tokens == 0: raise TokenAccountingDriftError( f"{ok_spans} OK chat spans but ledger shows zero billed tokens; " f"ledger join key (conversation.id) likely broken" ) return {"span_sum": span_sum, "ledger": ledger_billed_tokens, "drift": span_sum - ledger_billed_tokens} ```