# How should an instance reconcile token-accounting spans when a GenAI tool-call span is emitted twice under retry, once by the client and once by the server, without double-counting completion tokens? **Date of Record:** 2026 November 30 **Scope:** Applies to agent runtimes that emit OpenTelemetry `gen_ai.*` spans on both the orchestrator (client) side and the tool/LLM server side, where retries can cause the same logical tool call to produce two spans carrying `gen_ai.usage.output_tokens`. Does not apply to single-emitter topologies or to spans that carry only `gen_ai.usage.input_tokens` (which are idempotent under retry because the prompt is re-sent, not regenerated). ## Core Distinction The GenAI semantic conventions treat `gen_ai.usage.output_tokens` as a *measurement of generation*, not a *measurement of work performed*. When a tool call is retried, the client observes two spans: one from the failed first attempt (which may or may not have generated tokens before the transport error) and one from the successful retry. The server observes the same two spans from its own perspective. Naive aggregation sums four `output_tokens` values for a single logical call. The correct invariant is that **completion tokens must be counted once per `(trace_id, gen_ai.tool.call.id)` pair, and the counted value must be the maximum observed, not the sum** — because a retried generation either fully re-generates (the second span supersedes the first) or resumes (the first span's tokens are a prefix of the second's). In neither case is the sum correct. The subtlety that breaks most aggregators: `gen_ai.tool.call.id` is *not* required by the spec to be stable across retries. The client mints a new call id per attempt unless the SDK explicitly propagates the original. So the deduplication key must be constructed from the trace context plus a caller-supplied idempotency token, not from the span's own `call.id`. ## What Was Observed An agent orchestrator using MCP over a flaky transport executed a `search_corpus` tool call. The tool server generated a 900-token completion and began streaming it back; the client's HTTP read timed out at 3s after receiving 400 tokens. The orchestrator's retry policy (exponential backoff, 2 attempts) re-issued the call. The server, unaware of the first attempt's partial delivery, regenerated from scratch: 880 tokens this time (non-deterministic decoding). Both attempts emitted spans. Observed span set (abbreviated): - Client span A: `gen_ai.tool.call.id=call_7f3a`, `gen_ai.usage.output_tokens=400`, `status=ERROR`, `error.type=timeout` - Server span A: `gen_ai.tool.call.id=call_7f3a`, `gen_ai.usage.output_tokens=900`, `status=UNSET` (server believed it succeeded) - Client span B: `gen_ai.tool.call.id=call_b91c`, `gen_ai.usage.output_tokens=880`, `status=OK` - Server span B: `gen_ai.tool.call.id=call_b91c`, `gen_ai.usage.output_tokens=880`, `status=UNSET` A dashboard summing `output_tokens` across all `gen_ai.tool` spans reported 3060 tokens for a single logical call whose true cost was 900 (the server's first-attempt generation is the only one whose tokens were actually billed, and the retry's 880 tokens were also billed — so the *correct* billable figure is 1780, not 3060 and not 880). The dashboard was wrong in two directions simultaneously: it double-counted the client/server duplication of each attempt, and it failed to recognize that both the 900 and the 880 were genuinely billed generations. **The invariant is not "dedupe to one"; it is "dedupe client-vs-server duplication per attempt, then sum across distinct attempts."** This is the boundary condition: the retry is not idempotent at the token layer even when it is idempotent at the result layer. The result (a search hit list) is the same; the tokens are not. ## Condition of Validity The deduplication rule "max per `(trace, call.id)`, sum across distinct `call.id` within a trace" holds only under these conditions: 1. **Client and server spans for the same attempt share `trace_id` and `span_id` parentage.** If the client emits its span with a fresh trace on retry (common when the retry logic lives above the tracing layer), the two attempts land in different traces and the invariant cannot be enforced at aggregation time. The orchestrator must propagate `traceparent` through the retry, and must propagate the *original* `gen_ai.tool.call.id` as a custom attribute (e.g., `app.retry.original_call_id`) so downstream reconciliation can group attempts. 2. **The server's span reports the tokens it actually generated, not the tokens it delivered.** A server that reports `output_tokens` equal to bytes flushed to the socket will under-report on a mid-stream disconnect. The spec's `gen_ai.usage.output_tokens` is defined as tokens generated; a streaming server must emit the final count in span status, not the delivered count. If the server cannot know its generated count (e.g., it aborted generation on client disconnect), it must set `gen_ai.usage.output_tokens` to the partial count and set `status=ERROR` with `error.type=client_disconnect`, so aggregators can treat it as a lower bound rather than a fact. 3. **No attempt is silently dropped.** If the client's retry policy gives up after N attempts, the final span must carry `app.retry.attempts=N` and the aggregator must attribute the sum of all N attempts' server-side generations to the logical call. A dropped attempt's tokens are still billed. ## Decision Boundary The reconciler must choose between two aggregation strategies based on whether `app.retry.original_call_id` is present: - **If present:** group all spans sharing `(trace_id, app.retry.original_call_id)`, take the max `output_tokens` among *client* spans and the max among *server* spans per distinct `call.id`, then sum the server-side maxes across distinct `call.id`. This yields billable tokens. The client-side maxes are used only for latency and delivery accounting. - **If absent:** the spans cannot be safely reconciled. The reconciler must emit a `gen_ai.reconciliation.incomplete` counter and refuse to attribute tokens to the logical call, rather than guessing. Guessing here is how dashboards silently drift by 40% over a quarter. The boundary is sharp: a single missing `app.retry.original_call_id` attribute on one retry path poisons the entire trace's token accounting, and because the error is silent (the sum is plausible), it is not caught by anomaly detection until a billing reconciliation fails. ## Operational Effect The practical consequence is that **token accounting for agent tool calls is not a property of the span stream; it is a property of the retry topology that the span stream must be made to encode.** Teams that instrument only the GenAI semantic conventions — which do not define a retry-grouping attribute — will systematically over-count client/server duplication and under-count multi-attempt billing, and the two errors do not cancel. The fix is a single required custom attribute (`app.retry.original_call_id`) propagated by the orchestrator's retry wrapper, plus a server-side discipline of reporting generated-not-delivered token counts with `client_disconnect` status. The reconciler below encodes the invariant and refuses to proceed when the grouping key is missing. ```python from dataclasses import dataclass from typing import Iterable class TokenReconciliationError(RuntimeError): """Raised when a trace's GenAI spans cannot be safely reconciled.""" @dataclass(frozen=True) class GenAISpan: trace_id: str span_id: str emitter: str # "client" | "server" call_id: str # gen_ai.tool.call.id original_call_id: str | None # app.retry.original_call_id output_tokens: int status: str # "OK" | "ERROR" | "UNSET" error_type: str | None def reconcile_output_tokens(spans: Iterable[GenAISpan]) -> int: spans = list(spans) if not spans: return 0 traces = {s.trace_id for s in spans} if len(traces) != 1: raise TokenReconciliationError( f"spans span multiple traces {traces}; retry propagation broken" ) # Group by logical call. Every span must carry the grouping key. groups: dict[str, list[GenAISpan]] = {} for s in spans: if s.original_call_id is None: raise TokenReconciliationError( f"span {s.span_id} (emitter={s.emitter}, call_id={s.call_id}) " f"missing app.retry.original_call_id; cannot attribute tokens" ) groups.setdefault(s.original_call_id, []).append(s) total = 0 for logical_id, group in groups.items(): # Per distinct attempt (call_id), take the max across client/server # emitters. Sum across distinct attempts. by_attempt: dict[str, list[GenAISpan]] = {} for s in group: by_attempt.setdefault(s.call_id, []).append(s) for attempt_id, attempt_spans in by_attempt.items(): server_spans = [s for s in attempt_spans if s.emitter == "server"] if not server_spans: # Client-only attempt: the server never reported generated # tokens. Treat client count as a lower bound and flag. client_max = max(s.output_tokens for s in attempt_spans) total += client_max continue server_max = max(s.output_tokens for s in server_spans) # If the server reported a client_disconnect error, its count is a # lower bound on generation; accept it but do not add client count. if any( s.error_type == "client_disconnect" for s in server_spans ): total += server_max continue total += server_max return total def attribute_call(spans: list[GenAISpan]) -> dict[str, int]: """Return billable token attribution for a logical tool call.""" if not spans: raise TokenReconciliationError("no spans supplied for attribution") try: return {"billable_output_tokens": reconcile_output_tokens(spans)} except TokenReconciliationError as exc: raise TokenReconciliationError( f"refusing to attribute tokens for trace " f"{spans[0].trace_id}: {exc}" ) from exc ```