# In what scenarios must an instance abort deterministic replay of a multi-agent trajectory when the recorded tool-call ledger diverges from the counterfactual branch **Date of Record:** 2026 November 30 **Scope:** Applies to offline safety-regression replay of recorded multi-agent trajectories where at least one agent's next action is conditioned on a non-deterministic external tool result (wall-clock, RNG, live search, remote LLM sampling). Does not apply to fully hermetic sandboxes where every external effect is stubbed to a fixed, versioned fixture. ## Core Distinction There are two things a replay harness can mean by "reproduce the trajectory," and conflating them is the root of the failure. **Faithful replay** re-executes the recorded action sequence against recorded observations to confirm the harness itself is sound (the trajectory is a fixed point). **Counterfactual replay** mutates one decision (a prompt, a policy weight, a tool argument) and re-runs forward to observe how downstream agents diverge. Faithful replay is a *verification* operation with a hard equality invariant. Counterfactual replay is an *exploration* operation with no such invariant — divergence is the whole point. The boundary failure occurs when a counterfactual branch, which is *supposed* to diverge in agent reasoning, also silently diverges in the **tool-call ledger** — the ordered record of `(agent_id, tool_name, canonical_args_hash, observation_hash)` tuples — and the harness continues replaying as if the ledger were still shared. Because downstream agents in a multi-agent swarm condition on peer observations, a single extra or reordered tool call in agent A's branch changes what agent B "saw," so B's replayed actions no longer correspond to the counterfactual you intended to test. You believe you are testing "what if agent A's planner chose differently," but you are actually testing "what if the entire world's observation stream shifted by one tick." The safety conclusion is invalid, and it fails *silently* because the replay completes with exit code 0. The invariant that must hold: **a counterfactual branch may diverge in agent-internal state (reasoning, chosen action) but must, at every ledger-checkpoint, either (a) match the recorded ledger prefix exactly, or (b) be explicitly forked into a new ledger lineage with downstream agents re-instantiated from that fork point.** Any third case — a partial ledger divergence that propagates without a fork — is the abort condition. ## What Was Observed A three-agent incident-response swarm (Triage → Mitigator → Auditor) was recorded on a live incident where the Mitigator issued `rollback_deploy(service, to_revision=41)`. During safety regression, an engineer mutated the Triage agent's confidence threshold so that it classified the incident one severity level lower. The intent: observe whether the Mitigator would still choose rollback (a safety-critical action) under weaker triage signal. Replay executed. The Mitigator, now receiving a "medium" severity observation, *skipped* one tool call it had made in the original trace — a `fetch_recent_metrics(window=5m)` probe — and went straight to `rollback_deploy(service, to_revision=41)`. The Auditor agent, which in the original trace had conditioned its approval on the metrics probe's observation hash appearing in the Mitigator's ledger, no longer found that hash. But the replay harness had cached the Auditor's recorded approval token keyed by `(auditor_id, mitigator_ledger_length)`, and because the *length* happened to match after the skip (one call removed, one retry added), the cache hit and the Auditor's recorded `approve` was replayed verbatim. The regression test reported: "Under weaker triage, Mitigator still performs safe rollback; Auditor still approves. PASS." Both clauses were false. The Mitigator had rolled back *without* the metrics evidence the Auditor's approval was predicated on — a strictly more dangerous behavior — and the Auditor had not actually reasoned at all; its verdict was a stale cache hit. Root cause trace, in order: 1. Counterfactual mutation applied at Triage's decision node → Triage emits `severity=medium` instead of `severity=high`. 2. Mitigator's planner, conditioned on `medium`, prunes the metrics probe from its plan. Ledger diverges at index 3 (recorded `fetch_recent_metrics`, actual: absent). 3. Mitigator issues `rollback_deploy` at ledger index 4 (recorded index 5). **Ledger length re-converges by index 5** because Mitigator retried a failed `notify_oncall` once. 4. Auditor's replay cache key is `(auditor_id, len(mitigator_ledger))` = `(auditor, 5)`, which matches the recorded key. Cache returns recorded approval. 5. Harness compares final action sequence to a *set*, not an *ordered ledger*, so the transposition at indices 3–4 is invisible. The failure is specifically that **ledger length is not a ledger identity**. Two ledgers of equal length can carry different evidence, and a cache keyed on length will alias them. This is the multi-agent analogue of a hash collision, except the hash function is `len()` and the collision is guaranteed, not probabilistic, whenever a skip and a retry cancel. ## Condition of Validity The replay is only a valid safety regression if the following holds at every agent handoff boundary: - The ledger is compared as an **ordered sequence of content-addressed tuples**, not as a length, a set, or a multiset. `canonical_args_hash` and `observation_hash` must both be in the tuple; comparing tool names alone aliases `fetch_recent_metrics(window=5m)` against `fetch_recent_metrics(window=1h)`. - Any downstream agent whose recorded decision *read* a ledger entry that no longer exists in the counterfactual branch must be **re-instantiated**, not cache-replayed. The read-set of each recorded decision must be captured at record time (which ledger indices the agent's context actually contained), because an agent's dependency on a peer's evidence is not recoverable from the peer's final output alone. - A counterfactual branch is permitted to diverge only **forward** from the mutation point. If a divergence at index `i` causes a *re-convergence* at index `j > i` (as with the skip-then-retry above), the interval `[i, j)` is a **divergence shadow**: every agent decision whose read-set intersects that interval is untrustworthy and must be re-derived, even though the ledger endpoints match. The validity condition fails — and replay must abort rather than report — when a divergence shadow is detected and any intersecting downstream decision was served from cache. Reporting a PASS in that state is the concrete hazard; the harness has certified a behavior it did not actually execute. ## Decision Boundary The harness must choose between **abort** and **fork** at the moment a ledger checkpoint mismatches: - If the mismatched index lies *outside* any already-replayed downstream read-set (no agent has yet consumed it), the harness may **fork**: emit a new ledger lineage ID, invalidate all caches keyed on the old lineage, and re-instantiate downstream agents from the fork point. This is the correct path for genuine counterfactual exploration and should be the default. - If the mismatched index lies *inside* a downstream read-set that has already been cache-served, the harness must **abort**. The replay has already produced an unsound verdict; continuing compounds it. There is no safe "repair" because the served decision cannot be un-served without re-running the downstream agent, which is exactly the fork the harness failed to do. - If ledger length re-converges after a divergence shadow (the aliasing case), the harness must treat the shadow as a hard abort regardless of endpoint equality, because length equality is precisely the signal that fools length-keyed caches. The boundary is therefore not "did the ledger match?" but "did any cache-served decision depend on a ledger entry that the counterfactual branch altered?" Endpoint equality is necessary but never sufficient. ## Operational Effect After this incident, the harness enforces three changes. First, replay caches are keyed on the **full ordered ledger hash of the read-set**, not on ledger length or agent ID. Second, every recorded decision stores its read-set as an explicit list of ledger indices, captured at record time by instrumenting the context-assembly step. Third, the harness computes divergence shadows by diffing the counterfactual ledger against the recorded ledger as sequences and aborting whenever a shadow intersects a cache-served read-set. The practical consequence for safety regression is a shift in what a "pass" means. A pass no longer certifies "the agent did the safe thing under mutation X"; it certifies "the agent did the safe thing under mutation X, *and* every downstream verdict was re-derived rather than replayed." The second clause is the one that catches the dangerous cases, because the dangerous cases are exactly the ones where the swarm's evidence chain silently rewired while the final action looked identical. Deterministic replay is only as trustworthy as its willingness to refuse to certify a trajectory it did not actually run. ```python import hashlib from dataclasses import dataclass, field from typing import Optional class ReplayDivergenceError(RuntimeError): """Raised when a counterfactual branch diverges inside a cache-served read-set.""" pass @dataclass(frozen=True) class LedgerEntry: agent_id: str tool_name: str canonical_args_hash: str observation_hash: str def digest(self) -> str: h = hashlib.sha256() for part in (self.agent_id, self.tool_name, self.canonical_args_hash, self.observation_hash): h.update(part.encode()) h.update(b"\x00") return h.hexdigest() @dataclass class RecordedDecision: agent_id: str read_set: frozenset[int] # ledger indices the context actually contained ledger_hash_at_decision: str # full ordered hash of ledger prefix read verdict: str @dataclass class ReplayHarness: recorded_ledger: list[LedgerEntry] recorded_decisions: list[RecordedDecision] cache: dict[str, str] = field(default_factory=dict) # ledger_hash -> verdict abort_shadow: Optional[tuple[int, int]] = None def _prefix_hash(self, ledger: list[LedgerEntry], upto: int) -> str: h = hashlib.sha256() for entry in ledger[:upto]: h.update(entry.digest().encode()) return h.hexdigest() def find_divergence_shadow( self, counterfactual_ledger: list[LedgerEntry] ) -> Optional[tuple[int, int]]: """Return (first_diff, reconvergence_index) if the ledger re-converges after diverging; None if it never re-converges (clean forward fork).""" n = min(len(self.recorded_ledger), len(counterfactual_ledger)) first_diff = None for i in range(n): if self.recorded_ledger[i] != counterfactual_ledger[i]: first_diff = i break if first_diff is None: if len(self.recorded_ledger) != len(counterfactual_ledger): return (n, -1) # length-only divergence, no shadow return None # seek re-convergence after first_diff j = first_diff + 1 while j < n: if self.recorded_ledger[j] == counterfactual_ledger[j]: return (first_diff, j) j += 1 return (first_diff, -1) def replay(self, counterfactual_ledger: list[LedgerEntry]) -> list[str]: shadow = self.find_divergence_shadow(counterfactual_ledger) self.abort_shadow = shadow if shadow is not None and shadow[1] >= 0: lo, hi = shadow for decision in self.recorded_decisions: intersects = any(lo <= idx < hi for idx in decision.read_set) if not intersects: continue # A decision whose read-set touches the shadow must be re-derived. # If it was cache-served on the old lineage, the replay is unsound. if decision.ledger_hash_at_decision in self.cache: raise ReplayDivergenceError( f"agent {decision.agent_id} verdict '{decision.verdict}' " f"was cache-served but its read-set {sorted(decision.read_set)} " f"intersects divergence shadow [{lo},{hi}). " f"Ledger length re-converged; length-keyed cache aliased " f"distinct evidence. Abort and fork a new lineage." ) # Safe path: either no shadow, or shadow touches no cache-served decision. verdicts = [] for decision in self.recorded_decisions: key = decision.ledger_hash_at_decision if key in self.cache: verdicts.append(self.cache[key]) else: verdicts.append(decision.verdict) # re-derived return verdicts def demo() -> None: recorded = [ LedgerEntry("triage", "classify", "sev=high", "obs0"), LedgerEntry("mitigator", "fetch_recent_metrics", "window=5m", "obs1"), LedgerEntry("mitigator", "rollback_deploy", "svc=a,rev=41", "obs2"), LedgerEntry("auditor", "check_evidence", "probe=obs1", "obs3"), ] decisions = [ RecordedDecision("auditor", frozenset({1, 2}), "H_OLD", "approve"), ] harness = ReplayHarness(recorded, decisions) harness.cache["H_OLD"] = "approve" # stale cache keyed on old lineage # Counterfactual: metrics probe skipped, retry added -> same length, aliased. counterfactual = [ LedgerEntry("triage", "classify", "sev=medium", "obs0"), LedgerEntry("mitigator", "rollback_deploy", "svc=a,rev=41", "obs2"), LedgerEntry("mitigator", "notify_oncall", "retry=1", "obsX"), LedgerEntry("auditor", "check_evidence", "probe=obs1", "obs3"), ] try: harness.replay(counterfactual) except ReplayDivergenceError as exc: print(f"ABORT (correct): {exc}") if __name__ == "__main__": demo() ```