# What structural signals indicate that OpenTelemetry GenAI span attributes have silently desynchronized from the agent's actual tool-call and token state **Date of Record:** 2026 November 22 **Scope:** Applies to agents whose execution is instrumented with OpenTelemetry GenAI semantic conventions (`gen_ai.*` attributes) on spans that wrap LLM invocations and tool calls, where span attributes are emitted at span *end* from a mutable in-process accumulator rather than captured at the moment of the event. Does not cover pure logging pipelines, nor spans emitted from immutable event streams (e.g., a message queue drained by a separate collector). ## Core Distinction The failure is not "telemetry is missing." It is **telemetry that is present, well-formed, schema-valid, and wrong** — specifically, `gen_ai.usage.input_tokens`, `gen_ai.usage.output_tokens`, and per-tool-call attributes that were accumulated into a shared mutable context and flushed at span close, after the agent had already mutated that context through retries, streaming partials, or tool-result overwrites. A span that *fails* to export is detectable (gap in trace, missing span ID). A span that exports `gen_ai.usage.output_tokens: 412` when the model actually emitted 412 tokens across *two* attempts, of which only the second was retained, is indistinguishable from a healthy span by any schema validator. The invariant that breaks is: **the attribute value at span end must equal the value at the event that the span claims to describe.** Under mutable-accumulator instrumentation, it does not. ## What Was Observed A tool-calling agent loop, instrumented with a single mutable `SpanContext` dict per turn: ``` turn_ctx = {"input_tokens": 0, "output_tokens": 0, "tool_calls": []} ``` On each model response, the handler did `turn_ctx["output_tokens"] += resp.usage.completion_tokens` and appended to `turn_ctx["tool_calls"]`. When a tool call returned a transient error (HTTP 503 from the tool backend), the agent's retry policy re-invoked the model with the *same* logical step. The retry path re-entered the accumulation block. Result: `output_tokens` was double-counted, and `tool_calls` contained two entries for one logical invocation — the failed and the succeeded — with no discriminator attribute distinguishing them. Three structural signals appeared, in order of how early they were detectable: 1. **Token accounting diverged from the provider's billing ledger by a stable ratio.** Aggregate `sum(gen_ai.usage.output_tokens)` over a 10k-trace window exceeded provider-reported completion tokens by ~1.07×. The ratio was *stable*, not noisy — the signature of deterministic double-counting on a fixed retry class, not of sampling error. A stable multiplicative bias is the fingerprint of accumulator re-entry; random loss produces a ratio that wanders. 2. **`gen_ai.tool.name` appeared more than once within a single parent span with identical `gen_ai.tool.call.id`.** The semantic conventions assume call IDs are unique per invocation; the retry reused the ID because it was minted at step entry, not per attempt. Two `tool_calls` entries sharing an ID is structurally impossible in a correct trace and is a hard, schema-adjacent tell. 3. **Span duration was consistent with one attempt while token count was consistent with two.** `gen_ai.usage.output_tokens` scaled with the retried attempt count, but the span's `end_time` was set at first-attempt completion (the retry mutated the context but the span had already been closed for the parent). The mismatch between *duration evidence* and *token evidence* on the same span is the cleanest single signal: no single model call can produce N tokens in the wall-clock of one call if N reflects two. The critical observation: none of these surfaced as errors. The collector accepted every span. Dashboards rendered. Only a cross-check against an external ground truth (provider ledger, or wall-clock × tokens/sec) exposed the drift. ## Condition of Validity The guardrail holds only under these conditions, and fails outside them: - **The accumulator must be append-only with attempt-scoped keys.** Retries must mint a new `attempt_id` and either (a) emit a child span per attempt, or (b) tag the attribute with `gen_ai.request.attempt` so double-counting is *visible* rather than *silent*. If retries overwrite rather than append, you lose the failed attempt entirely — a different, equally bad failure (undercounting). - **Token attributes must be captured at the model-response boundary, not at span close.** The convention's `gen_ai.usage.*` is defined per-response; capturing it at span end conflates all responses in the span. If the span wraps multiple model calls (a multi-step turn), you must either emit one span per call or accept that the attribute is an aggregate — and then it must be *named* as an aggregate, not as a single-call usage field. - **The cross-check ground truth must be independent.** Provider billing, or a tokens-per-second sanity bound from measured latency, is required. Self-consistency checks (does the span parse? does the sum match itself?) cannot detect this class, because the corrupted value is internally consistent. It does *not* hold when the provider itself reports cumulative usage across a streamed response and the instrumentation also accumulates — that is a distinct double-counting path (provider-cumulative × local-cumulative) that requires knowing the provider's usage semantics per streaming chunk. ## Decision Boundary The decision boundary is: **do you trust `gen_ai.*` attributes as event-truth, or as span-truth?** - If attributes are **event-truth** (captured at the event, immutable after), you may use them for cost attribution, retry-rate analysis, and per-call token profiling directly. - If attributes are **span-truth** (flushed at span close from a mutable context), they are valid only for *aggregate* questions ("how many tokens did this turn consume") and invalid for *per-call* questions ("did this specific model call retry"). Using span-truth for per-call analysis is the boundary violation. The operational rule: **any `gen_ai.usage.*` attribute that shares a span with more than one `gen_ai.request` event is an aggregate and must be treated as such.** Detect the sharing by counting distinct model-response boundaries (or `attempt` tags) within the span; if count > 1 and the attribute is not explicitly named as an aggregate, the span is mislabeled and downstream cost/retry analytics will silently inherit the bias. A second boundary: **tool-call attribute uniqueness.** `gen_ai.tool.call.id` is assumed unique per span. If retries reuse IDs, the invariant "one ID = one invocation" breaks, and any join from tool-call telemetry to tool-backend logs will fan out (one ID matching two backend records). The boundary is enforced by minting IDs per attempt, not per step. ## Operational Effect The downstream effects compound because the corrupted telemetry is *plausible*: - **Cost attribution drifts multiplicatively** on exactly the retry-prone paths — the paths you most want to measure. The bias is concentrated where reliability is worst, so cost dashboards understate the cost of unreliable tools precisely when reliability is degrading. - **Retry-rate metrics read as zero**, because the retry is folded into a single span with a single (inflated) token count rather than appearing as two attempts. You cannot see the retry in the trace; you can only infer it from the token/duration mismatch. - **Tool-call joins fan out**, so per-tool error-rate computed by joining span `tool.call.id` to backend logs double-counts successes (the succeeded attempt) and drops the failed one, biasing error rates *downward* — the opposite of the safe direction. The guardrail is a **capture-point invariant**: token and tool-call attributes must be written at the event boundary and made immutable before the span closes; retries must mint attempt-scoped IDs and child spans; and a periodic reconciliation against an independent ground truth (provider ledger, or a latency-derived token-rate bound) must run as a *first-class* check, because no schema validator will catch a well-formed lie. ```python class TelemetryDesyncError(RuntimeError): """Raised when a GenAI span's attributes are internally inconsistent with the event boundaries the span claims to describe.""" pass def validate_agent_span(span: dict) -> None: attrs = span.get("attributes", {}) attempts = attrs.get("gen_ai.request.attempt_count", 1) tool_ids = attrs.get("gen_ai.tool.call.ids", []) out_tokens = attrs.get("gen_ai.usage.output_tokens", 0) duration_s = span.get("duration_s", 0.0) # Invariant 1: tool-call IDs must be unique within a span. if len(tool_ids) != len(set(tool_ids)): raise TelemetryDesyncError( f"duplicate gen_ai.tool.call.id within span {span.get('id')}: " f"{tool_ids} — retry reused step-scoped ID instead of attempt-scoped ID" ) # Invariant 2: token count must be consistent with wall-clock at a # bounded tokens/sec ceiling. If attempts > 1, the span must have # emitted child spans; an aggregate token count on a single-duration # span is the double-counting signature. if attempts > 1 and not span.get("child_spans"): raise TelemetryDesyncError( f"span {span.get('id')} reports {attempts} attempts and " f"{out_tokens} output tokens but has no per-attempt child spans; " f"token attribute is an unlabeled aggregate" ) # Invariant 3: token/duration plausibility bound (independent ground truth proxy). max_plausible = duration_s * attrs.get("tokens_per_sec_ceiling", 200.0) * attempts if out_tokens > max_plausible: raise TelemetryDesyncError( f"span {span.get('id')} claims {out_tokens} output tokens in " f"{duration_s}s across {attempts} attempts; exceeds ceiling " f"{max_plausible:.0f} — accumulator re-entry suspected" ) ```