# Why does an instance lose tool-call attribution when OpenTelemetry GenAI spans are emitted from a resumed agent turn **Date of Record:** 2026 November 19 **Scope:** Applies to agent runtimes that emit OpenTelemetry GenAI semantic-convention spans (`gen_ai.*`) for tool invocations and per-turn token accounting, and that support mid-task checkpoint/resume or cross-process handoff. Does not apply to single-shot, single-process inference calls where span context is created and closed within one uninterrupted execution frame. ## Core Distinction The GenAI semantic conventions model a tool call as a *child span of the agent turn span* whose `trace_id`/`span_id` parent linkage carries the causal attribution, and they model token usage as attributes (`gen_ai.usage.input_tokens`, `gen_ai.usage.output_tokens`) attached to the span that *produced* the completion. The conventions assume a monotonic, single-owner execution frame: one span owns one turn, and every tool call and token delta emitted during that turn nests beneath it. The distinction that breaks operators is between **span identity** and **span context**. When an agent checkpoints and resumes, the runtime can faithfully restore the *logical* turn (the prompt, the tool-call queue, the partial message history) while the *OTel span context* — the `SpanContext` object holding trace ID, span ID, trace flags, and the parent linkage — is a process-local, in-memory object that does not survive serialization unless explicitly captured. The resumed turn re-creates a *new* root span. Tool calls that were queued before the checkpoint and executed after it get parented to the new root, while their token deltas — already partially accounted to the pre-checkpoint span — are split across two trace trees that share no parent. The trace looks complete per-tree but is causally severed: no single span aggregates the full turn's tool calls and tokens. ## What Was Observed A multi-tool research agent (planner → 4 parallel retrieval tools → synthesizer) checkpointed after the planner turn and again after tool dispatch, resuming in a fresh worker process. Instrumentation used the OTel Python SDK with a `TracerProvider` re-initialized per process and `gen_ai.operation.name=execute_tool` child spans for each retrieval. Post-resume traces exhibited three concrete artifacts: 1. **Orphaned tool spans.** The four retrieval spans carried `trace_id` values from the *resumed* trace, but their `gen_ai.tool.call.id` attributes matched call IDs recorded in the checkpointed planner output. A join on `tool.call.id` across the two trace trees returned 4 rows with two distinct `trace_id`s and no shared ancestor — the synthesizer span could not be linked to the planner span by parentage. 2. **Double-counted input tokens.** The planner span (pre-checkpoint) recorded `gen_ai.usage.input_tokens=1180`. On resume, the runtime replayed the planner's message array into a fresh span to reconstruct state, emitting `input_tokens=1180` again. Aggregate token accounting over the trace set reported 2360 input tokens for a turn that consumed 1180. The convention has no `gen_ai.usage.replayed` or dedup key, so a naive `sum()` over `gen_ai.usage.input_tokens` is wrong by the replay factor. 3. **Broken `gen_ai.conversation.id` continuity.** The conversation ID was stable across the checkpoint, but because it is a *span attribute* rather than a trace-level resource attribute, downstream correlation by conversation required a full-scan attribute filter rather than a trace-tree walk, and the two trees never merged. The failure is silent: every span is individually well-formed and passes schema validation. The corruption lives only in the *relational* structure between spans, which the semantic conventions do not validate. ## Condition of Validity The invariant that holds in uninterrupted execution — *every tool call and every token delta of a logical turn is reachable from the turn's root span by parent traversal* — is **valid only when the turn's `SpanContext` is captured at checkpoint and re-attached on resume as the parent of the resumed root.** Formally, resume is safe iff: - the checkpoint payload contains the serialized `SpanContext` (trace ID, span ID, trace flags) of the in-flight turn span, and - the resumed runtime starts the continuation span with `context=extracted_span_context` rather than as a new root, and - token accounting is emitted exactly once per completion (either at production or at replay, never both), keyed by a stable `gen_ai.response.id` or equivalent dedup token. Absent any one of these, the parent-traversal invariant fails and the trace set is causally fragmented. The condition is *not* restored by sharing `gen_ai.conversation.id`, by timestamp ordering, or by log correlation — those are weak joins that cannot reconstruct parentage and cannot deduplicate replayed token counts. ## Decision Boundary The boundary is between **checkpointing execution state** and **checkpointing observability state**. Agent runtimes routinely serialize the former (messages, tool queue, scratchpad) and treat the tracer as ambient infrastructure that "just works" across process boundaries. It does not: `SpanContext` is not in the serialized state, and the OTel SDK's context propagation (`traceparent`) is designed for *request* boundaries (HTTP, message headers), not for *resumption* of a suspended execution frame. Operators must decide, per turn, whether a resume is a **continuation** (re-attach parent `SpanContext`, suppress replayed token emission, treat as same logical span) or a **new attempt** (new root span, but then the checkpointed turn must be marked `gen_ai.operation.name=resume` with an explicit `gen_ai.turn.attempt` attribute and token deltas must be attributed to the attempt, not double-counted against the original). Choosing neither — the default — produces the fragmented, double-counted trace observed above. The decision must be made at checkpoint-write time, because the `SpanContext` is unrecoverable after the process dies. ## Operational Effect The practical consequence is that token-cost dashboards and tool-latency SLOs computed from these traces are wrong in a *bounded but non-obvious* way: they over-count input tokens by the replay factor (one full re-emission per resume) and under-count tool latency (orphaned tool spans are excluded from the turn's critical path because they have no parent link to the turn root). For an agent that checkpoints aggressively — say every tool call — the inflation is proportional to resume count, and a single long task can report 3–5× its true input-token cost while its p99 turn latency appears *lower* than reality because the expensive tool spans fell out of the tree. The guardrail is a checkpoint-time assertion that the serialized state includes a non-empty `SpanContext`, plus a resume-time check that the continuation span's `trace_id` equals the checkpointed `trace_id`. The code below enforces both and fails closed, because a silently fragmented trace is worse than a loud resume failure: the former corrupts cost attribution for every downstream consumer, the latter surfaces the missing invariant at the exact moment it can still be fixed. ```python from dataclasses import dataclass from typing import Optional class CheckpointSpanContextError(RuntimeError): """Raised when a checkpoint lacks a serializable SpanContext or resume breaks trace continuity.""" @dataclass class SpanContext: trace_id: str span_id: str trace_flags: int = 1 def is_valid(self) -> bool: return bool(self.trace_id) and bool(self.span_id) and self.trace_id != "0" * 32 @dataclass class Checkpoint: turn_id: str messages: list tool_queue: list span_context: Optional[SpanContext] emitted_input_tokens: int def write_checkpoint(turn_id: str, messages: list, tool_queue: list, active_span_context: Optional[SpanContext], emitted_input_tokens: int) -> Checkpoint: """Persist execution state AND the in-flight span context. Fails closed if context is missing.""" if active_span_context is None or not active_span_context.is_valid(): raise CheckpointSpanContextError( f"turn {turn_id}: refusing to checkpoint without a valid SpanContext; " "resume would fragment the trace tree and double-count tokens" ) return Checkpoint( turn_id=turn_id, messages=messages, tool_queue=tool_queue, span_context=active_span_context, emitted_input_tokens=emitted_input_tokens, ) def resume_turn(cp: Checkpoint, new_root_span_context: SpanContext, replay_input_tokens: int) -> SpanContext: """Resume as a continuation: new span must share the checkpointed trace_id.""" if cp.span_context is None or not cp.span_context.is_valid(): raise CheckpointSpanContextError( f"turn {cp.turn_id}: checkpoint has no recoverable SpanContext; cannot continue trace" ) if new_root_span_context.trace_id != cp.span_context.trace_id: raise CheckpointSpanContextError( f"turn {cp.turn_id}: resume trace_id {new_root_span_context.trace_id} " f"!= checkpoint trace_id {cp.span_context.trace_id}; " "tool calls will orphan and token deltas will split across trees" ) if replay_input_tokens != cp.emitted_input_tokens: raise CheckpointSpanContextError( f"turn {cp.turn_id}: replay emitted {replay_input_tokens} input tokens " f"but checkpoint already accounted {cp.emitted_input_tokens}; " "suppress re-emission or tag as gen_ai.turn.attempt to avoid double-count" ) # Continuation is valid: attach new span as child, do not re-emit usage. return cp.span_context ```