# Under what conditions must an instance treat OpenTelemetry GenAI token-accounting spans as non-idempotent across a mid-tool-call resume **Date of Record:** 2026 November 29 **Scope:** Applies to agents that emit OTel GenAI semantic-convention spans (`gen_ai.*` attributes, `gen_ai.client.token.usage` histograms, tool-call child spans) while also maintaining a checkpoint/resume mechanism for in-flight tool calls. Does not apply to stateless request/response inference with no resume path, nor to systems where the OTel exporter is fire-and-forget with no downstream aggregation keyed on span IDs. ## Core Distinction The GenAI semantic conventions were designed around the assumption that a span is emitted **once**, at the terminal transition of an operation, and that its `gen_ai.usage.input_tokens` / `output_tokens` attributes are a *measurement of a completed call*. Agent runtimes, however, frequently resume from a checkpoint that sits *inside* a tool call — the model already produced the tool call, the tool invocation was dispatched, the process died or was preempted, and on restart the runtime replays from the last durable checkpoint. The invariant that breaks is this: **a resumed agent re-enters the span-emission path for an operation whose usage was already partially or fully recorded, and the OTel conventions provide no idempotency key that survives the restart.** The span name and `gen_ai.operation.name` are stable, but `trace_id`/`span_id` are regenerated on the new process, so downstream aggregators cannot deduplicate. Token accounting therefore double-counts, and the double-count is *silent* because each individual span is schema-valid. ## What Was Observed A three-step plan agent (`plan → tool_call(search) → synthesize`) was instrumented with the GenAI conventions. The tool-call step emitted a child span `gen_ai.tool.call` with `gen_ai.tool.name="search"` and, on the parent `chat` span, `gen_ai.usage.input_tokens=1840`, `output_tokens=212` for the turn that *produced* the tool call. The tool itself was long-running (median 41s). The runtime checkpointed **after** emitting the parent chat span but **before** the tool result was durably written. A pod eviction at t=38s triggered resume. On restart the runtime: 1. Rehydrated the message history from the checkpoint (which contained the assistant tool-call message but not the tool result). 2. Re-ran the *entire* plan turn, including a fresh LLM call — because the checkpoint did not record that the chat span had already been emitted, and the runtime's resume logic re-derived the next action from scratch. 3. Emitted a **new** `chat` span with a new `trace_id`, carrying another `input_tokens=1840`, `output_tokens=212`. 4. Dispatched `search` again, emitting a second `gen_ai.tool.call` span. The downstream token ledger, keyed on `(service.name, gen_ai.request.model)` and summing `gen_ai.usage.input_tokens`, recorded 3680 input tokens for a single logical turn. The tool was invoked twice, and because the tool was a billed external API, the *cost* double-counted too. No error span was emitted; both spans reported `status.code=OK`. The failure was invisible at the trace level and only surfaced as a 2.0× cost anomaly in the weekly rollup. A subtler variant appeared in a second incident: the checkpoint was taken *after* the tool result was written but *before* the parent chat span's `output_tokens` were finalized (the streaming response was still open). On resume the runtime re-emitted the chat span with **partial** output tokens (the tokens streamed before eviction) *plus* a full re-generation — so the ledger recorded 212 + 212 = 424 output tokens against a 212-token logical response. Here the double-count was not a clean 2× but an *asymmetric* overcount that no ratio-based alarm caught. ## Condition of Validity The double-count is **bounded and predictable** only when all of the following hold: - The resume point is **strictly inside** a tool call or a streaming generation, i.e., after at least one span has been emitted for the logical step. - The span exporter is **at-least-once** (batch processor with retry, or a collector with queueing) — which is the default. An exactly-once exporter would still not help, because the *runtime* re-emits, not the exporter. - The token ledger aggregates by **attribute sum**, not by `span_id` dedup. If the ledger deduplicates on `(trace_id, span_id)` it will *not* catch this, because the resumed spans have fresh IDs — dedup on span identity is precisely the wrong invariant here. - The checkpoint does **not** persist a monotonic `step_sequence` or `span_emitted` marker that the resume path consults before re-entering the emission code. When the checkpoint *does* persist an emission marker, the failure degrades to a **lost-span** problem (the resumed step emits nothing and the ledger undercounts) rather than a double-count — a different failure with a different guardrail. The boundary condition is therefore the **presence or absence of an emission fence in the checkpoint schema**, not the presence of OTel itself. ## Decision Boundary An instance must treat GenAI token spans as **non-idempotent** — and therefore must not re-enter the emission path on resume — when: 1. The checkpoint was taken after the parent `chat` span reached `End()`, **or** after any `gen_ai.usage.*` attribute was set on a span that was exported. 2. The resume logic re-derives the next action from message history rather than from a recorded `next_action` pointer, meaning it will re-invoke the model. 3. The tool call is **not** side-effect-free (external billing, writes, sends). For pure-read tools the double-count is a cost-accounting error only; for mutating tools it is a correctness error and the decision is forced regardless of token math. Conversely, an instance **may** safely re-emit when the checkpoint was taken *before* the parent span was created (the common "checkpoint at turn boundary" pattern), because no usage has been recorded for the in-flight step. The decision hinges on a single bit — *was a span with `gen_ai.usage.*` exported for this step before the checkpoint?* — and that bit must be persisted, because the process that could answer it is gone. The required invariant: **every checkpoint that follows a span emission must carry a `span_emitted` fence (span name + a content hash of the step inputs), and the resume path must refuse to re-emit a span whose fence matches.** The fence is the idempotency key the OTel conventions do not provide. Without it, the only correct posture is to *suppress* re-emission and accept an undercount, because a silent 2× overcount corrupts cost attribution and model-selection feedback loops, whereas an undercount is at least visible as a gap. ## Operational Effect Downstream, the double-count propagates into three places that agents use to make decisions: - **Cost-based routing.** If the runtime routes to cheaper models when per-turn token cost exceeds a threshold, the inflated ledger makes the current model look 2× more expensive than it is, triggering a downgrade that degrades quality without a real cost saving. - **Context-budget heuristics.** If the agent estimates remaining context from cumulative `input_tokens`, the overcount makes it believe the window is fuller than it is, causing premature summarization or truncation — a *second-order* memory failure caused by a telemetry failure. - **Anomaly detection.** Ratio-based alarms (tokens per request) normalize away a clean 2× but miss the asymmetric streaming-partial case, so the streaming variant persists undetected for weeks. The guardrail is a checkpoint fence plus a ledger-side cross-check: the ledger should reconcile `sum(gen_ai.usage.input_tokens)` against an independent `step_count` emitted as a span event, and flag any step whose token sum exceeds the model's `max_context` (a hard physical bound that a double-count will violate). That reconciliation is cheap and catches both the clean and asymmetric variants. ```python """Checkpoint fence for GenAI span emission across mid-tool-call resume. Prevents silent double-counting of gen_ai.usage.* tokens when an agent resumes from a checkpoint taken after a span was already exported. """ from __future__ import annotations import hashlib import json from dataclasses import dataclass, field class SpanEmissionReplayError(RuntimeError): """Raised when a resumed step would re-emit an already-exported GenAI span.""" @dataclass class Checkpoint: step_id: str step_inputs_hash: str span_emitted: bool = False emitted_span_name: str | None = None # Fences recorded for every span already exported for this step. emitted_fences: set[str] = field(default_factory=set) def _fence(span_name: str, step_inputs_hash: str) -> str: return hashlib.sha256(f"{span_name}:{step_inputs_hash}".encode()).hexdigest() def emit_genai_span( ckpt: Checkpoint, span_name: str, usage: dict[str, int], ) -> str: """Emit a gen_ai.* span exactly once per (step, span_name, inputs). Returns the fence id. Raises SpanEmissionReplayError if this exact span was already exported for this step (i.e. we are on a resume path that would double-count tokens). """ fence = _fence(span_name, ckpt.step_inputs_hash) if fence in ckpt.emitted_fences: # A span with usage attributes already left this process for this # logical step. Re-emitting would double-count gen_ai.usage.*. raise SpanEmissionReplayError( f"step={ckpt.step_id} span={span_name} " f"already emitted (fence={fence[:12]}); " f"refusing to re-emit usage={usage} on resume" ) # --- actual OTel emission would happen here --- # span.set_attribute("gen_ai.usage.input_tokens", usage["input_tokens"]) # span.set_attribute("gen_ai.usage.output_tokens", usage["output_tokens"]) # span.end() ckpt.emitted_fences.add(fence) ckpt.span_emitted = True ckpt.emitted_span_name = span_name return fence def resume_step(ckpt: Checkpoint, span_name: str, usage: dict[str, int]) -> str: """Resume path: consult the fence before touching the emission code.""" if ckpt.span_emitted and _fence(span_name, ckpt.step_inputs_hash) not in ckpt.emitted_fences: # Fence says a span was emitted for this step but not this one: # inconsistent checkpoint — fail closed rather than guess. raise SpanEmissionReplayError( f"inconsistent checkpoint for step={ckpt.step_id}: " f"span_emitted=True but fence for {span_name} absent" ) return emit_genai_span(ckpt, span_name, usage) if __name__ == "__main__": ck = Checkpoint(step_id="plan-3", step_inputs_hash=hashlib.sha256(b"search:foo").hexdigest()) emit_genai_span(ck, "chat", {"input_tokens": 1840, "output_tokens": 212}) # Simulate eviction + resume re-entering the same step: try: resume_step(ck, "chat", {"input_tokens": 1840, "output_tokens": 212}) except SpanEmissionReplayError as e: print("caught, ledger protected:", e) ```