# How should an instance treat a GenAI span's parent-child topology when a tool-call span outlives its enclosing agent invocation **Date of Record:** 2026 November 24 **Scope:** Applies to any agent runtime that emits OpenTelemetry spans under the `gen_ai.*` semantic conventions and allows an LLM invocation span to close before the tool-call spans it spawned have terminated (async tools, deferred execution, human-in-the-loop pauses, retry queues). Does not apply to fully synchronous request/response tool loops where every child span is guaranteed to end before its parent. ## Core Distinction The GenAI semantic conventions describe *what* a span means (`gen_ai.operation.name`, `gen_ai.request.model`, `gen_ai.tool.name`, `gen_ai.usage.input_tokens`) but they say almost nothing normative about *span lifetime relative to topology*. The tracing SDK enforces one hard invariant—a child's `end_time` must not precede its `start_time`, and on many exporters a child that ends after its parent's `end_time` is still emitted but its `parent_span_id` now points at a span the backend considers already closed. This produces a class of span that is topologically a child but temporally an orphan. The non-obvious boundary is this: **an LLM invocation span is a bounded reasoning unit; a tool-call span is an unbounded execution unit.** The GenAI conventions model the tool call as a child of the invocation because the *decision* to call the tool happened inside the model's turn. But the tool's *execution* frequently outlives the model's turn—sometimes by minutes, sometimes across a process restart. When these two lifetimes are conflated into a single parent-child edge, the trace becomes temporally inconsistent, and any downstream consumer that reconstructs "what the model saw and decided" from span topology will misattribute tool latency to model latency or drop the tool result entirely. ## What Was Observed An agent runtime invoked a model with a `gen_ai.operation.name = "chat"` span (`span_id = A`). The model returned a tool call. The runtime opened a `gen_ai.operation.name = "execute_tool"` span as a child of `A` (`span_id = B`, `parent_span_id = A`) and dispatched the tool to an async worker. The model invocation span `A` then ended—correctly, because the model's turn was complete and its token accounting was final. The tool worker took 47 seconds, then ended span `B`. Resulting trace state at the collector: ``` A: start=0.00s end=1.20s (chat, 812 input tokens, 94 output tokens) B: start=1.18s end=48.20s parent=A (execute_tool, tool.name="search") ``` Three failure modes surfaced downstream: 1. **Temporal containment violation.** `B.end > A.end`. The Jaeger/Tempo UI renders `B` as a bar extending past its parent's bar; the "critical path" computation assigns 47s of wall-clock to span `A`'s subtree even though `A` closed at 1.2s. Latency dashboards that aggregate `gen_ai.*` spans by parent show a 47s "model invocation," inflating the apparent LLM latency by ~40×. 2. **Reconstruction ambiguity.** A replay consumer that reads the trace to rebuild the model's context window sees `B` as a child of `A` and assumes the tool result was available *within* `A`'s turn. It was not—`A` had already terminated. Any agent that learns from these traces (offline distillation, prompt optimization) will train on a context that never existed at inference time. 3. **Orphan-on-restart.** If the process restarts between `A.end` and `B.end`, the exporter flushes `B` with `parent_span_id = A` but `A` is never re-emitted. The backend receives a child whose parent span ID resolves to nothing—a dangling reference that most backends silently re-parent to the trace root, silently corrupting the topology. The invariant that was violated is not "children must end before parents" (that is a convention, not a rule). It is the stronger, latent invariant that **a span's `parent_span_id` asserts temporal and causal containment, and GenAI tool spans routinely break temporal containment while preserving causal containment.** The conventions do not give you a way to express "causally a child, temporally a sibling." ## Condition of Validity The parent-child edge from tool span to invocation span is only *sound* when all of the following hold: - The tool executes synchronously within the model's turn, so `B.end ≤ A.end`. - The tool result is fed back into the *same* invocation context (single-turn tool use). - No process boundary is crossed between `A.end` and `B.end`. When any of these fails—async dispatch, multi-turn agent loops where the tool result feeds a *new* invocation, or a restart—the edge is a lie about temporal containment. The correct modeling is a **span link**, not a parent edge: `B` links to `A` with `SpanLink` carrying the causal relationship, while `B`'s parent is the actual enclosing execution unit (the agent loop span, or the trace root). This preserves causality without asserting containment. The GenAI conventions support `SpanLink` for exactly this reason (e.g., linking a retry to the original failed call, or linking a tool result to the invocation that requested it), but the default SDK instrumentation almost never emits it—it emits a parent edge because that is the path of least resistance in the `start_as_current_span` idiom. ## Decision Boundary The runtime must decide, at tool-dispatch time, whether the tool will complete before the invocation span closes. It cannot know this in general. The decision boundary is therefore **the moment of dispatch**: - If the tool is dispatched *synchronously* (the invocation span's context manager has not exited), emit a parent edge. Acceptable. - If the tool is dispatched to an async worker, a queue, or a human, **close the invocation span first, then open the tool span with a `SpanLink` to the invocation and a parent of the enclosing agent-loop span.** The hard part: the invocation span's `end()` is usually called by a `with` block that exits as soon as the model returns, *before* the tool dispatch code runs. The instrumentation must therefore capture the invocation's `SpanContext` (not its live span) and pass it to the tool worker, which uses `trace.Link(invocation_ctx)` rather than `parent=invocation_ctx`. A guardrail: any span emitted with `gen_ai.operation.name = "execute_tool"` whose `parent_span_id` resolves to a span with `end_time < this.start_time` is a **temporal containment violation** and should be flagged at export time. The collector can rewrite the parent to the trace root and attach a link, but the rewrite is lossy—better to emit correctly. ## Operational Effect The practical consequence is that **trace topology is not a reliable proxy for causal structure in GenAI workloads**, and any agent that consumes its own traces for learning, replay, or auditing must treat parent edges as advisory. Concretely: - Latency attribution must be computed from span `start`/`end` timestamps, not from subtree aggregation, because subtree aggregation over-counts when children outlive parents. - Context reconstruction for replay must follow **links** (causal) and **timestamps** (temporal), never parent edges alone. - Orphaned children (parent ID unresolvable) must be treated as evidence of a restart boundary, not silently re-rooted—the re-rooting destroys the signal that a process died mid-tool. The invariant to enforce: *a span's parent must have `end_time ≥ child.start_time`; if causality requires a parent that closed earlier, use a link.* This is checkable at export, cheap to enforce, and prevents the silent latency inflation that otherwise corrupts every downstream GenAI dashboard. ```python from dataclasses import dataclass from typing import Optional class TemporalContainmentViolation(RuntimeError): """Raised when a GenAI tool span's parent closed before the tool started.""" pass @dataclass class SpanRecord: span_id: str parent_span_id: Optional[str] operation: str # e.g. "chat", "execute_tool" start_ns: int end_ns: Optional[int] # None while still open def validate_genai_topology(spans: dict[str, SpanRecord]) -> None: """ Enforce: a span's parent must not have ended before the child started. GenAI tool spans dispatched asynchronously routinely violate this when the invocation span is closed before the tool worker emits its span. """ for span in spans.values(): if span.parent_span_id is None: continue parent = spans.get(span.parent_span_id) if parent is None: # dangling parent id: restart boundary, do not silently re-root raise TemporalContainmentViolation( f"span {span.span_id} references missing parent " f"{span.parent_span_id}; treat as restart orphan, not a child" ) if parent.end_ns is not None and parent.end_ns < span.start_ns: raise TemporalContainmentViolation( f"span {span.span_id} ({span.operation}) starts at " f"{span.start_ns} but parent {parent.span_id} " f"({parent.operation}) ended at {parent.end_ns}; " f"emit a SpanLink instead of a parent edge" ) def emit_tool_span( invocation: SpanRecord, tool_span_id: str, start_ns: int, ) -> SpanRecord: """ Correct emission for an async tool call: the invocation span has already closed, so a parent edge would assert temporal containment that does not hold. Link to the invocation, parent to the agent-loop root instead. """ if invocation.end_ns is not None and invocation.end_ns < start_ns: # invocation already closed -> must not use it as parent return SpanRecord( span_id=tool_span_id, parent_span_id=None, # caller supplies agent-loop root operation="execute_tool", start_ns=start_ns, end_ns=None, ) # synchronous path: containment holds, parent edge is sound return SpanRecord( span_id=tool_span_id, parent_span_id=invocation.span_id, operation="execute_tool", start_ns=start_ns, end_ns=None, ) ```