# Why does an instance miscount tokens when OpenTelemetry GenAI span accounting diverges across a resumed agent turn **Date of Record:** 2026 November 29 **Scope:** Applies to agents that emit OTel `gen_ai.*` spans per LLM call and tool call, and that can be suspended and resumed (checkpoint/restore, human-in-the-loop pause, or worker migration) mid-turn. Does not apply to single-shot, non-resumable invocations where one span tree maps one-to-one to one process lifetime. ## Core Distinction There are two different things an OTel GenAI span tree can mean, and they are routinely conflated: 1. **The logical turn** — one user-visible agent action, which may span multiple LLM calls, tool calls, and *process lifetimes*. 2. **The physical span tree** — a parent/child DAG rooted at a trace that is only valid within a single process context that owns the `TracerProvider` and its `SpanProcessor`/exporter queue. The invariant that most implementations silently assume is: *the root span of a turn is open for the entire duration of that turn, in the same process, so children accumulate into one tree and `gen_ai.usage.input_tokens` / `output_tokens` sum correctly at the root.* The moment a turn is checkpointed and resumed in a new process, the resumed instance opens a **new root span** with a new `trace_id` (or reuses the `trace_id` but with a fresh root), and the token accounting for the logical turn is now split across two trees that no downstream consumer reconciles. The result is not a crash — it is a *silent* under-count, and it is non-obvious because every individual span is individually correct. ## What Was Observed A three-step agent turn (plan → tool call → summarize) was instrumented per the GenAI conventions: each LLM call gets a `gen_ai.chat` span with `gen_ai.usage.input_tokens` and `gen_ai.usage.output_tokens`; the tool call gets a `gen_ai.tool` span; the turn gets a parent span. The agent was configured to pause after the tool call for a human approval gate, serialize its state, and resume in a fresh worker. The observed sequence on resume: - The pre-pause worker emitted root span `R1` (trace `T1`) with children `plan` (input 1,204 / output 312) and `tool` (no tokens). `R1` was exported and closed when the worker shut down. Its `gen_ai.usage.*` attributes, if aggregated by a naive collector that sums *root* spans, report 1,204/312 for the turn. - The post-resume worker reconstructed state but had no live parent context. It emitted a **new root** `R2` (trace `T2`) with child `summarize` (input 2,890 / output 470). `R2` reports 2,890/470. - The dashboard summed per-root spans and reported **2,890 input tokens** for the turn. The true logical turn consumed **4,094** input tokens (1,204 + 2,890). The 1,204 was invisible because it lived only on `R1`, which the dashboard treated as a *separate* turn. Two secondary effects compounded it. First, the resumed worker often re-sends the conversation history to the model to reconstruct context, so the `summarize` call's `input_tokens` already *includes* tokens that were counted on the pre-pause `plan` call — meaning naive summation across the two trees **double-counts** the replayed history while the per-root view **undercounts** the turn. Neither number is the cost of the logical turn. Second, `gen_ai.usage` attributes are emitted per-span by the model client, and the conventions do not require the *root* span to carry an aggregate — so there is no span that claims to hold the turn total. The aggregation is left to the consumer, who has no way to know `R1` and `R2` belong together. ## Condition of Validity The miscount is bounded and predictable only under this condition: **the resumed span tree carries a link back to the pre-pause trace.** The GenAI conventions permit this via span links (`SpanLink` to the pre-pause root's `SpanContext`) or via a turn-scoped attribute such as `gen_ai.conversation.id` / a custom `agent.turn.id` that is stable across the checkpoint. If the state serializer persists *only* the message history and tool results — the common case, because that is what the model needs — and drops the `SpanContext`, the resumed worker has no way to re-parent and no way to link. The two trees are then genuinely disconnected, and no downstream reconciliation is possible without an out-of-band join key. The invariant that must hold for correct accounting is therefore: *turn-scoped identity (conversation/turn id) must survive the checkpoint independently of span context, because span context is process-local and is destroyed by serialization.* Token totals for a turn are then computed by grouping spans on that identity and **deduplicating replayed history** — not by summing root spans and not by summing all `gen_ai.chat` spans without regard to whether a call re-sent prior context. ## Decision Boundary The boundary is whether the resume path treated the checkpoint as a *new turn* or a *continuation of the same turn*: - If the checkpoint boundary is also a **turn boundary** (the agent finished a user-visible action and the resume starts a new request), then opening a new root is *correct*, and per-root summation is *correct*. The bug only appears when the checkpoint falls **mid-turn** — between a tool call and its consumption, or after a plan but before execution. - If the checkpoint is mid-turn, the resumed instance must either (a) re-parent its root under the pre-pause `SpanContext` if the exporter still holds it (rare — usually the pre-pause worker has flushed and exited), or (b) emit a root with an explicit link and a stable `agent.turn.id`, and the accounting pipeline must group on `agent.turn.id` and subtract replayed history. The non-obvious failure is that **both paths produce valid-looking spans**. There is no schema violation, no missing required attribute, no exporter error. The GenAI conventions are satisfied span-by-span. The divergence is purely in the *semantics of aggregation*, and it is invisible to any validator that checks spans individually. ## Operational Effect The operational consequence is that cost attribution, budget enforcement, and rate-limit accounting all read the wrong number, and they read it *confidently*. A token-budget guard that sums root-span `input_tokens` will under-count mid-turn resumes and let a turn exceed its budget by exactly the pre-pause consumption — which is unbounded if the agent resumes many times (each resume adds a root whose pre-pause portion is dropped). Conversely, a guard that sums all `gen_ai.chat` spans will over-count by the replayed history on every resume, and the over-count grows with conversation length, so long conversations with frequent pauses get throttled early while short ones sail through. Neither guard fails loudly. The fix is architectural, not a patch: persist a turn-scoped identity alongside the message state, emit span links from resumed roots, and make the accounting layer group-by-turn-id with replay deduplication rather than sum-by-root. The span tree is a *process-local artifact*; the turn is a *logical entity that outlives it*, and the two must be joined on a key that survives serialization. ```python import hashlib from dataclasses import dataclass, field from typing import Optional class TurnAccountingError(RuntimeError): """Raised when a resumed agent turn cannot be reconciled to a single token total.""" pass @dataclass class GenAISpan: span_id: str trace_id: str parent_span_id: Optional[str] turn_id: Optional[str] input_tokens: int = 0 output_tokens: int = 0 replayed_history_tokens: int = 0 # tokens re-sent to reconstruct context on resume is_root: bool = False @dataclass class TurnLedger: spans: list[GenAISpan] = field(default_factory=list) def add(self, span: GenAISpan) -> None: self.spans.append(span) def reconcile_turn(self, turn_id: str) -> tuple[int, int]: """Return (true_input, true_output) for a logical turn. Requires every span in the turn to carry the same turn_id. Sums all gen_ai.chat spans in the turn and subtracts replayed history so that context re-sent on resume is not double-counted. """ turn_spans = [s for s in self.spans if s.turn_id == turn_id] if not turn_spans: raise TurnAccountingError(f"no spans found for turn_id={turn_id!r}") roots = [s for s in turn_spans if s.is_root] if len(roots) > 1: # Multiple roots for one turn means a mid-turn resume produced a # disconnected tree. This is only safe if the turn_id is shared; # otherwise the pre-pause consumption is unrecoverable. pass true_input = sum(s.input_tokens for s in turn_spans) - sum( s.replayed_history_tokens for s in turn_spans ) true_output = sum(s.output_tokens for s in turn_spans) if true_input < 0: raise TurnAccountingError( f"replay deduction exceeded reported input for turn {turn_id!r}; " "replayed_history_tokens likely mis-attributed across spans" ) return true_input, true_output def emit_resumed_root( ledger: TurnLedger, pre_pause_trace_id: str, turn_id: str, new_trace_id: str, ) -> GenAISpan: """Emit a root for a resumed worker, linking back to the pre-pause trace. Refuses to emit if the turn_id is absent, because an unlinked root cannot be reconciled and will silently under-count the logical turn. """ if not turn_id: raise TurnAccountingError( "resumed root requires a stable turn_id; without it the pre-pause " "span tree cannot be joined and token totals will diverge" ) span = GenAISpan( span_id=hashlib.sha1(f"{new_trace_id}:root".encode()).hexdigest()[:16], trace_id=new_trace_id, parent_span_id=None, turn_id=turn_id, is_root=True, ) ledger.add(span) return span ```