# Why does an instance lose trace correlation when a model span re-enters a tool span under retry **Date of Record:** 2026 November 28 **Scope:** Applies to agent runtimes that propagate a single correlation ID (trace/span ID) across model invocations, tool calls, and sub-agent handoffs, where a tool call is retried or replayed after a model-side failure. Does not apply to purely stateless single-shot inference with no tool loop, nor to systems that regenerate a fresh correlation ID per span with no parent linking. ## Core Distinction There is a difference between *ID propagation* and *ID identity continuity*. Most agent frameworks propagate a correlation ID by copying it into the span context at each boundary. That is not the same as guaranteeing the ID is the same ID at every hop. The distinction matters because a model span and a tool span have different lifecycle owners: the model span is owned by the inference client (which may retry internally on 429/5xx or on a malformed tool-call schema), while the tool span is owned by the tool executor (which may retry on timeout). When both layers retry independently, the correlation ID can fork: the model client re-emits a *new* parent span on its internal retry while the tool executor still holds the *old* correlation ID from the first attempt. The trace is no longer a tree; it is two trees that share a leaf. The invariant that must hold is: **for any given logical agent task, the correlation ID is immutable across all retries of all descendant spans.** The failure mode is when a retry layer re-derives the ID from a fresh root context rather than from the captured parent context. ## What Was Observed A three-hop agent executed `plan -> search_tool -> summarize`. The runtime injected `correlation_id=C7A1` at the planner. The planner emitted a model span `M1` (parent `C7A1`) and a tool-call intent for `search_tool`. The tool executor opened span `T1` (parent `M1`, correlation `C7A1`). The search backend returned a 503. The tool executor's retry policy fired: it re-opened `T2` with parent `M1` and correlation `C7A1` — correct so far. The problem surfaced one hop up. The inference client wrapping the model call had its own retry policy on malformed function-call JSON. On the second model turn (after `T2` succeeded), the model emitted a tool call whose `arguments` field was truncated mid-JSON. The inference client caught the parse error and retried the *model call itself*, but it rebuilt the request from the agent's root context rather than the captured `M1` context. The retried model span came back as `M2` with a **new** correlation ID `C7A2`, because the client's retry helper called `start_span()` with `parent=None` when the captured parent handle had been garbage-collected after the first attempt. Result: the trace store held two disjoint traces. `C7A1` contained `M1 -> T1 (failed) -> T2 (ok)` and stopped. `C7A2` contained a fresh `M2'` and a *duplicate* `T2'` that re-executed the search. The summarizer, running under `C7A2`, saw a tool result that had actually been produced under `C7A1`. The join key was broken, and the duplicate tool execution was invisible in either trace because each trace only saw its own half. The tell was a non-monotonic span count: the summarizer's context listed three tool results but the union of both traces contained four tool spans. The correlation ID had silently forked at the model-retry boundary, and the tool executor had no way to know its second invocation was a replay rather than a new request. ## Condition of Validity The fork is only possible under a conjunction of three conditions, and the guardrail only needs to break one: 1. **Independent retry ownership.** The model client and the tool executor each own a retry loop, and neither consults the other's attempt counter. 2. **Parent-context reconstruction from root.** The retrying layer rebuilds the span context from the agent's root handle instead of from the captured parent span object. This is the actual bug — it happens when the parent handle is a short-lived object (a context manager, a `with` block variable, or a coroutine-local that is popped on exception) rather than a durable reference. 3. **No idempotency key on the tool call.** If the tool call carried a deterministic idempotency key derived from `(correlation_id, tool_name, canonical_args)`, the duplicate `T2'` would have been deduplicated at the executor and the fork would have been harmless. If any one is false, the trace stays coherent. Condition 2 is the one that is easiest to violate accidentally, because it looks like correct cleanup: releasing the parent span handle on attempt completion is standard resource hygiene, but it destroys the only durable reference the retry path needs. ## Decision Boundary The decision is whether to make correlation continuity a *captured* property or a *reconstructed* property. - **Reconstruct from root** (the failing pattern): cheap, requires no state threading, but forks under independent retry. Use only when exactly one layer owns retries and the other is a pure function. - **Capture at boundary** (the correct pattern): every span that may be retried must hold a durable, immutable reference to its parent context — not a handle that can be closed, but a serialized `(correlation_id, parent_span_id, attempt_epoch)` tuple that survives the retry. The retry path must re-open from that tuple, never from root. - **Idempotency key** (the belt-and-suspenders): derive `idempotency_key = hash(correlation_id, canonical_args)` and have the tool executor reject or dedupe replays with a matching key. This bounds the *blast radius* of a fork even when it happens, converting a duplicate side effect into a logged collision. The boundary rule: **a correlation ID may only be minted at the task root; every retry, at every layer, must re-open from a captured parent tuple, and any tool with side effects must carry an idempotency key.** Minting anywhere below root is the defect. ## Operational Effect When the invariant holds, trace correlation is a reliable join key: you can reconstruct the full causal chain of a task across model, tool, and sub-agent spans by filtering on one ID, and duplicate tool executions are detectable as idempotency-key collisions rather than invisible forks. When it breaks, you get two symptoms that are easy to misdiagnose: (a) traces that look *complete* individually but whose span counts don't reconcile across the task, and (b) replayed side effects (duplicate writes, duplicate searches, duplicate charges) that appear in no single trace because each trace owns only one execution. The reconciliation check — union of all traces sharing a task must equal the expected span multiset, with no duplicate idempotency keys — is the cheapest detector and should run as a post-task audit rather than relying on eyeballing a trace viewer. ```python import hashlib from dataclasses import dataclass class TraceCorrelationForkError(RuntimeError): """Raised when a retry re-opens a span from root instead of captured parent.""" @dataclass(frozen=True) class SpanContext: correlation_id: str parent_span_id: str | None attempt_epoch: int def open_retry_span( captured: SpanContext | None, root_correlation_id: str, layer: str, ) -> SpanContext: # Invariant: a correlation ID is minted only at the task root. # Any retry below root MUST re-open from the captured parent tuple. if captured is None: if layer != "root": raise TraceCorrelationForkError( f"layer={layer} attempted to mint correlation_id={root_correlation_id!r} " "from root during a retry; parent context was not captured. " "This forks the trace and duplicates downstream tool spans." ) return SpanContext(root_correlation_id, None, 0) if captured.correlation_id != root_correlation_id: raise TraceCorrelationForkError( f"correlation mismatch: captured={captured.correlation_id!r} " f"root={root_correlation_id!r} at layer={layer}" ) # Re-open from captured tuple; increment epoch, never re-mint the ID. return SpanContext( correlation_id=captured.correlation_id, parent_span_id=captured.parent_span_id, attempt_epoch=captured.attempt_epoch + 1, ) def idempotency_key(correlation_id: str, tool_name: str, canonical_args: str) -> str: return hashlib.sha256( f"{correlation_id}|{tool_name}|{canonical_args}".encode() ).hexdigest() def execute_tool_with_replay_guard( ctx: SpanContext, tool_name: str, canonical_args: str, seen_keys: set[str], ) -> str: key = idempotency_key(ctx.correlation_id, tool_name, canonical_args) if key in seen_keys: # Replay under same correlation ID: dedupe, do not re-execute. return f"deduped:{key}" seen_keys.add(key) return f"executed:{key}" ```