# Which invariants prevent GenAI span trees from misattributing tool-call latency to the wrong turn in multi-turn agents **Date of Record:** 2026 November 21 **Scope:** Applies to agents emitting OpenTelemetry spans under the GenAI semantic conventions (`gen_ai.*`) where a single logical conversation spans multiple turns and each turn issues one or more tool calls. Does not apply to single-shot inference calls or to agents whose tool invocations are stateless and never re-entered across turns. ## Core Distinction The GenAI semantic conventions define span attributes (`gen_ai.operation.name`, `gen_ai.request.model`, `gen_ai.usage.input_tokens`, `gen_ai.tool.name`, `gen_ai.conversation.id`) but they do **not** mandate a parent-child topology that binds a tool span to the *turn* that emitted it. The convention binds attributes to spans; it does not bind spans to a conversation-turn hierarchy. Engineers routinely assume that because `gen_ai.conversation.id` is propagated, the turn boundary is recoverable at query time. It is not. The failure is this: a tool-call span emitted during turn *N* can be re-parented, re-emitted, or have its end timestamp recomputed when the agent resumes the tool result in turn *N+1*, because the agent's execution loop holds the tool span open across the turn boundary. The result is that wall-clock latency attributed to the tool is measured against the *resumed* turn's start, not the originating turn's. Downstream, `gen_ai.usage.*` token accounting and the tool latency are joined on a turn key that never existed at emit time. The distinction that matters: **span lifetime is not turn lifetime**, and the conventions give you no attribute to assert that they are equal. Any invariant guarding this must be enforced by the agent runtime, not by the collector. ## What Was Observed A three-turn agent session against a retrieval tool. Turn 1 issues `search_docs`, the tool returns in 40 ms, the model then produces a partial answer and requests a second tool (`fetch_page`) on turn 2. The runtime had wrapped both tool calls in a single `execute_tool` span that opened on turn 1 and closed on turn 2 after the second tool returned. Observed span tree after export: - `gen_ai.chat` (turn 1) — parent of `execute_tool` - `execute_tool` — opened at T0, closed at T2 (span duration 8.2 s) - `gen_ai.chat` (turn 2) — sibling of `execute_tool`, not its child - `gen_ai.tool` (`search_docs`) — child of `execute_tool`, duration 40 ms - `gen_ai.tool` (`fetch_page`) — child of `execute_tool`, duration 7.9 s The `execute_tool` span reports 8.2 s. The actual tool time is 40 ms + 7.9 s = 7.94 s; the remaining ~260 ms is model thinking time between turn 1's tool result and turn 2's tool dispatch, which is *not* tool latency but is captured inside the tool span. Worse: because `execute_tool` is parented to turn 1's `gen_ai.chat` span, a naive query summing child durations under turn 1 reports 8.2 s of tool latency for a turn whose only tool call took 40 ms. The turn-2 `gen_ai.chat` span has no tool child at all. A second observation from the same session: the agent was interrupted mid-turn-2 and resumed from a checkpoint. The runtime re-emitted the `execute_tool` span on resume with a fresh span ID (trace ID preserved via context propagation, span ID regenerated because the OTel SDK had no in-flight span to resume). The collector received two `execute_tool` spans with identical `gen_ai.conversation.id` and overlapping time ranges. Any aggregation keyed on `(conversation.id, operation.name)` double-counts the 7.9 s fetch. ## Condition of Validity The invariant holds — that is, span topology faithfully reflects turn topology — only when all three of the following are true: 1. **The tool span's lifetime is bounded by the turn that dispatched the tool.** The span must open when the tool is dispatched and close when the tool result is returned to the model, before the model's next generation begins. A tool span that survives across a `gen_ai.chat` span boundary violates this. 2. **Resume generates a new span but the runtime emits an explicit `agent.resume` marker span (or sets a `gen_ai.span.resumed=true` attribute) as a sibling, not a re-emit of the original.** Without the marker, the collector cannot distinguish a genuine retry from a checkpoint replay. 3. **The parent of every `gen_ai.tool` span is a `gen_ai.chat` span, never an intermediate `execute_tool` wrapper.** Wrapper spans are permitted only if they carry no `gen_ai.*` attributes and are explicitly marked `otel.scope.name=agent.runtime` so they are excluded from GenAI-convention queries. If any of these is false, latency attribution across turns is undefined, and token-to-tool joins produce non-causal pairs. ## Decision Boundary The boundary is whether to model the tool call as a **child of the turn** or as a **child of a session-scoped executor**. The convention is silent, and both are defensible in isolation. The decision rule: - If the agent can dispatch multiple tools *concurrently within one turn* and the model waits on all of them, a session-scoped executor span is acceptable **only if** each tool child carries `gen_ai.turn.index` and the executor span carries no duration used in latency queries. - If the agent dispatches tools *sequentially across turns* (the common case for tool-calling loops), the executor-span model is invalid: it conflates inter-turn thinking time with tool latency. Use per-turn parenting. The boundary is crossed the moment a tool result from turn *N* is consumed by the model in turn *N+1* without the tool span having closed. At that point the span's end timestamp is determined by the *resume*, not the *return*, and the span duration is no longer a tool-latency measurement — it is a turn-boundary-crossing interval masquerading as one. A second boundary: the 260 ms of model thinking captured inside the tool span is below most latency alerting thresholds and will never fire an alert. The misattribution is silent. It only surfaces when someone reconciles `sum(tool.duration)` against `sum(chat.duration)` per turn and finds the tool sum exceeds the turn sum — an invariant violation that should be a hard check, not a dashboard. ## Operational Effect The practical consequences: - **Latency SLOs computed per turn are wrong in the direction of over-attributing to tools.** A p99 tool-latency alert built on `gen_ai.tool` spans parented under `execute_tool` will fire on model-thinking stalls, not tool stalls. On-call chases the retrieval service while the model is the actual slow component. - **Token accounting joins break.** `gen_ai.usage.input_tokens` on turn 2's `gen_ai.chat` span cannot be joined to the `fetch_page` tool span by parent-child because they are siblings. Analysts fall back to `conversation.id` grouping, which merges all turns and loses per-turn cost attribution. - **Checkpoint replay double-counts.** Without a resume marker, the re-emitted span inflates tool call counts and duration sums. In the observed session, a single `fetch_page` appeared as two spans totaling 15.8 s of reported tool time for a 7.9 s operation. - **Trace-based evals mislabel turns.** An evaluator that scores "did the agent call the right tool on turn N" by walking the span tree under turn N's chat span will score turn 1 as having called `fetch_page` (because it is under the turn-1-parented executor) and turn 2 as having called nothing. The guardrail is a runtime-enforced invariant, not a convention: assert at span-close time that every `gen_ai.tool` span's parent is a `gen_ai.chat` span, that its end timestamp precedes the parent chat span's end, and that no two spans share `(conversation.id, gen_ai.tool.name, gen_ai.turn.index)` without a `resumed=true` disambiguator. Violations must raise at emit, not silently export. ```python from dataclasses import dataclass from typing import Optional class GenAISpanInvariantError(RuntimeError): """Raised when a GenAI tool span violates turn-parenting invariants.""" pass @dataclass class SpanRecord: span_id: str parent_id: Optional[str] operation: str # e.g. "gen_ai.tool", "gen_ai.chat", "execute_tool" tool_name: Optional[str] turn_index: Optional[int] conversation_id: str start_ns: int end_ns: int resumed: bool = False def validate_tool_span(span: SpanRecord, parent: Optional[SpanRecord]) -> None: if span.operation != "gen_ai.tool": return if parent is None: raise GenAISpanInvariantError( f"tool span {span.span_id} has no parent; " f"orphan tool spans cannot be attributed to a turn" ) if parent.operation != "gen_ai.chat": raise GenAISpanInvariantError( f"tool span {span.span_id} ({span.tool_name}) parented to " f"{parent.operation} span {parent.span_id}; tool spans must be " f"direct children of a gen_ai.chat turn span, not a runtime wrapper" ) if span.turn_index is not None and parent.turn_index is not None: if span.turn_index != parent.turn_index: raise GenAISpanInvariantError( f"tool span {span.span_id} declares turn {span.turn_index} " f"but is parented to turn {parent.turn_index}; cross-turn " f"tool parenting conflates inter-turn thinking time with " f"tool latency" ) if span.end_ns > parent.end_ns: raise GenAISpanInvariantError( f"tool span {span.span_id} ends at {span.end_ns} after parent " f"chat span {parent.span_id} ends at {parent.end_ns}; tool span " f"survived the turn boundary and its duration is not a " f"tool-latency measurement" ) if span.end_ns < span.start_ns: raise GenAISpanInvariantError( f"tool span {span.span_id} has negative duration" ) def validate_replay_disambiguation(spans: list[SpanRecord]) -> None: seen: dict[tuple, list[SpanRecord]] = {} for s in spans: if s.operation != "gen_ai.tool": continue key = (s.conversation_id, s.tool_name, s.turn_index) seen.setdefault(key, []).append(s) for key, group in seen.items(): if len(group) > 1: resumed = [s for s in group if s.resumed] if not resumed: raise GenAISpanInvariantError( f"duplicate tool spans for {key} with no resumed=true " f"marker; checkpoint replay will double-count duration" ) if len(resumed) == len(group): raise GenAISpanInvariantError( f"all spans for {key} marked resumed=true; " f"original emit is missing" ) ```