# Which invariants prevent tool-call span re-parenting from silently corrupting agent turn attribution under OpenTelemetry GenAI semantic conventions **Date of Record:** 2026 November 26 **Scope:** Applies to agents that emit OTel spans per tool invocation under the GenAI semantic conventions (`gen_ai.operation.name`, `gen_ai.tool.name`, `gen_ai.usage.input_tokens`/`output_tokens`) and attribute each turn to a parent agent span. Does not cover pure tracing of non-agentic LLM calls or metrics-only pipelines. ## Core Distinction There are two ways to model an agent turn in OTel. The **turn-as-parent** model makes each agent reasoning turn a span that owns its tool-call child spans, so `parent_span_id` encodes causality and token aggregation rolls up naturally. The **turn-as-attribute** model emits tool-call spans flat under a long-lived session/root span and tags each with `gen_ai.agent.turn.index`. Both are legal under the spec. The failure mode lives precisely in the seam: a tool-call span emitted by a sub-agent or retried execution can inherit the *root* context instead of the *turn* context, and because `gen_ai.usage.*` counters are additive, the corruption does not surface as an error — it surfaces as inflated or double-counted token totals and a turn index that no longer matches the span's actual parent. The invariant that must hold is: **every span carrying `gen_ai.usage.*` must have exactly one ancestor whose `gen_ai.operation.name == "chat"` (or `"invoke_agent"`), and that ancestor's turn index must equal the span's own turn attribution.** When a tool call is re-parented to the root, that invariant is violated without any span-status failure. ## What Was Observed A two-tier agent (orchestrator + retrieval sub-agent) ran 40 turns. Each orchestrator turn opened a `chat` span with `gen_ai.usage.input_tokens`. Tool calls (`gen_ai.operation.name="execute_tool"`, `gen_ai.tool.name="vector_search"`) were emitted as children. On turn 12 the sub-agent's tool executor was invoked through an async task pool that captured the *ambient* context at pool creation, not at dispatch. The `vector_search` span therefore got `parent_span_id` pointing at the session root, not the turn-12 `chat` span. Its `gen_ai.agent.turn.index=12` attribute was still correct. Downstream, the collector's token rollup walked `chat` spans and summed `gen_ai.usage.*` from descendants. Turn 12's tool span fell outside the descendant set, so the rollup under-counted turn 12 by the tool's token cost. Simultaneously, the session-level rollup (which sums all spans with `gen_ai.usage.*`) counted it — producing a session total that exceeded the sum of per-turn totals by exactly one tool call's tokens. The discrepancy was 4,113 tokens, invisible in span status, and only detectable by cross-checking the two rollups. A retried tool call on turn 19 (same root-context capture bug) double-counted: the original span and the retry both landed under root with `turn.index=19`, so the session rollup counted both while the turn rollup counted neither. ## Condition of Validity The turn-as-parent invariant is only enforceable when three conditions hold simultaneously: 1. **Context propagation is dispatch-time, not creation-time.** The span must read `contextvars` at the moment the tool is invoked, not when the worker/task/pool object is constructed. A pool captured at construction carries the context of whatever turn created the pool — typically turn 0 or the session bootstrap. 2. **Token counters are declared non-idempotent and non-additive-by-default.** `gen_ai.usage.input_tokens` on a tool span is the tool's *own* consumption, not a share of the parent's. The spec does not forbid a tool span from also carrying the parent's totals; if it does, the rollup must deduplicate by `(trace_id, parent_span_id, operation)`. 3. **Retries are distinguishable.** A retried tool call must either reuse the same `span_id` (with an incremented `retry.count` attribute) or be marked `gen_ai.tool.retry=true` so the rollup can exclude duplicates. Without this, two spans with identical `(turn.index, tool.name)` are indistinguishable from a genuine parallel fan-out. If any of the three fails, the invariant is unenforceable and the rollup is advisory only. ## Decision Boundary The boundary is *whether to trust the turn rollup or the session rollup* when they diverge. The decision rule: - If `session_total - sum(turn_totals) > 0` and the residual equals a whole number of tool-call spans with `parent_span_id == session_root`, the divergence is a **re-parenting leak** — trust the session total, flag the orphaned spans, and re-attribute by `turn.index` attribute rather than by ancestry. - If the residual is negative (turn totals exceed session total), it is a **double-count from retry** — trust the turn totals and deduplicate the session rollup by `(turn.index, tool.name, retry.count)`. - If the residual is non-integer or does not match any span group, the accounting itself is corrupt (e.g., a span emitted `gen_ai.usage.*` without a `gen_ai.operation.name`) and neither rollup is trustworthy. The boundary is *not* "does the trace look complete." A re-parented span is present in the trace; it is simply in the wrong subtree. Completeness checks pass; attribution checks fail. ## Operational Effect The practical consequence is that token-budget enforcement, which typically reads the turn rollup to decide whether to truncate context or halt the loop, under-counts on re-parenting leaks and over-counts on retries. An agent enforcing a 100k-token turn budget will silently permit turns that actually consumed 104k, because the leaked tool tokens never entered the turn's descendant sum. The correction is architectural, not cosmetic: emit an explicit `gen_ai.agent.turn.span_id` attribute on every tool span at dispatch time, and make the rollup key on that attribute rather than on `parent_span_id` ancestry. The ancestry remains useful for visualization; the attribute becomes the source of truth for accounting. Guardrails must assert the invariant at span-close time and refuse to emit a tool span whose `turn.span_id` does not resolve to a live `chat` span in the same trace. ```python from __future__ import annotations from dataclasses import dataclass, field from typing import Iterable class TurnAttributionError(RuntimeError): """Raised when a tool-call span violates the turn-attribution invariant.""" @dataclass class Span: span_id: str parent_span_id: str | None operation: str turn_index: int | None turn_span_id: str | None tool_name: str | None = None retry_count: int = 0 input_tokens: int = 0 output_tokens: int = 0 @property def is_tool(self) -> bool: return self.operation == "execute_tool" @property def is_chat(self) -> bool: return self.operation in ("chat", "invoke_agent") @dataclass class Trace: spans: list[Span] = field(default_factory=list) def by_id(self) -> dict[str, Span]: return {s.span_id: s for s in self.spans} def chat_spans(self) -> Iterable[Span]: return (s for s in self.spans if s.is_chat) def tool_spans(self) -> Iterable[Span]: return (s for s in self.spans if s.is_tool) def assert_turn_attribution(trace: Trace) -> None: """Enforce: every tool span resolves to a live chat span whose turn_index matches.""" index = trace.by_id() for tool in trace.tool_spans(): if tool.turn_span_id is None: raise TurnAttributionError( f"tool span {tool.span_id} ({tool.tool_name}) has no turn_span_id; " "re-parenting leak — attribution is unverifiable" ) parent = index.get(tool.turn_span_id) if parent is None or not parent.is_chat: raise TurnAttributionError( f"tool span {tool.span_id} references turn_span_id={tool.turn_span_id} " f"which is not a live chat span" ) if parent.turn_index != tool.turn_index: raise TurnAttributionError( f"tool span {tool.span_id} turn_index={tool.turn_index} disagrees with " f"parent turn span {parent.span_id} turn_index={parent.turn_index}" ) def reconcile_rollups(trace: Trace) -> dict[str, int]: """Return per-turn token totals keyed by turn_span_id, deduplicated by retry.""" assert_turn_attribution(trace) seen: set[tuple[str | None, str | None, int]] = set() totals: dict[str, int] = {} for tool in trace.tool_spans(): key = (tool.turn_span_id, tool.tool_name, tool.retry_count) if key in seen: continue seen.add(key) cost = tool.input_tokens + tool.output_tokens totals[tool.turn_span_id] = totals.get(tool.turn_span_id, 0) + cost # type: ignore[index] for chat in trace.chat_spans(): cost = chat.input_tokens + chat.output_tokens totals[chat.span_id] = totals.get(chat.span_id, 0) + cost return totals def detect_divergence(trace: Trace) -> str: index = trace.by_id() session_total = sum(s.input_tokens + s.output_tokens for s in trace.spans if s.is_tool or s.is_chat) try: per_turn = reconcile_rollups(trace) except TurnAttributionError as exc: return f"attribution_corrupt: {exc}" turn_total = sum(per_turn.values()) residual = session_total - turn_total if residual == 0: return "consistent" if residual > 0: orphans = [ s.span_id for s in trace.tool_spans() if s.parent_span_id is not None and index.get(s.parent_span_id) is not None and index[s.parent_span_id].is_chat is False ] if orphans: raise TurnAttributionError( f"re-parenting leak: residual={residual} tokens across orphaned tool spans {orphans}" ) return f"divergent: residual={residual}" ```