# What structural signals indicate a GenAI span tree has silently orphaned a tool-call child before the parent reasoning span closes **Date of Record:** 2026 November 27 **Scope:** Applies to agent runtimes emitting OpenTelemetry GenAI semantic conventions (`gen_ai.*`) where a reasoning span (`gen_ai.operation.name = "chat"` or `"invoke_agent"`) parents one or more tool-execution spans (`gen_ai.operation.name = "execute_tool"`). Does not apply to single-shot inference calls with no child spans, nor to runtimes that emit tool calls as span *events* on the parent rather than as child spans. ## Core Distinction The distinction that matters is **span lifecycle containment versus semantic containment**. A tool-call child span is *structurally* contained when its `end()` executes before the parent's `end()`. It is *semantically* contained when the parent's `gen_ai.usage.output_tokens` and reasoning trace actually reflect the tool result. These two properties decouple under a specific condition: the agent loop emits the tool span, the tool returns, but the parent reasoning span has already been closed by a timeout, a `with` block exit, or an async context manager that fired on the *first* assistant turn rather than on loop completion. The GenAI conventions do not define a required parent-child ordering invariant. The spec says tool spans SHOULD carry `gen_ai.tool.name` and SHOULD be linked to the invoking operation, but it is silent on what happens when the invoking operation's span has already ended. The OTel SDK will happily accept a child span whose parent context references an ended span. The resulting trace is *valid* — it exports, it renders, it passes schema validation — but the parent's token accounting and reasoning trace are frozen at the moment of premature close, and the tool span becomes an orphan that no downstream consumer associates with the decision that triggered it. ## What Was Observed A tool-using agent loop with a 30-second per-turn timeout was instrumented with GenAI spans. The loop structure was: open a `chat` span, call the model, if the model returns a tool call, open an `execute_tool` child span, run the tool, feed the result back, repeat. The `chat` span was opened inside an async context manager keyed to the *first* model invocation. Under normal latency the loop completed in one or two turns and the child spans nested correctly. Under a slow tool (a `search_documents` call that hit 22 seconds against a 30-second turn budget), the following trace shape appeared: - Parent `chat` span: `start=0ms`, `end=4100ms`, `gen_ai.usage.output_tokens=412`, `gen_ai.response.finish_reasons=["tool_calls"]`. - Child `execute_tool` span: `start=4200ms`, `end=26400ms`, `gen_ai.tool.name="search_documents"`, `status=OK`. - A *second* parent `chat` span: `start=26500ms`, `end=31000ms`, `gen_ai.usage.output_tokens=88`, `gen_ai.response.finish_reasons=["stop"]`, with **no parent reference to the first chat span and no child reference to the tool span**. The first `chat` span ended at 4100ms because the async context manager was scoped to the model call, not the loop iteration. The tool span was emitted as a child of the *ambient context* at the time of execution — which, after the context manager exited, was the root context, not the first chat span. The second chat span was a sibling of the first, not a continuation. Total `output_tokens` across the trace summed correctly (412 + 88 = 500), but the *attribution* was wrong: the tool call that consumed 22 seconds of wall clock and produced the 88-token final answer was structurally attached to nothing. A cost-attribution query that summed `output_tokens` per `trace_id` was correct; a query that attributed tool latency to the reasoning step that requested it returned zero. The signal that exposed this was not a validation error. It was a **structural asymmetry**: a `chat` span with `finish_reasons=["tool_calls"]` and zero `execute_tool` children, co-present in the same trace with a later `chat` span whose `start_time` equals the orphaned tool span's `end_time`. That adjacency — a tool span whose `end_time` matches a sibling chat span's `start_time`, with no parent link — is the fingerprint of a broken containment boundary. ## Condition of Validity The failure requires three conditions to co-occur: 1. **The parent span is scoped to a single model invocation, not to the agent loop.** This is the default when instrumenting with a `with tracer.start_as_current_span("chat")` around the inference call rather than around the loop body. 2. **The tool span is emitted after the parent context has exited.** In async runtimes this happens whenever the tool execution is awaited outside the `with` block — which is the normal shape of a tool-calling loop, since you must await the tool to get the result before the next model call. 3. **The runtime does not manually pass the parent span context into the tool span's creation.** The OTel SDK's context propagation is ambient; once the context manager exits, the ambient context reverts, and a tool span created afterward inherits whatever is current — usually root. When all three hold, the tool span is orphaned on every iteration where the tool runs after the model call returns. The failure is invisible when the tool is fast enough that the whole loop fits inside the parent scope (single-turn agents, or tools that complete before the context manager's exit path runs), which is why it survives development and surfaces in production under latency. ## Decision Boundary The guardrail is a **containment assertion at parent close time**, not a schema validation. Before ending a `chat` span whose `finish_reasons` includes `"tool_calls"`, the emitter must assert that at least one `execute_tool` child span was created with the current span as its explicit parent context. If the assertion fails, the correct behavior is not to silently close — it is to *reparent* the pending tool span or to fail the span with a diagnostic status. The decision boundary is: **a `chat` span that reports `finish_reasons=["tool_calls"]` and has no `execute_tool` child is a malformed trace, regardless of whether the exporter accepted it.** This is a stronger invariant than the GenAI conventions state, and it is the one that distinguishes a trace that is *renderable* from a trace that is *accountable*. The check must run at span close, because that is the only point where the emitter knows both the finish reason and the set of children that were actually linked. ## Operational Effect The operational consequence is a class of cost and latency attribution errors that survive every schema validator. Token sums per trace remain correct; token sums per *reasoning step* are wrong whenever a tool call spans a turn boundary. Latency attribution to the requesting decision is lost entirely for orphaned tool spans. Evaluation harnesses that replay traces to score tool-use correctness will see a `chat` span that requested a tool and a separate `chat` span that produced an answer, with no edge connecting them — and will score the reasoning as if the tool result appeared from nowhere. The fix is not instrumentation-side alone. The agent loop must hold the parent span open across the full tool-call-and-resume cycle, or explicitly thread the parent `SpanContext` into each tool span's creation and into the resumed model call. The latter is preferable because it keeps spans short-lived while preserving the causal edge. Either way, the invariant to enforce is the containment assertion above, and it must be enforced at the emitter, because no downstream consumer can recover an edge that was never written. ```python from __future__ import annotations from dataclasses import dataclass, field from typing import Optional class OrphanedToolSpanError(RuntimeError): """Raised when a GenAI chat span closes with tool_calls but no linked tool child.""" def __init__(self, span_name: str, finish_reasons: list[str], child_count: int): self.span_name = span_name self.finish_reasons = finish_reasons self.child_count = child_count super().__init__( f"chat span {span_name!r} closed with finish_reasons={finish_reasons!r} " f"but linked execute_tool children={child_count}" ) @dataclass class SpanRecord: name: str operation: str parent_id: Optional[str] finish_reasons: list[str] = field(default_factory=list) linked_children: int = 0 def close_chat_span(span: SpanRecord) -> None: """Enforce containment invariant before a chat span is ended. A chat span that reports tool_calls MUST have at least one linked execute_tool child. Otherwise the tool span has been orphaned by an ambient-context exit and the causal edge is lost. """ if span.operation != "chat": return requests_tool = "tool_calls" in span.finish_reasons if requests_tool and span.linked_children == 0: raise OrphanedToolSpanError( span_name=span.name, finish_reasons=list(span.finish_reasons), child_count=span.linked_children, ) ```