# When must an instance distrust a causal span link? Orphaned-span reparenting under concurrent trace export in multi-agent cost attribution **Date of Record:** 2026 November 29 **Scope:** Applies to multi-agent systems whose observability pipeline reconstructs causal DAGs from parent-span-id references emitted asynchronously by agents and tool proxies, and then attributes token/compute cost by walking that DAG. Does not apply to single-agent traces with synchronous in-process span emission, nor to flat log aggregation without causal linking. ## Core Distinction The distinction that matters is between *causal ancestry* (which invocation logically caused which) and *emission order* (which span record reached the collector first). Most observability backends conflate them at exactly one point: when a child span arrives before its declared parent, the collector must choose between (a) buffering the orphan until the parent resolves, or (b) reparenting it to the nearest resolved ancestor or to a synthetic root. Option (b) is the default in most SDKs because it keeps the trace view live. It is also the mechanism that silently corrupts cost attribution in multi-agent swarms, because cost is computed by summing descendant spans under an agent root, and reparenting moves a subtree across agent boundaries. The non-obvious part: the corruption is *not* a lost span. Every span is present. The DAG is acyclic. The trace renders. The only artifact is that a tool-call subtree that logically belonged to agent B gets billed to agent A because B's parent span was still in flight when the child's export fired. This is invisible to span-count and error-rate dashboards; it only surfaces when per-agent cost totals are reconciled against ground-truth token meters. ## What Was Observed A three-agent pipeline (planner → executor → verifier) with a shared MCP tool proxy. Each agent emits an `agent.invoke` root span and child `tool.call` spans. Tool proxies emit their own `tool.result` spans with `parent_span_id` set to the calling agent's `agent.invoke` span id. Export is batched with a 250 ms flush interval per process; the proxy runs in a separate process from the agents. Trigger condition: the executor agent's `agent.invoke` span is large (long reasoning trace, ~40k tokens of span attributes) and its export batch is delayed past the proxy's flush. The proxy's `tool.result` spans for executor-originated calls arrive at the collector first, with `parent_span_id` pointing at a span the collector has not seen. The collector's orphan buffer has a 500 ms TTL; under load the executor's batch exceeds it. Failure trace: 1. `tool.result` span `S_r` arrives, `parent_span_id = S_exec`. `S_exec` unknown → orphan buffer. 2. TTL expires. Collector reparents `S_r` to the trace's current root, which is `S_planner` (planner's root resolved first, and the collector's "nearest resolved ancestor" heuristic falls back to the trace root when no intermediate ancestor exists). 3. `S_exec` arrives 80 ms later and resolves normally, now with zero children. 4. Cost walker sums `S_r`'s token cost (tool proxy bills the executor's tool calls at executor rates) under `S_planner`'s subtree. 5. Per-agent cost: planner inflated by executor's tool spend; executor under-reported. Reconciliation against token meters shows a 14–19% misattribution on affected traces. The tell is not an error. It is a *negative residual* when you subtract summed child costs from each agent root's own meter: the planner root's subtree cost exceeds its meter, the executor root's subtree cost falls short by the same amount. Symmetric residuals across two agent roots within one trace are the signature of a reparented orphan, not of a metering bug. ## Condition of Validity The reparenting heuristic is only safe under the invariant: **for every span, the logical parent resolves in the collector before the orphan TTL expires, or the child carries an explicit agent-id and cost-basis tag independent of its parent link.** If either holds, reparenting is cosmetic and cost attribution is unaffected. The invariant fails when (i) parent span payload size pushes export latency past the orphan TTL — long reasoning traces are the dominant cause because span attributes scale with token count — and (ii) the child's cost basis is derived from the parent's agent identity rather than carried on the child. Multi-agent pipelines with heterogeneous export batching violate (i) routinely; proxies that bill at the caller's rate rather than at their own identity violate (ii) by construction. It does not fail for synchronous single-process tracing, nor when the collector is configured with unbounded orphan buffering plus a parent-arrival barrier before trace finalization. ## Decision Boundary The boundary is the orphan TTL versus the p99 export latency of the slowest-emitting parent class. Concretely: if `p99(parent_export_latency) > orphan_ttl`, reparenting will fire on a non-trivial fraction of traces and cost attribution must not depend on the parent link. Two admissible resolutions: - **Raise the barrier:** set `orphan_ttl > p99(parent_export_latency) + max_batch_jitter`, and finalize traces only after all declared parent ids resolve or the barrier times out. Cost is deferred trace finalization; unacceptable for real-time cost dashboards. - **Decouple cost from topology:** stamp every span with `agent_id` and `cost_basis` at emission time, and attribute cost by that stamp, never by DAG ancestry. Topology remains for causal debugging; cost becomes topology-independent. This is the correct boundary for swarm systems where export order is not controllable. The wrong resolution — the one most pipelines ship — is to keep reparenting and keep ancestry-based cost, accepting silent misattribution below whatever threshold the team happens to eyeball. ## Operational Effect With the decoupled design, per-agent cost reconciles against meters to within metering noise regardless of export order, and orphan reparenting becomes a purely visual artifact in the trace view. With the coupled design, cost dashboards drift as a function of reasoning-trace length: longer agent reasoning → larger parent spans → later export → more reparenting → more spend shifted toward whichever agent's root resolved first (typically the planner, which starts earliest). The drift is systematic, not random, and it biases budget alarms toward the wrong agent. Guardrail: a reconciliation job that computes, per trace, the residual between subtree-summed cost and meter-summed cost for each agent root; any trace with symmetric non-zero residuals across two or more roots is flagged as topology-corrupted and excluded from cost rollups until the emitter stamps are backfilled. ```python from dataclasses import dataclass, field from typing import Optional class TopologyCorruptedTrace(RuntimeError): """Raised when a trace's cost attribution cannot be trusted because a span was reparented across an agent boundary during orphan resolution.""" pass @dataclass class Span: span_id: str parent_span_id: Optional[str] agent_id: str # stamped at emission, independent of topology cost_basis: float # tokens * rate, stamped at emission resolved: bool = False @dataclass class Trace: spans: dict = field(default_factory=dict) reparented: list = field(default_factory=list) def attribute_cost(trace: Trace, meters: dict) -> dict: """Attribute cost by emission-time agent_id stamp, never by DAG ancestry. Reconcile against ground-truth meters; refuse to roll up corrupted traces.""" per_agent = {} for span in trace.spans.values(): per_agent[span.agent_id] = per_agent.get(span.agent_id, 0.0) + span.cost_basis residuals = {} for agent_id, meter in meters.items(): residual = per_agent.get(agent_id, 0.0) - meter if abs(residual) > 0.01 * max(meter, 1.0): residuals[agent_id] = residual if len(residuals) >= 2 and abs(sum(residuals.values())) < 1e-6: # Symmetric residuals across roots: signature of a reparented orphan. raise TopologyCorruptedTrace( f"trace has symmetric cost residuals {residuals}; " f"reparented spans: {trace.reparented}. " "Exclude from rollups; backfill emission stamps before retry." ) return per_agent def resolve_orphan(trace: Trace, span: Span, nearest_resolved: Optional[str]) -> None: """Reparent an orphaned span. Must record the event so cost reconciliation can detect topology corruption downstream.""" if span.parent_span_id not in trace.spans: trace.reparented.append((span.span_id, nearest_resolved)) if nearest_resolved is None: raise TopologyCorruptedTrace( f"span {span.span_id} orphaned with no resolved ancestor; " "cannot place in trace without synthetic root" ) span.parent_span_id = nearest_resolved trace.spans[span.span_id] = span span.resolved = True ```