# When must an instance abandon OpenTelemetry GenAI span nesting to preserve tool-call causality **Date of Record:** 2026 November 28 **Scope:** Applies to LLM agent runtimes that emit OpenTelemetry spans using the GenAI semantic conventions (`gen_ai.*`) for agent orchestration and tool invocation, where a single agent instance issues tool calls that may themselves spawn sub-agents or re-enter the same process. Does not apply to stateless single-shot inference servers that emit one span per request with no nested tool activity. ## Core Distinction The GenAI semantic conventions treat a tool call as a child span of the agent span that issued it, linked by `parent_span_id` and tagged with `gen_ai.operation.name = "execute_tool"`. This nesting encodes a *causal* claim: the tool execution happened-because-of the agent turn. That claim is only valid when the parent span's lifetime strictly contains the child's, and when the parent's identity is stable for the duration of the child. The non-obvious boundary is this: **an agent instance must abandon strict span nesting (and switch to span links or a flattened sibling model) the moment a tool call can outlive, re-enter, or be re-parented relative to the agent span that emitted it.** The failure is not "missing spans" — it is *mis-attributed causality*: a tool span whose `parent_span_id` points at an agent span that has already ended, was checkpointed and resumed under a new trace, or was replayed by an auditor. The trace looks complete. The causal graph is a lie. Downstream attribution — token cost per tool, error compounding per turn, latency budget per agent — silently sums across the wrong parent. ## What Was Observed A multi-step agent (five tool calls per turn, sub-agent delegation on call three) emitted spans with a single `trace_id` per turn. On cold-start resume after a context-window checkpoint, the runtime rehydrated the agent state and continued execution. The resumed instance generated a *new* `trace_id` (the process had restarted; the tracer provider reinitialized). Tool calls issued after resume carried `parent_span_id` values pointing into the *old* trace's span IDs — because the agent's in-memory span context was serialized into the checkpoint and restored verbatim, but the new tracer had no record of those parent spans. Trace backend behavior: every post-resume tool span was rejected as an orphan or, worse, accepted with a dangling parent reference. The `gen_ai.tool.name` and `gen_ai.usage.*` attributes were intact; the *edge* was broken. Two consequences surfaced: 1. **Cost attribution collapsed.** Per-tool token accounting, which the backend computed by walking parent→child edges, attributed all post-resume tool cost to a synthetic root span named `unknown`. The agent's actual turn cost was undercounted by 60% on resumed turns. 2. **Error compounding went invisible.** A tool failure on call four (post-resume) was logged as a child of a nonexistent parent, so the "error propagated to agent turn" assertion — implemented as a parent-span status check — never fired. The agent continued reasoning on a poisoned tool result for two more turns. A second, subtler observation: when the sub-agent on call three was invoked, it correctly created its own `trace_id` (delegation across process boundaries is a legitimate trace break). But the *return* handoff re-entered the parent agent and emitted a tool span whose parent was the pre-delegation agent span — again dangling, because the parent agent's span had been closed at the delegation boundary to bound its duration. The runtime had assumed "the agent span stays open across the whole turn," which is false the moment a turn contains a delegation that closes and reopens the agent's execution context. ## Condition of Validity Strict GenAI span nesting (`tool_span.parent_span_id == agent_span.span_id`) is valid **if and only if** all three hold: - **Lifetime containment:** the agent span is open for the entire interval `[tool.start, tool.end]`. This fails whenever the agent span is closed to bound latency, or when the agent is checkpointed mid-turn. - **Identity stability:** the `span_id` and `trace_id` encoded in the agent's serialized context are still resolvable by the active tracer at the time the tool span is emitted. This fails on process restart, tracer reinit, or checkpoint/resume across instances. - **Single-writer causality:** exactly one agent instance owns the parent span and no replay/auditor re-emits the same child. This fails under verification replay, where an auditor re-executes the tool call and would emit a duplicate child against the same parent. When any condition fails, the correct invariant is: **the tool span must be emitted as a sibling (same trace, no `parent_span_id`, or an explicit span link) with the causal relationship expressed via `SpanLink` and a `gen_ai.agent.turn_id` attribute, not via parent nesting.** The causal edge becomes data, not structure — which is the only representation that survives checkpoint, replay, and re-entry. ## Decision Boundary The runtime must evaluate a *nesting eligibility predicate* immediately before emitting any tool span: ``` nest_tool_span = ( agent_span.is_recording() and agent_span.context.trace_id == active_tracer.current_trace_id() and not execution_state.resumed_from_checkpoint and not execution_state.under_replay and not execution_state.delegation_boundary_crossed ) ``` If `nest_tool_span` is false, emit the tool span with `parent=None`, set `trace_id` to the *current* tracer's trace, attach a `SpanLink` to the originating agent span context (which may be from a different trace), and stamp `gen_ai.agent.turn_id` and `gen_ai.agent.instance_id` as attributes so the causal edge is reconstructable by the backend. Do **not** emit a dangling parent — a broken parent reference is strictly worse than an explicit link, because backends differ on whether they drop or misattribute orphans. The boundary is sharp: the predicate must be checked per tool span, not per turn, because a single turn can transition from nestable to non-nestable at a delegation or checkpoint boundary mid-flight. ## Operational Effect Adopting the predicate changes three downstream computations: - **Cost attribution** moves from parent-walk to `turn_id` grouping, which is resume- and replay-stable. Per-tool token sums become correct across restarts. - **Error-compounding detection** must query `SpanLink` edges (or `turn_id` joins) rather than parent status, because the parent may not exist in the same trace. The assertion "tool error propagated to agent turn" becomes a link-traversal, not a parent lookup. - **Trace topology** becomes a forest of per-instance traces joined by links, rather than one tree per turn. This is the honest representation: a resumed agent *is* a different execution instance, and pretending otherwise is the bug. The cost is that naive trace viewers show fragmented traces. The benefit is that causality is never fabricated. A dangling `parent_span_id` is a claim the system cannot back; a `SpanLink` is a claim it can. ```python from dataclasses import dataclass from typing import Optional class DanglingParentSpanError(RuntimeError): """Raised when a tool span would be emitted with a parent that the active tracer cannot resolve.""" pass @dataclass class SpanContext: trace_id: str span_id: str @dataclass class ExecutionState: resumed_from_checkpoint: bool = False under_replay: bool = False delegation_boundary_crossed: bool = False def emit_tool_span( tool_name: str, agent_ctx: Optional[SpanContext], active_trace_id: str, agent_span_recording: bool, state: ExecutionState, turn_id: str, instance_id: str, ) -> dict: nest = ( agent_ctx is not None and agent_span_recording and agent_ctx.trace_id == active_trace_id and not state.resumed_from_checkpoint and not state.under_replay and not state.delegation_boundary_crossed ) if nest: return { "name": f"execute_tool {tool_name}", "trace_id": active_trace_id, "parent_span_id": agent_ctx.span_id, "links": [], "attributes": { "gen_ai.operation.name": "execute_tool", "gen_ai.tool.name": tool_name, "gen_ai.agent.turn_id": turn_id, "gen_ai.agent.instance_id": instance_id, }, } # Non-nestable path: causality must be expressed as a link, never a dangling parent. if agent_ctx is not None and agent_ctx.trace_id != active_trace_id: # Cross-trace link is legal; cross-trace *parent* is not. pass elif agent_ctx is not None and agent_ctx.trace_id == active_trace_id: # Same trace but parent may be closed/unrecording: link, do not nest. pass if agent_ctx is None and not state.resumed_from_checkpoint: # No agent context at all and not a known resume: this is a genuine bug, # not a boundary transition. Refuse to fabricate a root. raise DanglingParentSpanError( f"tool '{tool_name}' has no agent context and no resume/replay/delegation " f"justification; refusing to emit an orphan span" ) return { "name": f"execute_tool {tool_name}", "trace_id": active_trace_id, "parent_span_id": None, "links": [agent_ctx] if agent_ctx else [], "attributes": { "gen_ai.operation.name": "execute_tool", "gen_ai.tool.name": tool_name, "gen_ai.agent.turn_id": turn_id, "gen_ai.agent.instance_id": instance_id, "gen_ai.causality.mode": "linked", }, } ```