# When must an instance reject a GenAI agent span whose token accounting double-counts cached prompt tokens across a tool-call fan-out **Date of Record:** 2026 November 26 **Scope:** Applies to any agent runtime that emits OpenTelemetry spans conforming to the GenAI semantic conventions (`gen_ai.*`) for a parent `invoke_agent` span with child `execute_tool` and nested `chat` spans, where prompt caching is enabled. Does not apply to single-shot inference with no tool fan-out, nor to runtimes that emit only leaf `chat` spans with no agent-level aggregation. ## Core Distinction The GenAI semantic conventions define `gen_ai.usage.input_tokens` and `gen_ai.usage.output_tokens` as *per-span* usage for the model call the span represents. They do **not** define a parent-agent aggregate. The failure mode is not "wrong numbers"—it is that a parent `invoke_agent` span, when it aggregates child `chat` spans, will double-count prompt tokens whenever the provider reports `cached_tokens` as a *subset* of `input_tokens` on some calls and as a *disjoint* field on others. The distinction that matters: **cached tokens are a subset relation on some providers and a partition relation on others**, and the semantic conventions do not disambiguate which. An agent that sums `input_tokens + cached_tokens` across children to build a parent cost attribute is silently over-billing by the cache-hit fraction of every turn after the first. ## What Was Observed A three-tool agent loop (search → fetch → summarize) on a provider whose `usage` object reports: ``` {"input_tokens": 1200, "cached_tokens": 800, "output_tokens": 90} ``` Here `cached_tokens ⊆ input_tokens`: 800 of the 1200 prompt tokens were cache hits. The correct billable prompt count is 1200 (or 1200 minus a cache discount), *not* 2000. The instrumentation layer, written against a second provider that reports `cached_tokens` as a *separate additive* field (prompt = `input_tokens + cached_tokens`), summed both fields on every child span. Across a 6-turn fan-out with a stable 800-token cached prefix, the parent `invoke_agent` span emitted `gen_ai.usage.input_tokens = 12,000` when the true prompt-token volume was 7,200. The 4,800-token delta equals `800 × 6` turns of double-counted cache. The trace looked internally consistent—child spans each had plausible values, the parent was the arithmetic sum—so no span-level validator flagged it. The error only surfaced when the cost dashboard diverged from the provider invoice by exactly the cache-hit ratio. ## Condition of Validity The invariant holds only when all of the following are true: 1. The parent agent span aggregates child `chat` spans by summation rather than by delegation of a provider-reported total. 2. At least one child span's provider reports `cached_tokens` as a subset of `input_tokens` (OpenAI-style), while the instrumentation assumes the additive/partition semantics (some Anthropic and Gemini responses expose cache reads as a distinct counter). 3. The cached prefix is stable across turns—i.e., the agent reuses a long system prompt or tool schema block, which is exactly the condition that makes caching worthwhile and therefore the condition under which the bug is largest. If the runtime stores a provider-returned `total_tokens` on the parent and never re-derives it, the invariant is trivially satisfied and the failure cannot occur. The boundary is *derived aggregation*. ## Decision Boundary An agent instance must **reject** a parent agent span (fail closed) when it cannot prove the subset-vs-partition semantics of every child's `cached_tokens` field. The decision rule: - If the provider's usage schema is registered as `SUBSET` (cached ⊆ input), aggregate as `sum(input_tokens)` and report `cached_tokens` as an informational attribute, never added. - If registered as `PARTITION` (cached disjoint from input), aggregate as `sum(input_tokens) + sum(cached_tokens)`. - If **unregistered**—a new model, a proxy that rewrites usage, a fallback provider—the parent span must not emit an aggregated token count. It must emit the per-child spans and a `gen_ai.agent.usage.aggregation = "unverified"` attribute, and the cost pipeline must treat the parent as non-authoritative. The non-obvious part: the safe default is *not* "assume subset" (which under-counts on partition providers) and *not* "assume partition" (which over-counts on subset providers). The safe default is **refuse to aggregate**. A missing number is recoverable from child spans; a wrong number silently poisons every downstream cost, budget, and rate-limit decision that the agent makes about itself. ## Operational Effect An agent that self-budgets against its own aggregated token count (a common pattern: "if I've used 80% of my context budget, summarize and reset") will, under the double-count bug, believe it is closer to its budget than it is. It triggers premature summarization, which compacts the cached prefix, which destroys the cache hit rate, which raises real cost—a feedback loop where the accounting error *causes* the cost it mismeasures. The correct guardrail is to make the parent aggregate a *verified* quantity: either delegated from the provider or computed only against a registered schema, with `unverified` as an explicit, alertable state rather than a silent fallback to summation. ```python class UnverifiedCacheSemanticsError(RuntimeError): """Raised when a parent agent span cannot safely aggregate child token usage.""" pass # Registry mapping provider/model -> how cached_tokens relates to input_tokens. CACHE_SEMANTICS = { ("openai", "gpt-4o"): "SUBSET", # cached_tokens is a subset of input_tokens ("anthropic", "claude-3-5-sonnet"): "PARTITION", # cache_read distinct from input } def aggregate_agent_usage(children: list[dict]) -> dict: """ children: each dict has keys provider, model, input_tokens, cached_tokens, output_tokens. Returns verified aggregate, or raises if any child's semantics are unknown. """ total_input = 0 total_cached = 0 total_output = 0 for i, child in enumerate(children): key = (child["provider"], child["model"]) semantics = CACHE_SEMANTICS.get(key) if semantics is None: # Fail closed: do not guess subset vs partition. raise UnverifiedCacheSemanticsError( f"child[{i}] provider={key[0]!r} model={key[1]!r} has no " f"registered cached_tokens semantics; refusing to aggregate " f"parent gen_ai.usage.input_tokens" ) if semantics == "SUBSET": # cached_tokens already inside input_tokens; do not add. total_input += child["input_tokens"] total_cached += child["cached_tokens"] elif semantics == "PARTITION": # cached_tokens disjoint from input_tokens; add both. total_input += child["input_tokens"] + child["cached_tokens"] total_cached += child["cached_tokens"] else: raise UnverifiedCacheSemanticsError( f"unknown semantics {semantics!r} for {key}" ) total_output += child["output_tokens"] return { "gen_ai.usage.input_tokens": total_input, "gen_ai.usage.output_tokens": total_output, "gen_ai.usage.cached_tokens": total_cached, # informational only "gen_ai.agent.usage.aggregation": "verified", } ```