Where must an instance refuse to emit a GenAI tool-call span when its parent agent span has already been closed by an out-of-band completion signal

**Date of Record:** 2026 December 1 **Scope:** Applies to any agent runtime that emits OpenTelemetry GenAI spans (`gen_ai.*` semantic conventions) where tool invocations are attributed to an enclosing agent/invoke-agent span and the span lifecycle is owned by the LLM loop rather than the tool executor. Does not apply to fire-and-forget telemetry sinks that tolerate orphan spans, nor to runtimes where tool execution is fully synchronous within the parent span's lexical scope.

Core Distinction

The GenAI semantic conventions treat a tool call as a *child event of an agent turn*: `gen_ai.operation.name = "execute_tool"`, `gen_ai.tool.name`, `gen_ai.tool.call.id`, and `gen_ai.agent.name` are all attributes whose meaning is anchored to the enclosing `invoke_agent` span. The invariant that is easy to miss is this: **the semantic validity of a tool-call span depends on the parent agent span being open at the moment the child span is *started*, not merely at the moment it is exported.** A span exporter will happily accept a child span whose parent context has already ended; the OTel SDK does not reject it. But the resulting trace is semantically incoherent — the tool call is attributed to a turn that the agent has already declared complete — and downstream consumers (trace-based evaluators, cost attribution, replay harnesses) will either double-count the turn or drop the tool call entirely.

The distinction that matters operationally is between *transport-level acceptance* (the exporter takes the span) and *semantic-level validity* (the span's attributes are consistent with the parent's lifecycle state). These diverge precisely when an agent turn is terminated out-of-band — by a stop sequence, a token-budget cutoff, a supervisor cancel, or a `tool_choice: none` completion — while a tool executor is still in flight.

What Was Observed

A multi-step agent loop was instrumented so that each LLM turn opened an `invoke_agent` span, and each tool call opened a nested `execute_tool` span with `gen_ai.tool.call.id` matching the `tool_call_id` returned by the model. Under normal completion the nesting was clean: `invoke_agent → chat → execute_tool`, with the tool span closing before the agent span.

Under a specific trigger — the model emitting a final assistant message with `finish_reason: "stop"` *while* a tool executor dispatched on the prior turn was still awaiting a slow backend — the following trace was produced:

  1. Turn N: `invoke_agent` span opens, `chat` span opens, model returns `tool_calls` for `search_docs` with `id=call_abc`.
  2. Runtime dispatches `search_docs` asynchronously; `execute_tool` span is created but not yet ended.
  3. Model is re-invoked (turn N+1) and returns `finish_reason: "stop"` with a final answer. The agent loop treats this as terminal and **ends the `invoke_agent` span for turn N+1**.
  4. The `search_docs` executor returns 4.2s later. The runtime ends the `execute_tool` span and exports it.

The exported `execute_tool` span carried a valid `gen_ai.tool.call.id=call_abc` and a parent span context pointing at the *turn N* `invoke_agent` span, which had been ended ~4s earlier. The collector accepted it. The trace UI rendered it as a child of a closed span — visually orphaned, but structurally valid. A downstream cost-attribution job that summed `gen_ai.usage.output_tokens` per `invoke_agent` span *plus* its `execute_tool` children double-counted the tool latency against turn N and attributed zero tool cost to turn N+1, where the model had actually consumed the tool result.

The non-obvious part: **the failure was silent at every layer.** The SDK did not error, the exporter did not drop, the collector did not flag. The only signal was a semantic inconsistency — a `execute_tool` span whose `end_time` exceeded its parent's `end_time` by 4.2 seconds, which violates the implicit invariant that a child span's lifetime is contained in its parent's.

Condition of Validity

The invariant holds — and the guardrail is required — under the conjunction of three conditions:

  1. **Asynchronous tool dispatch.** The tool executor runs on a task/thread not joined to the LLM turn's `finally` block. Synchronous tool calls inside the turn cannot trigger this.
  2. **Out-of-band turn termination.** The agent loop can end an `invoke_agent` span on a signal other than "all child tool spans ended" — e.g., `finish_reason: "stop"`, a supervisor `cancel()`, or a token-budget guard that aborts the loop.
  3. **Late parent-context resolution.** The child span is created with `context=parent_ctx` captured at dispatch time, and exported after the parent has ended. If the runtime used an implicit current-context at export time, the span would instead become a root span (a different, also-wrong failure).

When any of these is absent — synchronous tools, or turn termination that awaits child joins, or root-span fallback — the specific incoherence described here does not occur (though other attributions may still be wrong).

Decision Boundary

An instance must **refuse to export** a `gen_ai.operation.name = "execute_tool"` span when the resolved parent `invoke_agent` span is already ended. The correct behavior is one of two bounded options, never silent export:

The boundary is sharp: the check is `child.start_time > parent.end_time` *at export time*, evaluated against the parent span object the runtime still holds. It is not a heuristic on wall-clock skew; it is a structural comparison of span lifecycle fields the runtime owns. Below the boundary (parent still open) export normally; above it (parent ended) the span is semantically invalid and must be quarantined.

Operational Effect

The practical consequence is that tool-call telemetry becomes *complete and attributable* rather than merely *delivered*. Without the guardrail, the trace looks fine in volume — span counts match invocation counts — but per-turn cost, latency, and error attribution silently drift, and any evaluator that joins tool results to turns by parent span will mis-join under exactly the slow-tool-plus-early-stop case that is most common in production. With the guardrail, orphaned tool spans are a first-class, countable signal: a rising `gen_ai.tool.span_dropped_orphan` rate is direct evidence that the agent loop is terminating turns before joining tool executors, which is itself a correctness bug worth fixing at the loop level. The guardrail converts a silent semantic corruption into a bounded, observable loss.

from __future__ import annotations

from dataclasses import dataclass
from typing import Optional


class OrphanedToolSpanError(RuntimeError):
    """Raised when a GenAI execute_tool span would be exported under an ended parent."""


@dataclass(frozen=True)
class SpanRef:
    name: str
    start_ns: int
    end_ns: Optional[int]  # None == still open
    operation: str


def validate_tool_span_export(
    tool_span: SpanRef,
    parent_agent_span: Optional[SpanRef],
    *,
    allow_reparent: bool = False,
) -> str:
    """Enforce the parent-containment invariant for gen_ai execute_tool spans.

    Returns a disposition string: "export", "reparent_orphan", or "drop_orphan".
    Raises OrphanedToolSpanError when the span is invalid and no bounded
    disposition was authorized by the caller.
    """
    if tool_span.operation != "execute_tool":
        return "export"

    if parent_agent_span is None:
        # No parent captured at dispatch: cannot attribute; must not silently export.
        if not allow_reparent:
            raise OrphanedToolSpanError(
                f"execute_tool span {tool_span.name!r} has no resolvable parent "
                "invoke_agent span; refusing silent root export"
            )
        return "reparent_orphan"

    if parent_agent_span.end_ns is None:
        # Parent still open: normal, valid nesting.
        return "export"

    if tool_span.start_ns > parent_agent_span.end_ns:
        # The exact failure mode: child started after the parent turn was closed
        # by an out-of-band completion signal (stop sequence, budget cutoff, cancel).
        if not allow_reparent:
            raise OrphanedToolSpanError(
                f"execute_tool span {tool_span.name!r} started at "
                f"{tool_span.start_ns} after parent {parent_agent_span.name!r} "
                f"ended at {parent_agent_span.end_ns}; "
                "parent-containment invariant violated"
            )
        return "reparent_orphan"

    # Child started before parent ended but may still outlive it; that is a
    # latency/attribution concern, not a containment violation.
    return "export"


def emit_tool_span(tool_span: SpanRef, parent: Optional[SpanRef], *, allow_reparent: bool) -> str:
    disposition = validate_tool_span_export(tool_span, parent, allow_reparent=allow_reparent)
    if disposition == "drop_orphan":
        raise OrphanedToolSpanError("orphan drop requested but not wired to counter")
    return disposition