# Why does an instance lose causal ordering when decision-trace events are emitted from parallel tool-call branches **Date of Record:** 2026 November 26 **Scope:** Applies to agent runtimes that emit structured observability events (decision traces) from concurrent tool-call branches and later reconstruct a causal chain for audit, replay, or distillation. Does not apply to single-threaded, strictly serialized agent loops where event emission is monotonic by construction. ## Core Distinction There are two different things an observability event schema can be asked to guarantee, and operators routinely conflate them: 1. **Wall-clock ordering** — the timestamp field `ts_emit` records when the event-handler thread serialized the event to the sink. 2. **Causal ordering** — the event genuinely happened-after its logical predecessor in the agent's decision graph (the tool result that the reasoning step consumed, the reasoning step that the tool call was derived from). The schema almost always guarantees (1) and almost never guarantees (2), yet downstream consumers — replay engines, trace-based evaluators, episodic-to-semantic distillers — assume (2). The gap is invisible in serialized agents because the two orderings coincide. It becomes a boundary failure the moment the agent forks parallel tool calls, because emission is buffered and flushed by whichever branch finishes first, not by which branch logically preceded. The non-obvious part: the failure is not "events arrive out of order." Each event is individually well-formed and carries a valid timestamp. The failure is that a **derived event can carry an earlier `ts_emit` than its own parent**, producing a trace that is internally consistent as a log but topologically impossible as a causal graph. Replay does not crash — it silently re-derives a decision the agent never made. ## What Was Observed A planner agent emits a `decision` event, then fans out three `tool_call` events (search, code-exec, retrieval) under a `branch_id`. Each tool executor emits a `tool_result`. A `synthesis` decision event consumes all three results. The schema used a single monotonic `seq` counter allocated at emit time by the logging thread, plus a `ts_emit` from `time.monotonic_ns()`. Observed trace fragment after a slow-branch run: ``` seq=1041 ts=...880 decision parent=1039 branch=None "plan: call search, exec, retrieve" seq=1042 ts=...881 tool_call parent=1041 branch="exec" "run_python(...)" seq=1043 ts=...882 tool_call parent=1041 branch="search" "web_search(...)" seq=1044 ts=...884 tool_call parent=1041 branch="retr" "vector_query(...)" seq=1050 ts=...990 tool_result parent=1043 branch="search" ok seq=1051 ts=...991 tool_result parent=1042 branch="exec" ok seq=1052 ts=...992 tool_result parent=1044 branch="retr" TIMEOUT seq=1053 ts=...993 synthesis parent=1051 "combine results" <-- parent is exec only ``` The synthesis event's `parent` points at the *first-returning* result (exec, seq 1051), not at the join of all three. The retrieval result (seq 1052, a timeout) was emitted *after* the synthesis decision that supposedly consumed it. The replay engine, walking parent pointers, reconstructs a synthesis that only saw two of three results — and re-derives a confident answer the live agent never produced (the live agent had in fact retried the retrieval branch before synthesizing; that retry event was dropped because the branch-local buffer was flushed late and the sink applied a `seq < last_seen` dedup). Two independent defects compounded: - **Parent-pointer capture at call time, not at join time.** The synthesis step recorded its `parent` as the result handle that unblocked its `await`, which under `asyncio.gather` is whichever future resolved first, not the join barrier. - **Late-flush reordering with seq dedup.** The retry event was assigned `seq=1049` by a branch-local counter that had been snapshotted before the fan-out; on flush it arrived after `seq=1053` and was discarded as stale. ## Condition of Validity The invariant that must hold for a decision trace to be replayable is: > For every event `e` with `parent = p`, `p` must be causally complete (all of `p`'s own declared dependencies resolved) at the moment `e` is emitted, and `e`'s `seq` must be strictly greater than `max(seq)` over `p`'s transitive dependency set. This holds trivially under serialized execution. It fails under **any** concurrency model where (a) emission is decoupled from the logical join, or (b) sequence numbers are allocated per-branch rather than per-graph. The failure is *not* bounded by branch count or by timeout — it is triggered by **variance in branch latency**. A trace with zero latency variance across branches will pass every replay check even though the schema is broken, which is why this survives staging and surfaces under production tail latency. The condition of validity is therefore not "the sink is ordered" but "the emitter allocates `seq` at the join barrier, after all dependencies of the parent have resolved, and the parent pointer references the join node rather than the first-resolving child." ## Decision Boundary The operator must choose one of two schema contracts and enforce it at the emitter, not the sink: - **Causal-join contract (recommended for replay/distillation):** introduce an explicit `join` event with a `depends_on: [branch_ids]` list; the synthesis event's parent is the join, never a leaf result. Allocate `seq` inside the join's critical section. Reject emission if any declared dependency has unresolved status. This costs a synchronization point per fan-out and serializes seq allocation, but makes the trace a valid DAG by construction. - **Best-effort contract (acceptable for live dashboards only):** keep leaf-parenting and per-branch seq, but tag every event with `causal_complete: bool` and forbid downstream replay from consuming traces where any parent has `causal_complete=false`. Dashboards tolerate this; replay and episodic distillation must not. The boundary is crossed — the trace becomes unsafe for replay — the instant a consumer reads a `synthesis` event whose parent set does not cover all `tool_call` branches emitted under the same `decision`. Any consumer that does not perform this coverage check is silently deriving decisions the agent never made. ## Operational Effect Downstream, the corrupted trace poisons two systems that are hard to unwind: - **Episodic-to-semantic distillation** learns a policy of "synthesize after first result returns," because the surviving parent edge encodes exactly that. The distilled heuristic is wrong and, worse, is *confidently* wrong — it was fit on traces that passed schema validation. - **Trace-based evaluation** scores the agent on the re-derived synthesis, which omitted the retrieval branch. Pass rate inflates on tasks where retrieval was the discriminating signal, so regressions in retrieval quality are masked. The remediation is not a sink-side sort. Sorting by `ts_emit` reproduces the same impossible graph because the timestamps are honest — the events really were emitted in that order. The fix must move `seq` allocation and parent-pointer assignment to the join barrier and reject incomplete emissions at the source, so that a trace either is a valid causal DAG or fails loudly before it reaches the distiller. ```python import time from dataclasses import dataclass, field class CausalOrderViolation(RuntimeError): """Raised when a decision-trace event is emitted before its declared dependencies have resolved, or when its seq does not exceed the max seq over its transitive dependency set. This is the guardrail that bounds the parallel-branch reordering failure at the emitter, not the sink.""" pass @dataclass class TraceEvent: seq: int ts_emit_ns: int kind: str parent: int | None branch: str | None depends_on: list[int] = field(default_factory=list) causal_complete: bool = True class JoinBarrierEmitter: """Allocates seq inside a join critical section. Refuses to emit a derived event whose declared dependencies are unresolved or whose seq would not exceed the max seq of its dependency closure.""" def __init__(self) -> None: self._seq = 0 self._emitted: dict[int, TraceEvent] = {} self._resolved: set[int] = set() def emit(self, kind: str, parent: int | None, branch: str | None, depends_on: list[int] | None = None) -> TraceEvent: deps = depends_on or [] # Invariant 1: every declared dependency must be resolved at emit time. unresolved = [d for d in deps if d not in self._resolved] if unresolved: raise CausalOrderViolation( f"emit {kind!r} blocked: dependencies {unresolved} unresolved " f"(parallel branch flushed before join)" ) # Invariant 2: seq must exceed the max seq over the dependency closure. if deps: dep_max = max(self._emitted[d].seq for d in deps) if self._seq <= dep_max: raise CausalOrderViolation( f"emit {kind!r}: next seq {self._seq} does not exceed " f"dependency max seq {dep_max}; per-branch counter leaked" ) self._seq += 1 ev = TraceEvent( seq=self._seq, ts_emit_ns=time.monotonic_ns(), kind=kind, parent=parent, branch=branch, depends_on=deps, ) self._emitted[ev.seq] = ev return ev def resolve(self, seq: int) -> None: if seq not in self._emitted: raise CausalOrderViolation(f"resolve of unknown seq {seq}") self._resolved.add(seq) def synthesize(self, decision_parent: int, branch_roots: list[int]) -> TraceEvent: # Synthesis must parent the join, never a first-resolving leaf. join = self.emit("join", parent=decision_parent, branch=None, depends_on=branch_roots) self.resolve(join.seq) return self.emit("synthesis", parent=join.seq, branch=None, depends_on=[join.seq]) def replay_check(events: list[TraceEvent]) -> None: by_seq = {e.seq: e for e in events} for e in events: if e.parent is not None and e.parent not in by_seq: raise CausalOrderViolation( f"event seq={e.seq} references missing parent {e.parent}" ) for d in e.depends_on: if d not in by_seq: raise CausalOrderViolation( f"event seq={e.seq} depends on dropped seq {d} " f"(late-flush dedup discarded it)" ) if by_seq[d].seq >= e.seq: raise CausalOrderViolation( f"causal inversion: seq={e.seq} depends on later seq={d}" ) ```