# In what scenarios must an instance reject a resumed OTel GenAI agent span when `gen_ai.usage.input_tokens` is replayed from a checkpoint after a tool-call retry? **Date of Record:** 2026 November 28 **Scope:** Applies to agent runtimes that emit OpenTelemetry spans conforming to the GenAI semantic conventions (`gen_ai.*`) and that checkpoint/resume mid-task, including retried tool calls. Does not apply to stateless single-shot inference spans with no checkpoint or retry boundary. ## Core Distinction The GenAI semantic conventions treat `gen_ai.usage.input_tokens` and `gen_ai.usage.output_tokens` as *per-span cumulative* counters describing the token cost of the operation the span represents. They are not per-attempt deltas, and they are not idempotent across replay. The distinction that matters: a *span* is a logical unit of work (one model invocation or one tool call as the agent understands it), while an *attempt* is one physical execution of that unit. When an agent resumes from a checkpoint and re-executes a tool call whose model invocation already succeeded, the naive instrumentation path re-emits the span with the checkpointed usage attributes attached. The result is a span whose `gen_ai.usage.input_tokens` no longer describes any real token consumption in this process lifetime — it describes a prior lifetime's consumption that has already been accounted for, or that will be double-counted downstream. The invariant: **a usage attribute on a span must describe tokens consumed by the execution that produced that span, and nothing else.** A resumed span carrying replayed usage violates this because the tokens were consumed by a different (earlier) execution whose span already exists in the trace, or whose cost was already billed. ## What Was Observed Trace from a research agent with a checkpoint at the tool-call boundary. The agent calls a retrieval tool, the tool returns, the model produces a follow-up invocation, and the process is killed mid-stream (OOM) after the checkpoint is written but before the follow-up span is exported. On resume, the runtime loads the checkpoint — which includes the prior span's `gen_ai.usage.input_tokens=18432`, `gen_ai.usage.output_tokens=611`, and `gen_ai.response.finish_reasons=["tool_calls"]` — and re-enters the tool-call loop. The tool call is retried (its prior result was not durably persisted, only the span attributes were). The retried tool call now emits a *new* span, but the runtime's span builder is seeded from the checkpointed attributes, so the new span carries the old usage numbers. The failure trace: 1. Attempt 1 span `S1` is created, model invocation runs, `input_tokens=18432` consumed, span is *not* exported (process dies before flush). 2. Checkpoint `C` is written containing `S1`'s attributes, including usage. 3. Resume: runtime reconstructs span `S1'` from `C`, re-runs the tool call, re-runs the model follow-up. 4. The model follow-up in attempt 2 consumes 19001 input tokens (slightly more, because the retried tool result differs in length). 5. `S1'` is exported with `input_tokens=18432` — the *checkpointed* value, not the *observed* value. The real 19001 is discarded because the span builder was seeded and the attribute was never overwritten. 6. Downstream cost aggregation sees 18432; the actual spend was 18432 (attempt 1, unbilled because span lost) + 19001 (attempt 2, mislabeled). The trace under-reports by 19001 and the two attempts are indistinguishable. A second, subtler variant: if the runtime *does* overwrite usage on resume but keeps the same `trace_id`/`span_id` as the checkpointed span, the collector receives two spans with identical IDs and different usage — a duplicate-ID collision that most backends resolve by last-write-wins, silently dropping attempt 1's cost. ## Condition of Validity The replay is *safe* (usage attributes may be carried forward) only when all of the following hold: - The checkpointed span was **already exported and acknowledged** by the collector before the crash, so the replayed span is a genuine *duplicate* that dedup-by-span-ID will collapse, not a *replacement* of a lost span. - The `trace_id` and `span_id` are **preserved** across resume, so the backend's dedup key is stable. - The token counts are **byte-identical** to the exported original — i.e., the resumed execution is a true replay, not a re-execution with different inputs. - No tool call between checkpoint and resume produced a **different result** than the original (different result ⇒ different prompt ⇒ different token count ⇒ the replayed usage is a lie). In practice the third and fourth conditions almost never both hold after a tool-call retry, because tool outputs are non-deterministic (retrieval indices shift, APIs return different pages, timestamps embed). So the default posture must be: **a resumed span that re-executes a tool call is a new attempt and must carry freshly measured usage, with the prior attempt's usage retained on a separate `attempt`-scoped span or as an explicit `gen_ai.usage.*.replayed` annotation — never silently merged.** ## Decision Boundary The runtime must decide, at resume time, between two mutually exclusive paths: - **Replay path** (carry checkpointed usage): admissible only if the span was durably exported *and* the resumed execution is a no-op replay (tool result served from cache, model invocation skipped). In this case emit the span with the original `span_id` and original usage; the backend dedups. - **Re-execution path** (measure fresh usage): required whenever any tool call is actually retried or any model invocation is actually re-run. In this case the span gets a **new `span_id`**, a `gen_ai.agent.attempt` (or equivalent custom) attribute incremented, and usage measured from this execution only. The checkpointed usage is *not* attached to this span; if cost attribution needs the lost attempt, it is recorded as a separate `gen_ai.usage.*` on a synthetic span with the original ID and a `replayed=true` flag. The boundary is crossed the moment the runtime cannot prove the resumed execution is a pure replay. Since "pure replay" requires cache-hit on every tool result and skip of every model call, and since checkpoint/resume exists precisely because those things were *not* durably persisted, the re-execution path is the correct default. Choosing the replay path without the four validity conditions is the bug. ## Operational Effect Downstream, the mislabeled span corrupts three things: (1) cost dashboards under-report because the lost attempt's tokens vanish and the retried attempt's real tokens are replaced by the stale count; (2) `gen_ai.usage.input_tokens` histograms develop a bimodal artifact where "replayed" spans cluster at the checkpointed value regardless of actual prompt size, poisoning any token-budget or context-saturation alerting that keys on this attribute; (3) trace-level token sums no longer reconcile with provider billing, because the provider bills per attempt and the trace bills per logical span. The reconciliation gap is the observable symptom — a trace that sums to less than the invoice, with a `finish_reasons` of `tool_calls` on a span whose successor never appears. The guardrail is a resume-time assertion: before emitting a span reconstructed from a checkpoint, verify that no tool call was retried and no model invocation re-ran; if either occurred, force the re-execution path and refuse to attach checkpointed usage. The code below encodes that guard as a hard failure rather than a silent fallback. ```python from dataclasses import dataclass from typing import Optional class ReplayedUsageViolation(RuntimeError): """Raised when a resumed agent span would carry checkpointed token usage after a tool-call retry or model re-execution, violating the OTel GenAI usage-attribute invariant (usage must describe this execution only).""" pass @dataclass class CheckpointedSpan: span_id: str trace_id: str input_tokens: int output_tokens: int finish_reasons: list exported: bool # was it acknowledged by the collector pre-crash? tool_result_cached: bool # is the retried tool result served from cache? model_invocation_skipped: bool @dataclass class ResumeContext: tool_call_retried: bool model_reran: bool observed_input_tokens: Optional[int] = None observed_output_tokens: Optional[int] = None def build_resumed_span(ckpt: CheckpointedSpan, ctx: ResumeContext) -> dict: # Determine whether this resume is a pure replay (safe to carry usage) pure_replay = ( ckpt.exported and ckpt.tool_result_cached and ckpt.model_invocation_skipped and not ctx.tool_call_retried and not ctx.model_reran ) if pure_replay: # Duplicate span: same IDs, original usage, backend dedups by span_id. return { "trace_id": ckpt.trace_id, "span_id": ckpt.span_id, "gen_ai.usage.input_tokens": ckpt.input_tokens, "gen_ai.usage.output_tokens": ckpt.output_tokens, "gen_ai.response.finish_reasons": ckpt.finish_reasons, "gen_ai.agent.replayed": True, } # Re-execution path: usage MUST be freshly measured. if ctx.observed_input_tokens is None or ctx.observed_output_tokens is None: raise ReplayedUsageViolation( f"Resume of span {ckpt.span_id} retried a tool call or re-ran the " f"model but supplied no freshly observed token counts. Refusing to " f"attach checkpointed usage ({ckpt.input_tokens} in / " f"{ckpt.output_tokens} out) to a re-executed attempt." ) if ctx.observed_input_tokens == ckpt.input_tokens and ctx.model_reran: raise ReplayedUsageViolation( f"Span {ckpt.span_id} re-ran the model yet reports identical input " f"tokens ({ckpt.input_tokens}); this indicates the checkpointed " f"usage was copied instead of measured." ) return { "trace_id": ckpt.trace_id, "span_id": f"{ckpt.span_id}-retry", # NEW id: distinct attempt "gen_ai.usage.input_tokens": ctx.observed_input_tokens, "gen_ai.usage.output_tokens": ctx.observed_output_tokens, "gen_ai.response.finish_reasons": ckpt.finish_reasons, "gen_ai.agent.replayed": False, "gen_ai.agent.prior_span_id": ckpt.span_id, "gen_ai.agent.prior_input_tokens": ckpt.input_tokens, "gen_ai.agent.prior_output_tokens": ckpt.output_tokens, } ```