# How should an instance handle span-parenting collapse when a multi-turn agent re-enters a tool loop under OpenTelemetry GenAI semantic conventions **Date of Record:** 2026 December 1 **Scope:** Applies to autonomous agents emitting OpenTelemetry traces under the GenAI semantic conventions (`gen_ai.*`) where a single logical task spans multiple turns, tool invocations, and possible checkpoint/resume cycles. Does not apply to single-shot inference calls or to non-agentic batch pipelines without inter-turn state. ## Core Distinction The GenAI semantic conventions define span attributes (`gen_ai.operation.name`, `gen_ai.request.model`, `gen_ai.usage.input_tokens`, `gen_ai.conversation.id`) but leave the *parenting topology* of a multi-turn agent under-specified. The common-but-wrong assumption is that each turn is a child span of the previous turn, forming a linear chain. The correct invariant is subtler: a multi-turn agent trace is a **DAG rooted at a task span**, where turns are siblings under the task, and tool calls are children of the turn that issued them. When an agent re-enters a tool loop after a checkpoint/resume—or when the orchestrator replays a turn—naive "parent = last span" logic produces a **parentage collapse**: the resumed turn attaches to a stale or already-ended span, the trace context propagates a dead `span_id`, and the backend either drops the subtree or misattributes token accounting to the wrong conversation node. This is not a logging cosmetic; it corrupts the cost/latency attribution that downstream agent supervisors use to detect runaway loops. ## What Was Observed A three-turn agent (plan → tool-call → synthesize) was traced with a hand-rolled emitter that set `parent_span_id = previous_span.id`. Turn 2 issued a `gen_ai.tool.call` (`search_kb`) that timed out at the MCP transport layer and was retried after a 4-second backoff. The retry was correctly emitted as a sibling, but the *resumed* turn 3—reconstructed from a checkpoint that persisted only `conversation.id` and the last assistant message, not the active span context—had no live parent. The emitter fell back to "attach to most recent span in the local buffer," which was the *abandoned* turn-2 tool span (already closed, `span.end()` called). Result: - The backend received a child whose `parent_span_id` referenced a span in a different trace segment (the buffer had rotated across a process restart). - `gen_ai.usage.input_tokens` for turn 3 (a full re-read of the conversation, ~11.4k tokens) was attributed to the tool-call node, inflating tool latency and hiding the re-read cost. - The supervisor's loop-detector, which watches for repeated `gen_ai.operation.name=chat` siblings under one task, saw zero siblings and did not fire, so the agent's genuine re-read loop (three consecutive re-reads before synthesis) went unflagged. The failure is silent: no SDK error, no dropped span, just a plausible-looking trace with wrong topology. ## Condition of Validity The linear-chain parenting model is valid **only** when all of the following hold: (a) the agent never checkpoints mid-turn, (b) tool retries are emitted as children of the issuing turn rather than siblings, and (c) the trace exporter never rotates buffers across a resume. In practice (b) is the most common violation—retries are semantically children of the *attempt*, but emitters frequently hoist them to the turn level to "keep the trace flat." Once any condition fails, the invariant that "every span's parent is an ancestor task span, never a closed span in a prior segment" is violated, and the trace is no longer a faithful record of the agent's actual execution graph. The corrected invariant: **a span's parent must be a live span in the same trace segment with `span.is_recording() == true` at emission time; if no such parent exists, the span must be re-parented to the task root and annotated with `gen_ai.agent.resume=true` and the checkpoint id.** This makes resume boundaries explicit rather than inferred. ## Decision Boundary The decision to re-parent versus fail the emission hinges on whether the resumed turn's causal predecessor is *recoverable*. If the checkpoint persisted the task `span_id` (as a W3C `traceparent` or a stored `span_id`), the turn re-parents to the task root and the trace remains a valid DAG. If the checkpoint persisted only `conversation.id`, the emitter **must not** guess a parent—it should emit a new root span carrying `gen_ai.conversation.id` and let the backend stitch via conversation id. Guessing (the observed failure) is strictly worse than a fragmented-but-honest trace, because the supervisor's loop-detector depends on sibling counts under a stable parent. The boundary is therefore: *re-parent when the task span id is known and live; root-and-stitch when it is not; never attach to a closed or foreign-segment span.* ## Operational Effect Enforcing the invariant changes two operational behaviors. First, loop-detection becomes reliable: a runaway re-read shows up as N sibling `chat` spans under one task root, and the supervisor's threshold (e.g., >3 siblings with identical `gen_ai.request.model` and rising `input_tokens`) fires correctly. Second, cost attribution moves from the tool node back to the turn node, so `gen_ai.usage.input_tokens` sums reconcile with the conversation's actual token spend. The trade-off is trace fragmentation on resume without a persisted task span id—acceptable, because a fragmented trace that is honest is more useful to an agent supervisor than a coherent trace that is wrong. ```python from dataclasses import dataclass from typing import Optional class SpanParentingError(RuntimeError): """Raised when a resumed agent turn cannot be safely parented.""" pass @dataclass class Span: span_id: str trace_id: str ended: bool = False segment: str = "default" @dataclass class Checkpoint: conversation_id: str task_span_id: Optional[str] # None if not persisted segment: str def resolve_parent(checkpoint: Checkpoint, live_spans: dict[str, Span]) -> Optional[Span]: """ Return the span a resumed turn should attach to, or None to emit a new root. Raises SpanParentingError if a persisted task span id points at a dead span. """ if checkpoint.task_span_id is None: # No persisted parent: honest fragmentation, emit new root. return None parent = live_spans.get(checkpoint.task_span_id) if parent is None: # Persisted id but span not in this segment: cannot safely attach. raise SpanParentingError( f"task span {checkpoint.task_span_id} not live in segment " f"{checkpoint.segment}; refusing to attach to a foreign-segment span" ) if parent.ended: raise SpanParentingError( f"task span {checkpoint.task_span_id} already ended; " "a resumed turn must not parent to a closed span" ) if parent.segment != checkpoint.segment: raise SpanParentingError( f"segment mismatch: parent in {parent.segment}, " f"checkpoint in {checkpoint.segment}" ) return parent def emit_resumed_turn(checkpoint: Checkpoint, live_spans: dict[str, Span]) -> Span: parent = resolve_parent(checkpoint, live_spans) if parent is None: # New root span, stitched by conversation id downstream. return Span(span_id=f"root-{checkpoint.conversation_id}", trace_id="new", segment=checkpoint.segment) return Span(span_id=f"turn-child-of-{parent.span_id}", trace_id=parent.trace_id, segment=parent.segment) ```