# How should an instance reconcile orphaned tool spans when a model-emitted call ID is reused across a retry boundary **Date of Record:** 2026 November 30 **Scope:** Applies to agent runtimes that propagate OpenTelemetry-style trace/span context across model invocations, tool dispatches, and retry boundaries, where tool-call identifiers are generated by the model rather than the runtime. Does not apply to runtimes that mint runtime-authoritative call IDs and treat model IDs as opaque metadata, nor to single-shot inference with no tool loop. ## Core Distinction The distinction that matters is between a *call identifier as a correlation key* and a *call identifier as an identity claim*. Most observability pipelines treat the model-emitted `tool_call.id` (e.g., `call_a8Xk2`) as a unique correlation key: the runtime opens a span named `tool.execute` with `tool.call_id=call_a8Xk2`, and the exporter joins the model's `tool_call` span to the tool's execution span on that string. This is sound only if the ID is *globally unique within the trace*. It is not. The model is a probabilistic generator of these strings; it has no registry, no monotonic counter, and no memory of which IDs it already emitted earlier in the same conversation. When the runtime retries a failed step, re-prompts after a context truncation, or forks a sub-agent from a checkpoint, the model can—and under temperature and prefix-shift pressure does—re-emit an ID it used before. The second `call_a8Xk2` is a *different logical invocation* wearing the *same correlation key*. The failure is not a duplicate-ID error. Nothing throws. The exporter happily accepts two spans with `tool.call_id=call_a8Xk2`, and the trace backend, which assumes one-to-one join, silently collapses them: the second tool execution is attributed to the first model span, the first tool's latency is added to the second's parent, and the causal chain from model reasoning to tool result is severed for one of the two branches. The trace *looks complete*—every span has a parent, no orphans flagged—while the causal graph is wrong. This is the observability equivalent of a false negative: the pipeline reports success on a corrupted join. ## What Was Observed A three-step agent (plan → tool → synthesize) was instrumented with a standard span-per-boundary model. The tool dispatch step called an external search API. On the first attempt the API returned a 503 after 8.2s; the runtime's retry policy re-invoked the *entire* model turn (not just the tool), because the retry wrapper sat above the model call. The model, seeing the same prompt prefix plus a "previous attempt failed" system note, regenerated its tool call and—with `temperature=0.7`—emitted `call_a8Xk2` again, a string it had produced on attempt one. Trace dump after the run, filtered on that ID: - `model.turn` span A, attempt 1, `tool_call.id=call_a8Xk2`, duration 1.9s - `tool.execute` span A, attempt 1, `tool.call_id=call_a8Xk2`, duration 8.2s, `status=ERROR` (503) - `model.turn` span B, attempt 2, `tool_call.id=call_a8Xk2`, duration 2.1s - `tool.execute` span B, attempt 2, `tool.call_id=call_a8Xk2`, duration 0.4s, `status=OK` Four spans, two distinct logical invocations, one key. The backend's join produced two *merged* tool executions: each `model.turn` was linked to *both* `tool.execute` spans. The synthesized answer's span showed a p99 latency of 10.3s (the sum of both attempts) and `tool.status=ERROR` inherited from span A, even though the run succeeded on attempt 2. Downstream alerting fired on the ERROR status for a run that never actually failed. Worse, the retry attribution was inverted: the analysis dashboard reported "retry did not improve tool latency" because span B's 0.4s success was averaged against span A's 8.2s failure under the same key. The mechanism is precise: the runtime's retry wrapper is *above* the model boundary, so it re-runs the model, which re-emits the ID. Had the retry wrapper sat *below* the model boundary (re-invoking only the tool with the already-materialized arguments), the ID would have been stable and the join correct. The span-linking invariant is violated not by the retry itself but by the *retry's placement relative to the ID-generating boundary*. ## Condition of Validity The one-to-one join on `tool.call_id` is valid if and only if the following invariant holds: > For every trace, the map from `tool.call_id` to logical tool invocation is injective, and the runtime—not the model—is the authority that assigns or disambiguates the key. This invariant is *not* satisfied by default because the ID originates in the model's token stream. It is satisfied only when the runtime enforces one of: 1. **Runtime-minted call IDs.** The runtime generates a UUID at dispatch time and records the model's emitted ID as a *separate* attribute (`model.call_id`, non-unique, for display only). The join key is the runtime UUID. This is the correct default and the only one that is robust to arbitrary model behavior. 2. **Attempt-scoped namespacing.** If the model ID must be the key, the runtime appends a retry/attempt discriminator: `call_a8Xk2#a2`. The join is then on `(call_id, attempt)`. This works only if every span in the branch carries the same attempt tag, which requires the attempt counter to be propagated through the context, not read from ambient state. 3. **Fork/checkpoint lineage tags.** When a sub-agent is forked from a checkpoint, the fork inherits the parent's conversation including prior IDs. The fork must stamp a `lineage_id` on all spans so that a reused ID in the child is distinguishable from the parent's. Without this, a forked agent's first tool call can collide with its parent's last. The invariant fails silently under any of: retry-above-model, context truncation that drops the prior tool-call record (so the model "forgets" it used the ID and is free to reuse it), temperature-driven sampling that happens to regenerate a prior string, and fork-from-checkpoint without lineage tagging. None of these raise; all produce a well-formed-but-wrong causal graph. ## Decision Boundary The runtime must decide, at span-emission time, whether the model-emitted ID is *trusted as a join key* or *demoted to an attribute*. The decision boundary is the presence of a runtime-authoritative discriminator. Concretely: - If the runtime has minted its own call UUID → join on UUID, model ID is display metadata. No further action. - If the runtime has *not* minted a UUID but *has* a reliable attempt counter in context → join on `(model_id, attempt)`. Acceptable, but fragile: any code path that dispatches a tool outside the retry wrapper will lack the attempt tag and produce a null-keyed span. - If neither → the runtime is in the unsafe regime and must *refuse to emit a tool span keyed solely on the model ID*. The correct behavior is to emit the span with `tool.call_id` unset and `tool.call_id_unverified=true`, forcing the trace backend to treat it as non-joinable rather than mis-joinable. A non-joinable span is a visible gap; a mis-joined span is an invisible lie. The boundary rule is: *prefer a detectable orphan over an undetectable collision.* The boundary is crossed—and the guardrail must fire—when a runtime attempts to open a tool span with a model-derived key while lacking a discriminator, or when it detects that the key it is about to use already exists in the current trace's span set with a different parent. The latter is the cheap runtime check: before emitting, consult the in-process span registry for the key; if present under a different logical parent, the key is reused and must be namespaced or demoted. ## Operational Effect With the guardrail in place, the failure mode converts from silent graph corruption to an explicit, countable event: `orphaned_tool_span` increments, the trace shows a gap at the collision, and the retry attribution is preserved because each attempt carries its own key. The 10.3s merged latency collapses back to two honest spans (8.2s error, 0.4s success), and the "retry did not improve latency" false signal disappears because the two attempts are no longer averaged under one key. The deeper operational lesson is that span linking across the model boundary is a *trust* decision, not a formatting decision. The model is an untrusted generator of correlation keys; the runtime is the only party that can guarantee injectivity. Any pipeline that joins on model-emitted strings without a runtime discriminator is asserting an invariant it does not enforce, and the assertion fails precisely at the retry and fork boundaries—the moments when observability matters most. ```python from dataclasses import dataclass, field from typing import Optional class SpanLinkCollisionError(RuntimeError): """Raised when a tool span would be keyed on a model-emitted call ID that already exists in the trace under a different logical parent, or when no runtime-authoritative discriminator is available.""" pass @dataclass class SpanRegistry: # key -> parent_span_id of the span that owns this key keys: dict[str, str] = field(default_factory=dict) def open_tool_span( registry: SpanRegistry, model_call_id: str, parent_span_id: str, attempt: Optional[int], runtime_uuid: Optional[str] = None, ) -> str: """Open a tool execution span, returning the join key to stamp on it. Invariant: the returned key must be injective within the trace. The model-emitted ID is only trusted when a runtime discriminator (runtime_uuid or attempt) is present to disambiguate reuse. """ if runtime_uuid is not None: # Preferred: runtime-authoritative key. Model ID is display-only. key = f"rt:{runtime_uuid}" elif attempt is not None: # Acceptable: attempt-scoped namespacing of the model ID. key = f"{model_call_id}#a{attempt}" else: # Unsafe regime: no discriminator. Refuse to emit a joinable span. raise SpanLinkCollisionError( f"cannot key tool span on model ID {model_call_id!r}: " "no runtime_uuid or attempt discriminator; " "emitting would risk silent mis-join on retry or fork" ) existing_parent = registry.keys.get(key) if existing_parent is not None and existing_parent != parent_span_id: # Key already claimed by a different logical parent: reuse detected. raise SpanLinkCollisionError( f"call key {key!r} already owned by parent {existing_parent!r}, " f"attempted reuse under parent {parent_span_id!r}; " "namespace by lineage_id or mint a fresh runtime_uuid" ) registry.keys[key] = parent_span_id return key ```