# Which invariants prevent OpenTelemetry GenAI span token accounting from silently misattributing cached prompt tokens across tool-call retries **Date of Record:** 2026 November 22 **Scope:** Applies to agents emitting OpenTelemetry GenAI spans (`gen_ai.*` attributes) where a single logical turn fans out into multiple tool calls and retries, and where prompt caching is enabled at the provider. Does not cover pure completion-only workloads without tool fan-out, nor streaming-only traces where span finalization is deferred past process exit. ## Core Distinction The GenAI semantic conventions treat `gen_ai.usage.input_tokens` as a monotonic cost signal per span, and `gen_ai.usage.cached_input_tokens` (or provider-equivalent, e.g. `gen_ai.usage.prompt_tokens_details.cached_tokens`) as a *subset* of that input. The invariant the spec leans on is set containment: cached ⊆ input ⊆ total. This is true for a single provider request. It is **not** true for an agent span that wraps a reasoning loop with retries, because the loop re-sends the same prompt prefix on each tool-call round-trip, and each round-trip re-reports its own cached-token count. Summing span-level usage across child spans double-counts the cached prefix, while the parent agent span—often instrumented as an aggregation of children—inherits an inflated `cached_input_tokens` that can exceed `input_tokens`. The distinction that matters operationally: *cached tokens are a per-request accounting fact, not a per-turn additive quantity*, and the semantic conventions do not encode a `retry_index` or `cache_reuse_scope` attribute to let a collector de-duplicate them. ## What Was Observed A tool-using agent (planner → 4 sequential tool calls → synthesis) emitted one `invoke_agent` parent span and five `chat` child spans. Prompt caching was active on the provider. Observed final attributes on the parent: - `gen_ai.usage.input_tokens = 18,240` - `gen_ai.usage.cached_input_tokens = 21,760` - `gen_ai.usage.output_tokens = 1,410` The cached count exceeded total input by ~19%. Root cause trace: each of the five child `chat` spans re-sent an identical ~4,000-token system+history prefix. The provider reported ~3,900 cached tokens per call (5 × 3,900 ≈ 19,500 cached reports), but the parent span's aggregator summed child `cached_input_tokens` while computing `input_tokens` from the *final* request's prompt size plus unique deltas—an asymmetric aggregation. The collector's cost model, which computes `uncached = input - cached`, produced a **negative uncached token count** and a negative billed-cost delta, which downstream anomaly detection interpreted as a credit/refund event and suppressed alerting for the following 40 minutes. The failure is silent because no span-level attribute is individually invalid. Each child span satisfies cached ⊆ input. Only the *aggregation across the retry fan-out* violates the invariant, and OpenTelemetry has no built-in aggregation guard for that. ## Condition of Validity The set-containment invariant `cached_input_tokens ≤ input_tokens` holds **only** under the following conjunction: 1. The span represents exactly one provider request (one `chat` call), not a loop or fan-out. 2. `gen_ai.usage.input_tokens` is populated from that single response's `usage` object, not summed from children. 3. No retry re-sends an identical cacheable prefix within the same span's lifetime without a distinct child span boundary. When an agent span aggregates children (the common `invoke_agent` pattern), conditions 1–2 are violated by construction. The valid aggregation rule is: **sum `output_tokens` and *unique* `input_tokens`; take `max` (not sum) of `cached_input_tokens` across children that share an identical prefix hash; and never derive `uncached` as `input − cached` on an aggregated span.** The spec does not mandate this, so instrumentation libraries diverge. ## Decision Boundary The boundary between "safe to aggregate" and "must de-duplicate" is the **prefix identity across children**. Concretely: - If two child `chat` spans share the same `gen_ai.request.model` **and** the same prompt-prefix hash (which the conventions do *not* standardize—you must add a custom `gen_ai.prompt.prefix_hash` attribute), their cached-token reports refer to the same physical cache entry and must be collapsed to `max`, not summed. - If prefix hashes differ (e.g., the tool result was injected into history between calls), the cached counts are disjoint and *may* be summed—but only the delta beyond the shared prefix, which requires per-request accounting the spec leaves to the provider. Because prefix hashing is non-standard, the safe default for any agent span with `child_count > 1` is: **do not emit an aggregated `cached_input_tokens` at all**; emit per-child values and let the backend de-duplicate using a custom attribute. Emitting the sum is the failure. ## Operational Effect The immediate effect is corrupted cost attribution and broken anomaly detection (negative uncached counts, phantom credits). The second-order effect is worse: cache-hit-rate dashboards computed as `cached / input` on agent spans read >100%, and teams "fix" this by clamping to 1.0, which masks genuine cache regressions in single-request paths. The durable guardrail is a collector-side validation: reject or quarantine any span where `cached_input_tokens > input_tokens`, tag it `otel.genai.accounting_violation=true`, and route to a per-request (child-span) reconciliation path rather than the aggregated one. This converts a silent accounting corruption into an explicit, observable boundary event. ```python class GenAIUsageInvariantError(RuntimeError): """Raised when an aggregated GenAI span violates cached ⊆ input containment.""" pass def validate_agent_span_usage(span: dict) -> None: attrs = span.get("attributes", {}) input_tokens = attrs.get("gen_ai.usage.input_tokens") cached_tokens = attrs.get("gen_ai.usage.cached_input_tokens") child_count = attrs.get("gen_ai.agent.child_span_count", 1) if input_tokens is None or cached_tokens is None: return # nothing to reconcile # Invariant: cached tokens are a subset of input tokens. if cached_tokens > input_tokens: raise GenAIUsageInvariantError( f"span={span.get('name')} cached_input_tokens={cached_tokens} " f"exceeds input_tokens={input_tokens} (child_count={child_count}); " f"likely summed across retry fan-out sharing a cached prefix. " f"Collapse to max() over children with identical prefix_hash, " f"or emit per-child usage without aggregation." ) # Guard against aggregated spans that should never carry a summed cache count. if child_count > 1 and attrs.get("gen_ai.prompt.prefix_hash") is None: raise GenAIUsageInvariantError( f"span={span.get('name')} aggregates {child_count} children but " f"lacks gen_ai.prompt.prefix_hash; cached token de-duplication is " f"undefined. Emit per-child usage or add prefix_hash." ) def reconcile(span: dict) -> dict: validate_agent_span_usage(span) attrs = span["attributes"] uncached = attrs["gen_ai.usage.input_tokens"] - attrs["gen_ai.usage.cached_input_tokens"] if uncached < 0: # defensive: should be unreachable post-validation raise GenAIUsageInvariantError("negative uncached token count after validation") return {"uncached_input_tokens": uncached} ```