# What happens when an instance double-counts cached prompt tokens across a retried tool-call span **Date of Record:** 2026 November 19 **Scope:** Applies to observability pipelines that derive per-agent cost and latency SLOs from span-level token telemetry emitted by LLM SDKs and gateway proxies, where prompt caching and retry/fallback logic coexist. Does not apply to flat per-request billing without cache semantics, nor to pipelines that receive authoritative token counts from a single upstream metering authority. ## Core Distinction There are two ways a token count can be "wrong" in an observability pipeline, and they are not the same failure. The first is *estimation error*: the SDK counts tokens with a local tokenizer that disagrees with the provider's billing tokenizer by a few percent. This is benign, monotone, and averages out across aggregation. The second is *duplication error*: the same physical token is attributed to more than one span, agent, or retry attempt. This is not benign. It is a structural invariant violation, because it breaks the conservation law the entire cost-attribution layer rests on: `sum(attributed_tokens) == provider_billed_tokens` for any closed accounting window. Duplication errors are invisible at the per-span level (each span looks internally consistent) and only surface as a residual when you reconcile the window total against the provider invoice — often 24–48 hours later, long after the SLO dashboards have already paged the wrong team. The distinction matters because the mitigations are orthogonal. You fix estimation error by calibrating the tokenizer. You fix duplication error only by enforcing a conservation invariant at write time. ## What Was Observed A multi-agent orchestrator (planner → 3 parallel workers → synthesizer) routed all LLM calls through a gateway proxy that emitted OpenTelemetry spans. Prompt caching was enabled: the planner's ~14k-token system prompt and tool schema were marked cacheable, and workers reused the same cached prefix. The failure trace: 1. A worker's tool call to an external search API returned a 503. The SDK's retry wrapper re-issued the *entire* LLM request — including the 14k-token cached prefix — as a new attempt, emitting a second child span under the same logical tool-call span. 2. Both attempt spans reported `prompt_tokens = 14,850` (the full prefix) because the SDK's usage object reports *request* token count, not *cache-hit* token count, unless the gateway explicitly splits `cache_read_input_tokens` from `input_tokens`. 3. The gateway proxy, configured to be "safe," emitted its own synthetic span for the same HTTP exchange, tagged with the same `trace_id` but a different `span_id`, and also reported 14,850 prompt tokens. 4. The attribution layer, which summed `prompt_tokens` grouped by `agent_id`, counted the cached prefix **three times**: once for the original attempt, once for the retry, once for the gateway's synthetic span. The provider billed it **once** at the cache-read rate (10% of input price) and the retry at full rate — so the true bill was `14,850 × 0.1 + 14,850 × 1.0`, but the pipeline attributed `14,850 × 3`. The per-agent cost dashboard for the worker agent read ~2.4× its true cost. The latency SLO tracer, meanwhile, computed p99 from *span duration* summed across the duplicated spans, inflating the worker's apparent tail latency by the retry backoff (2.1s) plus the duplicate span's own duration. The SLO fired. The on-call engineer spent four hours investigating a "slow worker" that was, in fact, a correctly-retried fast worker whose cost was mis-attributed. The tell was a reconciliation residual: `sum(attributed) − provider_billed = +2 × 14,850 × (1 − 0.1)` for that window, a number that was suspiciously close to exactly twice a cached prefix. ## Condition of Validity The duplication invariant holds — and therefore the failure is *possible* — only when all three of the following are simultaneously true: - **Cache-read tokens are reported as full prompt tokens by at least one emitter in the trace path.** If every emitter splits `cache_read_input_tokens` from `input_tokens`, the retry's cached prefix is billed at the cache rate and the duplicate is at least *rate-correct*, though still a conservation violation. - **Retries re-issue the full request rather than resuming from a checkpoint.** Stateless retry at the HTTP layer re-sends the prefix; a retry that resumes mid-generation does not. - **More than one component in the path emits token telemetry for the same physical exchange** (SDK span + gateway span, or SDK span + orchestrator span), and the attribution layer sums rather than deduplicates by a stable request identity. Remove any one condition and the failure collapses. The most common real-world configuration removes none of them, because each individual choice is locally reasonable: caching saves money, retries add resilience, and dual emission is "defense in depth." ## Decision Boundary The boundary is not "should we retry" or "should we cache." It is: **at what layer is the token count made canonical, and is that layer upstream or downstream of the retry and dual-emission logic?** If the canonical count is established *downstream* of retries and deduplication — i.e., you trust the provider's per-request usage object keyed by a provider-assigned request ID — duplication is structurally impossible, because the provider bills each request ID once. If the canonical count is established *upstream* — i.e., you sum whatever spans arrive — duplication is structurally *likely*, because spans are emitted by independent components that do not know about each other's retries. The decision boundary is therefore: **attribute cost from a request-ID-keyed ledger, never from a span-sum.** Spans are for latency and causality; the ledger is for money. Conflating them is the root cause. A span-sum can be *reconciled against* the ledger, but it must never *be* the ledger. A secondary boundary governs the SLO side: latency SLOs must be computed from the *logical operation's* wall-clock span (the parent tool-call span, from first attempt to final success), not from the sum of attempt-span durations. Summing attempts double-counts backoff and conflates retry cost with service degradation. ## Operational Effect The observable effect is a **conservation residual that grows with cache-prefix size and retry rate**. Because the duplicated quantity is the cached prefix — typically the largest single token block in an agent's context — the residual is not a rounding error; it scales with the very thing caching was meant to optimize. Teams that enable caching to reduce cost see their attributed cost *rise* relative to billed cost, which is a counterintuitive and frequently misdiagnosed signal. The guardrail is a write-time invariant enforced at the attribution layer: - Every token-bearing span must carry a `request_id` (provider-assigned) and a `cache_read_input_tokens` / `input_tokens` split. - The attribution layer must reject any span lacking a `request_id` rather than fall back to summing. - A reconciliation job must assert, per closed window, `abs(sum(attributed_cost) − provider_billed_cost) / provider_billed_cost < ε`, and raise on violation rather than silently adjusting. - Latency SLOs must be computed from parent-span wall-clock, with attempt spans retained only for retry-rate diagnostics. Without these, the pipeline does not merely mis-report; it *inverts the sign of the optimization signal*, making cache-enablement look like a regression and retry-resilience look like latency debt. The following guard enforces the invariant at span-ingest time. ```python from dataclasses import dataclass class TokenConservationError(RuntimeError): """Raised when span-level token attribution would violate the conservation invariant sum(attributed) == provider_billed.""" pass @dataclass(frozen=True) class TokenSpan: request_id: str | None agent_id: str input_tokens: int cache_read_input_tokens: int is_attempt_span: bool def attribute_window(spans: list[TokenSpan], provider_billed_tokens: int, epsilon: float = 1e-3) -> dict[str, int]: """Attribute tokens per agent, deduplicating by request_id and asserting conservation against the provider ledger.""" seen: set[str] = set() attributed: dict[str, int] = {} for span in spans: if span.request_id is None: # Never fall back to summing a span with no request identity; # that is exactly the duplication vector. raise TokenConservationError( f"span for agent {span.agent_id!r} lacks request_id; " "refusing to attribute by span-sum" ) if span.request_id in seen: # Duplicate emission (SDK + gateway, or retry re-emission). # Billable tokens for this request were already counted. continue seen.add(span.request_id) billable = span.input_tokens + span.cache_read_input_tokens attributed[span.agent_id] = attributed.get(span.agent_id, 0) + billable total = sum(attributed.values()) residual = abs(total - provider_billed_tokens) / max(provider_billed_tokens, 1) if residual > epsilon: raise TokenConservationError( f"conservation residual {residual:.4%} exceeds {epsilon:.4%}: " f"attributed={total} billed={provider_billed_tokens} " f"(likely cached-prefix duplication across retries)" ) return attributed ```