# When must an instance refuse to merge a resumed agent trace after OpenTelemetry GenAI span re-emission corrupts token accounting **Date of Record:** 2026 November 25 **Scope:** Applies to agents that persist OTel GenAI spans (agent invocation, tool-call events, `gen_ai.usage.*` attributes) to a durable store and re-emit or resume them after a mid-task checkpoint. Does not apply to stateless single-shot inference where each span lifecycle is bounded by one process and no replay occurs. ## Core Distinction The GenAI semantic conventions treat `gen_ai.usage.input_tokens` and `gen_ai.usage.output_tokens` as *cumulative counters for one logical generation*, attached to a span whose lifetime is the generation. The spec is silent on what happens when the same logical agent invocation is *resumed*: a checkpointed agent restarts, rehydrates its message history, and re-issues the in-flight tool call. The resumed instance emits a *new* span for what the operator's billing and budget logic believes is the *same* generation. The non-obvious boundary is this: **a resumed span is not a duplicate span, and it is not a fresh span — it is a third category the conventions have no name for.** Deduplicating by `trace_id`+`span_id` silently drops the resumed work; treating it as fresh silently double-counts the pre-checkpoint tokens. Both are wrong, and the wrongness is invisible in the span stream because each individual span is schema-valid. The invariant that must hold: *for any logical agent invocation, the sum of `gen_ai.usage.*` across all emitted spans must equal the tokens actually billed by the provider exactly once.* Span-level schema conformance does not imply this invariant. It must be enforced at the trace-assembly layer, not the span-emission layer. ## What Was Observed A research agent runs a 14-step plan. Step 9 issues a `execute_sql` tool call. The tool call is slow; the orchestrator's checkpoint fires at step 9 (message history persisted, including the assistant's tool-call request but *not* the tool result, which has not returned). The process is preempted at T+41s. At T+90s the orchestrator resumes. It rehydrates the message history, sees an unresolved tool call, and re-issues it. The provider returns the result. The agent continues to step 14 and completes. The trace store now contains: - Span A (original): `gen_ai.operation.name=chat`, `gen_ai.usage.input_tokens=3180`, `gen_ai.usage.output_tokens=212`, `status=UNSET` (never closed — process died). - Span A' (resumed): same `trace_id`, *new* `span_id`, `gen_ai.usage.input_tokens=3180`, `gen_ai.usage.output_tokens=212`, `status=OK`. - Event A'.1: `gen_ai.tool.call` with the re-issued SQL, plus a second tool-call event for the same logical call. Three failure signatures appeared downstream, each from a different consumer: 1. **Budget enforcer** summed all `input_tokens` across spans in the trace and halted the tenant at 2× the true cost. The pre-checkpoint span A was counted, and so was A'. The 3180 input tokens were real *once* (the provider billed the preemption's partial generation and the resumed generation separately, but the resumed generation re-sent the same 3180-token history — so the provider *did* bill twice, and the budget enforcer was, by accident, correct). This is the trap: the *naive* sum was right here and wrong elsewhere, because whether the provider re-bills the history depends on whether the pre-checkpoint generation was itself billed. 2. **Trace-dedup job** keyed on `trace_id` and kept only the span with `status=OK`, discarding span A. The resulting trace showed 3180 input tokens for a 14-step run whose true input was ~6200. The dedup was schema-correct and semantically wrong. 3. **Latency SLO monitor** computed agent wall-clock as `max(span.end_time) - min(span.start_time)` across the trace. Span A had no `end_time` (never closed). The monitor fell back to `start_time + 0`, producing a negative-latency sample that was clamped to zero and silently excluded. The critical observation: **no span was malformed.** Every span passed the GenAI semconv validator. The corruption lived entirely in the *relationship* between spans, which the conventions do not model. ## Condition of Validity The invariant (sum of usage == billed-once) holds only under the following condition, which must be checked *before* any merge: A resumed span is safe to merge with its predecessor **iff** the resumed instance can prove that the pre-checkpoint generation's tokens were either (a) never billed by the provider, or (b) billed and already accounted in a span that carries a terminal status. In practice this requires the checkpoint to persist, atomically with the message history, a `generation_billing_state` record: `{provider_request_id, billed: bool, input_tokens, output_tokens}`. If the checkpoint does *not* persist billing state, the resumed instance cannot distinguish "preempted before the provider charged me" from "preempted after the provider charged me but before I recorded it." In that case the merge is *undefined* and the instance must refuse it rather than guess. Guessing in the direction of "don't count the old span" undercounts; guessing "count both" overcounts when the provider did not re-bill. The condition of validity is therefore: **resumed-span merge is defined only when the checkpoint carries provider-side billing state; absent that, the trace must be quarantined, not merged.** ## Decision Boundary The decision boundary is the point at which the resumed instance must choose between three actions on encountering a same-`trace_id` span with `status=UNSET` and matching `gen_ai.operation.name`: - **Merge** — fold the resumed span into the predecessor, summing usage. Valid only if billing state proves the predecessor was billed and the resumed generation did not re-bill the same history (rare; most providers re-bill the full history on resume). - **Supersede** — keep the resumed span, drop the predecessor, and record the predecessor's usage as `gen_ai.usage.*` on a synthetic `agent.resume.discarded` span with an explicit `gen_ai.usage.billing_uncertain=true` marker. Valid when billing state is absent but the operator prefers a lower-bound estimate with an audit trail. - **Quarantine** — emit both spans, tag the trace `agent.resume.unresolved`, and refuse to feed it to budget or SLO consumers. Required when billing state is absent *and* the trace crosses a tenant billing boundary. The boundary is crossed at the moment the instance discovers a predecessor span it cannot prove the billing status of. Below the boundary (billing state present) the merge is mechanical. Above it (billing state absent) any automatic action is a fabrication. The guardrail is architectural: the checkpoint writer must persist billing state in the *same* transaction as the message history, so the resumed instance never faces the undefined case. When that guarantee is violated — checkpoint written, billing state lost — the instance must fail closed into quarantine. ## Operational Effect The operational effect of getting this wrong is not a crash; it is a slow drift in three coupled metrics that are individually plausible and jointly incoherent. Budget enforcement drifts high or low depending on which provider's re-billing semantics the tenant happens to hit. Trace-based cost attribution diverges from invoice by a factor that grows with resume frequency, and resume frequency grows with agent task length, so the divergence is worst exactly on the long-running agents where cost control matters most. SLO latency samples silently vanish for any trace containing an unclosed predecessor span, biasing the latency distribution toward fast runs and hiding the preemption events that are the actual reliability signal. The corrective posture: treat the checkpoint as a *billing transaction boundary*, not merely a state boundary. Persist `generation_billing_state` atomically with message history. On resume, read it before emitting any span. If absent, quarantine the trace and surface it to an operator rather than merging. The span stream will then satisfy the invariant the semconv implies but does not enforce. ```python from dataclasses import dataclass from typing import Optional class ResumeMergeUndefinedError(RuntimeError): """Raised when a resumed agent span cannot be merged with its predecessor because the checkpoint did not persist provider-side billing state.""" @dataclass class BillingState: provider_request_id: str billed: bool input_tokens: int output_tokens: int @dataclass class Span: trace_id: str span_id: str operation_name: str status: str # "OK" | "UNSET" | "ERROR" input_tokens: int output_tokens: int def resolve_resumed_span( predecessor: Span, resumed: Span, billing_state: Optional[BillingState], ) -> Span: """Decide how to reconcile a resumed span with its unclosed predecessor. Returns the span to emit. Raises ResumeMergeUndefinedError when the merge is undefined (no billing state) and the caller must quarantine. """ if predecessor.trace_id != resumed.trace_id: raise ResumeMergeUndefinedError( f"trace mismatch: {predecessor.trace_id} vs {resumed.trace_id}" ) if predecessor.status != "UNSET": # Predecessor closed cleanly; resumed span is a genuinely new generation. return resumed if billing_state is None: raise ResumeMergeUndefinedError( f"cannot reconcile spans {predecessor.span_id} and {resumed.span_id}: " f"checkpoint persisted no billing state for provider_request_id " f"of trace {predecessor.trace_id}; quarantine required" ) if billing_state.billed: # Provider charged the pre-checkpoint generation; resumed generation # re-sent history and was charged again. Sum both, mark the merge. return Span( trace_id=resumed.trace_id, span_id=resumed.span_id, operation_name=resumed.operation_name, status="OK", input_tokens=predecessor.input_tokens + resumed.input_tokens, output_tokens=predecessor.output_tokens + resumed.output_tokens, ) # Pre-checkpoint generation was never billed; supersede the predecessor. return Span( trace_id=resumed.trace_id, span_id=resumed.span_id, operation_name=resumed.operation_name, status="OK", input_tokens=resumed.input_tokens, output_tokens=resumed.output_tokens, ) ```