# How should an instance reconcile counterfactual replay when OTel span parentage is non-deterministic under concurrent agent fan-out **Date of Record:** 2026 December 4 **Scope:** Applies to post-hoc counterfactual debugging of multi-agent trajectories reconstructed from OpenTelemetry span trees, where a replay engine re-executes a recorded trajectory under modified conditions (altered prompt, swapped tool, injected fault). Does not apply to live tracing, single-agent linear traces, or replay systems that retain full message-level event logs independent of span structure. ## Core Distinction There are two distinct objects a replay engine can be asked to reproduce, and conflating them is the root of the failure: 1. **The causal trajectory** — the actual ordered sequence of LLM calls, tool invocations, and message handoffs that produced the observed outcome. This is what counterfactual debugging needs: "if agent B had received a different tool result, would the swarm still converge?" 2. **The span tree** — the parent/child structure emitted by OTel instrumentation. This is a *lossy, timing-influenced projection* of the causal trajectory. The invariant that counterfactual replay silently assumes is: **span parentage is a faithful, stable encoding of causal precedence**. Under concurrent fan-out (a supervisor agent dispatching N workers that each emit spans, or a baton-passing pipeline where handoff spans overlap in wall-clock time), this invariant is false. Parent assignment in OTel is by *context propagation*, not by causal ordering, and context propagation across an async agent boundary races against the very concurrency the fan-out introduces. The result: two replays of the same recorded trace can yield different DAGs, and a counterfactual that "changes one tool result" can silently reorder which agent's span becomes the parent of a downstream verification step. ## What Was Observed A supervisor agent `S` fans out to workers `W1`, `W2`, `W3` via a message bus. Each worker emits a `llm.call` span and a `tool.invoke` span. `S` then emits a `verify` span that consumes all three results. Instrumentation propagates `traceparent` by injecting the current active span into the outgoing message headers at send time. The failure trace: 1. `S` begins a `fanout` span, then enqueues three messages. For `W2`, the enqueue happens on a thread that shares the active-span context with `S`'s *subsequent* `verify` span because the async runtime reused the context slot before `W2` dequeued. `W2`'s spans therefore parent to `verify`, not `fanout`. 2. On first replay (unmodified), the replay engine topologically sorts the span DAG and executes `W2` after `verify`. Because `verify` in the recorded run had already consumed `W2`'s result, the replayed `verify` reads a not-yet-produced value and the engine falls back to a cached result — masking the inversion. 3. On the counterfactual replay ("what if `W2`'s tool returned an error?"), the engine injects the fault at `W2`'s `tool.invoke`. But because `W2` is now scheduled *downstream* of `verify` in the reconstructed DAG, the injected fault never reaches `verify`. The replay reports "swarm still converges" — a false negative. The actual system, with correct causal ordering, would have diverged. 4. The discrepancy only appears when the injected fault targets an agent whose span parentage was corrupted by the fan-out race. Faults targeting `W1` (correctly parented) reproduce faithfully. The tell is a *replay-order divergence*: the topological sort of the span DAG differs from the recorded wall-clock completion order by more than instrumentation jitter, specifically at fan-out join points. ## Condition of Validity Counterfactual replay from span trees is valid only when the following holds for every fan-out join: - **Causal-edge completeness:** every span that causally depends on another has an explicit parent or link edge, and no edge exists that is *not* causal. Context-propagation parentage satisfies the first but not the second. - **Order stability under replay:** the topological order used by the replay engine is invariant to the concurrency schedule. This requires that concurrent sibling spans be ordered by a recorded causal token (a sequence number stamped at message-send, not at span-start), not by `start_time` or by parent-child nesting. - **Fault-injection reachability:** an injected modification at span `X` must be reachable by every span that consumed `X`'s output in the recorded run. If parentage is corrupted, reachability is silently broken and the counterfactual is vacuous. When any of these fails — which is the default under unmodified OTel context propagation with async fan-out — the replay engine is not debugging the trajectory; it is debugging a plausible-looking but incorrect DAG. ## Decision Boundary The operator must decide, per trace, whether to **trust the span DAG as causal** or to **reconstruct causality from an independent signal**. The boundary: - **Trust the DAG** when: fan-out width is 1 (linear), or all concurrent siblings carry a monotonic causal sequence number in span attributes that the replay engine uses for ordering, or the instrumentation uses explicit `SpanLink`s for fan-out joins rather than context parentage. - **Do not trust the DAG** when: fan-out width > 1 AND parentage was assigned by ambient context propagation AND no per-message causal token was recorded. In this regime, the engine must either (a) refuse the counterfactual with a diagnosable error, or (b) fall back to message-log reconstruction if a message log exists. The dangerous middle ground — proceeding with a plausible DAG and reporting a convergence verdict — must be disallowed. A counterfactual replay that cannot certify causal-edge completeness is not a weaker result; it is an *anti-result* that will be cited as evidence. ## Operational Effect Concretely, the guardrail is a **causal-certification gate** at replay-plan construction time. Before executing any counterfactual, the engine computes, for each fan-out join in the recorded trace, whether sibling spans share a common parent and carry a strictly ordered causal token. If any join fails certification, the engine raises a typed error naming the offending spans and the join, rather than proceeding. This converts a silent false-negative class (counterfactuals that "prove" robustness because the fault never propagated) into a loud, per-trace failure that the operator can triage by re-instrumenting the agent or supplying a message log. The secondary effect: replay verdicts become *conditional on instrumentation quality*, and that conditionality must be surfaced in the verdict itself. A convergence claim from an uncertified DAG is downgraded to "inconclusive — causal edges unverified," which is the honest answer when the span tree cannot distinguish "the swarm is robust" from "the fault was scheduled into a dead branch." ```python from dataclasses import dataclass from typing import Sequence class CausalCertificationError(RuntimeError): """Raised when a span DAG cannot be certified as a faithful causal encoding.""" pass @dataclass(frozen=True) class Span: span_id: str parent_id: str | None agent_id: str causal_seq: int | None # stamped at message-send, not span-start start_ns: int def certify_replay_plan(spans: Sequence[Span], fanout_join_parents: set[str]) -> None: """ Refuse counterfactual replay when fan-out joins lack an ordered causal token. A join is any parent span with >1 direct child. Certification requires every sibling under a join to carry a distinct causal_seq; otherwise parentage may have been assigned by racing context propagation and the DAG is untrustworthy. """ children_by_parent: dict[str, list[Span]] = {} for s in spans: if s.parent_id is not None: children_by_parent.setdefault(s.parent_id, []).append(s) for parent_id in fanout_join_parents: siblings = children_by_parent.get(parent_id, []) if len(siblings) <= 1: continue seqs = [s.causal_seq for s in siblings] if any(q is None for q in seqs): raise CausalCertificationError( f"fan-out join {parent_id}: sibling span(s) " f"{[s.span_id for s in siblings if s.causal_seq is None]} " f"lack causal_seq; parentage may be a context-propagation artifact. " f"Counterfactual replay aborted to avoid a vacuous convergence verdict." ) if len(set(seqs)) != len(seqs): raise CausalCertificationError( f"fan-out join {parent_id}: duplicate causal_seq among siblings " f"{[s.span_id for s in siblings]}; recorded ordering is ambiguous " f"and replay topological order is not invariant to schedule." ) # Cross-check: a child whose start precedes its parent's start is a # red flag that context was injected after the fact. by_id = {s.span_id: s for s in spans} for s in spans: if s.parent_id and s.parent_id in by_id: p = by_id[s.parent_id] if s.start_ns < p.start_ns: raise CausalCertificationError( f"span {s.span_id} starts before its parent {p.span_id}; " f"parentage was likely assigned by reused async context." ) def run_counterfactual(spans: Sequence[Span], join_parents: set[str], inject_at: str) -> str: certify_replay_plan(spans, join_parents) if inject_at not in {s.span_id for s in spans}: raise CausalCertificationError( f"injection target {inject_at} not present in certified plan" ) return "replay-executed" ```