# Where must an instance reconcile nested span token accounting before cache-hit telemetry can be trusted across an agentic loop **Date of Record:** 2026 November 27 **Scope:** Applies to OpenTelemetry-style GenAI span trees emitted by agent runtimes where a single logical LLM call is decomposed into nested child spans (retrieval, tool, sub-agent, cache-lookup) and where `genai.usage.*` attributes are aggregated upward for billing and loop-topology reconstruction. Does not apply to flat single-span instrumentation, nor to runtimes that emit provider-authoritative aggregate usage on the root span only. ## Core Distinction There are two incompatible readings of `genai.usage.input_tokens` on a parent span: 1. **Inclusive aggregation** — the parent's token count is the sum of its own prompt plus all descendant spans' token counts (a subtree roll-up). 2. **Exclusive attribution** — the parent's token count is only the tokens consumed by the call the parent directly represents; children carry their own disjoint counts. Both are legal under the GenAI semantic conventions, because the spec does not mandate a roll-up direction. The failure is not that one is wrong. The failure is that **cache-hit telemetry is a ratio, and a ratio between a numerator and denominator drawn from different aggregation conventions is silently meaningless**. When a cache-aware child span reports `genai.usage.cache_read.input_tokens` under exclusive attribution but its parent reports `input_tokens` under inclusive roll-up, the computed cache-hit rate `cache_read / input_tokens` is deflated by exactly the subtree fan-out factor — and there is no schema field that records which convention was used. The invariant that must hold is: *cache-hit ratio is only reconstructible if numerator and denominator share an aggregation scope marker.* ## What Was Observed A two-level agent loop: an orchestrator span `agent.turn` wraps a `genai.chat` span (the model call) and a `tool.retrieve` span (a vector store hit that the model then conditions on). The model call had a provider-reported cache read of 8,192 tokens against an input of 9,000 tokens (91% hit rate — plausible for a long stable system prompt). The orchestrator emitted `genai.usage.input_tokens = 14,500`, computed by summing its own prompt (5,500) plus the chat child (9,000) with the runtime's inclusive roll-up helper. Reconstruction downstream computed `8192 / 14500 = 56.5%`. The dashboard reported a 56.5% cache-hit rate for the turn. The actual per-call rate was 91%. The 34.5-point gap was pure denominator contamination from a sibling retrieval span's tokens that were never part of any prompt the provider could have cached. The trace looked internally consistent: every span had a value, every value was non-negative, and the parent's value equaled the sum of its parts. No validator fired, because the sum *was* correct under the roll-up convention. The corruption was entirely in the cross-convention ratio. A second, subtler observation: on retried turns, the runtime emitted a *new* `genai.chat` child under the same parent and **added** its tokens to the parent's inclusive total without marking the parent as having multiple attempts. Loop-topology reconstruction that keyed on "one chat child per turn" saw two children and inferred a parallel fan-out (speculative decoding or best-of-N), which never happened. The topology was misread as a breadth-first expansion when it was actually a linear retry. ## Condition of Validity The cache-hit ratio is reconstructible **if and only if** the following three conditions co-hold on the same span: - **Aggregation scope is explicit.** The span carries a marker such as `genai.usage.aggregation = "inclusive" | "exclusive"`, and numerator and denominator are read from spans with the *same* marker. Absent the marker, treat the ratio as undefined, not as zero. - **Attempt multiplicity is encoded.** Retries are represented as `attempt.index` on sibling `genai.chat` spans, or as distinct span IDs with a shared `attempt.group` — never as an unmarked second child that a topology reconstructor must disambiguate from legitimate fan-out. - **Cache scope is bounded to the provider call.** `cache_read.input_tokens` is only comparable to the `input_tokens` of the *same* `genai.chat` span, because the provider's cache key is the prompt prefix of that call. It is not comparable to any ancestor's rolled-up total. If any condition is unmet, the correct downstream behavior is to **refuse to emit a cache-hit rate**, not to emit an approximate one. A missing metric degrades a dashboard; a wrong one corrupts capacity planning and cache-investment decisions that are hard to reverse. ## Decision Boundary The boundary is between **aggregation for cost** and **aggregation for ratio**. Cost is linear and additive: rolling up inclusive token counts is correct for billing because every token was paid for exactly once somewhere in the subtree. Ratios are not additive: `sum(cache_read) / sum(input)` across a subtree is only the subtree's effective cache rate if every span in the subtree participates in the same cache domain. A retrieval tool span contributes input tokens to the roll-up but contributes *zero* cache_read tokens, so including it in the denominator drags the ratio toward zero by construction. Concretely, the decision rule for a reconstructor walking the span tree: - **For cost totals:** roll up inclusively across all `genai.usage.*` counters. Safe. - **For cache-hit ratio:** descend to the leaf `genai.chat` spans, compute the ratio *per span*, then aggregate ratios weighted by each span's own `input_tokens` — never by the parent's rolled-up total. - **For loop topology:** count distinct `attempt.group` values, not distinct child spans, when inferring fan-out width. The failure mode this prevents is a reconstructor that is *correct for one purpose and silently wrong for another* while sharing the same traversal code. That sharing is the trap: the roll-up helper that is right for billing is exactly the helper that poisons the ratio. ## Operational Effect The immediate effect is a systematic under-reporting of cache effectiveness on any turn that mixes cached model calls with uncached tool or retrieval calls — which is most agentic turns. Teams observing a "56% cache hit rate" conclude their prompt caching is underperforming and invest in cache-key restructuring, when the true rate was 91% and the instrumentation was the problem. The remediation cost is paid in engineering time chasing a phantom. The second-order effect is topology corruption. Retry spans misread as fan-out inflate perceived parallelism, which downstream cost models interpret as concurrent token burn, which triggers rate-limit headroom alarms that never should have fired. Because the trace is internally sum-consistent, no schema validator catches it; the error surfaces only when someone reconciles the trace against provider billing exports and finds the token totals match but the derived ratios do not. The durable fix is to make the aggregation convention a *first-class attribute* rather than an implicit runtime default, and to make the reconstructor refuse ratio computation when the convention marker is absent. Cost roll-up and ratio computation must be separate code paths that cannot accidentally share a numerator/denominator source. The guardrail is a hard refusal — an exception at reconstruction time — rather than a best-effort approximation, because a wrong cache-hit rate is worse than a missing one. ```python from __future__ import annotations from dataclasses import dataclass from enum import Enum class AggregationScope(Enum): INCLUSIVE = "inclusive" EXCLUSIVE = "exclusive" UNSPECIFIED = "unspecified" class CacheRatioUnderivable(RuntimeError): """Raised when a cache-hit ratio cannot be reconstructed because the numerator and denominator do not share an explicit aggregation scope, or because attempt multiplicity is unencoded and would corrupt the denominator.""" pass @dataclass(frozen=True) class GenAISpan: span_id: str name: str input_tokens: int cache_read_input_tokens: int aggregation: AggregationScope attempt_group: str | None = None def cache_hit_ratio(span: GenAISpan) -> float: """Compute the cache-hit ratio for a single genai.chat span. The ratio is only meaningful on a leaf model-call span whose cache_read and input_tokens share one aggregation scope and whose prompt is the provider's cache key. It must never be computed against a parent roll-up total. """ if span.name != "genai.chat": raise CacheRatioUnderivable( f"span {span.span_id} ({span.name}) is not a model-call span; " f"cache_read/input ratio is undefined for aggregated parents" ) if span.aggregation is AggregationScope.UNSPECIFIED: raise CacheRatioUnderivable( f"span {span.span_id} has no aggregation scope marker; " f"numerator/denominator convention unknown, refusing ratio" ) if span.attempt_group is None: raise CacheRatioUnderivable( f"span {span.span_id} has no attempt_group; a retry sibling " f"would be indistinguishable from fan-out, corrupting topology" ) if span.input_tokens <= 0: raise CacheRatioUnderivable( f"span {span.span_id} has non-positive input_tokens; ratio undefined" ) if span.cache_read_input_tokens > span.input_tokens: raise CacheRatioUnderivable( f"span {span.span_id} cache_read exceeds input; " f"scopes are mismatched across numerator/denominator" ) return span.cache_read_input_tokens / span.input_tokens def weighted_turn_cache_rate(chat_spans: list[GenAISpan]) -> float: """Aggregate per-span ratios weighted by each span's own input_tokens, never by a parent roll-up. Groups by attempt_group so retries are counted as attempts, not as parallel branches.""" if not chat_spans: raise CacheRatioUnderivable("no genai.chat spans to aggregate") groups: dict[str, list[GenAISpan]] = {} for s in chat_spans: if s.attempt_group is None: raise CacheRatioUnderivable( f"span {s.span_id} missing attempt_group; cannot separate " f"retry from fan-out during topology reconstruction" ) groups.setdefault(s.attempt_group, []).append(s) total_in = 0 total_cached = 0 for group_spans in groups.values(): # Use the final successful attempt per group for the ratio; earlier # attempts are cost, not cache signal. final = group_spans[-1] ratio = cache_hit_ratio(final) total_in += final.input_tokens total_cached += int(round(ratio * final.input_tokens)) if total_in == 0: raise CacheRatioUnderivable("aggregate input_tokens is zero") return total_cached / total_in def reconstruct(spans: list[GenAISpan]) -> dict: chats = [s for s in spans if s.name == "genai.chat"] if any(s.aggregation is AggregationScope.INCLUSIVE for s in chats): raise CacheRatioUnderivable( "inclusive-scoped chat span present; subtree token totals are " "cost-correct but ratio-unsafe, refusing reconstruction" ) return { "turn_cache_rate": weighted_turn_cache_rate(chats), "fanout_width": len({s.attempt_group for s in chats}), "attempts": len(chats), } ```