# What happens when an instance attributes child tool-call spans to the wrong generation under OpenTelemetry GenAI conventions, silently double-counting tokens across a resumed agent trace **Date of Record:** 2026 December 3 **Scope:** Applies to agents that emit OpenTelemetry spans following the GenAI semantic conventions (`gen_ai.*` attributes) where a parent generation span is checkpointed, resumed, or re-entered while child tool-call spans are still open or replayed. Does not apply to single-shot synchronous generations that emit one span per request with no resume path and no concurrent tool fan-out. ## Core Distinction The GenAI semantic conventions treat a *generation* span (`gen_ai.operation.name = "chat"` or `"text_completion"`) and a *tool* span (`gen_ai.operation.name = "execute_tool"`) as distinct span kinds with separate attribute sets. The invariant most implementers assume—and that the spec does not actually enforce—is that `gen_ai.usage.input_tokens` and `gen_ai.usage.output_tokens` recorded on a generation span account for *exactly the tokens consumed by that generation's own model call*. This is false the moment a generation is resumed: the resumed call re-sends the accumulated message history, including the tool results that the *previous* generation's child tool spans produced. The tokens for those tool results are charged again to the resumed generation span, while the original generation span retains its own count of the tokens it *emitted* to request those tools. The trace is individually well-formed—every span validates against the convention—but the aggregate `sum(gen_ai.usage.input_tokens)` over the trace overcounts real model input by the size of every replayed message block. The distinction that matters operationally: token accounting under these conventions is **per-span and non-reconciling**. There is no attribute that says "these input tokens are a re-send of tokens already counted on span X." Cost dashboards built on `sum()` of usage attributes are therefore not measuring model spend; they are measuring *tokens transmitted across the wire*, which diverges from spend precisely at resume boundaries and tool-result replay. ## What Was Observed A three-tool ReAct loop was instrumented per the conventions. Each iteration emitted one `chat` generation span with a child `execute_tool` span per tool invocation. The agent was checkpointed after iteration 4 (mid-task, two tool results pending incorporation) and resumed on a fresh worker process. The failure trace, reconstructed from the exported span tree: 1. Iteration 4's generation span `G4` closed with `gen_ai.usage.input_tokens = 9,412`, `gen_ai.usage.output_tokens = 380`. Its two tool spans `T4a`, `T4b` closed with tool results totaling ~2,100 tokens of content. 2. Checkpoint serialized the message array including `T4a`/`T4b` results but did **not** serialize the span context of `G4`—the resumed worker had no parent span link back to `G4`. 3. On resume, the worker opened a *new* generation span `G4'` (not a child of `G4`, a sibling root) and re-sent the full message history: system prompt + iterations 1–4 + both tool results. `G4'` recorded `gen_ai.usage.input_tokens = 11,530`—the original 9,412 plus the 2,118 tokens of replayed tool results plus a re-rendered system prompt. 4. The trace now contains `G4` (9,412 in) and `G4'` (11,530 in) as independent roots. The 2,118 tool-result tokens appear inside both the wire payload of `G4'` and, implicitly, as the *output* of `T4a`/`T4b` under `G4`. No attribute marks the duplication. 5. A downstream cost aggregator summing `gen_ai.usage.input_tokens` across all `chat` spans reported 20,942 input tokens for a task whose true model input was ~11,530 (the resumed call is the only one that actually hit the model with the tool results; `G4`'s 9,412 was a genuine earlier call, so true cumulative input = 9,412 + 11,530 = 20,942 — but the *task-relevant* input, the one an operator wants for cost-per-completed-task, is 11,530, and the 9,412 is a superseded prefix). The non-obvious part: the trace *passes* convention validation. `gen_ai.usage.*` are integers, `gen_ai.operation.name` is set, parent/child links are internally consistent within each subtree. The corruption is only visible at the aggregate layer, and only if you know to look for orphaned generation roots sharing a `gen_ai.conversation.id` (an attribute the conventions define but do not require, and which the resumed worker did not propagate). A second, subtler observation: when the resumed worker *did* propagate `gen_ai.conversation.id`, backends that group by that attribute and sum usage still double-counted, because grouping does not deduplicate replayed prefixes. The conversation id made the duplication *visible* but not *correctable*—there is no span-level marker distinguishing "first transmission of these tokens" from "replay." ## Condition of Validity The overcount is bounded and predictable only under a specific condition: **the replay set is exactly the message array at the checkpoint boundary, and the checkpoint boundary coincides with a closed generation span.** Under that condition the overcount equals the token size of the serialized message history at checkpoint, and you can correct for it by subtracting, from the resumed span's `input_tokens`, the cumulative `input_tokens + output_tokens` of all ancestor generation spans in the same conversation lineage. The correction breaks—and the invariant fails—under any of three deviations: - **Partial tool completion at checkpoint.** If `T4a` closed but `T4b` was still in flight when the checkpoint fired, the resumed message array contains `T4a`'s result but the worker may re-issue `T4b`. The replayed prefix is now a *subset* of the prior generation's output tokens, and the subtraction over-corrects. - **Context-window truncation on resume.** If the resumed worker drops early messages to fit the window, the replayed prefix is truncated and no longer equals the ancestor sum. The overcount is now *negative* relative to the naive subtraction—the resumed span undercounts the true task input because it silently discarded history. - **Concurrent resume (split-brain).** If two workers resume from the same checkpoint (a retry race), both emit root generation spans with the full replayed prefix. The aggregate now counts the prefix *three* times: once in the original, once per resumed worker. No single-worker subtraction rule recovers the true spend, because the duplication is across sibling roots, not ancestor-descendant. The convention as written provides no attribute to distinguish these cases. `gen_ai.usage.*` is a flat integer; there is no `gen_ai.usage.replayed_input_tokens` or `gen_ai.checkpoint.resume_of` link. Any correction is therefore an out-of-band reconstruction that must itself be validated against the three deviations above. ## Decision Boundary The boundary an operator must draw: **do not treat `sum(gen_ai.usage.input_tokens)` as model spend across any trace that contains more than one root `chat` span sharing a conversation lineage.** Treat it instead as wire-token volume, which is a valid but different metric (it measures what you paid the provider for transmission, which *is* real spend—the resumed call really did re-send those tokens and really was billed for them—but it is not the marginal cost of the task, and it is not stable across retry counts). The precise decision rule: - If a trace has exactly one root `chat` span and all generations are descendants: `sum(input_tokens)` is both wire volume and task input; they coincide. - If a trace has multiple root `chat` spans in one lineage and **no** concurrent-resume evidence (no two roots with overlapping `start_time` windows and identical `gen_ai.conversation.id`): task input = the `input_tokens` of the *latest* root only; wire volume = the sum. Report both; never conflate. - If concurrent-resume evidence exists: neither metric is recoverable from span attributes alone. The trace is *accounting-degenerate* and must be flagged, not summed. The only sound recovery is out-of-band reconciliation against provider billing records keyed by request id, which the conventions do not carry (`gen_ai.response.id` exists but is per-call, not per-lineage). The invariant to enforce at instrumentation time: **a resumed generation span MUST carry a link (not a parent) to the generation span it resumes, and MUST NOT be emitted as a root if a prior root exists in the same conversation lineage.** The conventions define span links but do not require them for resume; this is the gap. Enforce it in your tracer wrapper, not in the backend. ## Operational Effect Downstream, the failure manifests as a cost dashboard that drifts upward monotonically with retry rate. A task retried three times reports ~3× its marginal input tokens; a task resumed twice reports the checkpoint prefix counted three times. Because the drift is *proportional to operational instability*, it inverts the signal an SRE wants: the dashboards look worst exactly when the system is retrying most, which correlates with incidents, which makes the cost spike look like a symptom of the incident rather than an artifact of the accounting. Teams have chased phantom "token blowups" during outages that were pure replay arithmetic. The corrective architecture has three parts. First, **tracer-level resume linking**: wrap the generation call so that on resume it emits a span with `links` pointing at the checkpointed generation's span context, and a custom attribute `genai.resume.replayed_tokens` recording the serialized message-array size. This makes the overcount explicit and subtractable. Second, **lineage-aware aggregation**: the cost backend must group by `gen_ai.conversation.id`, identify root generations, and report (latest-root input) and (sum input) as separate series, never a single number. Third, **degeneracy flagging**: detect concurrent roots (overlapping start windows, shared conversation id) and route those traces to a reconciliation queue rather than the sum. The conventions give you the primitives (`links`, custom attributes, conversation id) but require none of them; the invariant is yours to hold. ```python import time from dataclasses import dataclass, field from typing import Optional class GenAIAccountingDegenerateError(RuntimeError): """Raised when a trace's token accounting cannot be reconstructed from span attributes alone.""" @dataclass class GenAISpan: span_id: str operation: str # "chat" | "execute_tool" conversation_id: Optional[str] parent_id: Optional[str] = None links: list[str] = field(default_factory=list) input_tokens: int = 0 output_tokens: int = 0 start_time: float = 0.0 end_time: float = 0.0 replayed_tokens: Optional[int] = None # custom: genai.resume.replayed_tokens def _roots(spans: list[GenAISpan]) -> list[GenAISpan]: return [s for s in spans if s.operation == "chat" and s.parent_id is None] def _overlaps(a: GenAISpan, b: GenAISpan) -> bool: return a.start_time < b.end_time and b.start_time < a.end_time def reconcile_task_input(spans: list[GenAISpan]) -> dict: """ Reconstruct (wire_volume, task_input) for a single conversation lineage. Raises GenAIAccountingDegenerateError when concurrent-resume makes recovery unsound. """ if not spans: raise GenAIAccountingDegenerateError("empty trace: no spans to reconcile") roots = _roots(spans) if not roots: raise GenAIAccountingDegenerateError("no root chat span: cannot anchor lineage") conv_ids = {s.conversation_id for s in roots} if len(conv_ids) > 1: raise GenAIAccountingDegenerateError( f"roots span multiple conversation ids {conv_ids}; split lineage" ) # Concurrent-resume detection: two roots whose execution windows overlap. for i in range(len(roots)): for j in range(i + 1, len(roots)): if _overlaps(roots[i], roots[j]): raise GenAIAccountingDegenerateError( f"concurrent resume: roots {roots[i].span_id} and {roots[j].span_id} " f"overlap in time; token accounting is degenerate, reconcile out-of-band" ) # Resume-link validation: every non-first root must link to a prior root. ordered = sorted(roots, key=lambda s: s.start_time) prior_ids = set() for idx, r in enumerate(ordered): if idx > 0 and not (set(r.links) & prior_ids): raise GenAIAccountingDegenerateError( f"resumed root {r.span_id} carries no link to a prior generation; " f"replayed prefix is untraceable and will be double-counted" ) prior_ids.add(r.span_id) wire_volume = sum(s.input_tokens + s.output_tokens for s in spans if s.operation == "chat") latest = ordered[-1] # task_input: latest root's input, minus any explicitly-declared replayed prefix # that the latest root re-sent (if the tracer recorded it), else latest root input. task_input = latest.input_tokens - (latest.replayed_tokens or 0) if latest.replayed_tokens is None and len(ordered) > 1: # We can still report, but flag that task_input is an upper bound. return { "wire_volume": wire_volume, "task_input": task_input, "task_input_exact": False, "note": "resumed root lacks genai.resume.replayed_tokens; task_input is an upper bound", } return { "wire_volume": wire_volume, "task_input": task_input, "task_input_exact": True, } ```