# Which invariants prevent span-parent corruption when OpenTelemetry GenAI tool-call graphs are reconstructed across agent re-entrancy **Date of Record:** 2026 November 24 **Scope:** Applies to agents that emit OpenTelemetry GenAI spans (`gen_ai.operation.name`, `gen_ai.tool.name`, `gen_ai.agent.id`) for tool-call graphs where a single logical agent turn may suspend and resume (human-in-the-loop, async tool completion, or checkpoint/restore). Does not apply to stateless single-shot inference spans with no tool fan-out. ## Core Distinction The GenAI semantic conventions describe *what* a span represents (`gen_ai.operation.name = execute_tool`, `chat`, `invoke_agent`) but they do **not** define a parent-child invariant that survives agent re-entrancy. The tracer's ambient context (`contextvars` in Python, `AsyncLocalStorage` in Node) is a *thread/task-local* pointer to the current span. When an agent suspends mid-tool-call and resumes on a different task, the ambient context is either lost (cold resume) or stale (warm resume on a reused worker). The distinction that matters: **span identity is logical (belongs to the agent turn), but span parenting is physical (inherited from ambient context at emit time).** Any reconstruction that conflates these two produces a tool-call graph whose edges do not match the causal graph the agent actually executed. ## What Was Observed An `invoke_agent` span `A` (agent turn) emits a `chat` span `C1`, which requests tool `T1`. `T1` is a long-running async operation. The agent checkpoints and the worker task ends; span `A` remains open (or is serialized as a checkpoint with its `trace_id`/`span_id`). On resume, a fresh worker picks up the checkpoint and executes `T1`'s completion, emitting `execute_tool` span `T1'`. Three failure traces were observed: 1. **Orphaned tool span.** The resumed worker has no ambient context. `T1'` is emitted as a new root span with a new `trace_id`. The reconstructed graph shows `T1'` as a disconnected root, not a child of `A`. Downstream latency attribution attributes 100% of the tool's wall-clock to a phantom trace. 2. **Mis-parented sibling.** The worker is reused and still carries the ambient context of a *previous* agent turn `A_prev`. `T1'` is parented under `A_prev`, silently attaching a tool call to the wrong agent turn. The graph is connected—and wrong. This is the dangerous case: dashboards look healthy. 3. **Duplicate tool span.** The checkpoint resume re-emits `T1'` while the original worker's deferred `T1` emission also fires on timeout. Two `execute_tool` spans with the same `gen_ai.tool.name` and same logical call, different `span_id`, both parented under `A`. The graph double-counts the tool call and the verifier sees a fan-out of 2 where the agent executed 1. The root cause in all three: the parent link is captured from *ambient context at emit time*, not from the *agent's recorded causal parent at call time*. The semantic conventions give you `gen_ai.agent.id` and `gen_ai.conversation.id` as attributes but no normative rule binding a tool span's `parent_span_id` to the `chat` span that requested it. ## Condition of Validity Reconstruction is only sound when all of the following hold: - The agent records the requesting `chat` span's `span_id` **at the moment the tool call is decided**, and persists that `span_id` in the checkpoint alongside the tool invocation payload. - On resume, the emitter sets the parent **explicitly** from the persisted `span_id` (via `trace.set_span_in_context` / `Context` construction), never from ambient context. - A resume token (idempotency key = `trace_id` + requesting `span_id` + `gen_ai.tool.name` + call index) is written before the tool executes and checked on every emission path, so the timeout path and the resume path cannot both emit. - The worker clears ambient context at task boundary (explicit `context.detach` / `AsyncLocalStorage.run` with a fresh store) so a reused worker cannot inherit `A_prev`. If any of these is missing, the graph is structurally connected but causally wrong, and no downstream span processor can detect it—the OTel SDK validates that a parent span *exists*, not that it is the *correct* parent. ## Decision Boundary Choose explicit-parent reconstruction (persist `span_id`, set parent from checkpoint) over ambient-context inheritance whenever **any** of: tool calls can outlive a worker task; the agent checkpoints; workers are pooled/reused; or a single agent turn emits tool spans from more than one execution context. Ambient inheritance is acceptable only for fully synchronous, single-task agent turns with no suspension. The boundary is suspension, not tool count: a 50-tool synchronous turn is safe under ambient context; a 1-tool turn that awaits human approval is not. ## Operational Effect Without the invariant, tool-call graphs silently mis-attribute latency, break verifier replay (the auditor reconstructs a different graph than the executor emitted), and fail consensus checks that compare fan-out counts. Enforcing persisted-parent + idempotency key + context clearing converts all three failure traces into a single detectable condition: a resume whose persisted `span_id` no longer exists in the trace (parent-evicted) raises at emit time rather than producing an orphan. The cost is one extra attribute write per tool call; the benefit is that graph edges become a function of agent state, not of worker scheduling. ```python from dataclasses import dataclass class SpanParentCorruption(RuntimeError): """Raised when a resumed tool span cannot be soundly parented.""" pass @dataclass(frozen=True) class ToolCheckpoint: trace_id: str requesting_span_id: str # the chat span that decided the tool call tool_name: str call_index: int def idempotency_key(self) -> str: return f"{self.trace_id}:{self.requesting_span_id}:{self.tool_name}:{self.call_index}" def emit_resumed_tool_span( checkpoint: ToolCheckpoint, ambient_parent_span_id: str | None, known_span_ids: set[str], emitted_keys: set[str], ) -> dict: # Invariant 1: parent must come from the checkpoint, not ambient context. if ambient_parent_span_id is not None and ambient_parent_span_id != checkpoint.requesting_span_id: raise SpanParentCorruption( f"ambient parent {ambient_parent_span_id} != persisted parent " f"{checkpoint.requesting_span_id}; refusing to mis-parent {checkpoint.tool_name}" ) # Invariant 2: the persisted parent must still exist in the trace. if checkpoint.requesting_span_id not in known_span_ids: raise SpanParentCorruption( f"persisted parent {checkpoint.requesting_span_id} evicted from trace " f"{checkpoint.trace_id}; cannot attach {checkpoint.tool_name}" ) # Invariant 3: idempotency key prevents timeout/resume double-emit. key = checkpoint.idempotency_key() if key in emitted_keys: raise SpanParentCorruption( f"duplicate emission for {key}; tool call already recorded" ) emitted_keys.add(key) return { "name": f"execute_tool {checkpoint.tool_name}", "trace_id": checkpoint.trace_id, "parent_span_id": checkpoint.requesting_span_id, # explicit, from checkpoint "attributes": { "gen_ai.operation.name": "execute_tool", "gen_ai.tool.name": checkpoint.tool_name, "gen_ai.agent.id": checkpoint.trace_id, }, } ```