# What happens when an instance emits GenAI span attributes for a tool-calling turn whose tool results arrive after the parent span has already ended **Date of Record:** 2026 November 21 **Scope:** Applies to agents instrumented with OpenTelemetry GenAI semantic conventions (`gen_ai.*`) where tool execution is asynchronous relative to the model invocation span. Does not apply to fully synchronous single-shot call chains where every tool result is produced before the parent `gen_ai.chat` span closes. ## Core Distinction The GenAI semantic conventions model a chat turn as a span that *contains* its tool calls: the `gen_ai.chat` span is expected to carry `gen_ai.usage.input_tokens`, `gen_ai.usage.output_tokens`, and a set of tool-call child spans or events, all finalized before the parent span ends. This encodes a hidden invariant: **all attributes describing a turn are known at the moment the turn's span is closed.** Multi-turn tool-calling agents violate this invariant by design. The model emits a tool call, the span that represents "the model produced this reasoning step" *ends*, and only later does the tool return. The result is that a naive instrumenter either (a) keeps the parent span open across the tool round-trip, inflating its duration to include wall-clock time the model was not running, or (b) closes the parent span at generation time and then cannot attach the tool result, the follow-up tokens, or the corrected usage counts to anything. The distinction that matters operationally: a *turn* is not a *span*. The boundary condition is the gap between the model's generation span and the tool's completion, and what the telemetry says about the tokens and calls that live in that gap. ## What Was Observed A tool-calling agent loop instrumented with the GenAI conventions on a three-step task (search → read → summarize) produced trace trees where: - The `gen_ai.chat` span for the turn that *requested* the tool closed with `gen_ai.usage.output_tokens` reflecting only the tool-call emission, not the eventual answer. - The subsequent `gen_ai.chat` span (the one that consumed the tool result) was emitted as a **sibling**, not a child, of the requesting span, because the requesting span had already ended and the OTel SDK rejected late-arriving child spans under a finished parent — they were silently reparented to the nearest live ancestor or dropped depending on SDK version. - Total tokens reported by summing `gen_ai.usage.*` across the trace undercounted by the tool-result ingestion tokens, because those were attributed to a span that shared no causal edge with the request that produced the tool call. - When the tool call failed and the agent retried, the retry's `gen_ai.chat` span carried no link to the failed attempt; the trace showed two independent generations with no `gen_ai.tool.call.id` correlation surviving the span boundary. The concrete failure trace: the agent's control loop held the tool-call ID in its own state, but the telemetry layer had already flushed and closed the span. The tool-call ID existed only in the agent's memory, never in the trace, so a downstream auditor reconstructing the turn from spans alone saw an orphaned generation with no tool edge. ## Condition of Validity The convention holds — spans faithfully represent a turn — only when the tool result is available before the generation span closes. This is true for: - Synchronous function-calling where the tool is a pure in-process function and the runtime executes it inline before returning control. - Single-turn agents that emit at most one generation span per user message and never resume after a tool. It is **invalid** for any agent that (1) suspends execution across a tool call, (2) resumes in a different process or after a checkpoint, or (3) runs tools concurrently with generation. In those cases the span-as-turn model is structurally wrong, and the correct model is a *turn span* that encloses the generation span, the tool spans, and the resumption generation span as children — with `gen_ai.usage.*` aggregated on the turn span, not the generation span. ## Decision Boundary The instrumenter must decide, per turn, whether to: 1. **Close-on-generate** (span ends when the model stops emitting): correct for latency accounting of the model alone, but requires an explicit parent *turn* span to preserve causality and a `gen_ai.tool.call.id` attribute on both the requesting generation and the consuming generation so the edge is reconstructable from attributes even when the span tree cannot represent it. 2. **Close-on-turn** (span stays open across the tool round-trip): preserves tree causality but corrupts duration semantics — the span's duration now includes tool wall-clock and suspension time, so any latency SLO computed from `gen_ai.chat` duration is meaningless. There is no option that preserves both duration fidelity and tree causality without an added turn-level span. The boundary is crossed the moment a tool result arrives after the generation span has ended; past that point, the only recoverable design is attribute-level correlation (`gen_ai.tool.call.id`, `gen_ai.conversation.id`) plus an enclosing turn span, because the span tree can no longer be repaired after the fact. ## Operational Effect Downstream consumers of the trace — cost attributors, latency dashboards, and replay auditors — inherit the defect silently: - **Cost attribution** undercounts because tool-result tokens land on a span with no causal link to the request; per-conversation rollups that sum child spans miss them. - **Replay** cannot reconstruct the turn because the tool-call ID was never persisted to telemetry; an auditor replaying from spans sees a generation with no tool, then an unexplained generation. - **Retry analysis** loses the failed attempt entirely when the retry is reparented, so failure rates computed from span trees undercount tool-failure-induced regenerations. The guardrail is a turn-scoped span that is opened before the first generation and closed only after the last tool result is ingested, carrying aggregated usage and a stable `gen_ai.conversation.id`; generation spans remain children with their own accurate durations. The invariant to enforce in code: **no generation span may be closed while a tool call it emitted is still pending, unless a turn span exists to receive the eventual result and the tool-call ID is written to both spans before close.** ```python class OrphanedToolCallError(RuntimeError): """Raised when a generation span closes while a tool call it emitted is still pending and no enclosing turn span exists to receive the eventual result.""" pass class GenAITurnSpan: def __init__(self, conversation_id: str, parent_span): self.conversation_id = conversation_id self.parent_span = parent_span self.pending_tool_calls = set() self.aggregated_input_tokens = 0 self.aggregated_output_tokens = 0 self.closed = False def record_generation(self, span, tool_call_ids, input_tokens, output_tokens): if self.closed: raise OrphanedToolCallError( f"generation recorded after turn span {self.conversation_id} closed" ) self.aggregated_input_tokens += input_tokens self.aggregated_output_tokens += output_tokens for call_id in tool_call_ids: span.set_attribute("gen_ai.tool.call.id", call_id) self.pending_tool_calls.add(call_id) return span def close_generation(self, span): # Guard: refuse to close a generation span with un-resolved tool calls # unless this turn span will absorb the result. if self.pending_tool_calls and self.parent_span is None: raise OrphanedToolCallError( f"generation span closed with pending tool calls " f"{sorted(self.pending_tool_calls)} and no turn span to receive them" ) span.end() def record_tool_result(self, tool_call_id, result_span): if tool_call_id not in self.pending_tool_calls: raise OrphanedToolCallError( f"tool result for unknown or already-resolved call {tool_call_id}" ) result_span.set_attribute("gen_ai.tool.call.id", tool_call_id) self.pending_tool_calls.discard(tool_call_id) def close(self): if self.pending_tool_calls: raise OrphanedToolCallError( f"turn {self.conversation_id} closed with unresolved tool calls " f"{sorted(self.pending_tool_calls)}" ) if self.parent_span is not None: self.parent_span.set_attribute( "gen_ai.usage.input_tokens", self.aggregated_input_tokens ) self.parent_span.set_attribute( "gen_ai.usage.output_tokens", self.aggregated_output_tokens ) self.parent_span.end() self.closed = True ```