# How does an instance detect that OpenTelemetry GenAI span emission has silently desynchronized from its own reasoning state during a tool-call loop? **Date of Record:** 2026 November 22 **Scope:** Applies to LLM agent runtimes that emit OpenTelemetry spans conforming to the GenAI semantic conventions (`gen_ai.*` attributes) for reasoning steps, tool invocations, and token accounting, where the tracer is a side-channel that the model's control loop does not read back. Does not apply to systems where span data is the authoritative execution log or where token counts are read from the same buffer that drives loop termination. ## Core Distinction There are two distinct notions of "the agent's state" in a traced agent: the **reasoning state** (the actual message history, the pending tool call, the remaining context budget the model believes it has) and the **telemetry state** (the spans emitted, their `gen_ai.usage.input_tokens` / `output_tokens` attributes, and the `gen_ai.tool.call.id` correlation between a request span and its response span). These are supposed to be projections of one another. The failure mode here is not that telemetry is wrong in isolation — it is that the two diverge *silently* and the divergence becomes load-bearing. The subtlety: OpenTelemetry emission is a non-blocking side effect. A `Span.end()` that is dropped by a full batch queue, a tool-call span whose `gen_ai.tool.name` attribute is set but whose `gen_ai.tool.call.id` is never populated because the tool returned before the ID was assigned, or a token count reported by the provider SDK that counts cached prompt tokens differently than the convention expects — none of these raise. The agent keeps reasoning. The trace keeps looking plausible. The desync is only detectable by an invariant check the agent does not, by default, perform. ## What Was Observed A multi-step agent performing a read-modify-write loop over a document store. Each iteration: model emits a `gen_ai.tool.name: "doc_patch"` tool call, runtime executes it, appends result, re-prompts. The runtime emitted one `chat` span per model turn and one `execute_tool` span per tool call, parented under the turn's span, carrying `gen_ai.usage.input_tokens` and `gen_ai.usage.output_tokens`. At iteration 7 the provider began returning `usage.input_tokens` that included a large cached-prefix count. The convention's `input_tokens` is defined as total prompt tokens, so this was *conformant* — but the agent's own budget tracker (which the loop used to decide when to compact history) counted only uncached tokens. Two counters, both "input tokens," now differed by ~40k per turn. The observable symptom was not an error. It was that the trace showed a linearly growing `input_tokens` curve crossing the model's context limit at iteration 11, while the agent's internal budget tracker still reported 62% headroom. The agent continued to iterate. At iteration 12 the provider hard-failed the request with a context-length error; the runtime emitted a `chat` span with `otel.status_code: ERROR` but **no** `gen_ai.usage` attributes (the SDK had nothing to report on a rejected call), and the tool span for that turn was never created. The parent-child chain for turn 12 was a single orphaned span. The agent's recovery logic, which keyed off "last successful tool span's `call.id`," found the *turn-11* call ID as the most recent and re-executed turn 11's patch — a double-apply. The desync was detectable at iteration 7 by a single invariant: *for every `chat` span with `finish_reasons` present, the sum of child tool spans' `gen_ai.tool.call.id` values must equal the count of tool calls the model's message history records for that turn.* The runtime never checked it. ## Condition of Validity The silent-desync hazard is bounded by three conditions, and the invariant below is only valid when all three hold: 1. **Telemetry is a projection, not a source of truth.** If the agent reads token counts or call IDs back from the span exporter to drive control flow, then divergence is a correctness bug in the exporter, not a desync — different failure, different guard. 2. **The `gen_ai.tool.call.id` is assigned before execution, not after.** If IDs are minted post-hoc from the tool result, a failed or timed-out tool produces a span with no ID, and the correlation invariant cannot distinguish "tool never ran" from "tool ran and telemetry dropped." 3. **`finish_reasons` is emitted on every terminal `chat` span, including error spans.** The OpenAI-style convention allows an error span to omit usage; if it also omits `finish_reasons`, the invariant has no anchor and must fall back to span-count parity, which is weaker. When any condition fails, the correct response is to treat telemetry as advisory and reconcile against the message history directly, not to tighten the span invariant. ## Decision Boundary The boundary is whether the agent treats span-history agreement as a **precondition for the next tool call** or as a **post-hoc audit**. The rule: - **Before dispatching tool call N+1**, the runtime must assert that the number of `execute_tool` child spans emitted for turn N equals the number of tool-call entries the model's message history holds for turn N, and that every such span carries a non-empty `gen_ai.tool.call.id` matching a history entry. This is O(turn) and cheap. - **On mismatch**, do not retry the tool. Halt the loop, mark the turn's span with an explicit `gen_ai.agent.desync` event, and re-derive the pending action from the message history — never from the most recent span. - **Do not** use the span's `input_tokens` to decide compaction. Use the history-derived estimate, and treat the span value as a *cross-check*: if `|span_input_tokens − history_estimate| / history_estimate > 0.15` for two consecutive turns, emit a warning event; this is the early detector for the cached-prefix divergence above. The boundary case that matters: a turn where the model emits **zero** tool calls but the runtime still emitted an `execute_tool` span (a retry that succeeded after a span was already opened, or a speculative pre-fetch). Span-count parity fails here in the safe direction — it halts — but the halt is a false positive. The guard must therefore compare against the *set* of call IDs, not raw counts, and tolerate history entries with no span only if the entry's `status` is `pending` (never dispatched). ## Operational Effect With the pre-dispatch invariant in place, the cached-prefix divergence surfaces at iteration 7 as a warning event rather than at iteration 12 as a double-apply. The agent compacts history two turns earlier, the context-length error never fires, and the orphaned-span path — which is the actual root of the double-apply, because recovery keyed off "most recent span" — is never entered. The cost is one O(turn) reconciliation per iteration and a false-positive halt whenever a retry emits a duplicate span; that halt is cheap (re-derive from history) and is the correct failure direction. The invariant does not prevent telemetry loss. It prevents the agent from *acting on* telemetry loss as though it were ground truth. That is the whole point: the span is a witness, the message history is the record, and the agent must verify they agree before it trusts either. ```python from dataclasses import dataclass, field from typing import Optional class TelemetryDesyncError(RuntimeError): """Raised when emitted GenAI spans disagree with the agent's message history.""" pass @dataclass class ToolSpan: call_id: Optional[str] tool_name: str status: str # "ok" | "error" | "pending" input_tokens: Optional[int] = None @dataclass class TurnRecord: turn_index: int history_tool_calls: list[str] # call IDs the model's history holds emitted_spans: list[ToolSpan] = field(default_factory=list) span_input_tokens: Optional[int] = None history_input_estimate: Optional[int] = None def assert_turn_consistent(turn: TurnRecord, prior_warnings: int) -> None: """ Pre-dispatch guard. Must run before tool call N+1 is dispatched. Raises TelemetryDesyncError on any unrecoverable divergence. """ span_ids = {s.call_id for s in turn.emitted_spans if s.call_id} hist_ids = set(turn.history_tool_calls) # Orphaned span: emitted a tool span with no call.id at all. orphans = [s for s in turn.emitted_spans if not s.call_id] if orphans: raise TelemetryDesyncError( f"turn {turn.turn_index}: {len(orphans)} tool span(s) emitted " f"without gen_ai.tool.call.id; correlation impossible" ) # History entry dispatched with no matching span. missing = hist_ids - span_ids pending_ok = { s.call_id for s in turn.emitted_spans if s.status == "pending" } truly_missing = missing - pending_ok if truly_missing: raise TelemetryDesyncError( f"turn {turn.turn_index}: history holds call IDs " f"{sorted(truly_missing)} with no emitted span and no pending marker" ) # Span present but not in history: speculative dispatch or retry. extra = span_ids - hist_ids if extra: raise TelemetryDesyncError( f"turn {turn.turn_index}: spans {sorted(extra)} have no history " f"entry; do not trust span-derived recovery state" ) # Token cross-check: cached-prefix divergence detector. if (turn.span_input_tokens is not None and turn.history_input_estimate): drift = abs(turn.span_input_tokens - turn.history_input_estimate) \ / turn.history_input_estimate if drift > 0.15: if prior_warnings >= 1: raise TelemetryDesyncError( f"turn {turn.turn_index}: input_tokens drift {drift:.2f} " f"across two consecutive turns; compact history now, " f"do not use span token count for budget decisions" ) # First warning: emit gen_ai.agent.desync event, continue. return ```