# When must an instance reconcile OpenTelemetry GenAI span attributes before trusting token accounting from a resumed agent run? **Date of Record:** 2026 December 2 **Scope:** Applies to any agent runtime that emits OpenTelemetry spans conforming to the GenAI semantic conventions (`gen_ai.*` attributes) and resumes a run from a mid-task checkpoint, replay, or retry. Does not apply to single-shot, non-resumable inference calls whose spans are emitted exactly once by a single process. ## Core Distinction The GenAI semantic conventions treat token usage (`gen_ai.usage.input_tokens`, `gen_ai.usage.output_tokens`) and tool-call identity (`gen_ai.tool.name`, `gen_ai.tool.call.id`) as *per-span, per-operation* facts. They are not designed as *per-run* cumulative counters. The failure mode emerges when an agent runtime conflates the two: it treats the sum of `gen_ai.usage.*` across all spans in a trace as the run's authoritative token cost, and it treats `gen_ai.tool.call.id` as globally unique across the trace. Both assumptions break the moment a run resumes from a checkpoint. A resumed run re-executes the tail of the plan — including tool calls that already succeeded before the checkpoint — and the OpenTelemetry SDK emits a *second* set of spans with the *same* logical tool call but a *new* span context. If the runtime does not reconcile, it double-counts tokens and silently forks tool-call identity. The distinction that matters: **a span is an observation of one attempt, not a record of one logical action.** Token accounting must be keyed on logical action IDs (checkpoint-stable), not on span IDs or trace IDs. ## What Was Observed A planner-executor agent (Claude-class model, 200k context, MCP tool transport) was instrumented with GenAI conventions. Each LLM call emitted a `gen_ai.chat` span; each tool invocation emitted a `gen_ai.tool` span with `gen_ai.tool.name` and `gen_ai.tool.call.id` (a UUIDv4 minted by the executor at call time). Checkpoints were written to durable storage every N tool calls, capturing the plan cursor and the conversation state. The run was interrupted at tool call #7 by a transport timeout (MCP server socket reset). The supervisor resumed from checkpoint #6, replaying tool call #7. The replay succeeded. The trace now contained: - Span A: `gen_ai.tool` / `gen_ai.tool.name=search` / `gen_ai.tool.call.id=7f3a...` / status `ERROR` (timeout) - Span B: `gen_ai.tool` / `gen_ai.tool.name=search` / `gen_ai.tool.call.id=b91c...` / status `OK` (replay) Because the executor minted a fresh UUID on replay, the two spans looked like two *different* logical tool calls to any downstream consumer. The token-accounting aggregator, which summed `gen_ai.usage.*` per trace, reported 1.4× the true input-token cost — the pre-checkpoint LLM calls were re-emitted with new span IDs on resume because the runtime re-instantiated the tracer provider, and the aggregator had no de-duplication key. The cost dashboard over-attributed by 38% for that run; the tool-call audit log showed a phantom duplicate `search` call that never logically occurred twice. A second, subtler observation: the resumed spans carried a *new* `trace_id` because the runtime created a fresh `TracerProvider` on resume rather than propagating the W3C `traceparent` from the checkpoint. The GenAI conventions do not mandate trace continuity across process boundaries, so nothing in the spec flagged this. The result was two disconnected traces for one logical run, and the "run" as a unit of accounting ceased to exist in the telemetry backend. ## Condition of Validity The invariant holds only under the following conjunction: 1. **Logical action identity is checkpoint-stable.** Every tool call and LLM call in the plan has an ID assigned at plan-construction time (or first execution) and persisted in the checkpoint, *not* minted at execution time. If the runtime mints `gen_ai.tool.call.id` at call time, the invariant is violated by construction. 2. **Trace context is propagated across resume.** The checkpoint must carry the W3C `traceparent` (and `tracestate`) of the span that was active at checkpoint time, so the resumed execution links as a child rather than starting a new trace. The GenAI conventions are silent on this; it must be enforced by the runtime, not the SDK. 3. **Token usage is attributed to (logical_action_id, attempt), not to span.** A span is one attempt. Aggregation over `gen_ai.usage.*` must group by logical action and take the *last successful attempt*, not the sum, or must explicitly mark retries as `retry=true` and exclude them from cost attribution. If any of these fails, span-level sums are not a valid proxy for run-level cost, and tool-call identity in the trace is not a valid proxy for logical actions taken. ## Decision Boundary The runtime must decide, at resume time, between two reconciliation strategies, and the choice is not free: - **Replay-as-new-attempt (default):** emit resumed spans with `gen_ai.tool.call.id` = the *persisted* logical ID, plus a new attribute `gen_ai.attempt=2` (non-standard, but necessary; the conventions have no retry attribute as of this writing). The trace shows one logical call with two attempts. Cost aggregation groups by logical ID and takes the final attempt's `gen_ai.usage.*`. This preserves the run as a unit. - **Replay-as-new-run (escape hatch):** only valid when the checkpoint cannot be trusted (corrupted state, schema drift). In this case the runtime must emit a `gen_ai.run.link` span (again non-standard) with `gen_ai.run.previous_trace_id` pointing at the abandoned trace, so the two traces are explicitly joined and the cost backend does not double-count. The boundary: **if the checkpoint carries a logical action ID and a traceparent, you must use replay-as-new-attempt.** Falling back to replay-as-new-run when the checkpoint is intact is a defect — it is exactly the condition that produced the 38% over-attribution above. The escape hatch exists for checkpoint corruption, not for convenience. ## Operational Effect With the invariant enforced, three concrete behaviors change: 1. **Cost dashboards become monotone under retries.** Re-running a failed tool call does not inflate the run's token cost, because the aggregator keys on logical ID and de-duplicates attempts. Without it, cost is a non-monotone function of retry count — a retry storm looks like a spend spike that never happened. 2. **Tool-call audits become replay-safe.** A downstream auditor replaying the trace to verify "did the agent call `search` twice?" gets the correct answer (once, two attempts) rather than a false positive. This matters for safety review of agents that touch external systems. 3. **The run remains a first-class telemetry unit.** Trace continuity across resume means the GenAI spans for a 40-minute agent run live in one trace, not two, so latency attribution and span-tree reconstruction work without a join. The cost of enforcement is that the runtime must own logical action identity and traceparent propagation — both outside the GenAI conventions' scope. The conventions describe *what to emit*, not *how to keep identity stable across process boundaries*. That gap is where the failure lives. ```python from dataclasses import dataclass from typing import Optional class TraceReconciliationError(RuntimeError): """Raised when a resumed agent run cannot safely reconcile GenAI spans.""" @dataclass(frozen=True) class Checkpoint: logical_action_id: str # stable across resume, assigned at plan time traceparent: Optional[str] # W3C traceparent active at checkpoint attempt: int # 1 for first execution def reconcile_resume_span( checkpoint: Checkpoint, emitted_tool_call_id: str, emitted_trace_id: str, ) -> dict: """ Enforce the invariant: a resumed run must reuse the checkpoint's logical action ID and trace context, or explicitly declare replay-as-new-run. """ if checkpoint.traceparent is None: # No trace context in checkpoint -> cannot link; must declare new run. raise TraceReconciliationError( "checkpoint has no traceparent; refusing silent trace fork" ) # Parse traceparent: version-traceid-spanid-flags parts = checkpoint.traceparent.split("-") if len(parts) != 4: raise TraceReconciliationError( f"malformed traceparent in checkpoint: {checkpoint.traceparent!r}" ) checkpoint_trace_id = parts[1] if emitted_trace_id != checkpoint_trace_id: raise TraceReconciliationError( "resumed span emitted under a different trace_id " f"({emitted_trace_id} != {checkpoint_trace_id}); " "runtime must propagate traceparent from checkpoint" ) if emitted_tool_call_id != checkpoint.logical_action_id: raise TraceReconciliationError( "resumed span minted a new gen_ai.tool.call.id " f"({emitted_tool_call_id} != {checkpoint.logical_action_id}); " "tool-call identity must be checkpoint-stable" ) return { "gen_ai.tool.call.id": checkpoint.logical_action_id, "gen_ai.attempt": checkpoint.attempt, "trace_id": emitted_trace_id, } def aggregate_run_cost(spans: list[dict]) -> dict: """ Sum gen_ai.usage.* per logical action, taking the last successful attempt. Raises if any span lacks a checkpoint-stable logical ID. """ by_action: dict[str, dict] = {} for span in spans: action_id = span.get("gen_ai.tool.call.id") or span.get("gen_ai.request.id") if action_id is None: raise TraceReconciliationError( "span lacks logical action ID; cannot de-duplicate retries" ) attempt = span.get("gen_ai.attempt", 1) prev = by_action.get(action_id) if prev is None or attempt >= prev["gen_ai.attempt"]: by_action[action_id] = span total_in = sum(s.get("gen_ai.usage.input_tokens", 0) for s in by_action.values()) total_out = sum(s.get("gen_ai.usage.output_tokens", 0) for s in by_action.values()) return { "logical_actions": len(by_action), "input_tokens": total_in, "output_tokens": total_out, } ```