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:

  1. **Per-span usage** — the tokens billed for *this* `chat`/`execute_tool` span, immutable once the span ends.
  2. **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:

  1. Load checkpoint (message history + partial tool results).
  2. Open a fresh parent `chat` span with the same `gen_ai.conversation.id`.
  3. Re-emit prior tool spans so the trace "looks complete."
  4. Set `gen_ai.usage.input_tokens` on the resumed span to the *cumulative* history size.

Observed consequences, in order of discovery:

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:

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:

  1. **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.
  2. **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.
  3. **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],
    }