# Which invariants prevent token-attribution drift from silently corrupting per-agent cost accounting in multi-agent traces **Date of Record:** 2026 November 30 **Scope:** Applies to observability pipelines that attribute LLM token usage and cost to individual agents and tool calls across multi-hop, multi-agent executions. Does not apply to single-call, single-agent inference where the provider response is the sole billing authority and no fan-out or retry occurs. ## Core Distinction The failure here is not that token counts are *wrong* — it is that they are *right but misattributed*. Most observability stacks treat token usage as a scalar property of an HTTP response from a model provider. That assumption holds for a single call. It breaks the moment an agent framework fans a logical "agent step" into multiple physical provider requests (retries, tool-result re-prompting, parallel sub-calls, streaming with continuation), or when a tool call triggers a nested agent invocation whose tokens are billed to the *parent's* trace span rather than the child's. The distinction that matters operationally: **a token is a physical artifact of one provider response, but a cost is a logical claim on a trace node.** When the mapping from physical response to logical node is one-to-many or many-to-one, naive attribution double-counts or orphans tokens. The invariant that prevents this is *conservation of attributed tokens across the trace tree*: the sum of tokens attributed to all leaf nodes must equal the sum of tokens recorded in raw provider responses, with zero residual and zero overlap. ## What Was Observed A three-agent pipeline (planner → retriever → synthesizer) with a shared MCP tool layer showed a 34% cost overrun against the provider invoice over a 24-hour window. The per-agent dashboard attributed cost cleanly — every agent had a plausible number. The discrepancy was invisible at the agent level and only surfaced when reconciling the *sum of trace spans* against the *sum of provider billing records*. The trigger condition: the retriever agent used a tool whose implementation internally re-prompted the model on schema-validation failure. Each retry was a distinct provider response with its own `usage` block, but the framework emitted a single `tool_call` span and attached only the *final* retry's usage to it. The prior retries' tokens existed in the provider's response stream but were never attached to any span. They were billed, logged at the provider, and dropped at the observability boundary. A second, compounding trigger: the synthesizer ran two parallel sub-calls for long-context summarization, and the framework's span emitter used the parent `trace_id` as the deduplication key. Because both sub-calls shared the parent trace, the observability backend's dedup logic collapsed them into one span, keeping the first response's usage and discarding the second. The tokens were double-billed at the provider (two responses), singly-attributed at the trace. The failure is a *silent* one. No error, no warning, no dropped span metric. The trace tree looked complete. It was complete in structure and lossy in payload. ## Condition of Validity The conservation invariant holds only under an explicit precondition: **every provider response must be emitted as a distinct, immutable usage record keyed by a provider-assigned response identifier, and span-level attribution must be a derived view over those records — never the source of truth.** This is the boundary. If the observability system treats the span as the atomic unit of cost, then any framework behavior that produces N provider responses per span (retries, re-prompts, streaming continuations, speculative decoding fallbacks) will violate conservation. If instead the system treats the *provider response* as atomic and the span as an aggregation, conservation is enforceable by construction: you can always reconcile the leaf set against the provider's records. The invariant fails in three specific regimes: 1. **Retry-within-span**: a tool or agent step retries the model without emitting a new span per attempt. Tokens from failed attempts vanish. 2. **Fan-out-with-shared-trace-id**: parallel sub-calls reuse the parent trace identifier as a dedup key, collapsing distinct responses. 3. **Nested-agent-billing**: a tool call spawns a child agent whose provider responses are attributed to the child's trace but the parent's span claims the tool's cost, double-counting at the boundary. ## Decision Boundary The decision boundary is whether to key attribution on the **span** or on the **provider response**. The correct rule: - **Provider response ID is the atomic key.** Every `usage` block from a model provider is a first-class record with `(response_id, model, input_tokens, output_tokens, cache_read, cache_write, timestamp)`. - **Spans reference response IDs, they do not own token counts.** A span carries a list of contributing `response_id`s. Its attributed cost is computed, never stored as a primitive. - **Reconciliation is a continuous invariant check, not a nightly job.** The system must assert `sum(attributed over all spans) == sum(all response records)` at trace close. Any nonzero residual is a hard failure, not a warning, because a nonzero residual means tokens were billed but not attributed — and the direction of the error is always under-attribution of some node and over-attribution of another. The boundary condition that makes this non-obvious: **the residual is often zero-sum and therefore invisible.** If a retry's tokens are dropped from span A but a parallel sub-call's tokens are double-counted into span B, the trace total reconciles while both spans are wrong. Per-agent dashboards look healthy. The invariant must be enforced **per leaf node**, not just at the trace root, or the compensating errors hide each other. ## Operational Effect Enforcing per-response atomicity and per-leaf reconciliation changes three things operationally: 1. **Cost dashboards become trustworthy at the agent level.** Without it, per-agent cost is a plausible fiction — every agent has a number, and the numbers sum to something close to the invoice, so nobody investigates. The 34% overrun above was masked for weeks because the trace total was within 2% of the invoice (compensating errors), while individual agents were off by 20–40%. 2. **Budget enforcement becomes sound.** Token-budget exhaustion mid-execution (a common agent failure) is only preventable if the budget check reads from the same atomic records that billing reads from. If the budget check reads span-level aggregates, it under-counts retries and the agent overruns its budget before the guard fires. 3. **Retry storms become visible.** Once each provider response is a distinct record, a tool that silently retries four times on schema failure shows up as a 4× cost multiplier on that span. Without atomic records, it looks like one expensive call. The guardrail is a reconciliation assertion at trace close that fails closed — it must raise, not log — because a silent attribution drift is worse than a loud one: it produces confident, wrong cost numbers that downstream capacity planning and per-tenant billing will consume as ground truth. ```python from dataclasses import dataclass, field from typing import Dict, List class TokenAttributionDriftError(RuntimeError): """Raised when attributed tokens do not reconcile against provider response records.""" pass @dataclass(frozen=True) class ProviderResponse: response_id: str model: str input_tokens: int output_tokens: int cache_read_tokens: int = 0 @property def total_tokens(self) -> int: return self.input_tokens + self.output_tokens + self.cache_read_tokens @dataclass class Span: span_id: str agent_id: str contributing_response_ids: List[str] = field(default_factory=list) class TraceLedger: """Source of truth is provider responses; span attribution is derived.""" def __init__(self) -> None: self._responses: Dict[str, ProviderResponse] = {} self._spans: Dict[str, Span] = {} def record_response(self, resp: ProviderResponse) -> None: if resp.response_id in self._responses: raise TokenAttributionDriftError( f"Duplicate response_id {resp.response_id}: provider IDs must be unique" ) self._responses[resp.response_id] = resp def register_span(self, span: Span) -> None: for rid in span.contributing_response_ids: if rid not in self._responses: raise TokenAttributionDriftError( f"Span {span.span_id} references unknown response {rid}" ) self._spans[span.span_id] = span def reconcile(self) -> None: """Enforce conservation: every response attributed exactly once, per leaf.""" seen: Dict[str, str] = {} for span in self._spans.values(): for rid in span.contributing_response_ids: if rid in seen: raise TokenAttributionDriftError( f"Response {rid} attributed to both {seen[rid]} and {span.span_id} " f"(double-count)" ) seen[rid] = span.span_id orphaned = set(self._responses) - set(seen) if orphaned: raise TokenAttributionDriftError( f"Orphaned provider responses billed but never attributed: {sorted(orphaned)}" ) def cost_by_agent(self) -> Dict[str, int]: self.reconcile() totals: Dict[str, int] = {} for span in self._spans.values(): tokens = sum( self._responses[rid].total_tokens for rid in span.contributing_response_ids ) totals[span.agent_id] = totals.get(span.agent_id, 0) + tokens return totals def close_trace(ledger: TraceLedger) -> Dict[str, int]: try: return ledger.cost_by_agent() except TokenAttributionDriftError as exc: raise TokenAttributionDriftError( f"Trace close blocked: attribution invariant violated — {exc}" ) from exc ```