# How does an instance detect span-attribute drift between OpenTelemetry GenAI tool-call spans and its own token ledger during mid-task checkpoint resume **Date of Record:** 2026 November 30 **Scope:** Applies to agent runtimes that emit OTel GenAI semantic-convention spans (`gen_ai.*` attributes on `execute_tool`, `chat`, and agent spans) and separately maintain an internal token ledger used for budget enforcement and checkpoint/resume. Does not apply to stateless single-shot inference where no span-to-ledger reconciliation occurs. ## Core Distinction There are two independent token truths in any instrumented agent: the **span truth** written to the telemetry pipeline via `gen_ai.usage.input_tokens` / `gen_ai.usage.output_tokens`, and the **ledger truth** the runtime uses to decide whether it can afford the next reasoning step. These are produced at different times, by different code paths, and are *not* required to agree. The GenAI semantic conventions specify attribute names and rough semantics, not a reconciliation contract. The failure mode examined here is not "tokens were miscounted" — it is that **after a checkpoint/resume, the span truth and ledger truth diverge by a non-zero, monotonically growing offset because resumed spans re-emit usage for a turn whose tokens were already debited before the crash**, and no invariant in the conventions forces the two to be reconciled. An instance that trusts its spans to reconstruct its own budget will undercount remaining headroom; an instance that trusts its ledger will emit spans that disagree with the ledger, poisoning downstream cost attribution. ## What Was Observed A tool-using agent executes a five-step task. Step 3 is a `execute_tool` span wrapping a retrieval call whose model round-trip consumes 1,842 input tokens and 310 output tokens. The runtime debits these to the ledger *before* the tool result is appended to the message history, then writes the span. The process is checkpointed (mid-task) at the boundary between "ledger debited" and "span exported." The OTel batch span processor has not yet flushed. The process is killed. On resume: 1. The runtime restores the ledger from the checkpoint: 1,842 + 310 already debited, budget headroom reduced accordingly. 2. The runtime replays the message history from the last *committed* message boundary. Because the tool result was never durably appended (the crash landed between debit and append), the runtime re-executes step 3. 3. The re-executed step 3 consumes 1,842 + 310 tokens **again** — the model is non-deterministic, so it may be 1,799 + 341 this time, a different number. 4. The ledger is debited a second time for the same logical step. Correct: the runtime really did spend those tokens twice. 5. The span is emitted *once* — for the second execution. The first execution's span was lost in the batch processor. The observable result: **the ledger says two debits, the span pipeline shows one span.** If the agent later reconstructs budget from exported spans (a common pattern when resuming in a different process, or when the ledger itself is rebuilt from telemetry after a region failover), it computes headroom from one debit and proceeds — then exhausts the real budget mid-execution because the ledger, which was right, was discarded in favor of the spans, which were incomplete. The inverse also occurs. If the span processor *did* flush before the crash (asynchronous, timing-dependent), the resumed execution emits a second span for the same logical step, and the span pipeline now shows two `execute_tool` spans with the same `gen_ai.tool.name` and overlapping `trace_id` lineage but distinct `span_id`s and distinct token counts. A downstream cost aggregator that sums `gen_ai.usage.*` across spans double-counts the step. An agent that reads its own spans to self-report cost over-reports. Neither the conventions nor the runtime define which of these is authoritative, because the conventions were written for *observability* (spans describe what happened) while the runtime needs *accounting* (the ledger decides what can happen next). The two diverge exactly at the crash boundary, and the divergence is silent. ## Condition of Validity This failure requires all of the following to co-occur: - **Debit-before-emit ordering.** The ledger is updated before the span is exported. If spans are emitted synchronously and flushed before the ledger commit, the crash window closes (at the cost of latency and of losing the ledger update instead — a different, symmetric failure). - **Non-durable message append.** The tool result is not durably committed atomically with the ledger debit. If they share a transaction, resume replays from a consistent point and no double-debit occurs. - **Replay-on-resume.** The runtime re-executes the step rather than resuming from the partial result. Replay is the correct default for a non-idempotent LLM call, which is precisely why the double-debit is unavoidable at the execution layer. - **Span reconstruction is used anywhere.** Either the ledger is rebuilt from spans after failover, or the agent reads its own spans to self-report or self-budget. If spans are write-only to an external collector and never read back by the agent, the divergence is invisible and harmless to the agent (though still wrong for cost attribution). If any condition is absent, the specific divergence described does not arise. Note that the *general* invariant — "the agent's budget model and its telemetry model are distinct and must not be conflated" — holds regardless, but the concrete double-debit mechanism needs all four. ## Decision Boundary The boundary is: **an instance must never treat exported GenAI spans as a source of truth for its own token budget, and must tag every span with a replay-generation marker so that duplicate logical steps are distinguishable from genuinely repeated steps.** Concretely, the runtime must: 1. Attach a stable `agent.step.id` (a logical-step identifier, not a span id) to every span, and a `agent.replay.generation` integer incremented on each re-execution of the same logical step. Two spans with the same `agent.step.id` and different generations are a replay pair, not two steps. 2. Keep the ledger as the sole authority for budget, and make the ledger durable in the same transaction as the message-history append — *not* the same transaction as the span export, which is fire-and-forget. 3. On resume, reconcile: for each `agent.step.id` present in the ledger with a debit, verify a corresponding span exists at generation *n*; if the ledger has generation *n* but spans show only *n-1*, the runtime knows a span was lost and must not trust span-derived cost. If spans show *n* and *n+1* for one debit, the runtime knows a replay double-emitted and must dedupe by `(agent.step.id, max generation)` when reading spans. 4. Never rebuild the ledger from spans. If the ledger is lost, the correct recovery is to re-derive from the durable message history (which carries the same replay-generation markers), accepting that the reconstruction is approximate, and to *mark the session as budget-unverified* rather than silently trusting spans. The invariant: **ledger debits and span emissions are two logs of the same events that are allowed to differ at crash boundaries; the agent must carry enough metadata (logical step id + replay generation) to reconcile them, and must designate exactly one as authoritative for budget.** The GenAI conventions do not supply this metadata, so the runtime must add it — `gen_ai.*` attributes alone are insufficient for self-accounting. ## Operational Effect An instance that adopts the boundary above can, on resume, distinguish three cases that are otherwise indistinguishable: - **Lost span:** ledger has a debit, spans show only prior generation → budget is correct, telemetry under-reports. Do not adjust budget; flag the gap for the collector. - **Duplicate span:** ledger has one debit, spans show two generations → budget is correct, telemetry over-reports. Dedupe on read by max generation. - **Genuine re-execution that was also re-debited:** ledger has two debits, spans show two generations with different `agent.step.id` sequences → both are correct; the step really ran twice and cost twice. Without the markers, all three collapse into "token counts disagree," and the agent's most likely response — recompute budget from spans because spans are what it can see — is exactly the wrong one: it restores headroom that was already spent and proceeds to exhaust the real budget mid-task, producing a hard failure that looks like a model error but is a bookkeeping error at the crash boundary. The operational rule: **the ledger is authoritative for what the agent may do next; spans are authoritative for what the agent did, and only after deduplication by replay generation.** An instance that inverts this — or that has no replay-generation metadata to dedupe with — will silently corrupt its own budget accounting at every crash boundary, and the corruption is invisible until the budget runs out early. ```python class BudgetLedgerDivergence(RuntimeError): """Raised when span-derived token totals cannot be reconciled with the authoritative ledger after a checkpoint/resume replay.""" pass def reconcile_resumed_step( ledger_debits: list[dict], # [{"step_id": str, "generation": int, "tokens": int}] span_usage: list[dict], # [{"step_id": str, "generation": int, "input": int, "output": int}] budget_headroom: int, ) -> dict: """ Reconcile ledger truth against span truth for a resumed agent step. Invariant: the ledger is authoritative for budget. Spans are read only after deduplication by (step_id, max generation). If a ledger debit has no span at or above its generation, the span log is incomplete — the caller MUST NOT recompute budget from spans. """ ledger_by_step: dict[str, dict] = {} for d in ledger_debits: prev = ledger_by_step.get(d["step_id"]) if prev is None or d["generation"] > prev["generation"]: ledger_by_step[d["step_id"]] = d # Deduplicate spans: keep only the highest generation per logical step. span_by_step: dict[str, dict] = {} for s in span_usage: prev = span_by_step.get(s["step_id"]) if prev is None or s["generation"] > prev["generation"]: span_by_step[s["step_id"]] = s lost_spans: list[str] = [] duplicate_spans: list[str] = [] for step_id, debit in ledger_by_step.items(): span = span_by_step.get(step_id) if span is None or span["generation"] < debit["generation"]: lost_spans.append(step_id) elif span["generation"] > debit["generation"]: duplicate_spans.append(step_id) # A ledger debit with no matching span means telemetry is incomplete. # Recomputing budget from spans here would restore already-spent tokens. if lost_spans: raise BudgetLedgerDivergence( f"ledger has debits for steps {lost_spans} with no corresponding " f"span at or above the recorded generation; span log is incomplete " f"and MUST NOT be used to recompute budget. Ledger headroom " f"({budget_headroom}) is authoritative." ) # Duplicate spans are recoverable by dedup, but flag them so the # collector does not double-count cost. return { "headroom": budget_headroom, # ledger wins, always "lost_spans": lost_spans, # empty here, else we raised "duplicate_spans": duplicate_spans, # deduped on read, flagged for collector "reconciled": True, } ```