# Where must an instance reconcile the parent span's token ledger before emitting a child span, or per-node cost attribution silently double-counts cached prefixes **Date of Record:** 2026 December 2 **Scope:** Applies to agent graphs where spans are emitted per node and token counts are attributed from provider usage payloads (including `cached_tokens` / `prompt_tokens_details`) under a shared prefix cache. Does not apply to single-call, non-nested inference with no cache reuse and no parent/child span hierarchy. ## Core Distinction The distinction that matters is between **token accounting as a billing reconciliation** and **token accounting as a causal attribution**. Provider usage payloads are defined for the former: each response reports the tokens it was billed for, net of cache discounts it received. Observability systems naively treat these per-response numbers as additive across a span tree, summing child usage into parent totals. That is correct for billing (the sum of invoices equals the bill) but wrong for attribution, because a cached prefix is *physically read once* by the KV cache but *logically referenced* by every downstream node that inherits it. The cache discount is applied at the leaf that first populates the cache; every subsequent sibling or descendant that reuses the prefix reports a *reduced* `prompt_tokens` with a *larger* `cached_tokens`, and the sum of "fresh" tokens across the tree understates the true compute while the sum of "total" tokens overstates the true cost. Neither number alone is the causal cost of a node. ## What Was Observed A planner-executor agent graph with fan-out: one `plan` node emits a shared system+task prefix, then N `execute` nodes run concurrently, each appending its own tool schema and instruction. All N children share the identical prefix and hit the provider's prefix cache after the first child warms it. Trace observed on a 6-way fan-out: - `plan` span: `prompt_tokens=4200`, `cached_tokens=0`, `completion_tokens=310`. - First `execute` child (cache miss): `prompt_tokens=5100`, `cached_tokens=0`. - Remaining five `execute` children (cache hit): `prompt_tokens=5100`, `cached_tokens=4200` each. The attribution layer summed `prompt_tokens` across all seven spans and reported `plan` cost as 4200 plus a per-child cost of 5100 each — total 34,800 prompt tokens. The provider invoice showed 4200 + 5100 + 5×(5100−4200) = 13,800 billable prompt tokens. The dashboard overstated cost by 2.5×. Separately, a "fresh compute" view that summed `prompt_tokens − cached_tokens` reported the plan node as the dominant cost center, when in reality the plan node's *output* (the 310 completion tokens) is what every child conditioned on — the causal driver of the fan-out's cost is the plan, not the shared prefix. The non-obvious failure: the child span is emitted and closed *before* the parent span's ledger is finalized, and the parent cannot know whether its own prefix will be cached downstream until children complete. Attribution must therefore be **deferred and reconciled at the parent**, not committed at the child. ## Condition of Validity The double-count is only possible under all of the following: 1. **Shared prefix cache is active** and the provider reports `cached_tokens` (or equivalent) as a *subset* of `prompt_tokens`, not as a separate field excluded from the total. 2. **Spans form a tree** where a child's prompt logically contains the parent's prompt as a prefix (the common "append-only context" pattern). If children construct independent prompts, no reuse occurs and naive summation is correct. 3. **Child spans are finalized before the parent's usage is known.** In streaming or concurrent fan-out, the child's `end` event fires while the parent's aggregate is still open. 4. **The attribution layer treats usage fields as additive** rather than as a partition (fresh vs. cached) requiring a set-union over prefix identity. If any of these fails — no cache, disjoint prompts, or synchronous parent-first finalization — the naive sum is coincidentally correct and the bug is latent. ## Decision Boundary The invariant to enforce: **a token may be attributed as "fresh compute" to exactly one span in the tree — the span that first materialized the prefix — and every other span that reuses it must attribute it as "cache-referenced," a non-additive annotation, never as fresh cost.** The decision boundary for the observability layer is: - At child close, do **not** emit a final `cost` attribute. Emit `prompt_tokens_total`, `prompt_tokens_cached`, and a `prefix_hash` identifying the shared prefix. - At parent close, perform a **set-union reconciliation over `prefix_hash`**: the first span (by start time) to present a given `prefix_hash` owns the fresh tokens; all later spans with the same hash contribute zero fresh tokens and increment a `cache_reuse_count`. - The parent's reported cost is `sum(fresh_tokens) × input_rate + sum(completion_tokens) × output_rate`, with cache-referenced tokens reported as a separate, non-summed dimension. The guardrail must fire when a child span closes with `cached_tokens > 0` but no ancestor span in the same trace has registered the corresponding `prefix_hash` as materialized — that is a reconciliation gap (cache hit without a known origin), and attributing it to the child silently loses the true origin. ## Operational Effect Without reconciliation, three downstream systems corrupt: (a) per-node cost dashboards overstate fan-out cost and mis-rank the plan node, causing teams to optimize the wrong node; (b) budget governors that sum child costs trip token-budget limits 2–3× early on high-fan-out graphs, aborting runs that would have fit; (c) latency attribution confuses cache-hit latency (fast) with fresh-compute latency (slow) when correlating cost to wall-clock, producing false "cheap but slow" classifications. With deferred reconciliation, the parent span becomes the single source of truth for the subtree's causal cost, and the child spans carry only annotations sufficient to reconstruct the partition. The cost of this correctness is that **no span's cost is final until its subtree closes** — which forces the observability pipeline to buffer subtree ledgers and emit cost on parent close, not child close. ```python import hashlib from dataclasses import dataclass, field class AttributionReconciliationError(RuntimeError): """Raised when a child span claims cached-prefix tokens whose origin span is not registered in the trace, or when a fresh-token owner is ambiguous.""" pass @dataclass class SpanUsage: span_id: str parent_id: str | None start_ns: int prompt_tokens_total: int prompt_tokens_cached: int completion_tokens: int prefix_hash: str @dataclass class SubtreeLedger: fresh_by_prefix: dict[str, str] = field(default_factory=dict) # hash -> owning span_id fresh_tokens: int = 0 cache_referenced_tokens: int = 0 completion_tokens: int = 0 def reconcile_subtree(spans: list[SpanUsage]) -> SubtreeLedger: """Reconcile a closed subtree. First span (by start_ns) presenting a prefix_hash owns its fresh tokens; later spans with the same hash contribute only cache-referenced tokens.""" ledger = SubtreeLedger() for s in sorted(spans, key=lambda x: x.start_ns): fresh = s.prompt_tokens_total - s.prompt_tokens_cached if s.prompt_tokens_cached > 0: owner = ledger.fresh_by_prefix.get(s.prefix_hash) if owner is None: # Cache hit with no known materialization in this subtree: # the origin span is missing or out of trace scope. raise AttributionReconciliationError( f"span {s.span_id} reports {s.prompt_tokens_cached} cached " f"tokens for prefix {s.prefix_hash[:8]} but no ancestor span " f"materialized that prefix; refusing to attribute." ) if owner == s.span_id: raise AttributionReconciliationError( f"span {s.span_id} is both origin and cache-referencer for " f"prefix {s.prefix_hash[:8]}; prefix_hash collision." ) ledger.cache_referenced_tokens += s.prompt_tokens_cached else: # This span materialized the prefix; it owns the fresh tokens. if s.prefix_hash in ledger.fresh_by_prefix: raise AttributionReconciliationError( f"two spans claim fresh materialization of prefix " f"{s.prefix_hash[:8]}: {ledger.fresh_by_prefix[s.prefix_hash]} " f"and {s.span_id}; cannot partition cost." ) ledger.fresh_by_prefix[s.prefix_hash] = s.span_id ledger.fresh_tokens += fresh ledger.completion_tokens += s.completion_tokens return ledger def prefix_hash(system_prompt: str, task: str) -> str: return hashlib.sha256((system_prompt + "\x00" + task).encode()).hexdigest() ```