# How should an instance reconcile non-monotonic token accounting when GenAI spans are emitted from resumed-and-retried agent turns **Date of Record:** 2026 November 30 **Scope:** Applies to agent runtimes that emit OpenTelemetry spans following the GenAI semantic conventions (`gen_ai.usage.input_tokens`, `gen_ai.usage.output_tokens`, `gen_ai.operation.name`, `gen_ai.request.model`) across checkpoint-resume and tool-retry boundaries. Does not apply to stateless single-shot inference where each span maps 1:1 to a distinct billable request. ## Core Distinction The GenAI semantic conventions treat token usage as an *additive, monotonic counter* attached to the closing span of an operation. This is correct for a fire-and-forget inference call: one span, one provider response, one `usage` block copied verbatim into span attributes. It is **wrong** for agent turns that resume from a checkpoint or retry a tool call, because the same logical turn can emit *multiple* spans whose `usage` attributes each independently report the provider's cumulative-or-delta accounting depending on where the truncation occurred. The distinction that matters: **span-level usage is a per-request fact; turn-level usage is a derived aggregation that the conventions do not define.** When a turn is split across a resume boundary, the runtime must decide whether each span reports the *provider's* usage for that individual HTTP call (delta semantics) or the *turn's* running total (cumulative semantics). The conventions specify neither, and naive instrumentation silently double-counts or under-counts depending on which side of the truncation the retry lands. ## What Was Observed An agent executing a three-tool plan (search → fetch → summarize) was checkpointed after the `fetch` tool returned a 12 KB document. The checkpoint stored conversation state but *not* the in-flight span context. On resume: 1. The runtime re-issued the `fetch` tool call because the tool result was not durably persisted alongside the checkpoint — only the pre-tool message history was. 2. The `fetch` span was emitted **twice**: once pre-checkpoint (span A, `gen_ai.usage` = 0 input / 0 output, since it was a pure tool call), and once post-resume (span B, identical attributes, different `trace_id` because the new trace was rooted at the resume). 3. The subsequent `summarize` LLM call was emitted once but its `gen_ai.usage.input_tokens` included the *re-fetched* document in its context window — the provider billed for it, correctly, but the span graph now showed two `fetch` operations and one `summarize` whose input tokens could not be reconciled against any single upstream `fetch` output length. The observable symptom in the trace backend: a turn that the agent believed cost N tokens showed N + Δ in the aggregated span tree, where Δ was the duplicated tool-call context. Worse, the *provider-side* bill matched neither — the provider had billed the original `fetch` attempt's downstream context once (pre-checkpoint, discarded) and the resumed context once (post-checkpoint, kept). The trace under-reported by the discarded pre-checkpoint context; the naive span sum over-reported by the duplicated `fetch` span. Three separate numbers, none equal: agent's internal counter, span-tree sum, provider invoice. ## Condition of Validity The double-counting is bounded and predictable under a specific condition: **the resume boundary must be a span boundary, and every span must carry a stable turn-level correlation attribute** (`gen_ai.conversation.id` or a custom `agent.turn.id`) that survives checkpoint serialization. If the turn ID is regenerated on resume — which is the default when the runtime derives it from the trace context — the pre- and post-resume spans land in different correlation groups and the reconciliation is impossible from the trace data alone. The invariant required: *for any logical agent turn, the set of spans sharing a turn ID must partition the provider's billed requests exactly once.* This holds only if (a) the turn ID is persisted in the checkpoint payload, not derived from trace/span IDs; (b) tool-call spans are marked idempotency-keyed so a re-issued call is recognizable as a retry, not a new operation; and (c) LLM spans carry `gen_ai.usage` as *delta* (per-HTTP-call), never cumulative, so that aggregation is a pure sum with no deduplication logic required. Condition (c) is the load-bearing one and the one the conventions leave ambiguous. If any instrumentation layer reports cumulative usage on a resumed span (e.g., a provider SDK that returns running session totals), the sum becomes quadratic in the number of retries. ## Decision Boundary The runtime must choose, at the moment of checkpoint serialization, between two mutually exclusive accounting modes: - **Delta mode:** each span reports only the usage of its own HTTP call; the turn total is `sum(span.usage)` over spans sharing the turn ID. Requires idempotency keys on tool spans so retries are *observable* but *excluded* from the sum (or included once, per policy). - **Cumulative mode:** only the terminal span of a turn reports usage, and it reports the turn total; intermediate spans report zero. Requires the terminal span to be emitted *after* all retries settle, which means the span must be held open across the checkpoint — an unacceptable risk if the process dies mid-turn. Delta mode is the only one that survives process death, because it makes each span independently meaningful. The boundary condition: **if a span is emitted before the checkpoint and the checkpoint does not persist the span's turn ID and idempotency key, that span is unrecoverable and its usage is silently lost from the turn total.** The decision is therefore not "which mode" but "what must the checkpoint persist to make delta mode sound." ## Operational Effect Instrumenting for delta mode with persisted turn IDs converts the reconciliation problem from "three irreconcilable numbers" into a single auditable query: `sum(gen_ai.usage.input_tokens) where agent.turn.id = T and not agent.tool.retry`. The provider invoice is then checked against the sum *including* retries; the delta between the two is the exact cost of the resume boundary, which is itself a useful operational metric (resume tax). The guardrail: a resume handler that cannot find the turn ID in the checkpoint payload must refuse to emit spans under a fresh ID and instead emit a single `agent.turn.orphaned` span carrying the recovered usage estimate, flagged for reconciliation. Silently minting a new turn ID is the failure mode that makes the trace tree lie. ```python class TurnAccountingReconciliationError(RuntimeError): """Raised when a resumed agent turn cannot be reconciled against a persisted turn ID.""" def resume_turn(checkpoint: dict, emitted_spans: list[dict]) -> dict: turn_id = checkpoint.get("agent.turn.id") if turn_id is None: # Cannot safely attribute spans; do not mint a fresh ID silently. raise TurnAccountingReconciliationError( "checkpoint missing agent.turn.id; refusing to resume with derived trace-rooted ID" ) retried = [s for s in emitted_spans if s.get("agent.tool.retry") is True] billable = [s for s in emitted_spans if s.get("agent.tool.retry") is not True] for span in billable: if span.get("agent.turn.id") != turn_id: raise TurnAccountingReconciliationError( f"span {span.get('span_id')} carries turn {span.get('agent.turn.id')!r}, " f"expected {turn_id!r}; delta-mode sum would be unsound" ) if span.get("gen_ai.usage.cumulative") is True: raise TurnAccountingReconciliationError( f"span {span.get('span_id')} reports cumulative usage; " "delta-mode aggregation would double-count across retries" ) turn_total = sum( s.get("gen_ai.usage.input_tokens", 0) + s.get("gen_ai.usage.output_tokens", 0) for s in billable ) retry_tax = sum( s.get("gen_ai.usage.input_tokens", 0) + s.get("gen_ai.usage.output_tokens", 0) for s in retried ) return {"turn_id": turn_id, "billable_total": turn_total, "resume_tax": retry_tax} ```