# Where must an instance reject OpenTelemetry GenAI spans whose `gen_ai.tool.call.id` is reused across loop iterations, and why does the attribute model itself forbid the obvious fix? **Date of Record:** 2026 November 30 **Scope:** Applies to any agent runtime that emits OTel GenAI semantic-convention spans for tool invocations and agent-loop iterations, and to any downstream collector, evaluator, or replay harness that joins spans by `gen_ai.tool.call.id`. Does not apply to runtimes that emit custom span schemas outside the GenAI conventions, or to single-shot tool calls with no loop. ## Core Distinction The GenAI semantic conventions treat `gen_ai.tool.call.id` as a *correlation key* whose semantics are "the identifier the model/provider returned for this specific tool call," not "the identifier of the logical operation." These are different things the moment an agent loops. A retry, a re-plan, or a fan-out that re-invokes the same tool with the same arguments is a *new* tool call at the provider layer, but a naive runtime that derives the call id from `(tool_name, canonical_args_hash)` — a common optimization to make tracing "stable" across retries — will emit multiple spans sharing one `gen_ai.tool.call.id`. The convention does not forbid this syntactically (it is a string attribute), but it silently breaks the invariant that every span-joining consumer depends on: **one call id, one execution, one outcome.** The correct boundary is to reject the span at emit time rather than let a duplicated key propagate into the trace store, because the corruption is undetectable downstream — a joined trace with a duplicated call id looks structurally valid. ## What Was Observed A planner-executor agent on a 40-iteration budget was instrumented per the GenAI conventions. The runtime computed `gen_ai.tool.call.id = sha1(tool_name + sorted_json(args))[:16]` so that "the same call" would correlate across retries — a deliberate choice to make dashboards stable. On a task that repeatedly called `read_file(path="config.yaml")`, the following span sequence was emitted: - iteration 7: `execute_tool` span, call id `9f2c…`, status OK, `gen_ai.tool.name=read_file`. - iteration 8: same call id `9f2c…`, status ERROR (`FileNotFoundError`), because a concurrent writer had renamed the file between iterations. - iteration 9: same call id `9f2c…`, status OK, contents now different. Three spans, one key, two statuses, three distinct payloads. The evaluator that joins `execute_tool` spans to `chat` spans by call id attributed the iteration-8 error to the iteration-9 success (last-write-wins in its join map), and the replay harness — which reconstructs the loop by sorting spans on call id — collapsed all three into a single logical step, reconstructing a 38-iteration trajectory from a 40-iteration run. The divergence was invisible: no span was malformed, no attribute was missing, and the trace passed schema validation. ## Condition of Validity The invariant holds only under the following condition: **`gen_ai.tool.call.id` must be unique within the trace (and, for cross-trace joins, within the session) and must be bound 1:1 to a single provider-issued tool-call event.** This is satisfiable only when the id is sourced from the provider's response (e.g., the `tool_calls[].id` field in a chat completion) or from a monotonic runtime counter that increments on every *dispatch*, not on every *distinct argument set*. Any derivation from content (argument hashing, name+args tuples, semantic dedup) violates the condition the first time the loop retries, re-plans, or re-reads mutable state. The condition also fails silently under fan-out: if a planner emits two parallel tool calls with identical arguments (legitimate — e.g., polling two replicas), content-derived ids collide within a single iteration, and the two `execute_tool` spans become indistinguishable to any consumer that keys on call id alone. The convention offers `gen_ai.tool.call.id` as the join key precisely because the provider guarantees uniqueness per response; the runtime inherits that guarantee only if it preserves the provider's id verbatim. ## Decision Boundary The decision boundary is at span *emit* time, not at query time. A runtime must choose between two policies: 1. **Preserve-and-verify (correct):** take the provider-issued id, and if the provider did not issue one (some local tool runtimes synthesize calls), mint a fresh UUIDv7 per dispatch. Maintain an in-process set of ids seen in the current trace; on collision, this is a hard error — it means either the provider violated uniqueness or the runtime synthesized a duplicate. 2. **Derive-and-hope (incorrect):** hash content for stability. This is the failure above. The boundary is sharp because there is no downstream repair. A collector cannot distinguish "the same call retried" from "two calls with the same id" from "a provider bug" — all three present identically. The only place the information exists is the runtime's dispatch site, so the check must live there. Retrofitting uniqueness at the collector is impossible without the dispatch log, which is exactly what the trace was supposed to be. Note the asymmetry with `gen_ai.operation.name` and `gen_ai.tool.name`: those are *descriptive* and may legitimately repeat. `gen_ai.tool.call.id` is *identifying*; repetition is always a defect. ## Operational Effect Enforcing preserve-and-verify changes three downstream behaviors: - **Replay fidelity.** A replay harness can reconstruct the loop by sorting on `(trace_id, span start time)` and treating each call id as one step; duplicated ids no longer collapse iterations. - **Error attribution.** Evaluators that join tool errors to the originating `chat` span get the right iteration, because the join key no longer aliases. - **Retry accounting.** Retries become visible as distinct spans with distinct ids but a shared `gen_ai.tool.name` and a `retry.count` attribute — the loop's true cost is observable, where the content-hash scheme hid retries inside a single "logical" call. The cost is that dashboards keyed on content-hash ids break on upgrade; the migration is to re-key on the new ids and add a `call.args.hash` attribute for the stability the old scheme provided, without conflating it with identity. ```python import hashlib import uuid from dataclasses import dataclass, field class DuplicateToolCallIdError(RuntimeError): """Raised when a tool-call span would reuse an id already bound in this trace.""" @dataclass class ToolCallSpan: call_id: str tool_name: str args: dict status: str = "OK" @dataclass class TraceEmitter: trace_id: str _bound_ids: set[str] = field(default_factory=set) def emit_tool_call(self, provider_call_id: str | None, tool_name: str, args: dict) -> ToolCallSpan: # Preserve the provider-issued id; mint a fresh one only if absent. call_id = provider_call_id or str(uuid.uuid4()) if call_id in self._bound_ids: raise DuplicateToolCallIdError( f"gen_ai.tool.call.id={call_id!r} already bound in trace {self.trace_id}; " f"tool={tool_name!r}. A call id must identify exactly one dispatch. " f"Do not derive the id from content (name+args hash); mint per dispatch." ) self._bound_ids.add(call_id) return ToolCallSpan(call_id=call_id, tool_name=tool_name, args=args) def args_hash(self, tool_name: str, args: dict) -> str: # Stability for dashboards, kept separate from identity. canonical = f"{tool_name}:{sorted(args.items())}" return hashlib.sha1(canonical.encode()).hexdigest()[:16] def run_loop(emitter: TraceEmitter, iterations: int) -> list[ToolCallSpan]: spans = [] for i in range(iterations): # Simulate a provider that reuses an id on retry (a real provider bug). provider_id = "9f2c1a2b3c4d5e6f" if i < 3 else None try: spans.append(emitter.emit_tool_call(provider_id, "read_file", {"path": "config.yaml"})) except DuplicateToolCallIdError: # Runtime policy: mint a fresh id and record the provider anomaly. spans.append(emitter.emit_tool_call(None, "read_file", {"path": "config.yaml"})) return spans if __name__ == "__main__": em = TraceEmitter(trace_id="trace-abc") out = run_loop(em, iterations=5) assert len({s.call_id for s in out}) == len(out), "call ids must be unique" print(f"emitted {len(out)} unique tool-call spans") ```