When must an instance reconcile token accounting across a resumed agent span, and why the OpenTelemetry GenAI convention silently double-counts
**Date of Record:** 2026 December 2 **Scope:** Applies to agents that emit OpenTelemetry GenAI spans (`gen_ai.*`) across a checkpoint/resume boundary or an MCP/A2A handoff where the receiving instance re-emits or re-parents an in-flight span. Does not apply to single-shot, single-process invocations that never cross a serialization boundary.
Core Distinction
The GenAI semantic conventions define `gen_ai.usage.input_tokens` and `gen_ai.usage.output_tokens` as attributes on the *span that produced the completion* — they are cumulative counters describing one model invocation, not a running ledger. The failure mode here is not "wrong token count." It is a **semantic collision between the attribute's per-span meaning and the aggregator's per-trace meaning** when a span is resumed, re-emitted, or re-parented across an instance boundary.
Two things get conflated that must not be:
- **Per-span usage** — the tokens billed for *this* `chat`/`execute_tool` span, immutable once the span ends.
- **Trace-level accounting** — what a downstream collector sums to compute cost, quota, and loop-guard thresholds.
When an agent checkpoints mid-turn and a *new* instance resumes, the naive correct-looking move is to re-emit the span with the accumulated usage so the resumed span "carries" the full cost. This is where the invariant breaks: the original span was already exported (or buffered) before the crash, so the collector now sees the same tokens twice — once on the truncated original, once on the resumed continuation. The GenAI convention has no `gen_ai.usage.is_continuation` discriminator, so the aggregator cannot deduplicate.
What Was Observed
A tool-using agent (`execute_tool` spans nested under a `chat` span) hit a token-budget guard at ~70% of a 128k window during a long multi-step turn. The orchestrator checkpointed state and the process was rescheduled onto a new instance. The resume path followed the conventional pattern:
- Load checkpoint (message history + partial tool results).
- Open a fresh parent `chat` span with the same `gen_ai.conversation.id`.
- Re-emit prior tool spans so the trace "looks complete."
- Set `gen_ai.usage.input_tokens` on the resumed span to the *cumulative* history size.
Observed consequences, in order of discovery:
- **Double-count:** The pre-crash `chat` span had already flushed to the collector with `input_tokens=41,200`. The resumed span reported `input_tokens=41,900` (cumulative). The trace total read ~83k for a turn that consumed ~42k. The budget guard, keyed on trace-level sums, tripped a *second* time and aborted a turn that had 86k of headroom.
- **Orphaned tool events:** Re-emitted `execute_tool` spans carried the *original* `gen_ai.tool.call.id`, violating the convention's expectation that a call id maps to exactly one span. Downstream replay tooling flagged the duplicates as a verification discrepancy.
- **Clock skew in the span tree:** The resumed parent span's start timestamp was *after* its re-emitted children's end timestamps, producing a parent that ends before it begins from the collector's view. Trace UIs rendered it as a negative-duration gap.
The trigger condition is precise: **a span that was exported (or is export-eligible) before the checkpoint, whose logical work continues on another instance, and whose usage attributes are set cumulatively on the continuation.** Remove any one of those four and the failure does not occur — which is why it is invisible in single-instance testing.
Condition of Validity
The deduplication problem is only well-defined under the following invariant:
> **A token-usage attribute is valid only on a span whose `(trace_id, span_id)` pair was never exported before the current process began.** Continuation work MUST open a *new* span with a *new* span_id, set usage to *incremental* tokens consumed since resume, and link (not parent) to the checkpointed span via a `Span Link` carrying the original `span_id`.
Formally, for any trace, the collector's summed `gen_ai.usage.*` equals the true cost **iff** every span in the trace was emitted exactly once and every usage attribute is scoped to that span's own model calls. Re-emission violates exactly-once; cumulative usage violates per-span scoping. The convention provides `Span Links` (`opentelemetry.trace.Link`) and the `gen_ai.conversation.id` attribute precisely so continuation can be represented *without* re-emitting — but nothing in the spec forbids the re-emit pattern, and most resume templates do it anyway because it produces a prettier single-trace view.
The validity condition also requires that the checkpoint record the *exported* usage watermark: the token count already attributed to spans that have left the process. Without that watermark, the resuming instance cannot compute incremental usage and will either double-count (cumulative) or under-count (reset to zero, losing pre-crash cost). The watermark is the missing state that makes resume correct.
Decision Boundary
The boundary is whether the pre-crash span has crossed the export horizon. The agent must decide per-span:
- **Span not yet exported** (still in the batch processor's queue, process died before flush): safe to re-create with the same logical content and cumulative usage — the collector never saw it. But this is only knowable if the exporter's flush state is itself checkpointed, which it usually is not. Treat "unknown" as "exported."
- **Span exported** (flushed, or export-eligible and possibly flushed): MUST NOT re-emit. Open a continuation span, link to the original, set *incremental* usage, and record the pre-crash watermark in the checkpoint so the budget guard reads `watermark + incremental` rather than the trace sum.
- **Span re-parented across an A2A/MCP handoff**: the receiving instance owns a new `trace_id` unless the handoff explicitly propagates `traceparent`. If `traceparent` is propagated but usage is re-summed at the receiver, the same double-count recurs at the trust boundary between agents — and now two *different* principals are both billing the same tokens.
The decision is not "should I make the trace look complete." It is "has this span already been observed by the collector, and if so, what is the incremental delta I am allowed to attribute?" Completeness of the visual trace is subordinate to exactly-once accounting, because the budget guard, the cost ledger, and the loop detector all consume the aggregate, not the picture.
Operational Effect
Enforcing the invariant changes three things:
- **Resume cost is incremental, not cumulative.** The budget guard must be fed `checkpointed_watermark + sum(incremental usage on continuation spans)`. This requires the checkpoint to persist the watermark alongside message history — a field most agent state schemas omit entirely.
- **Trace topology becomes a DAG with links, not a re-emitted tree.** Continuation spans link to their predecessors. Trace UIs that assume strict parent-child will show a forest; that is correct and must be tolerated by replay tooling, which should follow links to reconstruct logical continuity.
- **The loop guard and the cost ledger share one source of truth.** When they diverge (guard reads trace sum, ledger reads per-span), a resumed agent can be simultaneously "over budget" and "under-billed" — the exact state observed. Reconciling them at the watermark is the guardrail.
The residual risk: an exporter that flushes *after* the checkpoint is written but *before* the crash produces a span the resuming instance believes was never exported. The watermark must therefore be written by the exporter's flush callback, not by the agent loop, or the invariant has a race window at the crash boundary.
from dataclasses import dataclass, field
class TokenAccountingReconciliationError(RuntimeError):
"""Raised when a resumed agent span would double-count exported token usage."""
@dataclass
class SpanUsage:
span_id: str
input_tokens: int
output_tokens: int
exported: bool
@dataclass
class Checkpoint:
conversation_id: str
exported_input_watermark: int = 0
exported_output_watermark: int = 0
prior_spans: list[SpanUsage] = field(default_factory=list)
def reconcile_resume(checkpoint: Checkpoint, continuation_input: int,
continuation_output: int, reemit_prior_spans: bool) -> dict:
"""
Enforce the exactly-once invariant: continuation usage must be incremental,
and spans already exported must not be re-emitted with cumulative usage.
"""
if reemit_prior_spans:
already_exported = [s for s in checkpoint.prior_spans if s.exported]
if already_exported:
ids = ", ".join(s.span_id for s in already_exported)
raise TokenAccountingReconciliationError(
f"Refusing to re-emit exported spans [{ids}] on resume of "
f"conversation {checkpoint.conversation_id!r}: this would "
f"double-count {sum(s.input_tokens for s in already_exported)} "
f"input tokens against the trace-level budget guard."
)
if continuation_input < 0 or continuation_output < 0:
raise TokenAccountingReconciliationError(
"Continuation usage must be a non-negative incremental delta, "
f"got input={continuation_input}, output={continuation_output}."
)
# Incremental attribution: watermark (already billed) + this span's delta.
return {
"trace_input_total": checkpoint.exported_input_watermark + continuation_input,
"trace_output_total": checkpoint.exported_output_watermark + continuation_output,
"continuation_span_input": continuation_input,
"continuation_span_output": continuation_output,
"link_to_span_ids": [s.span_id for s in checkpoint.prior_spans if s.exported],
}