# What structural signals indicate token-accounting drift when OpenTelemetry GenAI spans are emitted from resumed agent checkpoints **Date of Record:** 2026 November 21 **Scope:** Applies to autonomous agents that emit OpenTelemetry GenAI semantic-convention spans (`gen_ai.*`) across a checkpoint/resume boundary mid-task, where the same logical invocation is split across two or more process lifetimes. Does not apply to single-shot stateless inference calls or to spans emitted entirely within one uninterrupted process lifetime. ## Core Distinction The OpenTelemetry GenAI semantic conventions treat `gen_ai.usage.input_tokens` and `gen_ai.usage.output_tokens` as attributes of a single span representing one model invocation. This is correct when a span's lifetime equals a model call's lifetime. It breaks when an agent checkpoints mid-invocation: the pre-checkpoint process emits a span for the partial context it assembled and the tokens it already consumed, then dies. The resumed process reconstructs context from serialized state, re-emits a *new* span for what it believes is the same logical step, and reports the *reconstructed* prompt's token count—which is larger, because rehydration adds system-prompt scaffolding, memory summaries, and tool-result replay that the original process never counted. The failure is not that tokens are miscounted. It is that the aggregation invariant `sum(span.usage) == sum(billed_tokens)` holds per-span but breaks per-trace, because the resume boundary duplicates the shared prefix. The structural signal is a trace whose `gen_ai.usage.input_tokens` sum exceeds the provider's billing reconciliation by exactly the size of the rehydrated prefix, repeated once per resume. ## What Was Observed A planner agent running a 14-step research task checkpointed after step 9 because the host evicted the pod. On resume, the orchestrator deserialized the episodic buffer, re-injected the system prompt, the 8 completed tool results, and a rolling summary of steps 1–8. It then emitted `gen_ai.chat` span `step-9-resume` with `gen_ai.usage.input_tokens=18,442`. The pre-eviction process had already emitted `step-9-precheckpoint` with `gen_ai.usage.input_tokens=11,908` for the *same logical step*, covering the same 8 tool results plus the system prompt. The two spans shared no parent-child link—the resumed process had no access to the dead process's span context, so it started a fresh trace with a new `trace_id`. Observed structural signals in the exported telemetry: - Two spans with identical `gen_ai.operation.name=chat` and near-identical `gen_ai.request.model`, but different `trace_id` values, whose `gen_ai.prompt` message arrays share a long common prefix (the 8 tool results) offset by a rehydration delta. - `gen_ai.usage.input_tokens` on the resumed span exceeding the pre-checkpoint span by a constant equal to the rehydration scaffold size (system prompt + summary + serialization framing), not by the new user turn. - A `service.instance.id` change between the two spans with no `gen_ai.agent.checkpoint_id` attribute to correlate them. - Billing reconciliation showing 29,412 input tokens charged for step 9 across two provider calls, while the trace-level span sum for that step reports 30,350—the 938-token gap being the rehydrated prefix counted twice. The agent itself behaved correctly; it produced a valid step-9 result. The defect was purely in the observability contract: the semantic conventions have no attribute expressing "this span is a re-derivation of a prior partial span," so downstream cost dashboards double-counted and the per-step token budget guardrail (which reads span sums) tripped a false alarm at step 11. ## Condition of Validity The invariant that breaks is: *for a given logical agent step, exactly one span carries the full input-token accounting, and no span carries tokens for context that a sibling span also accounts for.* This holds only when span lifetime ⊆ process lifetime ⊆ logical-step lifetime. It is violated precisely when a checkpoint occurs after context assembly but before the model call completes, AND the resume path reconstructs context rather than resuming the in-flight provider request. Two structural preconditions make it observable: 1. The resumed process cannot attach to the dead process's span context (no W3C `traceparent` persisted in the checkpoint), so it cannot mark the new span as a retry of the old. 2. Context rehydration is non-idempotent with respect to token count—re-serializing a memory buffer produces a different token count than the original in-memory representation, because summary boundaries, message ordering, and tool-result formatting differ between live and serialized forms. If either precondition fails—if span context is checkpointed and restored, or if rehydration is byte-identical—the double-count collapses and the invariant holds. ## Decision Boundary The boundary is whether the checkpoint serializes *span context* alongside agent state. If it does, the resumed process opens a child span of the pre-checkpoint span and sets `gen_ai.usage.input_tokens` only for the incremental rehydration delta, attributing the shared prefix to the parent. If it does not, the resumed process must emit a span with an explicit `gen_ai.agent.checkpoint_resume=true` marker and a `gen_ai.agent.resumed_from_step` attribute, and downstream aggregation must deduplicate by treating the resumed span's input tokens as *replacing* rather than *adding to* the pre-checkpoint span's. The guardrail is a reconciliation check at export time: for any `trace_id` group containing a span marked as a resume, assert that the union of `gen_ai.prompt` message prefixes across sibling spans has no duplicated segment whose token length exceeds a threshold (say, 5% of the smaller span's input tokens). A duplicate prefix above threshold means the resume path is re-accounting shared context. ## Operational Effect Without the marker, cost dashboards over-report by (rehydration_delta × resume_count) per task, and token-budget guardrails that read span sums fire spuriously on long tasks with frequent evictions—the exact tasks where eviction is most likely. The agent's own reasoning is unaffected, but the observability layer's budget signal becomes adversarial: it degrades most under the conditions it exists to protect against. The fix is to make the resume boundary a first-class span relationship, not to suppress the duplicate span, because the duplicate span carries real information about rehydration cost that is otherwise invisible. ```python from dataclasses import dataclass from typing import Sequence class TokenAccountingDriftError(RuntimeError): """Raised when resumed GenAI spans double-count a rehydrated context prefix.""" @dataclass class GenAISpan: trace_id: str span_id: str operation: str input_tokens: int prompt_prefix_tokens: int checkpoint_resume: bool = False resumed_from_step: str | None = None def reconcile_trace(spans: Sequence[GenAISpan], drift_threshold: float = 0.05) -> int: """Return corrected input-token total for a trace, or raise on undedupable drift.""" by_trace: dict[str, list[GenAISpan]] = {} for s in spans: by_trace.setdefault(s.trace_id, []).append(s) total = 0 for trace_id, group in by_trace.items(): chat_spans = [s for s in group if s.operation == "chat"] resumed = [s for s in chat_spans if s.checkpoint_resume] if not resumed: total += sum(s.input_tokens for s in chat_spans) continue for r in resumed: if r.resumed_from_step is None: raise TokenAccountingDriftError( f"resumed span {r.span_id} in trace {trace_id} lacks resumed_from_step; " f"cannot attribute rehydrated prefix, input_tokens={r.input_tokens}" ) siblings = [s for s in chat_spans if s is not r] shared = max((s.prompt_prefix_tokens for s in siblings), default=0) if shared / max(r.input_tokens, 1) > drift_threshold: overlap = min(shared, r.input_tokens) total += r.input_tokens - overlap else: total += r.input_tokens total += sum(s.input_tokens for s in chat_spans if not s.checkpoint_resume) return total ```