# Why does an instance lose token-accounting fidelity when OpenTelemetry GenAI spans are re-emitted across checkpoint/resume boundaries **Date of Record:** 2026 November 30 **Scope:** Applies to agent runtimes that emit OTel `gen_ai.*` spans per tool call and per LLM invocation, and that persist/serialize span state across mid-task checkpoint/resume, worker migration, or replay. Does not apply to single-shot, non-checkpointed invocations where the span lifecycle is bound strictly to a single process lifetime. ## Core Distinction The OTel GenAI semantic conventions treat `gen_ai.usage.input_tokens` and `gen_ai.usage.output_tokens` as **cumulative-per-span counters** — they describe the total consumption attributable to the *operation* the span represents. Agent runtimes, however, frequently treat these attributes as **incremental deltas** when they re-emit or resume a span. These two readings are both locally defensible and mutually incompatible. The boundary failure is not a schema mismatch (the attribute names and types validate fine) — it is a **semantic-mode mismatch on resume**. A resumed worker inherits a checkpointed span whose `usage.*` attributes already reflect prior consumption, then writes *additional* usage onto a fresh span with the same `span_id`, producing either double-counting (if the collector dedupes by span_id and sums) or silent truncation (if it overwrites). The invariant that must hold: *for any `span_id`, the terminal value of `gen_ai.usage.*` equals the total consumption of the represented operation, written exactly once.* ## What Was Observed A multi-step agent (planner → 4 tool calls → synthesizer) ran under a runtime that checkpoints after each tool call. Each LLM invocation emits one `chat` span; each tool call emits one `execute_tool` span. The checkpoint serialized the in-flight span context, including `gen_ai.usage.input_tokens=1180`, `gen_ai.usage.output_tokens=340`, and `gen_ai.usage.total_tokens=1520` for the planner span, which had *not yet been ended* when the worker was preempted after tool call #2. On resume, the new worker: 1. Rehydrated the planner span from checkpoint with its existing `usage.*` attributes intact. 2. Made a *new* LLM call to continue planning (the previous turn's output was truncated mid-tool-arg), consuming an additional 610 input / 190 output tokens. 3. Applied the new call's usage by **overwriting** `gen_ai.usage.input_tokens` with `610` rather than adding to `1180`, because the instrumentation helper assumed a fresh span. 4. Ended the span and exported it. Downstream, the cost aggregator summed `gen_ai.usage.total_tokens` across all spans for the trace and reported 1520 + (the four tool spans, which correctly carried 0 usage) + the synthesizer. The planner's 610/190 continuation was **invisible** — total undercounted by exactly the resumed-call consumption. In a second configuration where the runtime used an *append* strategy on a new span with the same `span_id`, the collector's `span_id`-keyed dedup kept both records and the aggregator double-counted the pre-checkpoint 1180/340, overcounting by the checkpointed portion. Both failure modes are silent. Neither trips schema validation. `gen_ai.usage.total_tokens` remained internally consistent with its own input+output in every individual span — the inconsistency lives *between* spans sharing an operation identity, which no single-span validator can see. ## Condition of Validity The cumulative-per-span reading is only valid when the span's start and end bound the entire operation. Checkpoint/resume breaks this: the operation's lifetime now spans two process lifetimes and one serialization boundary, but the span's `start_time_unix_nano` is inherited from the original, so the span *claims* to cover the whole operation while its attributes reflect only one segment. The invariant holds if and only if one of the following is enforced: - **Segment-then-aggregate:** the resumed call emits a *new* span with a fresh `span_id` and a `link` to the pre-checkpoint span (OTel `Span.Link` with `trace_state` carrying the parent operation id), and the aggregator sums across the linked group. Cumulative semantics are preserved per-span because each span covers exactly one segment. - **Single-writer reconciliation:** the resumed worker reads the checkpointed `usage.*`, adds its own delta, and writes the sum exactly once at span end — with the checkpoint marked *consumed* so a second resume cannot re-add the same base. Absent either, the "cumulative" attribute is being written by multiple writers against a shared base without a reconciliation protocol — a lost-update problem dressed in observability clothing. The validity condition is: *no `span_id` may have its `gen_ai.usage.*` attributes written by more than one process without an explicit additive merge that reads the persisted base first.* A secondary validity trap: `gen_ai.usage.total_tokens` is defined as input+output for chat spans, but some providers include cached-input or reasoning tokens in `total` only. On resume, if the runtime recomputes `total` from the resumed call's input+output but inherits a `total` that included cached tokens, the three attributes become mutually inconsistent even under correct additive merge. Reconciliation must add each of the three fields independently and *not* recompute `total` from the other two. ## Decision Boundary The architectural fork is **when to end the span relative to the checkpoint**. Two defensible designs, one invalid: - **End-before-checkpoint (valid):** End the span, flush it, checkpoint *after* export. On resume, a new span begins with a `link` back. Cumulative semantics hold per span; the aggregator must follow links. Cost: trace becomes a linked chain, not a single wide span; dashboards keyed on single-span totals under-report unless they traverse links. - **Checkpoint-open-span (valid only with reconciliation):** Persist the open span, and on resume require a read-modify-write of `usage.*` guarded by a checkpoint-consumption token. Cost: every resume path must implement the merge; a single instrumentation helper that writes deltas directly silently corrupts. - **Checkpoint-open-span with fresh-write (invalid):** Rehydrate the span, write new-call usage as if fresh. This is the observed failure. It is the *default* behavior of most instrumentation wrappers, which is why it recurs. The boundary is crossed the moment the runtime persists a span that has already accumulated `usage.*` and later writes to it again. The decision is not whether to checkpoint spans (you must, to preserve trace continuity) but whether the resume path treats `usage.*` as a base to merge or a slot to fill. ## Operational Effect The practical consequence is that **token accounting becomes non-monotonic and non-reconcilable across the resume boundary**, and — critically — the error is *directional and predictable*: overwrite-resume undercounts by exactly the pre-checkpoint consumption; append-resume overcounts by exactly the pre-checkpoint consumption. This means budget-enforcement loops that read `gen_ai.usage.total_tokens` to decide whether to halt an agent will systematically mis-fire at resume: an overwrite-resume agent appears to have consumed less than it did and is granted budget it has already spent, while an append-resume agent is halted early. Neither error surfaces as an exception; both surface as "the agent stopped for no reason" or "the agent blew the budget." The guardrail is a resume-path assertion: before ending any rehydrated span, verify that the written `usage.*` is ≥ the checkpointed base and that the delta equals the resumed call's measured consumption, and that `total` was additively merged rather than recomputed. ```python class UsageAccountingDivergence(RuntimeError): """Raised when a resumed GenAI span's usage attributes violate cumulative-per-span semantics.""" pass def reconcile_resumed_span_usage( checkpointed: dict, resumed_call: dict, written: dict, ) -> dict: """ checkpointed: usage.* persisted at checkpoint time (base). resumed_call: usage measured for the continuation call only (delta). written: usage.* the instrumentation actually wrote onto the resumed span. Returns the reconciled usage dict, or raises if the write diverged. """ for field in ("input_tokens", "output_tokens", "total_tokens"): if field not in checkpointed or field not in written: raise UsageAccountingDivergence( f"missing {field} in checkpointed or written usage; cannot reconcile" ) # total_tokens must be merged additively, never recomputed from input+output, # because providers may fold cached/reasoning tokens into total only. expected = { "input_tokens": checkpointed["input_tokens"] + resumed_call.get("input_tokens", 0), "output_tokens": checkpointed["output_tokens"] + resumed_call.get("output_tokens", 0), "total_tokens": checkpointed["total_tokens"] + resumed_call.get("total_tokens", 0), } for field, exp in expected.items(): got = written[field] if got == exp: continue if got == resumed_call.get(field, 0): raise UsageAccountingDivergence( f"overwrite-resume detected on {field}: wrote delta {got}, " f"expected cumulative {exp} (base {checkpointed[field]} + delta)" ) if got == checkpointed[field] + resumed_call.get(field, 0) * 2: raise UsageAccountingDivergence( f"append-resume double-count on {field}: wrote {got}, expected {exp}" ) raise UsageAccountingDivergence( f"unreconcilable {field}: wrote {got}, expected {exp} " f"(base {checkpointed[field]}, delta {resumed_call.get(field, 0)})" ) # Monotonicity invariant: a resumed span may never report less than its base. if written["total_tokens"] < checkpointed["total_tokens"]: raise UsageAccountingDivergence( "non-monotonic total_tokens across resume boundary" ) return expected ```