# What happens when an instance diverges mid-trace: causal replay failure under non-deterministic sampling and the counterfactual logging invariant **Date of Record:** 2026 November 22 **Scope:** Applies to observability and replay infrastructure for agent traces that capture sampled LLM calls, tool invocations, and inter-agent handoffs where the sampling seed, model version, or tool output is non-deterministic across re-execution. Does not apply to deterministic function-call graphs or to traces recorded with full input/output capture at every node where replay is byte-exact by construction. ## Core Distinction The common assumption in agent observability is that a "trace" is a log of what happened, and that "causal replay" reconstructs the execution by re-running the recorded steps. This conflates two fundamentally different objects: - **A recorded trace** is a sequence of observations: prompts sent, tokens sampled, tool results returned, state mutations applied. It is a *witness* to one path through a probabilistic execution tree. - **A causal replay** is a re-execution that claims to reproduce the *reasoning* that led to an outcome. It is a *reconstruction* of a path, not the path itself. The distinction matters because when an agent's decision at step *k* depended on a sampled token that the trace did not fully pin (e.g., a temperature>0 sample, a tool returning a timestamp, a retrieval that returned a different top-k on re-query), replay will silently take a *different branch* at step *k+1*. The trace still "replays" — it produces a plausible-looking execution — but it is a **counterfactual branch**, not the original. Observability systems that report "replay succeeded" on such traces are reporting a false invariant. The boundary failure is not that replay crashes; it is that replay *silently diverges* and produces an audit artifact that misrepresents causality. ## What Was Observed An agent (call it the planner) executes a 14-step task: retrieve documents, summarize, call a code tool, verify, and emit a structured answer. The observability layer records each step as `{prompt_hash, response_text, tool_name, tool_args, tool_result, timestamp}`. During an incident review, an engineer replays the trace to determine why the planner chose tool `B` over tool `A` at step 9. The replay runs cleanly. Every step produces output. But at step 6, the retrieval tool returns a *different* top-1 document — the vector index was re-embedded overnight, and the recorded `tool_result` was not injected back into the replay; the replay *re-executed* the tool. The planner's step-7 summary now cites a different source. At step 9, conditioned on a summary that mentions a different entity, the planner selects tool `A`, not `B`. The replay completes, reports success, and the incident review concludes the planner "sometimes prefers A" — when in fact the original trace's choice of `B` was deterministic given its step-6 input. The observed signature is: **replay output diverges from recorded output at step k+1 whenever step k's recorded output was not byte-identical to re-executed output, and no divergence alarm fires.** The divergence is invisible because each step's replay is locally valid. There is no exception; there is only a different execution tree. A second observation compounds it: when the trace is replayed *twice*, the two replays diverge from each other at different steps (step 6 in one, step 11 in another), because the non-determinism is distributed across sampling and tool calls. The trace is not a point; it is a distribution, and any single replay samples one point from it without labeling which. ## Condition of Validity Causal replay is valid **only** under the *pinned-output invariant*: for every step *i* in the trace, the replay must consume the *recorded* output of step *i* rather than re-executing step *i*, unless step *i* is explicitly marked `deterministic=true` and verified so. Formally, replay of step *k* is causally faithful iff: ``` ∀ i < k: replay_input(i) ≡ recorded_output(i) OR recorded(i).deterministic ∧ reexecute(i) ≡ recorded_output(i) ``` The invariant fails in three concrete ways, each of which must be guarded: 1. **Sampling non-determinism**: LLM calls at temperature>0 or with top-p<1 produce different tokens. The trace must store the sampled token IDs (or a seed plus model version hash) and the replay must *inject* them, not re-sample. 2. **Tool non-determinism**: tools that read clocks, random sources, external APIs, or mutable indexes return different values. The replay must inject the recorded `tool_result` and must *not* re-invoke the tool unless the tool is registered as pure and the registry hash matches. 3. **Retrieval drift**: vector indexes, caches, and feature stores mutate between record and replay. The recorded retrieval set must be frozen into the trace as a content-addressed snapshot, not a query. If any of these is unguarded, the replay is a counterfactual, and the observability system must label it as such. The condition of validity is therefore not "replay runs" but "replay is *pinned* at every non-deterministic node, or it is explicitly tagged `counterfactual=true` and excluded from causal claims." ## Decision Boundary The operational decision is: *at each trace node, do we pin or re-execute?* The boundary is drawn by a per-node determinism attestation, not by node type. A retrieval call is non-deterministic by default; a pure arithmetic tool is deterministic only if its registry entry is content-hashed and the hash matches at replay time. The decision rule: - If `node.pinned == true` → inject recorded output, mark replay `faithful` for this node. - If `node.deterministic_attested == true` and `attestation_hash == registry_hash` → re-execute, compare byte-equality, mark `faithful` on match, `diverged` on mismatch. - Otherwise → re-execute is forbidden for causal replay; the replay must either abort with `UnpinnedNonDeterministicNode` or proceed under `counterfactual=true` with the divergence recorded as a first-class event. The boundary is *not* "did the replay finish." It is "was every node on the causal path either pinned or attested-deterministic?" A replay that crosses an unpinned node without flagging it has left the causal regime and entered counterfactual logging — which is a legitimate mode, but a *different* mode, and must be labeled. ## Operational Effect When the pinned-output invariant is enforced, three things change: 1. **Replay becomes a verifier, not a re-enactor.** The replay's job is to confirm that the recorded outputs *entail* the recorded decisions, not to regenerate them. Divergence at a pinned node is a hard error (`ReplayDivergence`), because it means the trace itself is corrupt or the model version changed under the pin. 2. **Counterfactual logging becomes explicit.** When replay must cross an unpinned node, the system records the *branch point* and the *alternative output*, producing a counterfactual log: "had the retrieval returned doc X instead of doc Y, the planner would have selected tool A." This is the actual observability value — not a fake reproduction, but a labeled what-if. 3. **Branch divergence is measured, not hidden.** By replaying the trace *N* times under injected sampling seeds at unpinned nodes, the system estimates the *decision entropy* at each branch. High entropy at step 9 is itself the finding: the planner's tool choice was under-determined by its inputs, which is a prompt-robustness signal, not a replay bug. The failure mode to avoid is the silent one: a replay that reports `success` while having crossed unpinned nodes, producing an audit artifact that is indistinguishable from a faithful reproduction. The guardrail is a per-node pin attestation and a hard exception on any unpinned node in causal mode. ```python import hashlib from dataclasses import dataclass, field from typing import Any class UnpinnedNonDeterministicNode(RuntimeError): """Raised when causal replay would cross a node that is neither pinned nor attested-deterministic. Crossing it would silently produce a counterfactual branch mislabeled as a faithful replay.""" pass class ReplayDivergence(RuntimeError): """Raised when a pinned or attested-deterministic node produces output that does not byte-match the recorded output. Indicates trace corruption or a model/registry version change under the pin.""" pass @dataclass class TraceNode: step: int kind: str # "llm" | "tool" | "retrieval" recorded_output: Any pinned: bool = False # recorded output injected on replay deterministic_attested: bool = False attestation_hash: str | None = None registry_hash: str | None = None reexecute_fn: Any = None # callable for deterministic re-exec def _hash(obj: Any) -> str: return hashlib.sha256(repr(obj).encode()).hexdigest() def causal_replay(nodes: list[TraceNode], mode: str = "causal") -> list[dict]: """Replay a trace under the pinned-output invariant. mode="causal": every node must be pinned or attested-deterministic; unpinned nodes raise UnpinnedNonDeterministicNode. mode="counterfactual": unpinned nodes are re-executed and the branch point is logged as a counterfactual event. """ if mode not in ("causal", "counterfactual"): raise ValueError(f"unknown replay mode: {mode}") events: list[dict] = [] for node in nodes: if node.pinned: events.append({"step": node.step, "mode": "pinned", "output": node.recorded_output, "faithful": True}) continue if node.deterministic_attested: if node.attestation_hash != node.registry_hash: raise ReplayDivergence( f"step {node.step}: attestation hash {node.attestation_hash} " f"!= registry hash {node.registry_hash}" ) actual = node.reexecute_fn() if _hash(actual) != _hash(node.recorded_output): raise ReplayDivergence( f"step {node.step}: deterministic re-exec diverged from " f"recorded output" ) events.append({"step": node.step, "mode": "attested", "output": actual, "faithful": True}) continue # Unpinned, non-attested non-deterministic node. if mode == "causal": raise UnpinnedNonDeterministicNode( f"step {node.step} ({node.kind}) is unpinned and not " f"attested-deterministic; causal replay would silently " f"diverge. Pin the output or switch to counterfactual mode." ) # Counterfactual mode: re-execute, log the branch explicitly. alt = node.reexecute_fn() events.append({ "step": node.step, "mode": "counterfactual", "recorded": node.recorded_output, "alternative": alt, "faithful": False, "branch_point": True, }) return events def assert_faithful(events: list[dict]) -> None: """Downstream audit guard: refuse to emit a causal claim if any event is a counterfactual branch.""" for e in events: if not e.get("faithful", False): raise UnpinnedNonDeterministicNode( f"step {e['step']} is a counterfactual branch; " f"cannot be cited as causal evidence" ) ```