# Which invariants prevent OTel GenAI agent spans from silently collapsing retried tool calls into a single logical invocation **Date of Record:** 2026 November 25 **Scope:** Applies to agents that emit OpenTelemetry GenAI semantic-convention spans (`gen_ai.operation.name`, `gen_ai.tool.call.id`, `gen_ai.usage.input_tokens`, etc.) where a single logical tool invocation may be retried, hedged, or re-executed across model turns. Does not apply to single-shot, non-retried model calls or to tracing systems that do not carry `trace_id`/`span_id` linkage across agent handoffs. ## Core Distinction There is a difference between a *tool attempt* and a *tool invocation*. The OTel GenAI conventions define attributes for `execute_tool` spans (`gen_ai.tool.name`, `gen_ai.tool.call.id`, `gen_ai.tool.type`) and for model client spans (`gen_ai.usage.input_tokens`, `gen_ai.usage.output_tokens`, `gen_ai.request.model`). What the conventions do **not** mandate is a stable parent-child topology that distinguishes a retried attempt from a fresh invocation when the model re-emits the same tool call after a transient failure. The failure mode is this: the agent's retry loop re-enters the tool executor, the executor emits a *new* `execute_tool` span with the *same* `gen_ai.tool.call.id` (because the model replayed the same call ID from its prior turn), and the backend aggregation — which keys model-invocation metrics by `call.id` — double-counts or silently deduplicates depending on ingestion order. The invariant that prevents this is that **`gen_ai.tool.call.id` must be unique per emitted attempt, and logical-invocation identity must be carried on a separate attribute** (e.g., `gen_ai.tool.invocation.id`) that is stable across retries. ## What Was Observed A three-turn agent (plan → tool → synthesize) called a `search_documents` tool. The first attempt hit a 503 from the upstream service; the executor retried after 400 ms and succeeded. Both attempts emitted spans. The model client span for turn 2 reported `gen_ai.usage.input_tokens=1820`, `output_tokens=210`, and the tool span carried `gen_ai.tool.call.id="call_9f3a"` on both attempts because the model had serialized that ID into its tool-call JSON and the retry loop reused the serialized payload verbatim. In the collector, the span processor batched by `(trace_id, gen_ai.tool.call.id)` to compute a per-call latency histogram. Because both attempts shared the key, the histogram recorded a single sample at the *first* attempt's duration (the failed one, 312 ms including timeout) and dropped the second. The model-invocation metric for turn 2 counted the tool result once, but the *error* counter incremented once for the failed attempt and was never decremented. Downstream, the agent's own semantic-memory write recorded a "tool succeeded on first try" summary because the executor returned success and the span with `status=ERROR` was orphaned in a batch that the exporter flushed after the success span. The observable symptom: dashboards showed tool error rate 4.1% while the agent's task success rate was 99.2% — an impossible gap that took two days to trace to the shared call ID. ## Condition of Validity The single-call-ID-per-attempt invariant holds only when all three of the following are true: 1. The executor treats `gen_ai.tool.call.id` as *attempt-scoped*, minting a fresh ID (or appending an attempt suffix such as `call_9f3a#2`) for every re-entry, and never reuses the model-supplied ID as the span's sole identity. 2. The retry loop propagates a stable `gen_ai.tool.invocation.id` (derived from the original model turn's call ID plus a logical-invocation counter) so that aggregation can collapse attempts *by intent* while keeping attempts *distinct by span*. 3. The exporter's batch ordering does not allow a late-flushed `ERROR` span to arrive after a `OK` span for the same logical invocation without an explicit reconciliation step — because OTel does not guarantee intra-trace span delivery ordering across separate export batches. If any condition fails, the failure is silent: no exception is raised, the agent's task completes, and the corruption is only visible as a metric inconsistency. ## Decision Boundary The boundary is whether the agent's retry policy is *inside* or *outside* the span-emitting boundary. - **Retry inside the executor span:** the executor opens one `execute_tool` span, and internal retries are recorded as span *events* (`retry.attempt`, `retry.reason`) on that single span. This is correct and safe — one span, one call ID, attempts visible as events. Use this when retries are fast (<1 s) and do not change the tool's observable contract. - **Retry outside the executor span:** the orchestrator re-enters the executor, producing multiple `execute_tool` spans. This is correct *only if* the executor mints attempt-scoped call IDs and carries the invocation ID separately. Use this when retries cross turn boundaries, change the model context, or involve a different backend (e.g., fallback tool). The dangerous middle ground — retry outside the span but reusing the model's serialized call ID — is the exact configuration that produced the observed corruption. It arises naturally because the model's tool-call payload is treated as immutable input, and the retry loop replays it without rewriting identity fields. ## Operational Effect The guardrail is a two-attribute identity contract enforced at the executor boundary, plus a collector-side reconciliation that refuses to fold attempts under a shared key. Concretely: - Every `execute_tool` span carries `gen_ai.tool.call.id` unique to the attempt and `gen_ai.tool.invocation.id` stable across attempts. - The span processor asserts that no two spans in the same trace share `(gen_ai.tool.call.id)`; a violation raises at export time rather than silently aggregating. - Model-invocation metrics key on `invocation.id`, not `call.id`, so token and latency totals reflect logical work while attempt-level error counters remain honest. Without this, the agent's own memory distillation (which reads back its traces to write episodic summaries) ingests the corrupted view and reinforces a false belief about tool reliability — a second-order failure where the observability layer poisons the agent's semantic memory. The invariant is not merely a metrics hygiene concern; it is a continuity invariant for the agent's self-model. ```python class GenAiSpanIdentityCollision(RuntimeError): """Raised when two execute_tool spans in one trace share gen_ai.tool.call.id.""" pass def mint_tool_attempt_identity( model_call_id: str, invocation_seq: int, attempt_seq: int, ) -> dict: """ Build the identity attributes for an execute_tool span. model_call_id : the ID the model serialized into its tool-call payload invocation_seq: logical invocation counter for this model turn (0-based) attempt_seq : retry attempt counter within the invocation (0-based) Invariant: gen_ai.tool.call.id is attempt-scoped and unique per span; gen_ai.tool.invocation.id is stable across retries of the same intent. """ if not model_call_id: raise GenAiSpanIdentityCollision( "model_call_id is empty; cannot derive attempt identity" ) if attempt_seq < 0 or invocation_seq < 0: raise GenAiSpanIdentityCollision( f"negative sequence: invocation={invocation_seq} attempt={attempt_seq}" ) invocation_id = f"{model_call_id}:inv{invocation_seq}" call_id = f"{invocation_id}:att{attempt_seq}" return { "gen_ai.tool.call.id": call_id, "gen_ai.tool.invocation.id": invocation_id, "gen_ai.tool.attempt": attempt_seq, } def assert_no_call_id_collision(spans: list[dict]) -> None: """ Enforce the per-trace uniqueness invariant before export. Called by the span processor; a collision must fail loudly, not aggregate. """ seen: dict[tuple[str, str], int] = {} for span in spans: attrs = span.get("attributes", {}) call_id = attrs.get("gen_ai.tool.call.id") if call_id is None: continue key = (span.get("trace_id", ""), call_id) if key in seen: raise GenAiSpanIdentityCollision( f"duplicate gen_ai.tool.call.id={call_id!r} in " f"trace={span.get('trace_id')!r}; attempt-scoped IDs required" ) seen[key] = 1 ```