# How does an instance detect orphaned spans when a sub-agent's trace context is reparented by an async tool-call DAG? **Date of Record:** 2026 November 21 **Scope:** Applies to observability pipelines that reconstruct a single causal DAG from spans emitted by a root agent, its nested sub-agents, and the tool calls they invoke asynchronously. Does not apply to flat, single-process tracing where every span shares one in-memory context object, nor to synchronous tool calls whose parent span is guaranteed live at emit time. ## Core Distinction The failure is not "missing spans." Missing spans are a lossy-export problem, detectable by counting. The boundary condition here is **span reparenting under deferred emission**: a span that *was* emitted correctly, with a valid `parent_span_id`, but whose parent arrives at the collector *after* the child, and whose parent's own `parent_span_id` was rewritten by the sub-agent's context-propagation layer during an async handoff. The child is not lost — it is *mis-parented*. The reconstructed DAG is fully connected and internally consistent, which is exactly why naive validators pass it. The topology is wrong, not broken. The invariant that fails: **a span's causal ancestry must be a function of the execution that produced it, not of the wall-clock order in which the collector received it.** Async tool-call DAGs violate this because the sub-agent that owns the tool call may fork its trace context, run the tool on a worker with a re-derived `trace_id`/`parent_span_id`, and only reconcile the context after the tool returns. During the window between fork and reconcile, any grandchild span emitted by the tool carries a parent pointer to a span the collector has never seen — and if the reconcile step *drops* the original parent (a common "flatten to root" optimization), the grandchild is permanently reparented to the sub-agent's root, silently collapsing a three-level causal chain into two. ## What Was Observed A root agent (span `A`) dispatched sub-agent `B` over an A2A-style transport. `B` invoked tool `T` asynchronously. `T` internally called a nested tool `U`. The emitted spans, in collector-arrival order: 1. `A` — root, `parent_span_id=None` 2. `B` — `parent_span_id=A`, `trace_id=t1` 3. `U` — `parent_span_id=T`, `trace_id=t1` (arrived before `T`) 4. `T` — `parent_span_id=B`, `trace_id=t1` On arrival, the collector buffered `U` because `T` was unknown. When `T` arrived, `U` was linked under `T` correctly — a standard out-of-order join. The DAG reconstructed as `A → B → T → U`, which is *correct*. This run passed. The failure appeared on the next run, when `B`'s async tool wrapper took the "context flatten" path: because `T` was dispatched on a worker pool with a fresh context, the wrapper reassigned `T.parent_span_id = A` (the root) rather than `B`, on the theory that the worker had no access to `B`'s span object. `U` still carried `parent_span_id=T`. Reconstructed DAG: `A → B` and `A → T → U`. `B` became a leaf. The causal claim "sub-agent `B` caused tool `T`" was erased, and the trace *still validated* — no orphans, no cycles, every `parent_span_id` resolvable. The tell was not a dangling pointer. It was a **topological anomaly**: `B` had a nonzero `end_time` strictly before `T`'s `start_time`, yet `B`'s span carried attributes (`tool.invoked=T`, `tool.worker_id=w3`) that only the `T` dispatch path could have set. A span that terminated before its own recorded effect began is causally impossible. That contradiction — not a missing edge — is the detection signal. ## Condition of Validity The detection rule is valid only when all of the following hold: - Every span carries both `start_time` and `end_time` from a clock that is *monotonic within a single host* and *boundedly skewed across hosts* (NTP-synced to within the async dispatch latency). If cross-host skew exceeds the tool's dispatch-to-return window, the temporal contradiction test produces false positives. - The sub-agent's context wrapper does not rewrite `trace_id`. If it does, the spans land in separate traces and the anomaly is invisible to a single-trace validator — you need a cross-trace join on a correlation attribute (e.g., `agent.session_id`), which is a different and weaker invariant. - Attribute provenance is trustworthy: the `tool.invoked` / `tool.worker_id` attributes on the parent must be set by the dispatch path, not by the sub-agent's own bookkeeping. If the sub-agent stamps them on itself, the contradiction test collapses. When any of these fail, the anomaly is undetectable from the trace alone and must be caught at the propagation layer (a signed context token that pins `parent_span_id` at fork time and refuses reparenting on reconcile). ## Decision Boundary An instance should treat a temporal-provenance contradiction as a **hard topology fault** — quarantine the trace, do not feed it to downstream causal analysis or cost attribution — rather than a soft warning, *if and only if* the contradiction is on a span that also carries provenance attributes pointing at the orphaned child. A bare temporal inversion (child ends before parent starts) with no cross-referencing attributes is more likely clock skew and should be downgraded to a warning. The boundary is the presence of the **provenance cross-reference**: the parent span names the child's tool/worker, but the child's ancestry does not route through the parent. That conjunction is the signature of reparenting, and it is the only condition under which the trace must be rejected outright. Without it, you are guessing. ## Operational Effect Downstream consumers of the DAG — causal root-cause ranking, per-sub-agent cost rollup, failure-attribution to a specific tool — silently attribute `T`'s and `U`'s cost and latency to the root agent `A` instead of sub-agent `B`. In a swarm, this systematically over-attributes to the orchestrator and under-attributes to the sub-agent that actually misbehaved, which inverts the signal an auditor uses to decide which agent to retrain or throttle. The fix is not "buffer more" or "retry the join"; it is to **pin parentage at fork time with an immutable context token and reject any reconcile that would reparent a span whose children have already been emitted.** The validator below encodes the contradiction test as the gate. ```python from dataclasses import dataclass from typing import Optional class TraceTopologyFault(RuntimeError): """Raised when a reconstructed span DAG violates causal-provenance ordering.""" pass @dataclass class Span: span_id: str parent_span_id: Optional[str] start_time: float end_time: float attrs: dict def validate_provenance(spans: dict[str, Span]) -> None: """ Reject traces where a span's recorded effect (a provenance attribute naming a child tool/worker) precedes the child's ancestry routing through that span. This is the reparenting signature: the parent claims the child, but the child's parent pointer points elsewhere. """ for sid, span in spans.items(): # Provenance cross-reference: does this span claim to have invoked a tool? claimed_child = span.attrs.get("tool.invoked") if claimed_child is None: continue # Find the span that actually owns that tool's causal ancestry. child = next( (s for s in spans.values() if s.attrs.get("tool.name") == claimed_child), None, ) if child is None: continue # child not yet collected; out-of-order join, not a fault # If the child's ancestry routes through this span, topology is sound. if child.parent_span_id == sid: continue # Otherwise: parent claims the child, but the child is parented # elsewhere. If the parent also terminated strictly before the # child began, the claim is causally impossible -> reparenting. if span.end_time < child.start_time: raise TraceTopologyFault( f"Span {sid} claims tool '{claimed_child}' (worker " f"{span.attrs.get('tool.worker_id')}) but child {child.span_id} " f"is parented to {child.parent_span_id}, not {sid}; " f"parent ended at {span.end_time} before child began at " f"{child.start_time}. Trace context was reparented during " f"async dispatch. Quarantine trace; do not attribute " f"child cost to parent." ) def reconstruct_and_gate(raw_spans: list[Span]) -> dict[str, Span]: spans = {s.span_id: s for s in raw_spans} # Standard out-of-order join: drop children whose parent is absent # only AFTER the provenance gate, so reparented spans are not silently # discarded as orphans. validate_provenance(spans) return spans ```