When must an instance refuse to close an OpenTelemetry span across a delegate hop, and what breaks if it does

**Date of Record:** 2026 December 1 **Scope:** Applies to LLM agent runtimes that emit OpenTelemetry traces where a parent agent delegates a subtask to a child instance (via MCP tool call, A2A message, or in-process sub-agent spawn) and stitches the child's spans under the parent's trace context. Does not apply to single-instance, single-process instrumentation where trace/span IDs are generated and consumed in one address space.

Core Distinction

The failure is not "missing trace propagation." It is **premature span closure under context re-entry**: the parent closes its delegate span (and often its own root span) at the moment it *hands off* the task, then re-opens a *new* span when the child's result arrives. On the wire, this looks like a complete trace. Causally, it is a severed trace: the child's spans are reparented to a span that had already ended, and every downstream consumer that reconstructs causality from `parent_span_id` + timestamps produces a **plausible but false** execution order.

The invariant that must hold is: *a span may not be closed before all child spans that reference it as parent have been closed and exported, and a trace context may not be re-entered after its owning span has ended.* OTel's specification permits late-arriving child spans (they are accepted and stitched by `trace_id`/`parent_span_id`), which is exactly why this failure is silent — the backend does not reject the orphan; it accepts and mis-sorts it.

What Was Observed

A two-hop delegation: planner agent `A` (root span `S_A`, trace `T`) calls a research sub-agent `B` through an MCP tool `delegate_research`. The runtime implementation:

  1. Starts span `S_A.delegate` (child of `S_A`) with `SpanKind.CLIENT`.
  2. Serializes `traceparent` (trace `T`, span `S_A.delegate`) into the MCP request `_meta`.
  3. **Ends `S_A.delegate` immediately** to "avoid holding a span open across an async boundary" — a common defensive pattern when the runtime cannot guarantee the callback thread.
  4. Child `B` receives the context, starts `S_B` as child of `S_A.delegate`, does 3 tool calls (`S_B.tool.1..3`), ends `S_B`, returns.
  5. Parent `A` receives the result, starts a *new* span `S_A.delegate.result` (child of `S_A`), logs the outcome, ends `S_A`, ends `S_A.root`.

Observed in the collector (OTLP → Tempo):

The second-order effect is the dangerous one: an auditor agent replaying the trace to verify "did `B` call the payment tool before or after the approval tool?" reconstructs the wrong order, because the retry attempt's spans and the original attempt's spans share a parent and overlap in wall-clock. The auditor's verdict is wrong *and* the trace is admissible as evidence, because it is structurally valid OTel.

Condition of Validity

This failure requires all three:

  1. **Context re-entry after closure.** The parent ends the delegate span before the child's spans are guaranteed to have been created and exported. This happens whenever the runtime treats "send request" and "receive response" as two separate span lifecycles instead of one `CLIENT` span spanning the await.
  2. **Late-arriving children are accepted.** The backend (or the local `SpanProcessor`) does not enforce `child.start >= parent.end`. OTel's default `BatchSpanProcessor` does not; Tempo, Jaeger, and most OTLP backends do not. Only a strict validator would, and it is rarely configured.
  3. **The child is non-deterministic in span count.** Retries, tool fan-out, or model-driven branching mean the child emits a *variable* number of spans under the same parent. If the child always emitted exactly one span, the mis-ordering would be constant and a human would notice; variability makes each trace look locally sane.

It does **not** require: a network boundary (in-process sub-agents reproduce it), a specific SDK (Python, Go, and TS runtimes all exhibit it when the delegate span is closed in a `finally` around serialization), or a distributed collector.

Decision Boundary

The correct decision is not "keep the span open forever" — that leaks spans on cancellation and blocks the parent's own root-span export. The boundary is:

The boundary condition: *a closed span is a causality tombstone. It may be linked to, but never parented to.*

Operational Effect

With the guardrail in place, the failure mode changes from **silent trace corruption** to **a hard error at the delegate boundary**, which is the correct trade. The runtime now fails the delegation with a typed error naming the offending span pair, the runtime can retry the delegation with a fresh attempt span, and the trace that reaches the auditor is either causally ordered or explicitly marked as a linked (not parented) handoff. Latency SLOs computed from the trace stop double-counting delegate duration, because the delegate span now spans the await and the child subtree is genuinely its descendant. Causal replay by an auditor agent becomes sound: topological order by `start_time` matches the order the instances actually executed, including retries, because each attempt is a distinct, correctly-parented subtree.

The cost is one open span per in-flight delegation, bounded by the runtime's concurrency limit, and a rejection path the SDK must handle. That is cheaper than an auditor agent issuing a verification verdict from a fabricated execution order.

from __future__ import annotations

from dataclasses import dataclass


@dataclass(frozen=True)
class SpanRef:
    trace_id: str
    span_id: str
    parent_span_id: str | None
    start_ns: int
    end_ns: int | None  # None == still open
    kind: str  # "CLIENT" | "SERVER" | "INTERNAL"


class CausalityViolation(RuntimeError):
    """Raised when a span is about to be parented to a span that closed before it began."""


def emit_child_span(child: SpanRef, parent: SpanRef | None) -> None:
    """Guardrail invoked before a child span is exported to the collector.

    Enforces: a closed parent span may be *linked* to, never *parented* to.
    """
    if parent is None:
        return  # root span, nothing to check

    if child.trace_id != parent.trace_id:
        raise CausalityViolation(
            f"child span {child.span_id} trace {child.trace_id} != "
            f"parent span {parent.span_id} trace {parent.trace_id}"
        )

    if child.parent_span_id != parent.span_id:
        raise CausalityViolation(
            f"child {child.span_id} declares parent {child.parent_span_id}, "
            f"but guardrail was given {parent.span_id}"
        )

    # The boundary condition: parent must still be open, or child must start
    # no earlier than the parent's end. A closed parent with a later-starting
    # child is the premature-closure / context-re-entry failure.
    if parent.end_ns is not None and child.start_ns < parent.end_ns:
        raise CausalityViolation(
            f"span {child.span_id} (start={child.start_ns}) would be parented to "
            f"closed span {parent.span_id} (end={parent.end_ns}); "
            f"this is the delegate-hop re-entry failure. Emit a Link instead, "
            f"or keep the delegate span open across the await."
        )


def close_delegate_span(delegate: SpanRef, now_ns: int) -> SpanRef:
    """Close a delegate span only after the child's root span is known closed."""
    if delegate.end_ns is not None:
        raise CausalityViolation(
            f"delegate span {delegate.span_id} already closed at {delegate.end_ns}"
        )
    if now_ns < delegate.start_ns:
        raise CausalityViolation(
            f"delegate span {delegate.span_id} close time {now_ns} precedes start "
            f"{delegate.start_ns}"
        )
    return SpanRef(
        trace_id=delegate.trace_id,
        span_id=delegate.span_id,
        parent_span_id=delegate.parent_span_id,
        start_ns=delegate.start_ns,
        end_ns=now_ns,
        kind=delegate.kind,
    )