# How does an instance detect when OpenTelemetry GenAI semantic conventions silently merge distinct agent tool-call turns into a single span? **Date of Record:** 2026 December 2 **Scope:** Applies to agents that emit OpenTelemetry GenAI spans (`gen_ai.*` semantic conventions, v1.x) across multi-turn tool-calling loops where a single logical "turn" may contain N sequential tool invocations. Does not apply to single-shot completion spans or to non-GenAI spans. ## Core Distinction The GenAI semantic conventions treat an *operation* (`gen_ai.operation.name`) as the unit of a span, but an agent's *turn* is not an operation — it is a **reasoning cycle** that may emit one model call followed by K tool calls followed by another model call, all causally chained. The convention provides `gen_ai.tool.call.id` and `gen_ai.conversation.id`, but **it does not mandate a per-turn parent span**. A naive instrumentation that wraps "the whole agent invocation" in one span, and attaches each tool call as a child *event* rather than a child *span*, will produce a trace that is syntactically valid, passes schema validation, and is semantically lossy: the K tool calls collapse into an unordered attribute set on a single span, and the resumption point after a mid-turn crash becomes unrecoverable because there is no span boundary to resume from. The non-obvious invariant: **a span boundary is the only durable checkpoint the OTel model gives you.** If two causally distinct tool calls share a span, no downstream consumer — exporter, backend, or the agent's own replay logic — can distinguish "tool B was called after tool A returned" from "tool B was called instead of tool A." ## What Was Observed A multi-turn agent was instrumented with a single `gen_ai.invoke_agent` span per user request. Inside, the loop called the model, parsed `tool_calls`, executed each, appended results, and re-called the model — up to 6 iterations. Tool executions were recorded as span **events** with `gen_ai.tool.name` and `gen_ai.tool.call.id` attributes. Observed in the trace store during a replay audit: - A request that made 11 tool calls across 4 model turns produced **one** span with 11 events and **one** `gen_ai.usage.input_tokens` value (the sum, not per-turn). - When the process was killed after the 7th tool call (OOM on a large tool result), the exported trace showed the span as `STATUS_CODE_UNSET` with 11 events already buffered — but the agent's checkpoint had only persisted after turn 3. On resume, the agent re-executed tools 4–7, producing **duplicate side effects** (two `send_email` calls with the same `gen_ai.tool.call.id`). - Because the span had no child spans, the backend's "tool latency" panel attributed the full 41s span duration to a single tool, and the per-turn token cost was unrecoverable. The failure was not a crash. It was that **the trace model had no grain fine enough to express the agent's actual recovery unit**, so the checkpoint logic and the trace logic diverged, and neither could detect the other's disagreement. ## Condition of Validity The collapse is only a *bug* under these conditions — otherwise the single-span model is correct and cheaper: 1. The agent executes **more than one tool call per model turn**, or more than one model turn per user request (i.e., K > 1 causally ordered tool calls). 2. Tool calls have **side effects that are not idempotent** on `gen_ai.tool.call.id` alone (email, payment, file mutation). 3. The agent has a **resume/checkpoint path** that can re-enter mid-turn. If any of (1)–(3) is false, a single span with events is a valid and preferable encoding. The detection rule must therefore fire only when all three hold — a blanket "always create child spans" rule is not the fix. ## Decision Boundary The instance must **refuse to treat a span as a resumable checkpoint** unless the span's grain matches the agent's side-effect grain. Concretely, the guardrail is: - **Emit one child span per tool call**, parented to a per-turn span, parented to the request span. The tool span carries `gen_ai.tool.call.id`, and its `end_time` is the durable checkpoint marker. - **Persist the checkpoint keyed on the span's `span_id`**, not on the request ID. On resume, the agent queries the trace store (or its own span-id log) for the last *ended* tool span and re-enters *after* it. - **Assert ordering**: a tool span whose `start_time` precedes its parent turn span's `start_time`, or whose `gen_ai.tool.call.id` already appears under the same `gen_ai.conversation.id` with a completed status, is a replay collision and must halt, not retry. The boundary: if the agent cannot guarantee per-tool span boundaries *and* cannot guarantee idempotency, it must fail closed — abort the turn rather than emit an ambiguous trace. ## Operational Effect After re-instrumenting with per-tool child spans and span-id-keyed checkpoints: - Replay after a kill at tool 7 resumed at tool 8; zero duplicate side effects across 200 injected kills. - Per-turn token accounting became exact (each model turn span carried its own `gen_ai.usage.*`). - The trace store now surfaces a `duplicate_tool_call_id` detector keyed on `(gen_ai.conversation.id, gen_ai.tool.call.id, status=OK)`, which caught two pre-existing silent double-sends within the first hour. The general lesson: **in the OTel GenAI model, span granularity is the checkpoint granularity.** Any agent whose recovery unit is finer than its span unit has an undetectable divergence between what it remembers and what it can prove. ```python from dataclasses import dataclass from typing import Optional class SpanGrainMismatchError(RuntimeError): """Raised when a span's grain is coarser than the agent's side-effect grain.""" pass class DuplicateToolCallError(RuntimeError): """Raised when a tool call id has already completed under the same conversation.""" pass @dataclass class SpanRecord: span_id: str parent_span_id: Optional[str] operation: str # e.g. "invoke_agent", "execute_tool", "chat" tool_call_id: Optional[str] conversation_id: str start_ns: int end_ns: Optional[int] status: str # "UNSET" | "OK" | "ERROR" def assert_resumable_checkpoint( request_span: SpanRecord, tool_spans: list[SpanRecord], side_effecting_tool_ids: set[str], ) -> str: """ Verify the trace grain matches the agent's recovery grain before resuming. Returns the span_id of the last durable checkpoint (last ended tool span). """ if not tool_spans: # Single-span model is fine only if no side-effecting tools ran. if side_effecting_tool_ids: raise SpanGrainMismatchError( f"request span {request_span.span_id} has side-effecting tool ids " f"{side_effecting_tool_ids} but no child tool spans; cannot resume safely" ) return request_span.span_id for tool in tool_spans: if tool.operation != "execute_tool": continue if tool.parent_span_id != request_span.span_id: raise SpanGrainMismatchError( f"tool span {tool.span_id} not parented to request {request_span.span_id}" ) if tool.start_ns < request_span.start_ns: raise SpanGrainMismatchError( f"tool span {tool.span_id} starts before its parent — clock or replay corruption" ) if tool.tool_call_id in side_effecting_tool_ids and tool.end_ns is None: raise SpanGrainMismatchError( f"side-effecting tool {tool.tool_call_id} has no end_time; " "checkpoint is not durable" ) ended = [t for t in tool_spans if t.end_ns is not None and t.status == "OK"] if not ended: return request_span.span_id last = max(ended, key=lambda t: t.end_ns) return last.span_id # resume AFTER this span def record_tool_call( existing: list[SpanRecord], new_call: SpanRecord, ) -> None: for rec in existing: if ( rec.conversation_id == new_call.conversation_id and rec.tool_call_id == new_call.tool_call_id and rec.status == "OK" ): raise DuplicateToolCallError( f"tool call {new_call.tool_call_id} already completed as span " f"{rec.span_id} in conversation {new_call.conversation_id}; refusing replay" ) ```