# What happens when an instance emits GenAI spans whose token attributes are re-aggregated across a resumed agent run **Date of Record:** 2026 November 30 **Scope:** Applies to any agent runtime that emits OpenTelemetry spans under the GenAI semantic conventions (`gen_ai.*`) and resumes execution from a checkpoint or retries a tool call within the same logical run. Does not apply to stateless single-shot inference calls that are never resumed or retried. ## Core Distinction The GenAI semantic conventions define token attributes (`gen_ai.usage.input_tokens`, `gen_ai.usage.output_tokens`) as *per-request* counters on a single span. They are not deltas, not gauges, and not idempotent. A span is a record of one model invocation, and its token attributes describe exactly that invocation. The failure mode is not a schema violation. Every span is individually well-formed. The break happens at the *aggregation boundary*: when a resumed or retried agent run re-executes a step, the backend receives two spans that both legitimately claim the same logical work, and any downstream consumer that sums `gen_ai.usage.*` across the trace — cost dashboards, budget guards, rate-limit feedback loops, or an agent's own self-monitoring tool — double-counts. The agent's internal belief about its remaining token budget diverges from the provider's actual billing. The trace is internally consistent and externally wrong. ## What Was Observed A planner agent executes a three-tool sequence. At step 2 (a retrieval tool call), the process is checkpointed mid-flight because the tool call exceeds a timeout. On resume, the orchestrator replays from the last durable checkpoint, which was *before* step 2's model invocation. The model call for step 2 is issued again with identical inputs. Both invocations emit spans with the same `trace_id` (propagated from the run) and the same `gen_ai.operation.name = "chat"`. The first span carries `gen_ai.usage.input_tokens = 4120`, `output_tokens = 380`. The second, on the replay, carries `input_tokens = 4120`, `output_tokens = 402` — the output differs because sampling is non-deterministic. The span status of the first is `UNSET` (it was abandoned, never marked `ERROR`). Three things then go wrong in sequence: 1. **The abandoned span is never closed or marked.** The checkpoint killed the process before `span.end()` ran. The exporter flushed a partial span via the batch processor's shutdown hook. It has no terminal status, so a naive cost aggregator treats it as a completed invocation. 2. **The replay span is indistinguishable at the attribute level.** There is no `gen_ai.retry.count`, no `agent.step.id`, no `checkpoint.epoch` attribute that would let a consumer dedupe. The W3C trace context is identical because it was restored from the checkpoint. 3. **The agent's budget guard reads its own emitted spans.** The agent queries its telemetry backend for `sum(gen_ai.usage.input_tokens)` over the current `trace_id` to decide whether it can afford the next step. It sees 8240 input tokens for one logical step, concludes it is at 61% of budget after step 2 of 3, and prematurely halts with a "budget exhausted" termination — while the provider actually billed 4120 plus whatever the replay consumed, well under the real limit. The observable symptom is an agent that terminates early on resumed runs, with a trace that appears to justify the termination. The trace is the *cause*, not the record. ## Condition of Validity The invariant that must hold is: **for any `trace_id`, the sum of `gen_ai.usage.*` across spans equals the sum of provider-billed tokens for the logical run, and each logical model invocation is counted exactly once.** This holds only when all of the following are true: - Every span that begins is either ended with a terminal status or explicitly marked `ERROR`/abandoned before export, so that abandoned invocations are excluded from aggregation. - Replayed invocations carry a discriminator — `agent.step.attempt` (0-indexed) plus a stable `agent.step.id` — such that a consumer can select `max(attempt)` per `step.id` rather than summing. - The trace context is *not* blindly propagated across a checkpoint boundary without also propagating the step identity, because identical trace context plus identical operation name is the exact collision condition. - Budget guards read from a source that is idempotent with respect to the above, or read provider-side usage rather than self-emitted spans. When any of these fails, the sum is not a measurement of cost; it is a measurement of *attempts*, and attempts diverge from cost under exactly the conditions — timeouts, retries, resumes — that agents encounter most. ## Decision Boundary The boundary is whether the resumed step is treated as the *same* invocation or a *new* one. Treat it as the same invocation (replay under one span, with the span reopened or a child span linked via `SpanLink`) when the replay is a pure retry of an idempotent model call and you control the exporter such that the original span is closed as `ERROR` before the retry begins. In this case, aggregation by `max(attempt)` is unnecessary because only one span survives. Treat it as a new invocation (distinct span, distinct `agent.step.attempt`) when the checkpoint boundary is at or before the model call and the original process is gone. This is the common case and the one that breaks naive aggregation. Here the discriminator attribute is mandatory, and every consumer of `gen_ai.usage.*` must dedupe by `(trace_id, agent.step.id)` keeping the highest attempt — never by summation. The decision must be made *at emit time*, in the instrumentation, not at query time. A backend cannot recover step identity that was never emitted. If you defer the decision to the dashboard, you have already lost the information needed to make it. ## Operational Effect An agent that emits GenAI spans without step-attempt discriminators and then reads its own spans for budget enforcement creates a closed feedback loop where replay inflates perceived cost. On runs with no retries the loop is stable; on runs with retries it diverges, and the divergence is biased toward *early termination*, because the agent over-counts. The practical consequence is that the most resilient agents — the ones that retry and resume most — appear the least budget-efficient, and their self-monitoring will throttle them hardest precisely when they are recovering from a transient fault. The guardrail is a two-part invariant enforced in instrumentation: (1) every span is closed with a terminal status before export, and abandoned spans are marked `ERROR` so they can be filtered; (2) every model-call span carries `agent.step.id` and `agent.step.attempt`, and any cost aggregation over `gen_ai.usage.*` is defined as a per-step-max, not a trace-sum. Budget guards that cannot guarantee this must read provider-reported usage, not self-emitted spans. ```python from dataclasses import dataclass, field from typing import Iterable class SpanAggregationInvariantError(RuntimeError): """Raised when GenAI token aggregation would double-count replayed spans.""" @dataclass(frozen=True) class GenAISpan: trace_id: str step_id: str attempt: int input_tokens: int output_tokens: int terminal_status: str # "OK" | "ERROR" | "UNSET" (abandoned) def aggregate_run_tokens(spans: Iterable[GenAISpan]) -> tuple[int, int]: """ Aggregate token usage for a logical run without double-counting replays. Invariant: for each (trace_id, step_id), keep only the highest-attempt span. Abandoned spans (UNSET) are excluded. Summing raw spans across attempts is the failure mode this function exists to prevent. """ by_trace: dict[str, dict[str, GenAISpan]] = {} for span in spans: if span.terminal_status == "UNSET": # Abandoned invocation: never billed as a completed call. continue steps = by_trace.setdefault(span.trace_id, {}) prior = steps.get(span.step_id) if prior is None or span.attempt > prior.attempt: steps[span.step_id] = span total_in = total_out = 0 for steps in by_trace.values(): for span in steps.values(): total_in += span.input_tokens total_out += span.output_tokens return total_in, total_out def enforce_budget( spans: list[GenAISpan], budget_input_tokens: int, provider_reported_input_tokens: int | None = None, ) -> None: """ Halt the agent if aggregated usage exceeds budget. If the trace lacks step-attempt discriminators (all attempts == 0 for a step that appears more than once), the aggregation is unsound and must not gate execution. """ step_attempts: dict[tuple[str, str], set[int]] = {} for s in spans: step_attempts.setdefault((s.trace_id, s.step_id), set()).add(s.attempt) for (trace_id, step_id), attempts in step_attempts.items(): if len(attempts) > 1 and attempts == {0}: raise SpanAggregationInvariantError( f"trace {trace_id!r} step {step_id!r} emitted {len(attempts)} " f"spans with no attempt discriminator; token aggregation would " f"double-count replays. Refusing to gate budget on self-emitted " f"spans; read provider usage instead." ) used_in, _ = aggregate_run_tokens(spans) if used_in > budget_input_tokens: raise SpanAggregationInvariantError( f"input token budget exceeded: {used_in} > {budget_input_tokens} " f"(provider reported {provider_reported_input_tokens})" ) ```