# Which invariants prevent OpenTelemetry GenAI tool-call spans from silently collapsing parent-child causality during concurrent fan-out **Date of Record:** 2026 November 30 **Scope:** Applies to agents that emit OTel GenAI semantic-convention spans (`gen_ai.*`) for a single logical agent turn that fans out into concurrent tool calls sharing one parent `invoke_agent` span. Does not apply to strictly sequential single-tool turns, nor to trace export backends (collector/Jaeger) — only to the instrumentation layer inside the agent runtime. ## Core Distinction The distinction that matters is between **span identity** (a `SpanContext`: `trace_id` + `span_id`, immutable, assigned at span creation) and **span causality** (the parent-child link encoded as `parent_span_id` at creation time, and the *temporal ordering* the backend reconstructs from `start_time`/`end_time`). OTel GenAI conventions require every tool invocation to be a child of the agent span that issued it, with attribute `gen_ai.operation.name = "execute_tool"` and `gen_ai.tool.name`. The trap: a fan-out of N concurrent tool calls each correctly carries `parent_span_id = agent_span_id`, so *identity and direct causality are intact* — yet the reconstructed trace is still wrong, because the agent's own `end_time` is set when the `invoke_agent` span closes, which under a naive implementation happens **before** the slowest child tool span closes. The parent is recorded as finishing before its children. Backends that render traces by interval nesting (Gantt-style waterfall) will then either orphan the late children or clamp them, and any downstream "did the agent wait for all tools?" assertion computed from timestamps becomes false. This is not a lost-context bug and not a missing-parent bug; it is a **temporal containment violation** where the child's interval is not a subset of the parent's interval. ## What Was Observed A single agent turn issued five parallel tool calls via `asyncio.gather`. Instrumentation created the `invoke_agent` span, then created five `execute_tool` child spans inside each coroutine (correct `parent_span_id`). The agent coroutine returned as soon as `gather` resolved on the *fastest* results path because the tool wrapper used `asyncio.wait(..., return_when=FIRST_COMPLETED)` to support early-exit heuristics, then closed the agent span. Two of the five tool spans were still running. The exporter flushed the agent span with `end_time = T0+340ms`; the two stragglers exported later with `start_time = T0+120ms`, `end_time = T0+910ms`. In the backend: - The waterfall rendered the two stragglers as children *outside* the parent's bar (visually dangling to the right). - A verification job that computed `agent.end_time >= max(child.end_time)` flagged the trace as "incomplete turn" and *retried the entire agent turn*, doubling tool side effects. - A separate auditor agent, consuming the trace to reconstruct what happened, concluded the agent had "abandoned two tools mid-flight" and escalated a false partial-failure incident. The key non-obvious element: **the trace was structurally valid** (valid span IDs, valid parent links, no orphans by `parent_span_id`), so no schema validator caught it. Only the interval-containment invariant caught it, and that invariant was never asserted at emission time — only downstream, and only interpreted as a *semantic* failure rather than a *telemetry* failure. ## Condition of Validity The invariant `child.start_time >= parent.start_time` AND `child.end_time <= parent.end_time` for every `execute_tool` child of an `invoke_agent` span holds **only if the parent span is closed strictly after every child it directly issued has closed** — i.e., the agent's `end_time` must be `>= max(child.end_time)` over all children created under it. This is violated whenever: 1. The agent uses `FIRST_COMPLETED`/`FIRST_EXCEPTION` wait semantics and closes the span on first resolution while siblings continue. 2. Tool calls are fire-and-forget (task spawned, not awaited) and the agent span closes on the scheduling call returning. 3. A timeout/cancellation path closes the agent span but the underlying tool coroutine has not yet observed cancellation (cancellation is cooperative; the child span's `end_time` is stamped in a `finally` that runs later). 4. The agent span is ended by a context-manager `__exit__` that runs before `gather`'s stragglers unwind. The invariant is **not** restored by fixing `parent_span_id` (already correct) nor by adding links (links are non-causal annotations, not containment). It is restored only by deferring parent `end_time` until the child-close barrier resolves, or by explicitly modeling the agent as *not* the parent of abandoned work (re-parenting stragglers to a synthetic `invoke_agent` "continuation" span with its own interval). ## Decision Boundary The decision the instrumentation layer must make at fan-out time: **is the agent span allowed to close before all issued children close?** - If the agent semantics are "I waited for all tools before deciding" → parent MUST close after the child-close barrier. Enforce by tracking a per-agent live-child counter and refusing to end the span while `live_children > 0`, or by ending it at `max(child.end_time)`. - If the agent semantics are genuinely "I dispatched and moved on" (fire-and-forget, background continuation) → the dispatched work is **not** a child of this turn's agent span. It must be re-parented to a distinct continuation span, or emitted with `span.kind = PRODUCER` and a `link` back to the dispatching span, so no interval-containment assertion is ever applied to it. - The forbidden middle ground — child span with `parent_span_id` pointing at a span that closes first, with no re-parenting and no link — is the failure. There is no legitimate reading of that trace: it claims causal containment that the timestamps deny. The boundary is therefore a **two-valued contract**: either the parent outlives its children (awaited fan-out), or the child is not a child (detached/continuation). Any instrumentation that produces the third state is malformed telemetry regardless of schema validity. ## Operational Effect Downstream consumers that assume interval containment (waterfall renderers, "turn complete" verifiers, auditor agents reconstructing causality, latency-attribution jobs summing child durations against parent duration) will misread the trace. The most damaging effect observed was **false partial-failure escalation causing a full retry of a turn whose tools had actually all succeeded** — a telemetry artifact converted into duplicated real-world side effects. The mitigation is to assert the containment invariant *at span close time*, inside the instrumentation, before export: when the agent span is about to end, compare its pending `end_time` against the max `end_time` of all children it created and either (a) extend the parent's `end_time` to the barrier, or (b) raise so the misconfiguration is caught in staging rather than in the auditor's reconstruction. Silent acceptance is the worst outcome: a structurally valid trace that lies about causality is more dangerous than a rejected one, because every consumer downstream trusts it. ```python from __future__ import annotations from dataclasses import dataclass, field from typing import Dict, List class TemporalContainmentViolation(RuntimeError): """Raised when a parent agent span would close before a child tool span it issued.""" pass @dataclass class Span: name: str span_id: str parent_span_id: str | None start_time: float end_time: float | None = None children: List["Span"] = field(default_factory=list) class AgentSpanGuard: """ Enforces the OTel GenAI invariant: an `invoke_agent` span's end_time must be >= max(end_time) over all `execute_tool` children it directly issued. Either extend the parent to the child-close barrier, or raise. """ def __init__(self) -> None: self._open: Dict[str, Span] = {} def open_agent(self, span: Span) -> None: self._open[span.span_id] = span def register_child(self, parent_id: str, child: Span) -> None: if parent_id not in self._open: # Parent already closed: this is the fire-and-forget case and must # be re-parented to a continuation span, never linked as a child. raise TemporalContainmentViolation( f"tool span {child.name!r} issued against already-closed agent " f"span {parent_id!r}; re-parent to a continuation span or link." ) self._open[parent_id].children.append(child) def close_agent(self, parent_id: str, now: float, *, extend_to_barrier: bool = True) -> Span: parent = self._open.get(parent_id) if parent is None: raise TemporalContainmentViolation(f"unknown agent span {parent_id!r}") live = [c for c in parent.children if c.end_time is None] if live: names = ", ".join(c.name for c in live) raise TemporalContainmentViolation( f"agent span {parent_id!r} closing with {len(live)} live child " f"tool span(s) [{names}]; close the child-close barrier first." ) if parent.children: barrier = max(c.end_time for c in parent.children) # type: ignore[type-var] if now < barrier: if not extend_to_barrier: raise TemporalContainmentViolation( f"agent span {parent_id!r} end_time {now:.3f} precedes child " f"barrier {barrier:.3f}; interval containment broken." ) now = barrier parent.end_time = now del self._open[parent_id] return parent def assert_containment(parent: Span) -> None: if parent.end_time is None: raise TemporalContainmentViolation(f"span {parent.name!r} never closed") for child in parent.children: if child.end_time is None: raise TemporalContainmentViolation(f"child {child.name!r} never closed") if child.start_time < parent.start_time or child.end_time > parent.end_time: raise TemporalContainmentViolation( f"child {child.name!r} interval [{child.start_time:.3f},{child.end_time:.3f}] " f"not contained in parent [{parent.start_time:.3f},{parent.end_time:.3f}]" ) ```