# Which invariants prevent OTel GenAI span trees from silently orphaning tool-call attributes across agent retries **Date of Record:** 2026 November 29 **Scope:** Applies to agents instrumented with OpenTelemetry GenAI semantic conventions (`gen_ai.*` attributes) where a single logical task fans out into nested spans (`invoke_agent` → `execute_tool` → `chat`), and where any span in that tree may be retried, resumed from a checkpoint, or re-emitted by a different process. Does not apply to flat single-span instrumentation or to non-GenAI spans. ## Core Distinction The GenAI semantic conventions treat `gen_ai.operation.name`, `gen_ai.tool.name`, and `gen_ai.tool.call.id` as *attributes on a span*, not as a *correlation key across spans*. That distinction is load-bearing and routinely violated. A tool call is modeled as an `execute_tool` span whose `gen_ai.tool.call.id` names the logical invocation, and whose parent is the `invoke_agent` (or `chat`) span that requested it. The convention assumes the parent span is still *open* when the child is created, so the SDK can stamp `parent_span_id` at child-start time. When an agent retries a tool call — because the model re-emitted the call, because a timeout triggered a resume, or because a checkpoint replay re-ran the step — the retry creates a *new* `execute_tool` span. If the original parent span has already ended (the classic case: the `chat` span closed when the model returned its tool-call request, and the tool executor runs in a separate turn), the retry's child span is parented to the *root* or to whatever ambient context is active, not to the logical parent. The `gen_ai.tool.call.id` still matches, but the tree no longer does. The tool-call attributes are intact; the *edge* is gone. This is an orphaned attribute edge, and it is invisible in span-level validation because every span is individually well-formed. ## What Was Observed A three-hop agent (plan → tool → summarize) instrumented with `opentelemetry-instrumentation` and manual `invoke_agent` / `execute_tool` spans. The tool executor ran as an async worker off the main agent loop, consuming a queue of tool-call requests. On the happy path, the worker created `execute_tool` spans inside a `contextvars`-propagated context captured at enqueue time, so `parent_span_id` pointed at the requesting `chat` span. Correct trees. Under retry, three things diverged: 1. The `chat` span that requested the tool ended *before* the worker dequeued the request (the model returned; the span closed). The enqueued context still held the closed span's `SpanContext`, so the child span was created with `parent_span_id` pointing at an *ended* span. The backend accepted it — ended parents are legal — but the trace UI rendered the tool span as a child of a collapsed node, and any sampler that dropped the parent (tail sampling on error) left the child floating with a dangling `parent_span_id`. 2. On the second retry, the agent re-created the `chat` span (new `span_id`, same `gen_ai.conversation.id`) and re-emitted the same `gen_ai.tool.call.id`. The worker now produced *two* `execute_tool` spans with identical `gen_ai.tool.call.id` but different parents — one under the dead `chat` span, one under the new one. Downstream dedup keyed on `tool.call.id` collapsed them, discarding the retry's latency and error attributes. 3. When the tool executor was resumed from a checkpoint in a fresh process, `contextvars` were empty. The worker created `execute_tool` spans with *no* parent — orphaned at the trace root — while still carrying the correct `gen_ai.tool.call.id` and `gen_ai.tool.name`. The attributes said "this is tool call X"; the tree said "this is an unrelated root operation." The failure is not that attributes were lost. It is that the *tree invariant* — "every `execute_tool` span with a given `gen_ai.tool.call.id` is a descendant of exactly one `chat`/`invoke_agent` span that carries the same `gen_ai.conversation.id`" — was violated in three distinct ways, none of which any single-span validator flags. ## Condition of Validity The convention's implicit assumption holds only when: (a) the parent span remains open for the full lifetime of every child it spawns, and (b) `gen_ai.tool.call.id` is unique per logical invocation and never reused across retries. Both are false in any agent that (a) closes the model-turn span before executing the tool asynchronously, or (b) retries a tool call by re-emitting the same call ID. The invariant that must be enforced instead is a *reconciliation* invariant, not a *parenting* invariant: > For every `execute_tool` span, there exists exactly one *anchor* span — the `invoke_agent` or `chat` span with the same `gen_ai.conversation.id` and the same `gen_ai.tool.call.id` in its `gen_ai.tool.call.id` attribute set — and the tool span must carry that anchor's `span_id` in a dedicated `gen_ai.tool.anchor_span_id` attribute, independent of `parent_span_id`. This decouples *logical correlation* (which the attributes carry) from *structural parenting* (which the SDK stamps and which the retry/resume path breaks). The anchor attribute survives context loss, process restart, and parent-span closure because it is computed from the call ID and conversation ID, both of which are in the agent's durable state. ## Decision Boundary The boundary is whether the tool executor can *reconstruct* the anchor at child-span creation time from durable state alone. If the executor holds only an in-memory `contextvars` snapshot, it is on the wrong side of the boundary: a checkpoint resume or a retry that crosses a process boundary loses the parent and the child orphans silently. If the executor holds the `(conversation.id, tool.call.id)` pair in its checkpointed request record, it can look up the anchor span ID from the trace store (or from the agent's own span registry) and stamp `gen_ai.tool.anchor_span_id` even when `parent_span_id` is wrong or absent. Two concrete guards follow: - **Anchor resolution on enqueue, not on dequeue.** Capture `anchor_span_id` at the moment the tool request is created (parent span still open), persist it in the request record, and stamp it on the child span at creation regardless of ambient context. - **Call-ID monotonicity for retries.** A retry must mint a new `gen_ai.tool.call.id` (e.g., suffix `:r1`) and record the original in `gen_ai.tool.retry_of`. Reusing the original ID is what causes dedup collapse and makes anchor resolution ambiguous when two anchors claim the same call ID. If neither guard is in place, the trace is *structurally* valid and *semantically* unusable: you cannot answer "which model turn caused this tool error" for any retried or resumed call. ## Operational Effect Without the anchor attribute, three operational queries fail: (1) error attribution — a failed retried tool call cannot be tied to the model turn that requested it, so you cannot tell whether the model or the tool was at fault; (2) latency accounting — the retry's duration is dropped by dedup, under-reporting tool latency by the retry factor; (3) sampling correctness — a tail sampler that keeps error spans but drops their (closed) parents yields orphaned error tool spans with no conversation context, so the sampled trace is unreadable. With the anchor invariant enforced, the span tree may still be structurally wrong (retry children parented to root), but every tool span is reconcilable to its logical anchor via `gen_ai.tool.anchor_span_id`, and the reconciliation is a pure function of attributes — no reliance on `parent_span_id`, no reliance on `contextvars`, no reliance on parent-span liveness. The tree becomes a *derived view* over the anchor relation rather than the source of truth. ```python from dataclasses import dataclass from typing import Optional class OrphanedToolCallError(RuntimeError): """Raised when an execute_tool span cannot be reconciled to a unique anchor span.""" @dataclass(frozen=True) class ToolRequest: conversation_id: str tool_call_id: str retry_of: Optional[str] anchor_span_id: Optional[str] # captured at enqueue, persisted in checkpoint def resolve_anchor(req: ToolRequest, known_anchors: dict[tuple[str, str], str]) -> str: """ Reconcile a tool request to exactly one anchor span. known_anchors maps (conversation_id, tool_call_id) -> anchor span_id, populated at enqueue time while the parent chat/invoke_agent span is open. """ if req.retry_of is not None and req.tool_call_id == req.retry_of: # Retry reused the original call id: anchor resolution is ambiguous. raise OrphanedToolCallError( f"retry for {req.tool_call_id!r} reused the original call id; " f"mint a new id and record retry_of={req.retry_of!r}" ) key = (req.conversation_id, req.tool_call_id) anchor = req.anchor_span_id or known_anchors.get(key) if anchor is None: # No anchor captured at enqueue and no registry hit: the child span # will be parented to root with correct attributes but no logical edge. raise OrphanedToolCallError( f"no anchor span for conversation={req.conversation_id!r} " f"tool_call={req.tool_call_id!r}; span would orphan on resume" ) stamped = known_anchors.get(key) if stamped is not None and stamped != anchor: raise OrphanedToolCallError( f"conflicting anchors for {key!r}: {stamped!r} vs {anchor!r}" ) return anchor def emit_tool_span(req: ToolRequest, known_anchors: dict[tuple[str, str], str]) -> dict: anchor = resolve_anchor(req, known_anchors) return { "name": "execute_tool", "attributes": { "gen_ai.operation.name": "execute_tool", "gen_ai.tool.name": req.tool_call_id.split(":")[0], "gen_ai.tool.call.id": req.tool_call_id, "gen_ai.conversation.id": req.conversation_id, "gen_ai.tool.anchor_span_id": anchor, "gen_ai.tool.retry_of": req.retry_of, }, } ```