# What happens when an instance emits GenAI tool-call spans whose `gen_ai.usage.*` token counters are re-derived at span close instead of at model-response receipt **Date of Record:** 2026 November 24 **Scope:** Applies to any agent runtime that emits OpenTelemetry spans conforming to the GenAI semantic conventions (`gen_ai.operation.name`, `gen_ai.request.model`, `gen_ai.usage.input_tokens`, `gen_ai.usage.output_tokens`, tool-call child spans) and computes token usage at span finalization rather than at the moment the model response is parsed. Does not apply to batch/offline token reconciliation pipelines that operate on raw provider payloads outside the trace pipeline. ## Core Distinction The GenAI semantic conventions treat `gen_ai.usage.input_tokens` and `gen_ai.usage.output_tokens` as *observations of a discrete model invocation*. The provider returns these numbers exactly once, in the response envelope, at the instant the completion is produced. There is a second, tempting source of the same numbers: the runtime's own tokenizer, re-run at span close over the accumulated prompt and the accumulated output. These two sources diverge, and the divergence is not a rounding error — it is a category error about *when the measurement is valid*. The non-obvious boundary: a span that closes after a tool call has *already consumed* the model response. If the runtime defers attribute emission to span close and re-derives tokens from the message history at that point, it is measuring a different object than the one the provider billed. The trace looks internally consistent — every span has token attributes, every child span nests correctly — while being silently wrong about the one number downstream cost and budget governors depend on. ## What Was Observed A multi-tool agent loop (plan → `tool.search` → `tool.fetch` → synthesize) emitted well-formed GenAI spans. `gen_ai.operation.name="chat"` parent spans carried `gen_ai.request.model`, and child `execute_tool` spans carried `gen_ai.tool.name` and `gen_ai.tool.call.id`. On the surface the trace was convention-compliant. The defect surfaced under a specific trigger: **a tool call whose result was truncated by the runtime before being appended to the message history.** The fetch tool returned 40 KB; the runtime's context manager clipped it to 8 KB to protect the context window, but the *provider* had already been charged for the full prompt on the *next* turn — because the full tool result was sent to the model on that turn, and only the *subsequent* turn used the clipped version. The span-close tokenizer measured the clipped history. Result: `gen_ai.usage.input_tokens` on the synthesis span under-reported by roughly 4,800 tokens per fetch, every loop iteration. The failure was invisible in any single trace. It only appeared when the trace was summed and compared against the provider invoice: a 6–9% systematic under-count that grew with tool-result size. Worse, the `execute_tool` child span had *no* usage attributes at all — the convention does not require them on tool spans — so there was no per-tool token attribution to reconcile against. The loss was concentrated entirely in the parent `chat` span's input counter, which the runtime had re-derived from a history that no longer matched what was sent. A second, subtler trace appeared on retries. When the provider returned a 429 and the runtime retried, the retried request re-sent the *same* prompt. The runtime emitted one `chat` span with `gen_ai.usage.input_tokens` set once. The provider billed twice. The span model had no representation of the retry's token cost because the span was keyed to the logical operation, not the wire request. ## Condition of Validity The invariant that makes `gen_ai.usage.*` trustworthy is: > Token usage attributes on a GenAI span MUST be copied from the provider response envelope at the moment that response is received, before any mutation of the message history, context clipping, or retry logic can occur. This is valid only when three conditions hold simultaneously: 1. **Capture-at-receipt.** The counter values are bound to the span *before* the response is appended to history or passed to any tool. Deferring to span close is the failure. 2. **One span per wire request.** A retry is a distinct provider invocation and must be a distinct span (or carry an explicit `gen_ai.usage` per attempt), otherwise retry cost is unrepresentable. 3. **Tool-result accounting is explicit.** When a tool result is clipped or dropped before the next turn, the *next* `chat` span's input count must reflect what was actually sent, not what survived clipping. The clip must happen *after* the send, or the divergence must be recorded. When condition 1 fails, every downstream consumer — cost dashboards, budget governors, context-window headroom estimators — inherits the error. When condition 2 fails, retry storms are invisible in cost. When condition 3 fails, large tool outputs vanish from accounting precisely when they matter most. ## Decision Boundary The boundary is *where in the request lifecycle the token attributes are written*: - **Write at response receipt** → attributes reflect provider billing; safe for cost and budget governors; requires the span to be open and mutable at that instant. - **Write at span close (re-derived)** → attributes reflect the runtime's post-mutation view; unsafe whenever history was clipped, retried, or transformed between receipt and close. - **Write never (tool spans)** → acceptable only if the parent `chat` span's input count is captured at receipt, because the tool's contribution is folded into the next turn's input. If the parent is re-derived, the tool's tokens are lost entirely. The decision rule: if the runtime cannot guarantee capture-at-receipt (e.g., it uses a span processor that batches and finalizes attributes lazily), it must *not* emit `gen_ai.usage.*` from a re-derivation path at all — it should emit the provider's raw values verbatim into a side channel and mark the span's usage as `unavailable`, rather than emit a plausible-but-wrong number. A missing counter is recoverable; a wrong counter is not, because it silently passes every consistency check the trace pipeline performs. ## Operational Effect The practical consequence is a **silent budget-governor drift**. A governor that reads `gen_ai.usage.input_tokens` from spans to enforce a per-session token cap will under-count by the clipped-tool-result delta and the retry delta. The cap is never hit at the intended threshold; the session runs 6–12% over budget before the governor trips. Because the trace is internally consistent (child spans nest, attributes are present, no schema violation), no alert fires. The error is only detectable by cross-referencing against the provider invoice — a reconciliation step most runtimes do not perform per-session. The guardrail is a two-part invariant enforced at the emitter: 1. A `UsageCaptureError` raised if a `chat` span reaches close without having bound provider-reported usage at receipt time. 2. A reconciliation check that flags any span where the re-derived token count differs from the captured count by more than a tolerance, and refuses to emit the re-derived value. The following emitter enforces both, and fails loudly rather than emitting a wrong counter: ```python class UsageCaptureError(RuntimeError): """Raised when GenAI token usage cannot be attributed to a provider response.""" pass class GenAISpanEmitter: def __init__(self, tolerance_pct: float = 2.0): self.tolerance_pct = tolerance_pct def bind_usage_at_receipt(self, span, provider_usage: dict) -> None: # Must be called the instant the model response envelope is parsed, # before history mutation, clipping, or retry logic. if provider_usage is None: raise UsageCaptureError( "provider response carried no usage envelope; cannot bind " "gen_ai.usage.* at receipt. Refusing to defer to span close." ) span.set_attribute("gen_ai.usage.input_tokens", provider_usage["input_tokens"]) span.set_attribute("gen_ai.usage.output_tokens", provider_usage["output_tokens"]) span.set_attribute("gen_ai.usage.capture_point", "receipt") def close_span(self, span, rederived_usage: dict | None) -> None: bound = span.attributes.get("gen_ai.usage.capture_point") if bound != "receipt": raise UsageCaptureError( "chat span closed without usage bound at receipt; " "re-derived counters are not admissible for cost governance." ) if rederived_usage is not None: captured_in = span.attributes["gen_ai.usage.input_tokens"] drift = abs(rederived_usage["input_tokens"] - captured_in) pct = 100.0 * drift / max(captured_in, 1) if pct > self.tolerance_pct: # Do NOT overwrite the captured value. Emit a divergence marker. span.set_attribute("gen_ai.usage.rederive_divergence_pct", pct) raise UsageCaptureError( f"re-derived input_tokens diverged {pct:.1f}% from " f"provider-captured value; tool-result clipping or retry " f"likely. Captured value retained." ) span.end() ```