How should an instance reconcile OpenTelemetry GenAI tool-call spans when a model emits a tool_call whose id is replayed across a resumed agent run
**Date of Record:** 2026 December 2 **Scope:** Applies to agents that emit OpenTelemetry GenAI spans (`gen_ai.operation.name`, `gen_ai.tool.name`, `gen_ai.tool.call.id`, `gen_ai.response.id`) and that checkpoint/resume mid-run such that a model invocation is replayed. Does not apply to stateless single-shot inference with no persistence, nor to backends that key spans on `trace_id`+`span_id` alone without deduplicating tool-call ids.
Core Distinction
A model invocation event and a tool-call execution event are two different observability objects that share an identifier namespace in the GenAI semantic conventions. The model invocation span carries `gen_ai.response.id` (stable per provider response) while each tool call carries `gen_ai.tool.call.id` (stable per *emitted* call, not per *executed* call). On a clean run these are 1:N and monotonic.
On a resumed run they are not. When an agent checkpoints after the model invocation but before tool execution completes, the resume path re-drives the same model output — including the same `tool_call.id` values — because the id is a property of the sampled token sequence, not of the execution attempt. The span emitter then produces a *second* tool-call span with an identical `gen_ai.tool.call.id` under a *new* `span_id`. The distinction that matters operationally: **`gen_ai.tool.call.id` is a model-output artifact; `span_id` is an execution artifact.** Any reconciliation logic that treats the former as a primary key for the latter silently double-counts, double-attributes latency, and corrupts cost accounting.
What Was Observed
A research agent with a 90-second tool timeout checkpointed its conversation state (messages + pending tool calls) to durable storage after each model turn. On resume, the driver replayed the last assistant message verbatim, re-extracted the `tool_calls` array, and re-dispatched each call. The tool executor emitted GenAI spans per the conventions:
- parent span: `gen_ai.operation.name=chat`, `gen_ai.response.id=resp_9fA...`
- child span: `gen_ai.operation.name=execute_tool`, `gen_ai.tool.name=search_docs`, `gen_ai.tool.call.id=call_7Xb2...`
The failure trace, over one incident:
- Turn 4 model invocation returns `resp_9fA` containing two tool calls, `call_7Xb2` and `call_7Xb3`.
- `call_7Xb2` completes in 800ms; its span is exported.
- `call_7Xb3` hits the 90s timeout; the executor raises, the driver checkpoints, and the process is killed.
- Resume re-drives turn 4. The provider is *not* re-called (response cached in checkpoint), but the driver re-extracts both `tool_calls` and re-dispatches. `call_7Xb2` executes *again* — a duplicate side effect — and emits a second span with the same `gen_ai.tool.call.id=call_7Xb2`, a different `span_id`, and a fresh `start_time`.
- Downstream, the trace backend shows `call_7Xb2` twice under two different parent span_ids (the original `resp_9fA` span and the resumed one). Latency dashboards summed both; the 800ms call was billed twice; the span count for `search_docs` was inflated by ~40% across the incident window.
The non-obvious part: the *provider* did not re-emit anything. The duplicate was manufactured entirely by the resume driver re-reading a cached response and re-deriving ids from it. No retry logic, no at-least-once queue — just a checkpoint that stored model output as if it were execution state.
Condition of Validity
The invariant that makes reconciliation possible: **for a given `trace_id`, the tuple (`gen_ai.response.id`, `gen_ai.tool.call.id`) must map to at most one *executed* tool-call span, and any additional span bearing the same tuple is a replay artifact that must be marked, not merged.**
This holds only under three conditions:
- The provider's `gen_ai.response.id` is stable across the checkpoint (i.e., the resume path reuses the cached response rather than re-sampling). If the resume re-samples the model, a new `response.id` is minted and the ids are genuinely new — the invariant fails open and the duplicate is legitimate.
- The executor records a `gen_ai.tool.call.id` at *dispatch* time, before the tool runs, so a crash mid-execution leaves a span with a terminal status of `error`/`cancelled` rather than no span at all. Without this, a crash between dispatch and export produces a gap that is indistinguishable from "never called."
- The resume driver consults the checkpoint's *execution ledger* (which call ids reached a terminal span) before dispatching, not merely the conversation state.
If condition 3 is absent — the common case — the system is in a state where the observability layer is correct per-span but the aggregate is wrong. The GenAI conventions do not require an execution ledger; they describe span shape, not resume semantics. That gap is where the failure lives.
Decision Boundary
The boundary is between **replay-safe** and **replay-unsafe** call ids, and it is decided by whether the tool is idempotent *and* whether the driver dedupes on the execution ledger.
- **Idempotent read tools** (`search_docs`, `read_file`): a duplicate span is a metrics artifact only. Reconcile by collapsing spans sharing (`response.id`, `tool.call.id`) to the earliest terminal span, and annotate the rest with `gen_ai.tool.call.replay=true`.
- **Non-idempotent write tools** (`send_email`, `create_ticket`, `transfer_funds`): a duplicate span means a duplicate *side effect*. This is not an observability bug; it is a correctness bug that the span duplication merely *reveals*. The decision boundary here is hard: the driver must refuse to re-dispatch any `tool.call.id` present in the execution ledger with a terminal status, and must instead synthesize a tool-result message from the ledger's stored output.
- **Ambiguous** (tool timed out, no terminal span): must be treated as *possibly executed*. Re-dispatch requires an idempotency key derived from `(response.id, tool.call.id)` passed to the tool itself, so the tool can dedupe at its own layer.
The invariant to enforce at the driver: **the checkpoint must persist the set of `tool.call.id`s that reached a terminal span, and resume must partition pending calls into {never-dispatched, dispatched-unknown, dispatched-terminal} before acting.** Conflating "in the conversation state" with "needs execution" is the exact error.
Operational Effect
Without the ledger, three effects compound:
- **Cost and latency double-counting** in any dashboard that aggregates by `gen_ai.tool.name` — the most common GenAI SLO query — because replay spans are indistinguishable from fresh ones by attribute alone.
- **Silent duplicate side effects** on non-idempotent tools, with the trace showing two successful spans and no error, so the duplicate is invisible to alerting and only surfaces as a downstream data anomaly.
- **Trace-tree corruption**: a resumed run produces a second `chat` span for the same `response.id` (if the invocation span is also re-emitted), giving two parents for the same logical turn. Trace UIs that assume a single parent per `response.id` render an orphaned subtree.
The guardrail is a resume-time reconciliation pass that treats `(response.id, tool.call.id)` as a composite key, consults the execution ledger, marks replay spans explicitly, and refuses re-dispatch of terminal non-idempotent calls. The GenAI conventions give you the attributes to do this; they do not give you the ledger, and the ledger is the part that prevents the duplicate.
from dataclasses import dataclass, field
from typing import Optional
from datetime import datetime
class ReplayReconciliationError(RuntimeError):
"""Raised when a resumed agent run would re-dispatch a tool call whose
(response_id, tool_call_id) already reached a terminal span, or when the
execution ledger is missing for a non-idempotent pending call."""
pass
@dataclass(frozen=True)
class ToolCallKey:
response_id: str # gen_ai.response.id
tool_call_id: str # gen_ai.tool.call.id
tool_name: str # gen_ai.tool.name
@dataclass
class ExecutionRecord:
key: ToolCallKey
span_id: str
terminal: bool
status: str # "ok" | "error" | "cancelled"
start_time: datetime
output: Optional[str] = None
@dataclass
class ExecutionLedger:
records: dict[ToolCallKey, ExecutionRecord] = field(default_factory=dict)
def record_terminal(self, rec: ExecutionRecord) -> None:
existing = self.records.get(rec.key)
if existing is not None and existing.terminal and existing.status == "ok":
# A second terminal-ok for the same key is a replay artifact.
# Keep the first; do not overwrite.
return
self.records[rec.key] = rec
def lookup(self, key: ToolCallKey) -> Optional[ExecutionRecord]:
return self.records.get(key)
NON_IDEMPOTENT_TOOLS = {"send_email", "create_ticket", "transfer_funds"}
def reconcile_resume(
pending_calls: list[ToolCallKey],
ledger: ExecutionLedger,
) -> list[ToolCallKey]:
"""Partition pending calls into those safe to dispatch vs. those that must
be reconstructed from the ledger. Returns the calls still needing dispatch."""
to_dispatch: list[ToolCallKey] = []
for key in pending_calls:
rec = ledger.lookup(key)
if rec is None:
# Never dispatched (or dispatched without a ledger write — unsafe).
if key.tool_name in NON_IDEMPOTENT_TOOLS:
raise ReplayReconciliationError(
f"No execution ledger entry for non-idempotent tool "
f"{key.tool_name!r} call_id={key.tool_call_id!r} "
f"under response_id={key.response_id!r}; refusing to "
f"re-dispatch, as the call may have partially executed."
)
to_dispatch.append(key)
continue
if rec.terminal:
# Already executed; synthesize tool result from ledger, do not re-run.
continue
# Dispatched but not terminal (crash mid-execution): ambiguous.
if key.tool_name in NON_IDEMPOTENT_TOOLS:
raise ReplayReconciliationError(
f"Ambiguous state for non-idempotent tool {key.tool_name!r} "
f"call_id={key.tool_call_id!r}: dispatched at span {rec.span_id} "
f"but no terminal status. Re-dispatch requires an idempotency "
f"key derived from (response_id, tool_call_id)."
)
to_dispatch.append(key)
return to_dispatch
def emit_tool_span(
key: ToolCallKey,
span_id: str,
ledger: ExecutionLedger,
now: datetime,
) -> ExecutionRecord:
"""Emits a tool-call span record, marking replays explicitly so downstream
aggregation by gen_ai.tool.name does not double-count."""
existing = ledger.lookup(key)
is_replay = existing is not None and existing.span_id != span_id
rec = ExecutionRecord(
key=key,
span_id=span_id,
terminal=False,
status="running",
start_time=now,
)
if is_replay:
# gen_ai.tool.call.replay=true attribute must be set on the span.
rec.status = "replay"
ledger.records.setdefault(key, rec)
return rec