# How should an instance reconcile OpenTelemetry GenAI span attributes when a retried tool call double-counts `gen_ai.usage.input_tokens` across a resumed agent trace **Date of Record:** 2026 November 26 **Scope:** Applies to agents that emit OTel GenAI spans (`gen_ai.*` semantic conventions) and that resume a mid-task checkpoint after a transport-level retry of a tool call. Does not apply to single-shot, non-resumed invocations where the trace has no replay path. ## Core Distinction The failure is not "tokens are counted twice." It is a **span-identity vs. attempt-identity conflation**. OTel GenAI conventions bind token usage to a *span* (`gen_ai.usage.input_tokens`, `gen_ai.usage.output_tokens`), and a span is meant to model one logical model invocation or one logical tool call. But an agent that retries a tool call after a timeout, or that resumes from a checkpoint, will frequently re-enter the same logical step and emit a *second* span carrying the same `gen_ai.operation.name` and often the same `gen_ai.tool.call.id`. Downstream aggregators that sum `input_tokens` across spans (the ordinary, correct thing to do) now over-attribute cost and, worse, mis-attribute the *reasoning* — the retried call may have consumed a different prompt (larger context after the first attempt appended an error message) and thus a genuinely different token count. The invariant that breaks: **`sum(gen_ai.usage.input_tokens) over a trace == tokens actually billed to the provider for that logical task`**. It holds only if each logical invocation maps to exactly one span. Retry and resume both violate the mapping. ## What Was Observed A three-step agent task: `plan` → `search` (tool) → `summarize`. The `search` tool call hit a 30s client timeout. The agent's transport layer retried, but the retry was issued from a *resumed checkpoint* that had already appended the timeout error string into the conversation and re-serialized the full message history as the new prompt. Span trace as emitted: - Span A (`gen_ai.operation.name=chat`, attempt 1): `input_tokens=1180`, `output_tokens=42`, status `ERROR` (timeout on the tool sub-span). - Span B (`gen_ai.operation.name=execute_tool`, `gen_ai.tool.name=search`, `gen_ai.tool.call.id=call_7f3a`): status `ERROR`, no usage. - Span C (`gen_ai.operation.name=chat`, attempt 2, same logical step): `input_tokens=1310`, `output_tokens=38`, status `OK`. - Span D (`gen_ai.operation.name=execute_tool`, `gen_ai.tool.name=search`, `gen_ai.tool.call.id=call_7f3a`): status `OK`. Two things went wrong simultaneously: 1. **Token double-count.** A naive dashboard summed `input_tokens` = 1180 + 1310 = 2490 for a task whose *billed* input was 1180 (attempt 1, which the provider did charge for) + 1310 (attempt 2) = 2490 — actually correct here, *but only by accident*, because the provider billed both attempts. The real defect surfaced in a second run where the provider's SDK had *not* billed the failed attempt (connection refused before request body sent): the trace still reported 1180 + 1310 while the invoice showed 1310. The span-level sum and the invoice diverged by the phantom attempt. 2. **Tool-call identity collision.** Spans B and D share `gen_ai.tool.call.id=call_7f3a`. A verifier replaying the trace to check "did the tool call succeed?" sees one success and one failure under the same ID and cannot decide which is authoritative without a tiebreaker. The GenAI conventions do not define a disambiguator for repeated `tool.call.id` within a trace. ## Condition of Validity Token-sum-equals-invoice holds if and only if all three hold: - Every emitted `gen_ai.usage.*` span corresponds to a request the provider actually accepted and billed (no phantom spans from pre-send failures). - Retried attempts are distinguishable from the original by an attribute the aggregator is instructed to honor, not merely by span ordering. - `gen_ai.tool.call.id` is unique per *attempt*, or a sibling attribute (e.g., a retry counter) disambiguates attempts sharing a logical call ID. None of these are guaranteed by the base GenAI conventions. The conventions specify *what* to record on a span; they do not specify *how many* spans a retried logical step should produce, nor how to reconcile them. ## Decision Boundary The agent runtime must choose, at emit time, between two reconciliation strategies — and the choice is not free: - **Collapse:** emit one span per logical step, and on retry mutate the existing span (add an event `retry.attempt=2`, overwrite usage with the *billed* attempt's numbers). Preserves the sum invariant trivially. Loses per-attempt latency and error visibility. - **Preserve:** emit one span per attempt, tag each with `gen_ai.request.retry_attempt` (0-based) and a `billing.status ∈ {billed, phantom}`, and require the aggregator to sum only `billing.status=billed` spans. The boundary: **collapse is correct only when the runtime can prove the failed attempt was not billed.** If the runtime cannot distinguish a pre-send failure from a post-send timeout (common — the transport reports a timeout either way), collapse will *under*-count, and preserve will *over*-count. There is no strategy that is correct without a billing oracle or a transport-level signal that separates "request never left" from "request left, response lost." ## Operational Effect The practical consequence is that a trace is not a billing artifact and must not be treated as one without an explicit reconciliation step. Agents resuming from checkpoints must carry a `resume.epoch` attribute so that spans from different epochs of the same logical task are groupable and the aggregator can select the terminal epoch rather than summing across epochs. Tool-call IDs must be namespaced by epoch (`call_7f3a@epoch2`) or accompanied by an attempt index, because the verifier that replays a trace to confirm tool success will otherwise accept the failed attempt as evidence of failure and re-trigger the call — a replay discrepancy that compounds: the re-triggered call is billed again, and now the trace has three spans for one logical call. The guardrail is a **trace-level reconciliation pass** that runs before any consumer (dashboard, verifier, cost allocator) reads `gen_ai.usage.*`. It groups spans by `(trace_id, gen_ai.tool.call.id, logical_step)`, selects the terminal epoch, and rejects traces where the selected epoch is ambiguous. The pass must fail loudly rather than guess, because a silent guess here propagates into both cost accounting and the verifier's success determination. ```python from dataclasses import dataclass, field from typing import Optional class TraceReconciliationError(RuntimeError): """Raised when a GenAI trace cannot be reduced to one billed attempt per logical step.""" @dataclass class GenAISpan: span_id: str operation: str # "chat" | "execute_tool" tool_call_id: Optional[str] retry_attempt: int resume_epoch: int billing_status: str # "billed" | "phantom" | "unknown" input_tokens: int = 0 output_tokens: int = 0 def reconcile_trace(spans: list[GenAISpan]) -> dict: """ Reduce a trace to one authoritative attempt per (tool_call_id, resume_epoch) and return billed token totals. Raises if any logical step is ambiguous. """ groups: dict[tuple, list[GenAISpan]] = {} for s in spans: key = (s.tool_call_id, s.resume_epoch, s.operation) groups.setdefault(key, []).append(s) billed_input = 0 billed_output = 0 for key, attempts in groups.items(): terminal_epoch = max(a.resume_epoch for a in attempts) terminal = [a for a in attempts if a.resume_epoch == terminal_epoch] if any(a.billing_status == "unknown" for a in terminal): raise TraceReconciliationError( f"cannot reconcile {key}: terminal epoch has unknown billing status; " f"collapse would under-count, preserve would over-count" ) # Within the terminal epoch, exactly one attempt should be billed. billed = [a for a in terminal if a.billing_status == "billed"] if len(billed) != 1: raise TraceReconciliationError( f"logical step {key} has {len(billed)} billed attempts in terminal " f"epoch {terminal_epoch}; expected exactly 1" ) billed_input += billed[0].input_tokens billed_output += billed[0].output_tokens return {"input_tokens": billed_input, "output_tokens": billed_output} def verify_tool_success(spans: list[GenAISpan], tool_call_id: str) -> bool: """ A verifier replaying the trace must not accept a failed attempt as authoritative when a later epoch succeeded. """ relevant = [s for s in spans if s.tool_call_id == tool_call_id] if not relevant: raise TraceReconciliationError(f"no spans for tool_call_id={tool_call_id}") terminal_epoch = max(s.resume_epoch for s in relevant) terminal = [s for s in relevant if s.resume_epoch == terminal_epoch] if len({s.billing_status for s in terminal}) > 1: raise TraceReconciliationError( f"tool_call_id={tool_call_id} has mixed billing statuses in terminal " f"epoch {terminal_epoch}; verifier cannot determine success" ) return all(s.billing_status == "billed" for s in terminal) ```