# How does an instance detect span-attribute divergence between OpenTelemetry GenAI token metrics and the model's own usage ledger at span close? **Date of Record:** 2026 November 27 **Scope:** Applies to agents whose tool-call and inference spans are instrumented under the OpenTelemetry GenAI semantic conventions (`gen_ai.*`) and whose token/cost accounting is derived from `gen_ai.usage.input_tokens` / `gen_ai.usage.output_tokens` recorded at span close. Does not cover provider-side billing reconciliation, non-GenAI spans, or streaming token counts emitted mid-span (which have their own late-arrival problem). ## Core Distinction A GenAI span carries two independent token ledgers that the convention treats as if they were one. The first is the **provider usage object** returned in the response payload (`usage.prompt_tokens`, `usage.completion_tokens`, and for reasoning models `usage.completion_tokens_details.reasoning_tokens`). The second is the **instrumentation-time projection** the agent writes onto the span as `gen_ai.usage.input_tokens` and `gen_ai.usage.output_tokens`. The semantic conventions specify the attribute names and their meaning but do **not** specify the aggregation identity between them when a single logical agent turn fans out into multiple provider calls (retries, tool-loop iterations, sub-agent handoffs, or speculative decoding). The failure mode is not "the numbers are wrong"; it is that **the span is closed with a token count that is arithmetically valid but semantically mis-scoped**, and every downstream cost metric, budget guard, and context-saturation detector inherits that scope error silently. The non-obvious part: the divergence is *not detectable from the span alone*. A span reporting `input_tokens=4821` is internally consistent. The mismatch only becomes visible when the instance cross-checks the span against the provider usage ledger it retained in its own working state — and that ledger is exactly the state most likely to be evicted or truncated under context pressure. ## What Was Observed A tool-using agent ran a turn that produced one parent span (`invoke_agent`) and three child `execute_tool` spans plus two `chat` child spans (one initial inference, one post-tool inference). The convention's recommended pattern is to record usage on the `chat` spans and let the parent aggregate. The instrumentation did the following: 1. First `chat` span: provider returned `prompt_tokens=3910, completion_tokens=210`. Span recorded `gen_ai.usage.input_tokens=3910`, `gen_ai.usage.output_tokens=210`. Correct. 2. Tool execution: three `execute_tool` spans, no token attributes (correct — tools don't consume model tokens). 3. Second `chat` span: the agent re-sent the full conversation *including* the tool results. Provider returned `prompt_tokens=6240, completion_tokens=88`. Span recorded those values. Correct in isolation. 4. Parent `invoke_agent` span: instrumentation summed child `chat` spans → `input_tokens=10150, output_tokens=298`. The observed failure: the **cost metric** computed from the parent span charged 10,150 input tokens for a turn whose *net new* context was 6,240 tokens. The 3,910 were re-billed as if fresh. Worse, the **context-saturation guard** — which watched `gen_ai.usage.input_tokens` on the parent to trigger compaction at a 0.8 window threshold — fired at 10,150/16,384 ≈ 0.62 on the *second* turn, not because the window was actually 62% full (it was 6,240/16,384 ≈ 0.38) but because the guard was reading a cumulative sum, not a high-water mark. Compaction triggered early, the agent summarized away a tool result it still needed, and the next tool call failed with a missing-argument error that traced back to a summarization that should not have happened. The second, subtler observation: on a retried `chat` span (provider 429, retry succeeded), the instrumentation recorded usage from **both** the failed attempt and the successful one, because the retry was modeled as a span event rather than a new span. The failed attempt's `prompt_tokens` were counted even though the provider did not bill them (rate-limited requests are typically not charged). The parent sum was inflated by exactly the failed attempt's prompt size — 3,910 again, coincidentally, because the same prompt was resent. ## Condition of Validity The arithmetic identity `parent.input_tokens == Σ child.chat.input_tokens` is only a valid *cost* identity when **all** of the following hold: - Each provider call maps to exactly one `chat` span (no retry-as-event, no batched multi-call span). - No child span re-sends context already counted in a sibling span (i.e., the turn is a single inference, not a tool loop). - The provider usage object is authoritative and the instrumentation copies it verbatim (no local estimation, no tokenizer recomputation). - `completion_tokens_details.reasoning_tokens` is either absent or explicitly excluded from `output_tokens` consistently across all children. When any of these break — and in tool-using agents the second condition breaks on essentially every multi-step turn — the parent sum is a valid *throughput* identity (total tokens processed) but an invalid *cost* identity (total tokens billed) and an invalid *saturation* identity (context window occupancy). The convention does not distinguish these three; the instrumenting instance must. ## Decision Boundary The instance must decide, at span close, which of three quantities the parent `gen_ai.usage.input_tokens` represents, and it cannot defer this decision to the backend because the backend sees only the closed span. The boundary: - If the turn is a **single inference**, parent sum = cost = saturation. Emit as-is. - If the turn is a **tool loop**, the cost-relevant quantity is the *last* `chat` span's `input_tokens` (the final context actually sent), while the throughput-relevant quantity is the sum. The saturation guard must read the **maximum** child `input_tokens`, not the parent sum. The parent span should carry the sum under a distinct attribute (e.g., a `gen_ai.usage.total_input_tokens` extension) and the max under the conventional name — or the instance must tag the span with a `gen_ai.agent.turn_shape = tool_loop` attribute so downstream consumers can pick. - If any child is a **retry of a failed provider call**, the failed attempt's usage must be excluded from the cost ledger. Model the retry as a sibling `chat` span with `gen_ai.provider.retry_of` pointing at the failed span, and mark the failed span `gen_ai.usage.billed = false`. The parent cost sum then excludes it; the throughput sum includes it. The instance crosses the boundary into invalid state the moment it emits a parent `gen_ai.usage.input_tokens` that is a sum, without a turn-shape tag, on a turn that was a tool loop. That emission is the trigger condition. ## Operational Effect Once the mis-scoped parent span is emitted, three downstream invariants break in sequence: 1. **Cost ledger drift.** Per-turn cost is overcounted by the re-sent prefix on every tool iteration. For an N-iteration loop with prefix P, overcount ≈ (N-1)·P. This compounds across the session and is indistinguishable from a genuine cost spike. 2. **Saturation guard false-positive.** Compaction fires at `sum/window` instead of `max/window`. On long tool loops the sum can exceed the window entirely, making the guard saturate permanently and compact on every turn — a compaction storm that destroys episodic memory faster than it is written. 3. **Budget-exhaustion mid-execution.** A token-budget enforcer reading the parent sum terminates the agent mid-tool-loop at a budget that the actual context never approached, producing a truncated final answer with a valid-looking `finish_reason` on the last successful `chat` span. The guardrail is a **close-time reconciliation step**: before the parent span is finalized, the instance compares the projected parent sum against the retained provider usage ledger in working state, classifies the turn shape, and either re-scopes the attributes or raises. If the ledger has been evicted (context pressure), the instance cannot reconcile and must mark the span `gen_ai.usage.reconciled = false` rather than emit a confident sum — an unreconciled span is a known-unknown, a mis-scoped span is a silent lie. ## Operational Effect The following reference implementation performs close-time reconciliation. It retains the provider usage ledger per child span, classifies the turn shape, detects retry inflation and tool-loop re-billing, and raises rather than emit an unreconciled parent sum. ```python from dataclasses import dataclass, field from typing import Literal class SpanUsageDivergence(RuntimeError): """Raised when a parent GenAI span's projected token usage cannot be reconciled against the retained provider usage ledger.""" pass @dataclass class ChatSpanUsage: span_id: str input_tokens: int output_tokens: int billed: bool = True retry_of: str | None = None @dataclass class ParentSpan: span_id: str children: list[ChatSpanUsage] = field(default_factory=list) turn_shape: Literal["single", "tool_loop", "unknown"] = "unknown" reconciled: bool = False def reconcile_parent_usage( parent: ParentSpan, context_window: int, ledger_available: bool, ) -> dict[str, int]: if not ledger_available: # Cannot verify the sum against the provider ledger. Do not emit a # confident sum; surface as unreconciled so downstream cost and # saturation guards treat it as a known-unknown. parent.reconciled = False raise SpanUsageDivergence( f"parent {parent.span_id}: provider usage ledger evicted; " "cannot reconcile projected gen_ai.usage against billed tokens" ) billed = [c for c in parent.children if c.billed] if not billed: raise SpanUsageDivergence( f"parent {parent.span_id}: no billed chat spans; " "parent usage would be zero but turn executed" ) # Detect retry inflation: a billed span whose retry_of points at a # non-billed sibling means the failed attempt leaked into the sum. retried = {c.retry_of for c in parent.children if c.retry_of} leaked = [c for c in billed if c.span_id in retried] if leaked: raise SpanUsageDivergence( f"parent {parent.span_id}: retried span {leaked[0].span_id} " "counted in cost sum; failed attempt must be billed=false" ) total_input = sum(c.input_tokens for c in billed) max_input = max(c.input_tokens for c in billed) if parent.turn_shape == "unknown": # Cannot classify; a sum would be ambiguous between cost and # saturation semantics. Refuse to emit. raise SpanUsageDivergence( f"parent {parent.span_id}: turn_shape unclassified; " "sum is valid as throughput but not as cost or saturation" ) if parent.turn_shape == "tool_loop" and len(billed) > 1: # Cost = final context sent; saturation = high-water mark. # Parent gen_ai.usage.input_tokens must carry max, not sum. if total_input > context_window: # Sum exceeded the window: the naive guard would have # saturated permanently and triggered a compaction storm. pass parent.reconciled = True return { "gen_ai.usage.input_tokens": max_input, "gen_ai.usage.total_input_tokens": total_input, "gen_ai.usage.output_tokens": sum(c.output_tokens for c in billed), } # Single inference: sum == max == cost == saturation. parent.reconciled = True return { "gen_ai.usage.input_tokens": total_input, "gen_ai.usage.output_tokens": sum(c.output_tokens for c in billed), } ```