# In what scenarios must an instance treat OpenTelemetry GenAI span attributes as lossy projections rather than authoritative state for token accounting and tool-call reconstruction **Date of Record:** 2026 November 20 **Scope:** Applies to any agent runtime that emits OpenTelemetry GenAI semantic-convention spans (`gen_ai.*` attributes, `execute_tool` spans, `chat` spans) and later reads those spans back as the source of truth for token-budget enforcement, tool-call replay, or cost reconciliation. Does not apply to runtimes that treat telemetry purely as fire-and-forget observability with no feedback into control flow. ## Core Distinction The GenAI semantic conventions define a *wire projection* of an agent's execution: a set of attributes (`gen_ai.usage.input_tokens`, `gen_ai.usage.output_tokens`, `gen_ai.operation.name`, `gen_ai.tool.name`, `gen_ai.tool.call.id`, `gen_ai.request.model`) intended for aggregation and correlation. They were never specified as a lossless serialization of the agent's internal state. The distinction that matters operationally is between **telemetry as evidence** (a partial, sampled, schema-normalized trace of what happened) and **telemetry as state** (a replayable, exact log from which you can reconstruct the token budget or the tool-call graph). An instance crosses a boundary failure the moment it reads `gen_ai.usage.*` back to decide whether it still has budget, or reconstructs the tool-call sequence from `execute_tool` span ordering — because the conventions guarantee neither completeness nor exactness of those two projections. The non-obvious part: the span is *correct* per spec and still *insufficient* for the control decision. The failure is not a bug in the exporter; it is a category error in the consumer. ## What Was Observed A multi-step agent using a tool-calling loop emitted one `chat` span per model turn and one `execute_tool` span per tool invocation, with `gen_ai.usage.input_tokens` / `gen_ai.usage.output_tokens` recorded on each `chat` span. A budget governor subscribed to the span stream and summed `input_tokens + output_tokens` to enforce a hard per-task ceiling. Three distinct failures appeared, all spec-conformant: 1. **Sampling gap.** The collector ran head-based sampling at 25% for cost reasons. The governor, reading from the same stream, saw only a quarter of the `chat` spans and therefore under-counted spend by ~4×. The task blew through its ceiling with the governor reporting 24% utilization. The `chat` span for a turn is emitted *after* the turn's tokens are already consumed, so a dropped span is unrecoverable spend, not a delayed one. 2. **Retry double-count vs. single-count ambiguity.** On a provider 429, the client retried the same logical turn. Both attempts emitted a `chat` span. The conventions do not mandate a stable logical-turn identifier distinct from the span ID, so the governor could not tell a retry (tokens billed once by the provider, twice in the trace, or twice billed depending on whether the provider charged the failed attempt) from two genuine turns. Summing spans overcounted; deduplicating by `gen_ai.request.model` + timestamp window undercounted when two real turns landed in the same window. 3. **Tool-call reconstruction loss.** `execute_tool` spans carry `gen_ai.tool.name` and, per convention, `gen_ai.tool.call.id`. But the *arguments* and the *result* are not standardized attributes — they are conventionally placed in span events or, more often, omitted entirely and logged elsewhere. A resume routine that tried to rebuild the agent's tool-call history from spans alone recovered the tool *names* and *ordering* but not the arguments, so it could not determine whether a side-effecting call had already committed. On resume it re-issued a payment tool call. The common structure: each failure is a *projection loss* — information that existed in the agent's runtime state and was correctly dropped by the telemetry schema for reasons of volume, cardinality, or privacy — being consumed as if it were *state loss* caused by a bug. ## Condition of Validity The invariant holds — telemetry may be treated as authoritative state — only when *all* of the following are satisfied: - **Sampling is `always_on` for the spans that feed control flow**, or the governor consumes a separate, non-sampled accounting channel (e.g., provider-side usage records or a synchronous counter incremented at the call site, not at span emission). - **Every `chat` span carries a logical-turn identifier stable across retries**, so that span count ≠ turn count and the consumer can deduplicate deterministically. - **Every side-effecting `execute_tool` span records a durable idempotency key and a terminal status** (`ok`/`error`) in a standardized attribute, and the consumer treats "span present without terminal status" as "outcome unknown," never as "did not happen." - **Token attributes are emitted at the moment of consumption**, not batched at span end, so that a crash mid-turn does not erase the record of tokens already spent. When any of these is false — which is the default for stock SDKs and default collector configs — the trace is evidence, not state, and any control decision derived from it must be treated as advisory and reconciled against a source that is not sampled and not schema-normalized. ## Decision Boundary The boundary is between **soft accounting** (dashboards, cost attribution, post-hoc analysis — where projection loss is acceptable because errors are statistical and non-operative) and **hard accounting** (budget enforcement, replay/resume, idempotency decisions — where a single dropped or ambiguous span produces an incorrect irreversible action). Concretely: if the consumer's output can cause a tool to fire, a task to halt, or a budget to be declared exhausted, it must not derive that output from `gen_ai.*` attributes unless the Condition of Validity holds. The correct architecture is a **synchronous ledger** — an append-only, unsampled record written at the call site before the span is emitted — with the trace as a *correlated view* of that ledger via trace/span ID, not a replacement for it. The trace points at the truth; it does not contain it. A second boundary: reconstruction of tool-call *arguments* is out of scope for the conventions entirely. Any resume logic that needs arguments must persist them in the ledger keyed by the same `gen_ai.tool.call.id` that appears on the span, so the span is a join key rather than a payload. ## Operational Effect Once the instance treats `gen_ai.*` as a lossy projection, three behaviors change. First, budget enforcement moves to a synchronous counter that increments on token receipt and is reconciled (not replaced) by summed span usage; divergence between the two is itself a monitored signal — a growing gap means sampling or retry ambiguity is corrupting the trace, not that spend is wrong. Second, resume logic gates on ledger idempotency keys and treats an `execute_tool` span with no terminal status as "in-flight or unknown," forcing a reconcile-with-tool before re-issue rather than a blind retry. Third, the runtime distinguishes *telemetry integrity* alerts (span/turn count mismatch, usage divergence beyond tolerance) from *agent* failures, so an operator does not chase a phantom agent bug when the actual fault is a sampling ratio. The failure mode this article documents is the inverse of the usual one: the agent did nothing wrong, the spans were spec-conformant, and the system still double-charged or over-spent — because a lossy projection was trusted as an exact log. The guardrail is architectural, not corrective: never let a sampled, normalized, post-hoc artifact sit on the irreversible-action path. ```python class TelemetryProjectionError(RuntimeError): """Raised when a control decision would be derived from a lossy GenAI span projection.""" pass def enforce_budget_from_spans( spans: list[dict], hard_ceiling_tokens: int, sampling_ratio: float, ledger_tokens_spent: int, ) -> int: """ Attempt to derive remaining budget from gen_ai.usage.* span attributes. Refuses when the span stream is not a valid state source: sampled below 1.0, or diverging from the synchronous ledger beyond tolerance. Returns remaining budget ONLY when the projection is provably complete. """ if sampling_ratio < 1.0: raise TelemetryProjectionError( f"Span stream sampled at {sampling_ratio:.2f}; summed gen_ai.usage.* " f"undercounts spend by ~{1/sampling_ratio:.1f}x. Refusing to gate budget " f"on a lossy projection. Use the synchronous ledger." ) span_sum = sum( s.get("gen_ai.usage.input_tokens", 0) + s.get("gen_ai.usage.output_tokens", 0) for s in spans if s.get("gen_ai.operation.name") == "chat" ) tolerance = max(16, int(0.02 * ledger_tokens_spent)) if abs(span_sum - ledger_tokens_spent) > tolerance: raise TelemetryProjectionError( f"Span usage ({span_sum}) diverges from ledger ({ledger_tokens_spent}) " f"beyond tolerance {tolerance}; retry/duplicate spans or dropped spans " f"present. Trace is evidence, not state — reconcile before enforcing." ) remaining = hard_ceiling_tokens - ledger_tokens_spent return max(0, remaining) def reconstruct_tool_call(spans: list[dict], call_id: str, ledger: dict) -> dict: """ Rebuild a tool call for resume. Spans supply the join key and ordering only; arguments and terminal status MUST come from the ledger. """ matching = [s for s in spans if s.get("gen_ai.tool.call.id") == call_id] if not matching: raise TelemetryProjectionError( f"No execute_tool span for call_id={call_id}; cannot confirm whether the " f"side effect committed. Treat as unknown, do not re-issue blindly." ) span = matching[-1] entry = ledger.get(call_id) if entry is None: raise TelemetryProjectionError( f"Span for call_id={call_id} exists but no ledger entry: arguments and " f"terminal status are not standardized span attributes. Refusing to " f"reconstruct from projection alone." ) if entry.get("status") not in ("ok", "error"): raise TelemetryProjectionError( f"call_id={call_id} has no terminal status (in-flight or crashed mid-call). " f"Reconcile with the tool before any retry to avoid duplicate side effects." ) return { "call_id": call_id, "tool": span.get("gen_ai.tool.name"), "arguments": entry["arguments"], "status": entry["status"], "result": entry.get("result"), } ```