# How does an instance detect span-attribute collapse when OpenTelemetry GenAI tool-call spans are emitted from a retried or re-entrant agent step **Date of Record:** 2026 November 27 **Scope:** Applies to agent runtimes that emit OpenTelemetry spans using the GenAI semantic conventions (`gen_ai.operation.name`, `gen_ai.tool.name`, `gen_ai.tool.call.id`, `gen_ai.usage.input_tokens`, `gen_ai.usage.output_tokens`, plus `gen_ai.system`/`gen_ai.request.model`) for tool-call tracing, where a single logical step may be retried, replayed, or re-entered after a checkpoint resume. Does not apply to stateless one-shot inference calls with no retry or resume path, nor to spans emitted by a collector-side processor that has already deduplicated by trace/span ID. ## Core Distinction The GenAI conventions treat a span as a *record of one model or tool invocation*. Agent runtimes, however, treat a step as an *idempotent logical unit that may execute more than once*. When these two models disagree, the observable symptom is not a missing span but a **span-attribute collapse**: multiple physical executions of the same logical tool call are folded into one span (or emitted with duplicate, indistinguishable identities), so the attributes that downstream auditors depend on — token counts, tool name, call ID, status — describe a hybrid of executions that never occurred. The invariant that breaks is *attribute-per-execution uniqueness*: every `gen_ai.tool.call.id` must map to exactly one emitted span whose `gen_ai.usage.*` and status reflect exactly one execution. Retries and re-entrant resumes silently violate it because the second execution re-uses the first execution's span context and call ID. ## What Was Observed A planner agent invokes a `search_documents` tool. The tool call exceeds the client-side deadline, the transport layer surfaces a timeout, and the agent's retry wrapper re-issues the identical call with the same `gen_ai.tool.call.id` (correctly, for idempotency at the tool layer). Two spans are emitted with identical `trace_id`, `span_id` is *not* identical but the runtime's span exporter has been configured with `gen_ai.tool.call.id` as the dedup key in a custom processor, so the second span overwrites the first. The surviving span carries: - `gen_ai.tool.name = search_documents` - `gen_ai.tool.call.id = call_7f3a…` (same for both executions) - `gen_ai.usage.input_tokens` from execution 1 (the timed-out attempt, which had already billed prompt tokens) - `gen_ai.usage.output_tokens` and `status.code = OK` from execution 2 - `gen_ai.response.finish_reasons = ["stop"]` from execution 2 The trace now asserts that a single call consumed execution-1 input tokens and produced execution-2 output tokens with an OK status. An auditor replaying the trace against the billing ledger finds a token delta that cannot be attributed to any single call. A token-budget guard reading the trace to decide whether to continue sees a *lower* total than was actually spent, because the overwritten span discarded execution 1's output-token cost. The failure is non-obvious because every individual attribute is well-formed and schema-valid; only the *joint* distribution is impossible. A second, distinct observation from the same class: after a checkpoint resume, the agent re-enters a step whose span was already closed before the checkpoint. The runtime re-emits the span with the *original* `span_id` (persisted in the checkpoint) but a *new* wall-clock start time and a fresh `gen_ai.usage.*` block. The backend rejects the duplicate `span_id` and drops the span entirely, so the resumed execution is invisible in the trace while its tokens are billed. Detection here is the inverse: the trace is missing a span that the ledger says must exist. ## Condition of Validity The collapse is only possible under a conjunction of three conditions, and bounding it requires breaking at least one: 1. **Call-ID reuse across executions.** The runtime propagates `gen_ai.tool.call.id` from the first attempt into the retry, either because the tool requires idempotency keys or because the span context is inherited from the parent step. This is the trigger. 2. **A dedup or upsert keyed on a non-unique attribute.** Either an exporter processor keyed on `gen_ai.tool.call.id`, or a backend that treats `span_id` as an upsert key, or a checkpoint that persists `span_id` for re-emission. This is the mechanism. 3. **No attempt-scoped discriminator.** The span carries no attribute that distinguishes execution 1 from execution 2 — no `gen_ai.tool.call.attempt`, no distinct `span_id` per attempt, no `retry.count`. This is the missing guardrail. If any one condition is absent, the collapse does not occur: distinct `span_id`s per attempt survive a call-ID-keyed dedup only if the dedup is keyed on `(call.id, span_id)`; a persisted `span_id` is harmless if the backend accepts re-emission with an updated timestamp; an attempt discriminator makes the two spans distinguishable even if both are retained. ## Decision Boundary The instance must decide, at span-emission time, whether it is emitting the *first* execution of a logical call or a *re-execution*. The boundary is drawn by asking: **does a span for this `gen_ai.tool.call.id` already exist in the current trace context, and is the current execution a retry/resume of the same logical step?** - If no prior span exists → emit with the call ID as assigned, `span_id` fresh, no attempt attribute (or `attempt=1`). - If a prior span exists and the current execution is a genuine retry → emit a *new* span with a fresh `span_id`, carry `gen_ai.tool.call.id` unchanged (for tool-layer idempotency), and add an attempt discriminator (`gen_ai.tool.call.attempt = 2`). The dedup key downstream must be `(trace_id, gen_ai.tool.call.id, attempt)`, never `gen_ai.tool.call.id` alone. - If a prior span exists and the current execution is a *resume* of a step whose span was already closed → do not re-emit the closed span. Emit a continuation span with a fresh `span_id`, `gen_ai.operation.name` preserved, and a link (`Span Link`) back to the closed span's `span_id`. The checkpoint must persist the *closed span's ID as a link target*, not as a re-emission key. The boundary is violated the moment the runtime cannot answer "have I already emitted for this call ID in this trace?" — which is exactly the state after a cold start from checkpoint, because the span context is reconstructed from persisted fields rather than from live in-memory span state. ## Operational Effect When the collapse occurs undetected, three downstream consumers are poisoned simultaneously: the **token-budget guard** under-counts spend (it reads the surviving span's usage, which is the cheaper of the two executions or a hybrid), the **auditor replay** cannot reconcile trace against ledger (token deltas with no attributable call), and the **failure-attribution loop** sees `status.code = OK` on a call that actually timed out once, so it never learns that the tool is flaky at this deadline. The compounding effect is that the agent's own retry policy is never corrected, because the evidence of the timeout was overwritten by the evidence of the success. The guardrail is a **span-identity invariant enforced at the exporter boundary**: reject any span whose `(trace_id, gen_ai.tool.call.id, attempt)` tuple already exists, and reject any span whose `span_id` matches a previously-closed span in the same trace unless it carries a `Span Link` to that span. This converts a silent overwrite into a loud, catchable error at emission time, before the trace is persisted and before the budget guard reads it. ```python from dataclasses import dataclass, field class SpanAttributeCollapseError(RuntimeError): """Raised when a GenAI tool-call span would overwrite a prior execution's attributes.""" @dataclass class GenAISpan: trace_id: str span_id: str call_id: str # gen_ai.tool.call.id attempt: int # gen_ai.tool.call.attempt (1-based) tool_name: str # gen_ai.tool.name input_tokens: int # gen_ai.usage.input_tokens output_tokens: int # gen_ai.usage.output_tokens status_code: str # status.code links: list[str] = field(default_factory=list) # span_ids of prior closed spans class SpanIdentityGuard: """Enforces attribute-per-execution uniqueness at the exporter boundary.""" def __init__(self) -> None: self._emitted_keys: set[tuple[str, str, int]] = set() self._closed_span_ids: dict[str, str] = {} # span_id -> trace_id def close(self, span: GenAISpan) -> None: self._closed_span_ids[span.span_id] = span.trace_id def emit(self, span: GenAISpan) -> None: key = (span.trace_id, span.call_id, span.attempt) if key in self._emitted_keys: raise SpanAttributeCollapseError( f"duplicate execution key {key}: attempt {span.attempt} of " f"call {span.call_id} already emitted; a retry must carry a " f"fresh attempt discriminator, not reuse the prior span's identity" ) # A resumed step must link to the closed span, never re-emit its span_id. if span.span_id in self._closed_span_ids: if span.span_id not in span.links: raise SpanAttributeCollapseError( f"span_id {span.span_id} already closed in trace " f"{self._closed_span_ids[span.span_id]}; re-emission after " f"checkpoint resume requires a Span Link, not identity reuse" ) self._emitted_keys.add(key) self.close(span) def replay_retry_sequence(guard: SpanIdentityGuard) -> None: first = GenAISpan( trace_id="t-1", span_id="s-1", call_id="call_7f3a", attempt=1, tool_name="search_documents", input_tokens=812, output_tokens=0, status_code="ERROR", ) guard.emit(first) # The buggy path: retry re-uses the same attempt number and span_id. retry_buggy = GenAISpan( trace_id="t-1", span_id="s-1", call_id="call_7f3a", attempt=1, tool_name="search_documents", input_tokens=812, output_tokens=214, status_code="OK", ) guard.emit(retry_buggy) # raises SpanAttributeCollapseError ```