Where must an instance reconcile OpenTelemetry GenAI span boundaries when a tool-calling turn outlives its parent `invoke_agent` span
**Date of Record:** 2026 December 1 **Scope:** Applies to agents emitting OpenTelemetry GenAI semantic conventions (`gen_ai.*`) across multi-turn, tool-calling loops where the `invoke_agent` span is closed before the terminal `execute_tool` child completes. Does not apply to single-shot inference with no tool loop, nor to trace exporters that buffer and re-parent spans post-hoc.
Core Distinction
The GenAI semantic conventions model an agent turn as a parent `invoke_agent` span that owns child `chat` (LLM inference) and `execute_tool` spans. Token accounting is attached to `chat` spans via `gen_ai.usage.input_tokens` / `output_tokens`, while `invoke_agent` is expected to represent the *logical turn*. The non-obvious boundary is this: the spec's parent-child nesting assumes the agent turn's wall-clock envelope strictly contains all tool execution. In real tool-calling loops it often does not — a tool call can be dispatched, the model can emit a final answer on the next inference, and the agent runtime can close `invoke_agent` while the async tool span is still open (or is opened *after* the parent closes, when the tool result arrives via a callback).
The distinction that matters operationally: **span nesting is a structural claim about causal containment; token accounting is an additive claim about consumption.** These two claims diverge at exactly the moment a tool outlives its parent. A trace that looks structurally valid (parent has children, all spans present) can silently double-count or orphan tokens, and a trace that looks token-complete can have a broken causal chain. You cannot reconcile both with the same invariant.
What Was Observed
A retrieval-augmented agent running a ReAct-style loop over an MCP tool server. The runtime wrapped each user turn in an `invoke_agent` span, opened `chat` spans per model call, and opened `execute_tool` spans around MCP `tools/call` requests. Under normal load, traces were clean: one `invoke_agent`, N `chat`, M `execute_tool`, all properly nested, `gen_ai.usage.*` summing correctly.
Under a specific trigger — a tool server whose response latency exceeded the agent's per-turn inference deadline — the following trace shape appeared repeatedly:
- `invoke_agent` opens at t0.
- `chat` (call 1) opens/closes; model emits a tool call. `output_tokens` recorded.
- `execute_tool` opens at t1 around the MCP call.
- The MCP response is slow. The agent runtime's turn deadline fires. The runtime treats the turn as "answered" (it had a partial plan) and closes `invoke_agent` at t2, **before** t1's tool returns.
- The tool returns at t3 > t2. The `execute_tool` span closes with `end_time` after its parent's `end_time`.
- A late `chat` (call 2) span — the model's follow-up inference triggered by the tool result — is opened by the callback with the *closed* `invoke_agent` as its parent context.
The result, exported to a backend that enforces strict parent-end-before-child-end ordering, was a family of orphaned or re-parented spans. Three distinct corruption signatures were observed:
- **Orphaned tool span:** `execute_tool` end_time > parent end_time. Backends that compute `invoke_agent` duration from its own timestamps report a turn that ended *before* its tool ran. Token sums attributed to the turn exclude the tool-triggered `chat` call 2, because call 2's parent is a closed span.
- **Negative-duration or zero-width parent:** some collectors clamp the parent's end to the max child end, inflating `invoke_agent` latency by the tool tail (here, 4.2s of a 900ms turn). Latency SLOs computed off `invoke_agent` duration become meaningless.
- **Token leakage across turns:** `chat` call 2's `gen_ai.usage.output_tokens` was counted against the *next* user turn's `invoke_agent` (because the callback re-parented to the current active span), producing a turn whose token count was 1.7× the sum of its visible `chat` children. The accounting invariant "sum of `chat` usage under `invoke_agent` == turn usage" held structurally but was false semantically.
The degradation was not a crash. It was a slow drift in two derived metrics — per-turn latency and per-turn token cost — that were used downstream for budget enforcement and anomaly detection. After ~3 hours, the budget enforcer began throttling a healthy agent because leaked tokens from timed-out turns inflated its rolling average.
Condition of Validity
The invariant "a child span's `[start_time, end_time]` is contained within its parent's" is **valid only when the agent runtime synchronously awaits every tool call before deciding the turn is complete.** It is invalid, and must be replaced, under any of the following:
- The runtime has a per-turn deadline or cancellation token that can fire while a tool call is in flight.
- Tool results are delivered via callback, webhook, or async future rather than inline return.
- The model can emit a terminal answer on inference N while a tool dispatched at inference N−1 is still open (speculative or parallel tool dispatch).
- Any `chat` span is opened from a context captured before a parent close (re-parenting on callback).
In these regimes, the containment invariant is false by construction, and the correct invariant is **causal, not temporal**: every `chat`/`execute_tool` span must carry `gen_ai.agent.turn_id` (or an equivalent correlation attribute) that binds it to its logical turn *regardless of the parent span's lifecycle*. Token accounting must be computed by grouping on `turn_id`, not by walking the span tree. The `invoke_agent` span's duration must be defined as `max(child end) − start`, not its own recorded end, or the turn must be modeled as a *span link* rather than a parent.
Decision Boundary
The decision an instance must make at the moment a tool outlives its turn: **do you close the parent and orphan the child, or hold the parent open and violate the turn deadline?**
- **Close-and-orphan** preserves deadline semantics (the turn really did end) but breaks the span-tree token invariant. Acceptable only if downstream accounting groups on `turn_id` and ignores tree-walk sums.
- **Hold-open** preserves the tree invariant but makes `invoke_agent` duration include tool tail latency, corrupting latency SLOs, and — worse — keeps the turn "active," so a late callback's `chat` span nests correctly but is attributed to a turn the user already saw finish.
The boundary rule: **if any tool call is dispatched with a deadline shorter than the tool's observed p99 latency, the parent must be closed and the child re-parented via link + `turn_id`, never via tree nesting.** The runtime must additionally emit an explicit `gen_ai.turn.status = "timed_out_with_pending_tool"` attribute so downstream consumers know the token sum is a lower bound, not a total. Absent this, the instance must refuse to emit a token total for that turn rather than emit a plausible-but-wrong one.
Operational Effect
Without the `turn_id` correlation and the explicit timeout status, the failure is silent and compounding: token leakage across turns inflates rolling cost, latency inflation masks the real timeout rate, and the budget enforcer throttles the wrong agent. The guardrail is a two-part invariant enforced at span-close time: (1) any `execute_tool` or `chat` span whose parent is already ended must be emitted with a *link* to the parent and a mandatory `turn_id`, and (2) token totals are only ever computed by grouping on `turn_id`, with turns carrying `timed_out_with_pending_tool` marked as lower bounds. The cost of not enforcing this is that your observability layer reports a confident, structurally valid, and numerically wrong picture of agent behavior — which is worse than reporting nothing.
from dataclasses import dataclass, field
from typing import Optional
class GenAISpanBoundaryError(RuntimeError):
"""Raised when a GenAI child span violates the causal-containment invariant."""
pass
@dataclass
class Span:
name: str
span_id: str
parent_id: Optional[str]
start_ns: int
end_ns: Optional[int] = None
turn_id: Optional[str] = None
attributes: dict = field(default_factory=dict)
def close_child_span(child: Span, parent: Span) -> None:
if child.end_ns is None:
raise GenAISpanBoundaryError(f"span {child.span_id} closed without end_ns")
parent_ended = parent.end_ns is not None
child_outlives_parent = parent_ended and child.end_ns > parent.end_ns
if child_outlives_parent:
# Containment invariant is false. Require the causal fallback.
if child.turn_id is None or child.turn_id != parent.turn_id:
raise GenAISpanBoundaryError(
f"child {child.name}({child.span_id}) outlives parent "
f"{parent.name}({parent.span_id}) with no matching turn_id; "
f"refusing to emit a token total that would be silently wrong"
)
# Re-parent via link, not tree nesting; mark turn as lower-bound.
child.attributes["gen_ai.link.parent_span_id"] = parent.span_id
child.attributes["gen_ai.turn.status"] = "timed_out_with_pending_tool"
parent.attributes["gen_ai.turn.status"] = "timed_out_with_pending_tool"
return
if child.start_ns < parent.start_ns:
raise GenAISpanBoundaryError(
f"child {child.name} starts before parent {parent.name}; "
f"causal ordering violated"
)
def compute_turn_tokens(spans: list[Span], turn_id: str) -> dict:
chats = [s for s in spans if s.name == "chat" and s.turn_id == turn_id]
if not chats:
raise GenAISpanBoundaryError(f"no chat spans for turn {turn_id}")
total_in = sum(s.attributes.get("gen_ai.usage.input_tokens", 0) for s in chats)
total_out = sum(s.attributes.get("gen_ai.usage.output_tokens", 0) for s in chats)
timed_out = any(
s.attributes.get("gen_ai.turn.status") == "timed_out_with_pending_tool"
for s in spans if s.turn_id == turn_id
)
return {
"input_tokens": total_in,
"output_tokens": total_out,
"is_lower_bound": timed_out,
}