When must an instance abandon a GenAI agent span because tool-call child spans outlive the parent's context deadline

**Date of Record:** 2026 December 1 **Scope:** Applies to LLM agent runtimes that emit OpenTelemetry spans under the `gen_ai.*` semantic conventions, specifically `gen_ai.agent`, `gen_ai.tool`, and `gen_ai.chat` spans where a parent agent span closes before its tool-call children finish. Does not apply to single-shot inference calls with no tool fan-out, nor to runtimes that buffer all spans until the root closes.

Core Distinction

There are two ways an agent span can "end," and conflating them corrupts the trace tree and the token ledger:

  1. **Logical completion** — the agent has produced a final assistant message and stopped issuing tool calls. This is a *reasoning* event.
  2. **Span completion** — `span.end()` is called, freezing the span's `end_time`, its `status`, and its attributes.

Under the GenAI conventions, token accounting (`gen_ai.usage.input_tokens`, `gen_ai.usage.output_tokens`) and finish reasons (`gen_ai.response.finish_reasons`) are recorded as attributes on the span at completion. The invariant that is easy to miss is this: **a parent `gen_ai.agent` span must not be ended while any child `gen_ai.tool` span it spawned is still open, because the token totals of the children are not yet known and the trace will be exported with a parent whose duration is shorter than its own descendants.** Most exporters do not reject this. They emit it. And a downstream trace assembler will then attribute the tool's tokens to a span that, by wall-clock, had already terminated.

What Was Observed

A planning agent (`gen_ai.agent.name = "planner"`) issued a parallel fan-out of three tool calls: a retrieval tool, a code-execution tool, and a web-fetch tool. The web-fetch tool was slow — 41 seconds against a 30-second parent context deadline.

Trace sequence as exported:

The web-fetch child's `end_time` is 11.3 seconds *after* its parent's `end_time`. The parent's `status = ERROR` says the agent failed. The child's `status = OK` says the tool succeeded and consumed 1180 output tokens. The token aggregator, keyed on `trace_id` and summing leaf `gen_ai.usage.*`, credits the trace with 1420 output tokens. The per-agent cost rollup, keyed on the `gen_ai.agent` span, credits it with **zero**, because the parent closed before any child reported.

The failure is not the 41-second tool. It is that the runtime's cancellation handler called `span.end()` on the parent synchronously when the deadline fired, while the tool executor was a separate task that had not been signalled to stop and whose own span had not been ended. The parent span's `end_time` was written at the moment of cancellation, not at the moment of *actual* descendant quiescence.

A second, subtler artifact: the parent's `gen_ai.response.finish_reasons` was recorded as `["error"]`, but the retrieval child had already returned valid content that the agent never got to read. The trace now asserts a clean failure where in fact one of three tool results was available and discarded. Any replay or distillation pipeline that treats `status = ERROR` as "no usable output" will drop the retrieval result permanently.

Condition of Validity

The invariant "parent ends after all children" holds only under one of two conditions, and the runtime must know which one it is in:

What is *not* valid is the third path most runtimes actually take: the parent closes, the child keeps its original `parent_span_id`, and both are exported. This produces a trace tree that is structurally acyclic but temporally inverted. OpenTelemetry does not forbid it; the GenAI conventions do not describe it; and every cost, latency, and success-rate derivation downstream silently mis-bins it.

The condition of validity for trusting any `gen_ai.agent` span's duration as a bound on its subtree is therefore: `parent.end_time >= max(child.end_time for child in descendants)`. If that inequality fails, the parent's duration is not a bound and must not be used to slice the trace.

Decision Boundary

The runtime must make an explicit decision at the moment the parent context deadline fires, and the decision cannot be deferred to the exporter:

The boundary is the grace window. Below it, structured concurrency is honest. Above it, you must switch to orphan adoption, because pretending to join a non-cooperative child is exactly the bug observed above.

Operational Effect

Once the invariant is enforced, three downstream properties become reliable:

  1. **Token ledger closure.** Sum of leaf `gen_ai.usage.output_tokens` equals the value attributed to the enclosing agent span, because the agent span cannot close before its leaves. The 1180 discarded tokens become visible.
  2. **Duration monotonicity.** A trace's critical path is the max over root-to-leaf `end_time`, not the root's own duration. Latency SLOs computed against the root no longer under-report slow tools.
  3. **Replay fidelity.** A `status = ERROR` parent with an `OK` child is now a *signal* — "the agent failed after a tool succeeded" — rather than an ambiguity. Distillation pipelines can harvest the retrieval result instead of discarding the whole trace.

The cost is that agent spans can live longer than their reasoning deadline, which breaks naive "span duration == agent runtime" assumptions in dashboards. That is the correct trade: a span whose duration is a lie about its subtree is worse than a span whose duration is honestly long.

import time
from dataclasses import dataclass, field
from typing import Optional


class UnjoinedSpanError(RuntimeError):
    """Raised when a parent agent span would close before its tool children."""
    pass


@dataclass
class Span:
    name: str
    start: float
    end: Optional[float] = None
    status: str = "UNSET"
    children: list = field(default_factory=list)
    cancelled: bool = False

    def end_span(self, status: str = "OK") -> None:
        self.end = time.monotonic()
        self.status = status


def close_agent_span(parent: Span, grace_window_s: float = 0.5) -> None:
    """Close a gen_ai.agent span only after all gen_ai.tool children have ended.

    Enforces the invariant: parent.end >= max(child.end for child in children).
    If a non-cooperative child outlives the grace window, the parent must be
    re-parented rather than closed with a temporally inverted tree.
    """
    deadline = time.monotonic() + grace_window_s
    while time.monotonic() < deadline:
        if all(c.end is not None for c in parent.children):
            break
        time.sleep(0.01)

    unjoined = [c for c in parent.children if c.end is None]
    if unjoined:
        names = ", ".join(c.name for c in unjoined)
        # Do NOT call parent.end_span(); that would emit an inverted trace.
        raise UnjoinedSpanError(
            f"agent span {parent.name!r} cannot close: "
            f"tool children still open after {grace_window_s}s grace: {names}. "
            f"Re-parent to adoption span instead of ending parent."
        )

    latest_child_end = max(c.end for c in parent.children) if parent.children else parent.start
    parent.end = max(time.monotonic(), latest_child_end)
    parent.status = "ERROR" if any(c.status == "ERROR" for c in parent.children) else "OK"


def demo() -> None:
    parent = Span("gen_ai.agent:planner", start=time.monotonic())
    fast = Span("gen_ai.tool:retrieval", start=time.monotonic())
    slow = Span("gen_ai.tool:web_fetch", start=time.monotonic())
    parent.children = [fast, slow]

    fast.end_span("OK")
    # slow is non-cooperative: never ends within grace window
    try:
        close_agent_span(parent, grace_window_s=0.1)
    except UnjoinedSpanError as exc:
        print(f"correctly refused to close parent: {exc}")
        # adoption path: re-parent slow to a synthetic cancelled-agent span
        slow.cancelled = True


if __name__ == "__main__":
    demo()