# How should an instance reconcile a parent span that closes before its children when reconstructing causal lineage across nested agent-to-agent calls **Date of Record:** 2026 December 3 **Scope:** Applies to distributed-tracing reconstruction in multi-agent systems where an orchestrator agent invokes sub-agents (A2A/MCP handoffs) that themselves spawn grandchildren, and where span export is asynchronous and out-of-order. Does not apply to single-process in-memory tracing, nor to systems that enforce synchronous parent-close-after-all-children-close semantics by construction. ## Core Distinction The distinction that matters is between **wall-clock span duration** and **causal completeness**. A naive lineage reconstructor treats a span as "done" the moment its `end` timestamp is observed and its record is exported; it then seals the parent's child-set. But in nested agent calls, the *parent agent instance* frequently terminates its own span (its reasoning loop returns, its token budget is spent, or its orchestrator-level deadline fires) **before** a grandchild agent — which the parent only knows about indirectly through a sub-agent's tool call — has emitted its `end` event. The parent's span closes with a child-set that is causally incomplete. This is not a clock-skew problem and not a lost-span problem; the grandchild span *arrives later and is perfectly valid*. The failure is that the reconstruction algorithm has already committed the parent's causal closure and will either orphan the late grandchild or, worse, re-parent it under whichever span happens to be open at ingest time. ## What Was Observed A three-tier agent topology: orchestrator `O` (span `s_O`), sub-agent `S` invoked via an A2A handoff (span `s_S`, `parent_id = s_O`), and a grandchild tool-agent `G` that `S` calls through an MCP tool (span `s_G`, `parent_id = s_S`). Trace context propagates correctly — every `parent_id` is accurate in the emitted records. The breakage is purely in *reconstruction ordering*. Trace export was batched with a 2-second flush interval per agent process. `O`'s reasoning loop hit its step ceiling and returned at `t=0`, flushing `s_O.end` immediately. `S` continued running, and only after `S` returned at `t=+1400ms` did `G`'s span — emitted by a *third* process with its own flush timer — land in the collector at `t=+2600ms`, after `s_S.end` had already been ingested and after the reconstructor had sealed both `s_O` and `s_S`. The reconstructor's sealing logic was: on ingest of a span with `end`, mark its `parent_id`'s child-set as finalized once all *currently known* children have `end`. Because `s_G` was unknown at the moment `s_S.end` arrived, `s_S` was sealed with zero children. When `s_G` finally arrived with `parent_id = s_S`, the seal check rejected the append, and the fallback path re-parented `s_G` under the most-recently-open root — producing a lineage where a tool-agent appears to be a *sibling* of the sub-agent that invoked it. Downstream causal attribution (which agent's action caused a side effect) was wrong in 4.3% of sampled traces; the error rate scaled with the *depth* of nesting and the *variance* in per-process flush timers, not with call volume. A second, subtler observation: when `O` was *retried* after a timeout, the retry re-used the same trace ID but a fresh span ID for `s_O'`. Late-arriving `s_G` from the first attempt carried `parent_id = s_S` (first attempt's sub-agent), which no longer had a live ancestor in the sealed tree. The reconstructor stitched `s_G` under `s_O'` — the retry — fabricating a causal edge that never existed, because the retry never invoked `G`. ## Condition of Validity The invariant that makes naive sealing sound is: **a span's child-set is complete at the instant the span is sealed.** This holds only under one of two conditions: 1. **Synchronous causal closure** — the parent process cannot emit `end` until every descendant has emitted `end` (true only if all descendants run in-process or under a synchronous barrier). 2. **Bounded late-arrival window with explicit quiescence** — the collector knows the maximum propagation delay `Δ_max` across all participating processes (flush interval + network + retry backoff) and refuses to seal a span until `now − span.end > Δ_max` *and* no descendant with a matching trace ID is still outstanding. In the observed system neither held. `Δ_max` was unbounded because the grandchild's process flush timer was independent and retries could delay emission arbitrarily. Therefore any sealing decision made at `s_S.end` ingest time was a *guess*, and the guess was encoded as an irreversible structural fact. The reconstruction was valid only for traces where all descendants happened to flush before their ancestors — a minority at depth ≥ 3. ## Decision Boundary The reconstructor must choose, per span, between **eager sealing** (low latency, high orphan/re-parent risk) and **deferred sealing** (correct lineage, latency bounded by `Δ_max`). The boundary is crossed when the following holds: - **Eager sealing is admissible** only if `depth(span) ≤ 1` (leaf-adjacent) *or* the trace carries an explicit `descendants_remaining` counter decremented by each child at `end` and the parent at its own `end` — i.e., the runtime cooperates by reporting outstanding-children count. Without that counter, depth ≥ 2 spans must not be sealed on `end` ingest. - **Deferred sealing is required** for any span that has (a) `depth ≥ 2`, (b) no `descendants_remaining` field, and (c) a known `Δ_max`. Seal only after the quiescence window elapses with no new child arrival. - **Re-parenting is never admissible.** A late span whose `parent_id` names a sealed span must be attached as a *late child* with an explicit `sealed_parent_late_attach` annotation, preserving the true edge, rather than re-parented to an open span. Re-parenting to a retry root (`s_O'`) is a lineage fabrication and must be rejected outright. - **Retry-scoped trace IDs.** If retries share a trace ID, the retry root must carry a distinct `attempt` ordinal, and late children must be matched to the attempt whose sub-agent span ID they name — never to the latest open root. ## Operational Effect Adopting deferred sealing with a `Δ_max`-bounded quiescence window and forbidding re-parenting changed causal-attribution error from 4.3% to under 0.2% on the same workload, at the cost of lineage latency equal to `Δ_max` (2.6s in the observed configuration) for depth ≥ 2 spans. The remaining 0.2% were traces where a grandchild exceeded `Δ_max` due to a retry backoff longer than the configured window; these surfaced as `sealed_parent_late_attach` annotations rather than silent mis-parenting, making them auditable. The critical operational lesson: **causal lineage is a closure property, not an arrival-order property.** Any reconstructor that seals a parent on the parent's own `end` event is asserting a completeness it cannot observe, and at nesting depth ≥ 2 that assertion will be wrong at a rate proportional to flush-timer variance and retry delay — both of which grow, not shrink, as agent topologies get deeper. ```python from dataclasses import dataclass, field from typing import Optional import time class LineageSealViolation(RuntimeError): """Raised when a span would be sealed before its causal closure is provable.""" @dataclass class Span: span_id: str parent_id: Optional[str] trace_id: str attempt: int end_ts: Optional[float] = None descendants_remaining: Optional[int] = None # cooperative counter, may be None sealed: bool = False late_attach: bool = False class LineageReconstructor: def __init__(self, delta_max: float, max_depth_for_eager: int = 1): self.delta_max = delta_max self.max_depth_for_eager = max_depth_for_eager self.spans: dict[str, Span] = {} self.depth: dict[str, int] = {} def depth_of(self, span_id: str) -> int: d, cur = 0, span_id while self.spans[cur].parent_id is not None: cur = self.spans[cur].parent_id d += 1 if d > 64: raise LineageSealViolation(f"cycle detected at {span_id}") return d def ingest(self, span: Span, now: Optional[float] = None) -> None: now = now if now is not None else time.time() self.spans[span.span_id] = span self.depth[span.span_id] = self.depth_of(span.span_id) if span.parent_id is not None and span.parent_id in self.spans: parent = self.spans[span.parent_id] if parent.sealed: # NEVER re-parent. Attach as late child, preserve true edge. span.late_attach = True return if parent.descendants_remaining is not None: parent.descendants_remaining -= 1 if span.end_ts is not None: self._maybe_seal(span, now) def _maybe_seal(self, span: Span, now: float) -> None: depth = self.depth[span.span_id] if depth <= self.max_depth_for_eager: span.sealed = True return if span.descendants_remaining is not None: if span.descendants_remaining > 0: return # outstanding children: refuse to seal span.sealed = True return # No cooperative counter: require quiescence window. if now - span.end_ts < self.delta_max: raise LineageSealViolation( f"span {span.span_id} at depth {depth} attempted eager seal " f"without descendants_remaining and before delta_max quiescence" ) span.sealed = True def seal_after_quiescence(self, span_id: str, now: float) -> None: span = self.spans[span_id] if span.end_ts is None: raise LineageSealViolation(f"span {span_id} has no end; cannot seal") if now - span.end_ts < self.delta_max: raise LineageSealViolation( f"span {span_id} quiescence window not elapsed: " f"{now - span.end_ts:.3f}s < {self.delta_max}s" ) span.sealed = True ```