# Under what conditions must an instance treat OpenTelemetry GenAI span attributes as a lossy projection of agent state rather than a faithful record **Date of Record:** 2026 November 28 **Scope:** Applies to agents instrumented with OpenTelemetry GenAI semantic conventions (`gen_ai.*`) where spans are used as the source of truth for post-hoc reasoning, token accounting, or replay verification. Does not apply to systems where spans are purely diagnostic and no downstream logic consumes them. ## Core Distinction The GenAI semantic conventions were designed as an *observability projection*: a normalized, cardinality-bounded, PII-safe view of a model invocation. They were not designed as a *state record*. The distinction that matters operationally is between two different questions: - "What did the agent do?" — answered by the agent's own event log / checkpoint state. - "What does the telemetry say the agent did?" — answered by `gen_ai.*` span attributes. These diverge under specific, reproducible conditions. The most consequential divergence is in **token accounting across a multi-step tool loop**, because token counts are the quantity most often trusted as exact from telemetry and most often used to enforce budget invariants. The `gen_ai.usage.input_tokens` / `gen_ai.usage.output_tokens` attributes are per-span. An agent's *effective* context cost is a function of the conversation history re-sent on every turn, which no single span records. A loop of N turns where each turn re-sends the accumulated history produces a sum-of-spans token count that is correct per-span and structurally misleading as a total, because it double-counts cached/prefix tokens and omits provider-side caching discounts that the convention does not standardize. ## What Was Observed A tool-using agent executed a 7-turn loop (plan → tool → observe → replan → tool → observe → finalize). Each turn emitted a `gen_ai.chat` span with `gen_ai.usage.input_tokens` and `gen_ai.usage.output_tokens`. A downstream budget auditor summed `input_tokens` across spans and compared against a per-task budget of 40,000 tokens. The sum was 61,240. The provider's actual billed input was 18,900 (prefix caching absorbed turns 2–7's repeated history). The auditor raised a budget-exceeded halt and killed the task at turn 5, mid-replan, after a tool had already mutated external state. Three separate projection losses compounded: 1. **Cache accounting is not in the convention.** `gen_ai.usage.input_tokens` reports tokens *submitted*, not tokens *billed*. There is no standardized `gen_ai.usage.cached_input_tokens` attribute across providers at the time of this record; some emit it as an extension, most do not. A sum of `input_tokens` is an upper bound on cost, not a cost. 2. **Span count ≠ turn count under retries.** A provider 429 on turn 3 produced a retried span with the same `gen_ai.conversation.id` but a distinct `span_id`. The auditor counted both. Retried spans re-report input tokens for the *same* logical turn, so naive summation double-counts any turn that retried. 3. **Tool-call spans are siblings, not children, of the token-bearing span in some SDK auto-instrumentations.** When the tool span is emitted by a separate instrumentation library, it may land under the same trace but not under the chat span, so a parent-based aggregation of `gen_ai.usage.*` misses the tool's own token cost (if the tool itself invokes a model) or double-counts it (if both instrumentations observe the same call). The agent was killed on a *false* budget breach. The failure was not in the agent's reasoning; it was in treating a lossy projection as a faithful record. ## Condition of Validity Telemetry-derived token totals are valid as an exact accounting only when **all** of the following hold: - Every span in the trace is emitted by a single instrumentation library with a consistent parent-child structure (no mixed auto/manual instrumentation on the same call path). - No turn retried, or retries are deduplicated by a stable logical-turn identifier before summation. - The provider emits cached-token attributes and the auditor subtracts them, or the budget is defined against *submitted* tokens by policy (rare). - The trace is complete: no span was dropped by the sampler, the exporter queue, or a batch timeout. In practice, condition 4 fails silently and most often. A `BatchSpanProcessor` with a full queue drops spans without raising to the caller. The dropped span is not the one that matters for latency; it is whatever was in flight at shutdown, which is frequently the *final* turn — the one carrying the largest accumulated input count and the terminal output. The trace looks complete (it has a root, it has children) but is missing its most expensive span, and the auditor under-counts, not over-counts. The direction of error flips depending on whether the loss is retry-double-count (over) or drop (under). ## Decision Boundary The boundary is this: **a GenAI span may be consumed as a state record only for quantities the convention defines as exact and per-span-local; any cross-span aggregate must be reconstructed from the agent's own logical-turn log, with spans joined as a secondary check.** Concretely, the agent must not: - Sum `gen_ai.usage.input_tokens` across spans to enforce a budget. It must sum from its own per-turn ledger, keyed by logical turn, and use spans only to *reconcile* (flag divergence, not enforce). - Infer tool-call ordering or completion from span timestamps. Span start/end times are subject to clock skew across hosts and to exporter batching; a tool span may appear to end before its parent chat span starts. Ordering must come from the agent's event log. - Treat span presence as proof of execution. A dropped span is indistinguishable from a never-executed call in the trace alone; only the agent's own commit record distinguishes them. The invariant to enforce: **every budget or replay decision reads from the logical-turn ledger; telemetry is a reconciler that can raise a divergence alarm but cannot itself halt execution.** If the reconciler and the ledger disagree beyond a tolerance, the correct action is to log the divergence and continue, not to halt — because the ledger is the record of what the agent actually did and the span is a projection of it. ## Operational Effect With the ledger as source of truth and spans as reconciler, the 7-turn loop completes. The ledger records 18,900 billed input tokens (provider-reported per turn, captured at the call site before the span is emitted). The span sum is 61,240. The reconciler computes the ratio and flags `cache_or_retry_divergence` at severity info, because the ledger's per-turn records show caching on turns 2–7 and one retried turn deduplicated by logical-turn id. No halt. The task finalizes at turn 7. The cost is that the agent must maintain its own token ledger, which means the instrumentation cannot be pure auto-instrumentation — the call site must capture provider usage before it is projected into a span. This is the price of the invariant. A system that relies solely on `gen_ai.*` spans for accounting is operating on a lossy projection and will, under retry or cache or drop conditions, either over-count (false halt, as observed) or under-count (silent budget overrun). Neither is acceptable for a system that mutates external state mid-task, because a halt after a tool has committed leaves the world in a state the agent's record no longer describes. ```python from dataclasses import dataclass, field from typing import Optional class TelemetryProjectionError(RuntimeError): """Raised when a span-derived aggregate is used as a state record beyond the conditions under which the GenAI convention is exact.""" @dataclass class LogicalTurn: turn_id: str billed_input_tokens: int billed_output_tokens: int retried: bool = False @dataclass class SpanRecord: turn_id: str span_id: str input_tokens: int output_tokens: int cached_input_tokens: Optional[int] = None @dataclass class Ledger: turns: dict = field(default_factory=dict) def record(self, t: LogicalTurn) -> None: # Ledger keys by logical turn; a retry replaces, never appends. self.turns[t.turn_id] = t def billed_input(self) -> int: return sum(t.billed_input_tokens for t in self.turns.values()) def reconcile(ledger: Ledger, spans: list, tolerance_ratio: float = 0.05) -> dict: """Spans are a reconciler, not a source of truth. Returns a divergence report; never raises on divergence alone, because the ledger governs.""" span_sum = sum(s.input_tokens for s in spans) ledger_sum = ledger.billed_input() if ledger_sum == 0 and span_sum > 0: # Spans claim cost the ledger never recorded: a turn executed that # the agent did not commit. This IS a state-record failure. raise TelemetryProjectionError( f"spans report {span_sum} input tokens but ledger is empty; " "a turn executed outside the agent's commit path" ) ratio = abs(span_sum - ledger_sum) / max(ledger_sum, 1) return { "span_sum": span_sum, "ledger_sum": ledger_sum, "ratio": ratio, "diverged": ratio > tolerance_ratio, "action": "log_and_continue" if ratio > tolerance_ratio else "none", } def enforce_budget(ledger: Ledger, budget: int) -> None: """Budget enforcement reads ONLY the ledger. Spans cannot halt a task.""" spent = ledger.billed_input() if spent > budget: raise TelemetryProjectionError( f"ledger-billed input {spent} exceeds budget {budget}; " "halt is ledger-authorized, not span-authorized" ) ```