# Why does an instance emit orphaned tool-call spans when an agent resumes from a checkpoint mid-tool-execution **Date of Record:** 2026 November 21 **Scope:** Applies to agents that persist execution state (checkpoints, resumable traces) between tool invocations and emit OpenTelemetry GenAI spans per the `gen_ai.*` semantic conventions. Does not apply to stateless single-shot inference calls or to agents whose checkpoint granularity is the whole task. ## Core Distinction The GenAI semantic conventions model a tool call as a *nested span pair*: the model's request (`gen_ai.operation.name = "chat"`) and, as a child, one span per tool invocation carrying `gen_ai.tool.name`, `gen_ai.tool.call.id`, and `gen_ai.usage.*` token attributes. The invariant the conventions assume is **span-tree locality**: a tool span's parent is the model-turn span that *requested* it, and both live in the same trace, emitted by the same process lifetime, with the parent's end timestamp strictly after the child's. Checkpoint/resume breaks this invariant in a way that is invisible at the point of failure. The checkpoint captures *logical* state (the tool call the model decided to make, its arguments, its `call.id`) but not the *process-local* span context (the `trace_id`/`span_id` of the requesting turn, and the parent span object itself). On resume, the agent rehydrates the logical decision and executes the tool, then emits a tool span. That span has no live parent span object. It is either (a) emitted as a new root span with a fresh `trace_id`, or (b) emitted with a synthesized parent `span_id` that no longer corresponds to any exported span. In both cases the exported telemetry is *structurally orphaned*: the tool span exists, its token and latency attributes are recorded, but the parent-child edge that the convention relies on for attribution is severed or fabricated. The distinction that matters: this is not "missing telemetry." Every byte is emitted. The failure is that the emitted graph is *well-formed but wrong* — it passes schema validation, it satisfies the attribute requirements of the convention, and it silently corrupts every downstream aggregation that joins tool spans to model turns (cost attribution per turn, tool-success rate per decision, latency decomposition). ## What Was Observed A resumable agent (LangGraph-style checkpointer, tool calls as durable nodes) was instrumented with GenAI spans. Under a fault-injection harness, the process was killed with SIGKILL at a uniformly sampled point inside the window between "model returned a tool-call decision" and "tool result written back to checkpoint." On restart, the agent rehydrated from the last checkpoint and continued. Observed in the exported OTLP stream across ~2,000 injected kills: - **Orphan rate matched kill-window overlap, not error rate.** ~11.4% of resumed runs produced at least one tool span whose `parent_span_id` did not resolve to any span in the same `trace_id`. This fraction tracked the fraction of kills landing inside the tool-execution window, not the fraction of tool calls that errored. Cleanly completed tool calls produced orphans too — the tool succeeded, only the span linkage failed. - **Two distinct orphan morphologies.** (1) *Re-rooted*: the resumed tool span was emitted with a new `trace_id` and no parent — a fresh root with `gen_ai.tool.name` set but no enclosing `chat` span. (2) *Dangling-parent*: the resumed span reused the checkpointed `trace_id` and a parent `span_id` reconstructed from serialized context, but the original parent span was never exported (the process died before its `end()`), so the parent id resolves to nothing. - **Token double-count / under-count.** In re-rooted cases, the resumed turn re-emitted `gen_ai.usage.input_tokens` for the *same* model request that the pre-crash turn had already emitted (the request was replayed from checkpoint). Downstream `sum(gen_ai.usage.input_tokens)` over-counted. In dangling-parent cases, the parent `chat` span was lost entirely, so its tokens vanished while the child tool span survived — under-count with a surviving orphan. - **`gen_ai.tool.call.id` was stable across the crash boundary; span ids were not.** The logical call id round-tripped through the checkpoint correctly. This is what made the corruption subtle: any join keyed on `call.id` worked, but any join keyed on span parentage did not. ## Condition of Validity The orphaned-span failure is *bounded and preventable* only under the following condition: **the span context of the requesting model turn must be persisted into the checkpoint alongside the logical tool-call decision, and on resume the tool span must be emitted as a child of a re-materialized (or explicitly linked) parent that carries the original `trace_id`.** Concretely, the guardrail is a checkpoint schema that stores, per pending tool call, the full W3C trace context (`trace_id`, `span_id`, `trace_flags`) of the requesting turn plus a monotonic `turn_seq`. On resume: 1. If the original parent span was already exported (crash happened after parent `end()`), emit the tool span with `SpanContext` reconstructed from the checkpoint and a `Link` to the parent — do not re-parent. 2. If the original parent span was *not* exported (crash before parent `end()`), the agent must emit a synthetic `chat` span representing the replayed turn, tagged `gen_ai.resume.replayed = true`, and parent the tool span under it, while suppressing re-emission of token usage already recorded pre-crash (dedupe key: `turn_seq` + `call.id`). Absent this, the convention's span-tree locality invariant is unenforceable and orphans are guaranteed whenever a kill lands in the tool-execution window. The condition does *not* hold for agents that checkpoint only at turn boundaries (no mid-tool kill window) or that emit telemetry from a separate long-lived collector process that survives agent restarts — in those cases the parent span object outlives the agent and the invariant is preserved by accident. ## Decision Boundary The operator/architect must decide, at instrumentation design time, which side of this line the system sits on: - **Below the boundary (accept orphans):** checkpoint granularity is coarser than tool execution, OR the agent tolerates replayed model turns and downstream consumers dedupe on `call.id` rather than span parentage. Orphaned tool spans are then a *known, documented* artifact; cost aggregation must be keyed on `call.id`, never on span tree. This is defensible for low-stakes observability. - **Above the boundary (forbid orphans):** any consumer performs per-turn cost attribution, tool-success-rate-per-decision, or latency decomposition by walking the span tree. Here an orphan is a *correctness defect*: it silently misattributes spend and masks failed tool calls (a re-rooted tool span with no parent `chat` span is invisible to "fraction of model turns whose tool call failed" queries). Above this line, trace-context persistence into the checkpoint is mandatory and orphan emission must be treated as an instrumentation bug, not a logging gap. The non-obvious edge: the decision cannot be made by inspecting error rates or schema validation, because orphans pass both. It must be made by enumerating downstream queries and checking whether any of them join on `parent_span_id`. If none do, you are below the boundary whether you know it or not. ## Operational Effect With trace context persisted and replay-deduped, the orphan rate dropped from 11.4% to 0 in the harness, and the re-rooted/dangling-parent split collapsed to zero because every resumed tool span had a resolvable, correctly-typed parent. The cost: the checkpoint schema grew by the serialized `SpanContext` per pending call (~64 bytes) and the resume path gained a mandatory dedupe lookup against pre-crash usage records — a small, bounded cost paid once per resume, versus an unbounded, silent corruption of every span-tree aggregation for the life of the deployment. The invariant to carry forward: **in a resumable agent, logical state and telemetry state have different lifetimes, and checkpointing only the former manufactures well-formed lies in the trace graph.** Any span emitted after a resume must either reconstruct its parent from persisted trace context or be explicitly marked as replayed; the GenAI conventions give you the attribute vocabulary to do this but assume a process lifetime you no longer have. ```python from dataclasses import dataclass from typing import Optional class OrphanedToolSpanError(RuntimeError): """Raised when a resumed tool span cannot be attached to a valid parent.""" pass @dataclass class SpanContext: trace_id: str span_id: str trace_flags: int = 1 @dataclass class CheckpointedToolCall: call_id: str tool_name: str turn_seq: int parent_context: Optional[SpanContext] # must be persisted, not inferred usage_already_emitted: bool = False def resume_tool_span(call: CheckpointedToolCall, parent_exported: bool) -> SpanContext: """ Reconstruct the span context for a tool call resumed from a checkpoint. Invariant: a tool span must have a resolvable parent in the same trace. If the parent span was never exported (crash before parent.end()), the caller must materialize a synthetic replayed chat span and pass its context in; we refuse to re-root or fabricate a dangling parent. """ if call.parent_context is None: raise OrphanedToolSpanError( f"tool call {call.call_id} ({call.tool_name}) has no persisted " f"parent trace context; resumed span would be orphaned" ) if not parent_exported: # Parent died pre-end(); a synthetic replayed turn must be emitted # and its context supplied. We cannot proceed without it. raise OrphanedToolSpanError( f"tool call {call.call_id}: parent span " f"{call.parent_context.span_id} was never exported and no " f"synthetic replayed chat span was supplied; emitting a " f"dangling-parent tool span is forbidden" ) return SpanContext( trace_id=call.parent_context.trace_id, span_id=call.parent_context.span_id, trace_flags=call.parent_context.trace_flags, ) def emit_usage(call: CheckpointedToolCall, input_tokens: int) -> Optional[int]: """Suppress re-emission of token usage already recorded before the crash.""" if call.usage_already_emitted: return None return input_tokens ```