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:
- Starts span `S_A.delegate` (child of `S_A`) with `SpanKind.CLIENT`.
- Serializes `traceparent` (trace `T`, span `S_A.delegate`) into the MCP request `_meta`.
- **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.
- 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.
- 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):
- `S_B` and `S_B.tool.*` have `parent_span_id == S_A.delegate.span_id`, but `S_A.delegate`'s `end_time_unix_nano` precedes `S_B`'s `start_time_unix_nano` by 40–900 ms (the async gap). Every span in the subtree is "born after its parent died."
- The trace renders as a waterfall where the child bar hangs *below and to the right* of the parent's closed bar. Tempo's `parentSpanId` join still works, so the trace *looks* whole; the causality is inverted.
- `S_A.delegate.result` carries the latency of the actual work (because the parent measured wall-clock around the await), while `S_A.delegate` carries only serialization latency. Any latency SLO computed by summing leaf spans under `S_A` **double-counts** the delegate duration: once under `S_A.delegate.result`, and once under the orphaned `S_B` subtree, which is now a sibling of `S_A.delegate` rather than a descendant of the span that "owns" the wait.
- When `B` retries internally (it does — the MCP call timed out at 30 s on the first attempt), `S_B.attempt.2` is emitted with the *same* `parent_span_id = S_A.delegate`. The backend now has two attempt subtrees under a closed parent with no ordering key that distinguishes "retry" from "concurrent fan-out." A causal replay (topological sort by `start_time`) interleaves attempt 1 and attempt 2 tool calls, producing a fabricated execution history that no instance ever ran.
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:
- **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.
- **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.
- **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:
- **Open the delegate span with `SpanKind.CLIENT` and keep it open across the await, ending it in the same scope that started it, after the child's `SpanContext` has been received and the child's root span is known to be closed.** If the runtime cannot guarantee the await thread, propagate the *span handle* (not just the `traceparent`) to the callback and end it there.
- **If the delegate span must be closed early (e.g., fire-and-forget, or a transport that cannot carry a callback), do not reparent the child under it.** Instead, emit a `Link` from the child's root span to the closed delegate span, and start the child's root span as a sibling under `S_A` (the still-open ancestor). Links carry causality without asserting a parent-child time ordering that is false.
- **On retry, do not reuse the parent.** Each attempt gets its own delegate span (`S_A.delegate.attempt.1`, `.2`), each closed by its own callback. The retry loop is the parent; the attempt is the child. Reusing `S_A.delegate` as parent for attempt 2 is the exact condition that fabricates concurrent history.
- **Refuse to emit a child span whose `start_time` is earlier than its parent's `end_time` when the parent is in the same trace and the child is not a `Link`.** This is a local guardrail the runtime can enforce before export; it converts a silent corruption into a loud, attributable failure at the emitting instance.
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,
)