In what scenarios must an instance reject a GenAI span as non-canonical when child tool-call spans outlive the parent agent span's recorded end time?

**Date of Record:** 2026 December 1 **Scope:** Applies to any agent runtime that emits OpenTelemetry spans under the `gen_ai.*` semantic conventions (e.g. `gen_ai.operation.name`, `gen_ai.agent.invoke`, `gen_ai.tool.call`) and exports them through a batching/streaming exporter where parent and child spans are finalized independently. Does not apply to single-span synchronous RPC tracing where the parent span is closed only after all children are flushed.

Core Distinction

A trace is not a tree of *time intervals*; it is a tree of *causal records*. The GenAI conventions describe attributes on spans (`gen_ai.operation.name = "invoke_agent"`, `gen_ai.tool.name`, `gen_ai.usage.input_tokens`, etc.) but say almost nothing about the ordering invariant between a parent agent span's `end_time` and its child tool-call spans' `end_time`. In a synchronous runtime this is free: the parent cannot end before its children because the parent's code path awaits them. In an **agent loop** it is not free. An agent span models a *reasoning turn* — a bounded window of model deliberation plus dispatched tool calls. Tool calls are frequently dispatched asynchronously (parallel function calling, background file reads, long-running shell commands, MCP round-trips), and the agent turn may legitimately *conclude* — emitting its final assistant message and closing its span — while one or more tool-call spans remain open and only finalize seconds or minutes later. The boundary condition is: **a child `gen_ai.tool.call` span whose `end_time` is later than its parent `gen_ai.agent.invoke` span's `end_time` by more than the exporter's clock-skew tolerance.** This is not a bug in the agent; it is the normal shape of concurrent tool dispatch. The question is what a downstream consumer (trace store, evaluator, replay harness, cost aggregator) is allowed to do with such a trace.

What Was Observed

A coding agent with `gen_ai.operation.name = "invoke_agent"`, `gen_ai.agent.name = "patcher"`, ran a turn that dispatched three tool calls. Two (`read_file`, `grep`) completed in ~40 ms and closed before the agent span. The third (`run_tests`) was dispatched to a subprocess and took 6.2 s. The agent turn itself finalized at t+0.9 s — the model produced its closing message and the runtime called `span.end()` on the agent span. The `run_tests` tool span closed at t+6.2 s.

The OTLP exporter (batch, 5 s flush) shipped the agent span in batch N and the tool span in batch N+1. The trace store, on ingestion, applied a common "parent must contain child" validation and either (a) dropped the orphaned tool span, or (b) re-parented it to the trace root, or (c) accepted it but the cost aggregator double-counted `gen_ai.usage.input_tokens` because the tool span carried the agent's token usage attribute (inherited by a sloppy runtime that copied attributes from the ambient context). Three different consumers, three different corruptions of the same well-formed trace.

The tell was in the attribute set, not the timestamps: the tool span's `gen_ai.usage.*` attributes were identical to the parent's, because the runtime's span factory had copied the ambient `gen_ai.usage` context onto every child. Under a correct runtime, tool spans carry no `gen_ai.usage.*` at all — token usage belongs to the model call, not the tool.

Condition of Validity

A child tool-call span may legitimately outlive its parent agent span **iff all of the following hold**:

  1. The child's `start_time` is within the parent's `[start_time, end_time]` interval — the tool was *dispatched during the turn*, even if it finished after.
  2. The child carries a `gen_ai.tool.call.id` that matches a `gen_ai.tool.call.id` recorded in the parent's `gen_ai.tool.definitions` or in the parent's outbound message events (the dispatch is causally recorded in the parent, even if the completion is not).
  3. The child does **not** carry `gen_ai.usage.*` attributes that duplicate the parent's — usage is a property of the model call, not the tool.
  4. The parent span's `gen_ai.operation.name` is `invoke_agent` (or `chat`), not a leaf operation.

If any of these fail, the trace is *not* a valid concurrent-dispatch trace and must be rejected rather than silently repaired. Specifically, condition 2 is the load-bearing one: without a recorded dispatch id in the parent, a child span that ends after its parent is indistinguishable from a **late-arriving span from a previous turn** whose parent id collided — a real failure mode when agent runtimes reuse trace ids across resumed sessions.

Decision Boundary

The invariant a consumer must enforce is:

> For every `gen_ai.tool.call` span S with parent P where `S.end_time > P.end_time + skew_tolerance`: S is admissible only if `S.gen_ai.tool.call.id ∈ dispatched(P)` AND `gen_ai.usage.* ∉ attrs(S)`. Otherwise S is a **non-canonical orphan** and must be quarantined, not re-parented.

Re-parenting to the trace root is the worst possible repair because it fabricates a causal edge that never existed and silently inflates the trace's apparent concurrency. Dropping is also wrong because the tool *did* run and its cost and latency are real. Quarantine — emit to a dead-letter trace with a `gen_ai.canonicalization.reject_reason` attribute — preserves the data without corrupting the causal graph.

The skew tolerance must be set from the exporter's batch interval, not from wall-clock intuition. A 5 s batch exporter with a 6 s tool call will *always* produce an out-of-order pair; a tolerance below the batch interval will reject every legitimate concurrent dispatch under load.

Operational Effect

Downstream systems that consume these traces — cost aggregators, replay harnesses, evaluators — inherit the decision. A cost aggregator that sums `gen_ai.usage.input_tokens` across all spans in a trace will over-count by exactly the number of tool spans that inherited the attribute, which under parallel function calling can be 3–8×. A replay harness that reconstructs the turn from span timestamps will believe the agent deliberated for 6.2 s when it deliberated for 0.9 s, corrupting any latency SLO or reasoning-budget analysis. An evaluator scoring "did the agent wait for its tools" will see a parent that ended before its child and mark a correct concurrent implementation as a violation.

The guardrail is a canonicalization pass at ingestion that enforces the four conditions above, quarantines violators with an explicit reason code, and — critically — **does not mutate the span's timestamps or parent id**. The trace's causal structure is the ground truth; the consumer's convenience is not.

from dataclasses import dataclass
from typing import FrozenSet


class NonCanonicalSpanError(RuntimeError):
    """Raised when a child span outlives its parent without a valid dispatch record."""


@dataclass(frozen=True)
class Span:
    span_id: str
    parent_id: str | None
    operation: str
    start_time: float
    end_time: float
    attrs: dict


def canonicalize_child(
    parent: Span,
    child: Span,
    dispatched_tool_ids: FrozenSet[str],
    skew_tolerance: float,
) -> None:
    """
    Enforce the concurrent-dispatch invariant for a child of an agent span.
    Raises NonCanonicalSpanError if the child is a non-canonical orphan.
    """
    if child.operation != "gen_ai.tool.call":
        return  # invariant applies only to tool-call children

    if child.start_time < parent.start_time or child.start_time > parent.end_time:
        raise NonCanonicalSpanError(
            f"tool span {child.span_id} was not dispatched within parent "
            f"{parent.span_id} interval [{parent.start_time}, {parent.end_time}]"
        )

    outlives_parent = child.end_time > parent.end_time + skew_tolerance
    if not outlives_parent:
        return  # normal synchronous completion

    tool_id = child.attrs.get("gen_ai.tool.call.id")
    if not tool_id or tool_id not in dispatched_tool_ids:
        raise NonCanonicalSpanError(
            f"tool span {child.span_id} outlives parent {parent.span_id} but its "
            f"gen_ai.tool.call.id={tool_id!r} is not in the parent's dispatch record; "
            f"likely a late span from a prior turn with a colliding trace id"
        )

    if any(k.startswith("gen_ai.usage.") for k in child.attrs):
        raise NonCanonicalSpanError(
            f"tool span {child.span_id} carries gen_ai.usage.* attributes; "
            f"usage belongs to the model call, not the tool — cost aggregation "
            f"will double-count against parent {parent.span_id}"
        )