# Which invariants prevent GenAI agent spans from silently losing tool-call causality across retries **Date of Record:** 2026 November 27 **Scope:** Applies to any agent runtime that emits OpenTelemetry GenAI semantic-convention spans (`gen_ai.*`) for LLM invocations and tool executions, particularly when tool calls are retried, deduplicated, or replayed by orchestration layers. Does not address pure LLM-only observability without tool execution, nor non-OTel tracing backends. ## Core Distinction The GenAI semantic conventions describe *what* an LLM or tool operation did (`gen_ai.operation.name`, `gen_ai.request.model`, `gen_ai.usage.input_tokens`, `gen_ai.tool.name`, `gen_ai.tool.call.id`), but they do **not** prescribe a causal join key between a `gen_ai.tool.call.id` emitted by the model's tool-call block and the tool-execution span that actually ran. The convention leaves correlation to "the parent span." This is fine for a single successful attempt. It is catastrophic for retries. The failure mechanism: when an orchestrator retries a failed tool call, it typically emits a *new* tool-execution span under the *same* parent LLM span, but the model's original `gen_ai.tool.call.id` was already recorded as an attribute on the parent. Downstream consumers that join `tool.call.id → tool span` now see two tool spans for one call-id, or a call-id with no matching span if the retry reuses a fresh id. Token accounting double-counts, and the retrieval-augmented generation (RAG) span that fed the tool gets orphaned because its `gen_ai.retrieval` linkage only pointed at the first attempt. The invariant that must hold: **every `gen_ai.tool.call.id` recorded on a model span must resolve to exactly one terminal tool-execution span, and that span must be the one whose output was actually fed back into the next model turn.** Retries must not create a second span under the same id; they must create a child attempt span, or mutate the existing span's status. ## What Was Observed A multi-step agent (planner → retrieval tool → summarizer) was instrumented with `gen_ai` spans. The planner emitted a tool call with `gen_ai.tool.call.id = "call_7f3a"` and `gen_ai.tool.name = "vector_search"`. The executor's first attempt hit a timeout at 30s and the orchestrator retried. The retry used a *new* generated id `call_9b21` (because the model was re-invoked to regenerate the call block on retry). The parent LLM span therefore carried `call_7f3a` in `gen_ai.tool.call.id`, but the surviving tool span carried `call_9b21`. The trace backend showed: - Parent model span: 1 tool call referenced, `input_tokens=1840`, `output_tokens=210`. - Tool span A (`call_7f3a`): status `ERROR`, duration 30s, no output attribute. - Tool span B (`call_9b21`): status `OK`, duration 4s, `gen_ai.retrieval.documents_count=12`. - Next model turn: `input_tokens=3110` (the retrieved docs), but no attribute linking those docs to `call_7f3a`. The join `call_7f3a → tool span` returned the errored span. Any evaluator that scored "did the retrieval succeed for this call" read `ERROR` and marked the turn as a retrieval failure, even though the retry succeeded and the summarizer consumed real documents. Token cost was double-counted because both the failed attempt's prompt tokens and the retry's prompt tokens were summed against the same logical call. ## Condition of Validity The correlation invariant holds only if the orchestrator treats `gen_ai.tool.call.id` as **immutable for the logical call**, not as a per-attempt identifier. The convention's `gen_ai.tool.call.id` is defined as "the id of the tool call" from the model's perspective — it is a *logical* identifier, and retries are attempts within that logical call. Therefore: 1. The retry MUST reuse the original `gen_ai.tool.call.id` and instead open a child span (`gen_ai.tool.attempt=2`) or set the existing span's `otel.status_code` to `ERROR` and emit a sibling with an explicit `retry_of` link. 2. The parent LLM span's `gen_ai.tool.call.id` MUST NOT be re-derived from a re-generated model response; if the model is re-invoked to regenerate the call, the new call is a *new* logical call and the old one must be explicitly closed as abandoned. 3. Retrieval telemetry (`gen_ai.retrieval.*`) MUST be attached to the attempt span that actually produced the documents, and the parent model span's next-turn `input_tokens` MUST be attributable to that attempt via span link, not via id equality. Outside these conditions — e.g., if the runtime uses call-id purely as a per-attempt trace key — the invariant cannot be enforced and downstream joins are undefined. ## Decision Boundary The boundary is: **does the orchestrator regenerate the tool-call block on retry, or replay the original?** - If it *replays* the original call block (same arguments, same id), the invariant is trivially preserved; no new span should be created, only a status mutation or child attempt span. - If it *regenerates* (new id), the invariant is violated unless the runtime emits an explicit `gen_ai.tool.call.id.abandoned` event on the old id and links the new id as a replacement. Absent that link, the trace is causally broken. The decision point in code is the retry handler: it must inspect whether the retry source is the original model output or a fresh model invocation. If fresh, it must not overwrite the parent's `gen_ai.tool.call.id`; it must close the prior call and record a `gen_ai.tool.call.replacement_id`. ## Operational Effect Without the invariant, three concrete degradations occur: (1) evaluation harnesses that join on call-id score retries as failures, poisoning agent-quality metrics; (2) token accounting double-counts retried prompts, inflating cost-per-task and mis-tuning budget guards; (3) RAG attribution breaks — retrieved documents cannot be traced to the model turn that consumed them, so retrieval-quality regressions are invisible. With the invariant enforced, retries become *visible* as attempt children rather than *invisible* as duplicate ids, and the parent-child span tree remains a faithful causal record of what the agent actually executed. ```python from dataclasses import dataclass, field from typing import Optional class ToolCallCausalityError(RuntimeError): """Raised when a gen_ai.tool.call.id does not resolve to exactly one terminal tool-execution span, violating the retry correlation invariant.""" pass @dataclass class Span: name: str attributes: dict = field(default_factory=dict) status: str = "UNSET" parent: Optional["Span"] = None children: list = field(default_factory=list) def record_tool_attempt( parent_model_span: Span, call_id: str, attempt: int, outcome: str, replacement_id: Optional[str] = None, ) -> Span: """Emit a tool-execution span under a model span, enforcing that the logical call id is immutable across retries. The parent's gen_ai.tool.call.id must equal call_id. On a regenerated retry (new id), the caller must pass replacement_id and the prior id must already be closed as abandoned. """ parent_call_id = parent_model_span.attributes.get("gen_ai.tool.call.id") if parent_call_id is None: raise ToolCallCausalityError( f"parent span {parent_model_span.name!r} has no gen_ai.tool.call.id; " "cannot attribute tool execution" ) if replacement_id is not None: # Regenerated retry: the logical call id changed. The parent must # carry the abandoned marker or the trace is causally broken. abandoned = parent_model_span.attributes.get("gen_ai.tool.call.abandoned") if abandoned != parent_call_id: raise ToolCallCausalityError( f"retry with replacement_id={replacement_id!r} but parent call id " f"{parent_call_id!r} was not marked abandoned; " "downstream joins will double-count or orphan" ) if call_id == parent_call_id: raise ToolCallCausalityError( "replacement retry must carry a new call id, not the original" ) else: if call_id != parent_call_id: raise ToolCallCausalityError( f"tool attempt call_id={call_id!r} does not match parent " f"gen_ai.tool.call.id={parent_call_id!r}; " "replay retries must reuse the logical id" ) span = Span( name=f"execute_tool {parent_model_span.attributes.get('gen_ai.tool.name', '?')}", attributes={ "gen_ai.tool.call.id": call_id, "gen_ai.tool.attempt": attempt, "gen_ai.tool.replacement_id": replacement_id, }, status=outcome, parent=parent_model_span, ) parent_model_span.children.append(span) return span def resolve_call(spans: list, call_id: str) -> Span: """Exactly one terminal tool span must resolve for a call id.""" matches = [ s for s in spans if s.attributes.get("gen_ai.tool.call.id") == call_id and s.status in ("OK", "ERROR") ] if len(matches) != 1: raise ToolCallCausalityError( f"call id {call_id!r} resolved to {len(matches)} terminal spans; " "invariant requires exactly one" ) return matches[0] ```