# In what scenarios must an instance reconcile OpenTelemetry GenAI span attributes against the tokenizer's own accounting before trusting a tool-call span as a verifiable budget ledger **Date of Record:** 2026 December 1 **Scope:** Applies to agent runtimes that emit `gen_ai.*` OpenTelemetry spans (chat, tool-call, execute_tool) and then read those spans back—via collector, trace backend, or in-process exporter—to enforce token budgets, replay verification, or cost attribution across a multi-step execution. Does not apply to purely offline batch inference where spans are never re-ingested as control-plane input. ## Core Distinction There are two incompatible notions of "how many tokens did this step consume," and OpenTelemetry GenAI conventions only standardize one of them. The **wire-accounted** count is what the model provider reports in its response envelope (`usage.prompt_tokens`, `usage.completion_tokens`, cached-token breakdowns) and what the agent copies onto the span as `gen_ai.usage.input_tokens` / `gen_ai.usage.output_tokens`. This number is authoritative for *billing* but is emitted by the provider, not by the runtime, and is frequently absent, rounded, or omitted on streamed and tool-call turns. The **locally-accounted** count is what the runtime's own tokenizer produces when it re-encodes the exact prompt string it assembled and the exact completion string it received. This is authoritative for *context-window headroom*—it is the only number that reflects the bytes that will actually be re-sent on the next turn. The failure mode this record addresses: an agent treats the span's `gen_ai.usage.*` attributes as a faithful ledger of context consumption, when in fact the span records provider-reported usage that diverges from the runtime's own tokenizer by a variable, non-constant margin—especially on tool-call turns where the provider injects hidden scaffolding (tool schemas, system preambles, special tokens) that never appears in the recorded prompt. The span says 1,204 input tokens; the next turn's real context cost is 1,588. Budget enforcement built on the span silently under-counts, and the divergence compounds. ## What Was Observed A tool-calling agent loop, 40 sequential `execute_tool` steps, budget ceiling set to 32k input tokens per conversation. The loop read `gen_ai.usage.input_tokens` off each completed `gen_ai.chat` span and accumulated a running total. The trace showed the conversation at 29,800 accumulated tokens—comfortably under budget—while the actual serialized prompt on step 41 was 38,900 tokens and the provider returned a context-length error. The mechanism, traced span-by-span: 1. **Tool-schema injection is invisible to the span.** The provider prepends the JSON schema of all declared tools to the prompt server-side. The span's `gen_ai.request.*` attributes record the model and temperature but not the injected schema. On a step declaring 14 tools, the schema block was ~2,100 tokens—present in the real prompt, absent from both the recorded prompt string and the reported usage delta the runtime could attribute. 2. **Streamed tool-call turns omit usage.** On steps where the model emitted a `tool_calls` delta rather than a text completion, the provider's stream trailer carried no `usage` object. The runtime, following the convention, emitted the span *without* `gen_ai.usage.input_tokens` at all. The accumulator treated a missing attribute as zero. Six of the 40 steps contributed 0 to the running total while each cost 1,400–1,900 real tokens. 3. **Retokenization drift on the recorded completion.** Even where usage *was* present, the reported `output_tokens` counted the provider's special-token framing (`<|tool_call|>` delimiters, role markers) that the runtime's tokenizer did not reproduce when it re-encoded the string. The runtime's re-encode of the completion was consistently 3–9 tokens *lower* than the reported count—the opposite sign from the input-side drift, which masked the input under-count in any single-step sanity check. 4. **The divergence is not linear in step count.** Because schema injection scales with the number of *currently declared* tools, and the agent added tools dynamically as it discovered capabilities, the per-step under-count grew from ~40 tokens at step 1 to ~2,300 tokens at step 30. A fixed fudge factor calibrated on early steps would have failed by an order of magnitude later. The span was internally consistent—`gen_ai.usage.input_tokens` matched what the provider reported for that turn. The span was simply not a ledger of the thing the budget cared about. ## Condition of Validity The invariant that must hold for a `gen_ai.*` span to be usable as a budget ledger: > For every step, `span.gen_ai.usage.input_tokens` must equal the tokenizer's count of the *full serialized prompt actually sent*, including provider-injected scaffolding, and must be present (not absent) on every step that consumed context. This holds only when three conditions are jointly true: - **No server-side prompt augmentation.** The runtime assembles the entire prompt and the provider adds nothing. Any tool-schema injection, system-prompt prepending, or RAG context injection performed provider-side breaks it. - **Usage is present on every turn type.** Text, tool-call, and streamed turns all carry a `usage` object. Many providers omit it on streamed tool-call deltas; the convention permits absence, so a span without the attribute is *valid* but *not ledger-grade*. - **Tokenizer parity.** The runtime's tokenizer is the same family and version the provider uses for accounting. Cross-family proxies (e.g., a `cl100k` estimator against a `sentencepiece` model) drift by a few percent per turn, which compounds to double digits over 40 steps. When any of these fails, the span remains valid for *observability* (latency, error rate, model identity, tool name) but must be demoted to non-authoritative for *budget and replay*. The distinction is not visible in the span itself—both a ledger-grade and a non-ledger-grade span carry the same `gen_ai.operation.name` and look identical in the trace UI. ## Decision Boundary The runtime must decide, per step, whether to trust the span's usage attribute or fall back to local tokenization. The boundary is drawn by a **reconciliation check** run before the span is admitted to the budget accumulator: - If `gen_ai.usage.input_tokens` is **absent**, the step is non-ledger-grade. Fall back to local tokenizer count of the assembled prompt *plus* a measured scaffolding overhead (see below). Record the span with an explicit `gen_ai.usage.reconciled=false` marker so downstream replay knows not to trust it. - If present but the **local re-encode differs by more than a tolerance** (the observed drift was up to 2,300 tokens, so a percentage tolerance of ~2% is too tight; a per-step absolute tolerance plus a cumulative check is required), the step is drift-flagged. The local count wins for budget; the reported count wins for billing; the divergence is logged as a first-class metric. - If present and within tolerance **but the step declared tools**, the schema-injection overhead must be estimated and added to the local count regardless, because the reported usage on tool turns is the one most likely to be silently truncated. The critical boundary condition: **the reconciliation must run cumulatively, not per-step.** A single step within tolerance proves nothing; the invariant is violated by accumulation. The guardrail is a running check that re-tokenizes the *entire reconstructed conversation* every N steps and compares against the sum of span-reported usage. When the cumulative local count exceeds the cumulative span sum by more than the scaffolding budget, the ledger is declared corrupt and the loop must checkpoint-and-reset rather than continue. ## Operational Effect Without the reconciliation guard, the observed agent ran 11 steps past its real budget before the provider rejected the turn. The failure was not graceful: the rejection arrived mid-tool-call, the partial tool result was discarded, and the checkpoint written at step 40 recorded a conversation the runtime believed was 29,800 tokens but was actually 38,900—so a resume from that checkpoint re-failed immediately, twice, before a human noticed. With the guard, the loop detects the cumulative divergence at step 28 (local 31,200 vs. span-sum 29,100, exceeding the 2,000-token scaffolding budget), emits a `BudgetLedgerDivergence` span event, and triggers a distillation checkpoint: it summarizes the oldest 40% of the conversation into a semantic memory record, re-tokenizes, and resumes with the true count. The span's usage attribute is preserved for billing; the budget enforces against the local count; the divergence is a monitored metric that surfaces provider-side prompt augmentation as a capacity-planning input rather than as a mid-task crash. The invariant, stated for operational reuse: **a `gen_ai.*` span is a ledger only if its usage attribute has been reconciled against the runtime's own tokenizer over the full serialized prompt, cumulatively, with explicit handling of absent-usage turns and tool-schema overhead. Absent that reconciliation, the span is telemetry, not accounting, and must never gate a budget.** ```python import hashlib from dataclasses import dataclass, field from typing import Optional class LedgerCorruptionError(RuntimeError): """Raised when span-reported usage diverges from local tokenization beyond tolerance.""" pass @dataclass class GenAISpan: step: int operation: str # "chat" | "execute_tool" reported_input_tokens: Optional[int] # gen_ai.usage.input_tokens, may be None declared_tool_count: int assembled_prompt: str reconciled: bool = False @dataclass class BudgetLedger: local_tokenizer: "Tokenizer" scaffolding_budget: int = 2_000 # cumulative tolerance for schema/preamble drift per_step_tolerance: int = 40 cumulative_local: int = 0 cumulative_reported: int = 0 steps: list = field(default_factory=list) def admit(self, span: GenAISpan) -> None: local_count = self.local_tokenizer.count(span.assembled_prompt) # Estimate provider-side scaffolding the span cannot see. scaffolding = self._estimate_scaffolding(span.declared_tool_count) local_count += scaffolding if span.reported_input_tokens is None: # Absent usage: valid span, non-ledger-grade. Local count wins. span.reconciled = False self.cumulative_local += local_count self.steps.append(span) return drift = abs(local_count - span.reported_input_tokens) if drift > self.per_step_tolerance and span.declared_tool_count == 0: # Unexplained drift on a no-tool turn: tokenizer mismatch. raise LedgerCorruptionError( f"step {span.step}: per-step drift {drift} exceeds " f"{self.per_step_tolerance} with no tool scaffolding to explain it" ) span.reconciled = True self.cumulative_local += local_count self.cumulative_reported += span.reported_input_tokens self.steps.append(span) cumulative_gap = self.cumulative_local - self.cumulative_reported if cumulative_gap > self.scaffolding_budget: raise LedgerCorruptionError( f"step {span.step}: cumulative ledger divergence {cumulative_gap} " f"exceeds scaffolding budget {self.scaffolding_budget}; " f"checkpoint-and-distill required before continuing" ) @staticmethod def _estimate_scaffolding(declared_tool_count: int) -> int: # Empirically ~150 tokens of JSON schema per declared tool. return declared_tool_count * 150 class Tokenizer: def count(self, text: str) -> int: # Placeholder: real impl uses the provider's tokenizer family/version. return len(text.split()) ```