# Why does an instance emit a duplicate gen_ai.tool.call.id span after MCP handoff but the parent trace shows a single invocation? **Date of Record:** 2026 November 29 **Scope:** Applies to agent runtimes that emit OpenTelemetry GenAI semantic-convention spans (`gen_ai.tool.call`, `gen_ai.retrieval`, `gen_ai.chat`) across an MCP/A2A handoff where the downstream process re-derives span identity from its own state rather than inheriting the upstream span context. Does not apply to single-process agents or to handoffs that propagate a full W3C `traceparent` plus a stable `gen_ai.tool.call.id`. ## Core Distinction The failure is not a missing span. It is a *semantically duplicated* span: the parent trace correctly records one logical tool invocation, but two child spans carry the same `gen_ai.tool.call.id` with divergent `gen_ai.tool.call.result` values, because the upstream runtime and the downstream MCP server each mint their own `gen_ai.tool.call.id` from a local monotonically-increasing counter (or a hash of `(tool_name, arguments)`), and the two counters collide on the same string while describing different executions. The distinction that matters operationally: **`gen_ai.tool.call.id` is specified as an identifier for a single tool execution, not as a correlation key for a logical intent.** When a handoff re-executes the tool (retry, idempotency miss, or speculative prefetch), the downstream emits a *new* execution whose id happens to equal the upstream's id. Trace consumers that treat the id as a join key — dashboards, eval harnesses, replay verifiers — then silently collapse two executions into one, or double-count them depending on aggregation direction. ## What Was Observed Trigger sequence, reproduced on an agent runtime using an MCP client that spawns the server as a subprocess per session: 1. Upstream agent decides to call `search_docs(query="retry policy")`. It mints `gen_ai.tool.call.id = "call-7"` from a per-session counter and emits a `gen_ai.tool.call` span with `status = UNSET`, `gen_ai.tool.call.result` unset (streaming, result not yet known). 2. The MCP transport times out at the client's `request_timeout` (default 30s) *after* the server has already begun execution. Client emits span close with `status = ERROR`, `error.type = "timeout"`, and — critically — **does not** propagate the span context to the server because the server was launched without `OTEL_PROPAGATORS` and the client's `inject()` only fires on the initial `tools/call` frame, not on the retry. 3. Client retries. The retry opens a *fresh* MCP session (new subprocess). The new server process resets its counter and mints `gen_ai.tool.call.id = "call-7"` again for the same logical invocation. 4. Server executes, returns result, emits its own `gen_ai.tool.call` span with `gen_ai.tool.call.id = "call-7"`, `gen_ai.tool.call.result = "{...}"`, `status = OK`, and — because it has no parent context — it becomes a *root* span in a new trace. The observable trace now contains, under the same `trace_id` only if the collector's `groupbytrace` processor merges by resource, or under two separate `trace_id`s otherwise: - Span A: `gen_ai.tool.call.id="call-7"`, `status=ERROR`, `error.type="timeout"`, no result. - Span B: `gen_ai.tool.call.id="call-7"`, `status=OK`, result present. A replay verifier that joins on `gen_ai.tool.call.id` sees one id with contradictory status and result, and — depending on iteration order — either reports a spurious success (B overwrites A) or a spurious failure (A overwrites B). Neither is the truth: the tool executed twice, once timed out client-side, once succeeded server-side. ## Condition of Validity The duplicate-id collision is only possible when all three hold: 1. **Local id minting.** The `gen_ai.tool.call.id` is generated from process-local state (counter, timestamp, `uuid4` truncated to low entropy) rather than inherited from the initiating span's `span_id` or a UUIDv7 carried in the request payload. 2. **Context non-propagation on retry.** The retry path does not re-inject `traceparent`/`tracestate`, so the downstream server cannot adopt the upstream span context and instead starts a new trace. 3. **Non-idempotent execution with observable side effects.** The tool actually ran on the server before the client timeout, so the "duplicate" is a real double-execution, not a phantom. If any one fails, the invariant "one `gen_ai.tool.call.id` ⇒ one execution" holds. The dangerous case is (1)+(2) with a *read-only* tool: no side effect, but the replay verifier still mis-joins and the eval harness records a phantom retry, inflating tool-call latency percentiles by the timeout duration. ## Decision Boundary The architectural invariant to enforce: **`gen_ai.tool.call.id` must be derived from the initiating span context, not from local state, and must be propagated through every retry and handoff.** Concretely: - Mint `gen_ai.tool.call.id` as `f"{trace_id}:{span_id}"` of the initiating `gen_ai.chat` span, or as a UUIDv7 written into the `tools/call` `params._meta` field and echoed by the server. - On retry, reuse the *same* id and set `gen_ai.tool.call.retry.count` (a non-standard attribute; register it in your schema) so the verifier can distinguish "one execution retried" from "two executions." - Configure `OTEL_PROPAGATORS=tracecontext,baggage` on the MCP server subprocess and re-inject on every request, including retries. - In the replay verifier, treat `(gen_ai.tool.call.id, status)` as the join key, and reject any group where `status=OK` and `status=ERROR` coexist without a `retry.count` attribute — that is the signature of the collision. The boundary between "acceptable duplicate" and "corrupting duplicate" is whether the verifier can reconstruct execution count from the trace alone. If it cannot, the trace is non-authoritative and any downstream eval, cost attribution, or SLO computed from it is unsound. ## Operational Effect Left unguarded, the collision produces three concrete degradations: 1. **Cost attribution drift.** Token and tool-call cost is attributed to `gen_ai.tool.call.id`; a collided id bills the successful execution's tokens to the errored span's parent chat turn, understating the retry's true cost by the full timeout window's compute. 2. **Eval-harness false negatives.** Replay verifiers that join on id alone report the agent as "succeeded on first try" when the first try timed out — masking a real reliability regression in the MCP transport until it manifests as a user-visible failure. 3. **Retrieval-span contamination.** If the tool is a retrieval (`gen_ai.retrieval`), the duplicate carries two different `gen_ai.retrieval.documents` payloads under one `gen_ai.tool.call.id`; downstream RAG evaluation double-counts recall and inflates the retrieval-quality metric. The guardrail is cheap (one propagation config, one id-derivation rule) and the failure is silent until a metric is audited. Treat `gen_ai.tool.call.id` as a *derived, propagated* identifier, never a *minted, local* one, and validate the invariant at trace-ingest time. ```python from __future__ import annotations import re from dataclasses import dataclass from typing import Iterable class DuplicateToolCallIdError(RuntimeError): """Raised when a trace contains collided gen_ai.tool.call.id values with contradictory terminal statuses and no retry marker.""" @dataclass(frozen=True) class ToolCallSpan: trace_id: str span_id: str tool_call_id: str status: str # "OK" | "ERROR" | "UNSET" error_type: str | None retry_count: int | None result_present: bool _ID_PATTERN = re.compile(r"^[0-9a-f]{32}:[0-9a-f]{16}$") def validate_tool_call_ids(spans: Iterable[ToolCallSpan]) -> None: """Enforce: one gen_ai.tool.call.id => one execution, or an explicit retry marker.""" by_id: dict[str, list[ToolCallSpan]] = {} for span in spans: by_id.setdefault(span.tool_call_id, []).append(span) for call_id, group in by_id.items(): # Invariant 1: id must be derived from span context, not minted locally. if not _ID_PATTERN.match(call_id): raise DuplicateToolCallIdError( f"gen_ai.tool.call.id={call_id!r} is not of form " f"':'; it was minted from local state and " f"cannot be safely joined across handoffs." ) statuses = {s.status for s in group} retry_marked = any((s.retry_count or 0) > 0 for s in group) # Invariant 2: OK and ERROR under one id require an explicit retry marker. if "OK" in statuses and "ERROR" in statuses and not retry_marked: raise DuplicateToolCallIdError( f"gen_ai.tool.call.id={call_id!r} has both OK and ERROR spans " f"without gen_ai.tool.call.retry.count; this is the signature " f"of a non-propagated retry after MCP handoff. " f"Spans: {[(s.span_id, s.status, s.error_type) for s in group]}" ) # Invariant 3: at most one terminal OK per id (retries must be marked). ok_spans = [s for s in group if s.status == "OK"] if len(ok_spans) > 1 and not retry_marked: raise DuplicateToolCallIdError( f"gen_ai.tool.call.id={call_id!r} has {len(ok_spans)} OK spans " f"but no retry marker; tool executed more than once under one id." ) def ingest(spans: list[ToolCallSpan]) -> None: validate_tool_call_ids(spans) # downstream: emit to collector, attribute cost, feed eval harness ```