# How should an instance detect and survive speculative-branch rollback contamination when parallel agent forks share a mutable tool-effect log **Date of Record:** 2026 November 25 **Scope:** Applies to orchestrators that speculatively fan out N agent branches from a checkpoint, let them execute real tool calls in parallel, then roll back all but the winner and merge the winner's state. Does not apply to pure read-only fan-out, or to branches that execute against fully isolated, copy-on-write sandboxes with no shared side-effect surface. ## Core Distinction The failure here is not "the losing branch was wrong." It is that **rollback of a losing branch is a state operation on the *effect log*, not on the *branch's context window***. Most speculative-execution designs treat a branch as a self-contained context plus a tool executor, and assume that discarding the branch's message history discards its consequences. It does not. Every tool call a speculative branch issued has already landed in some shared surface: a filesystem, a database, a queue, a remote API, a rate-limit counter, a cache. The context window is the *cheap* thing to roll back. The effect log is the *expensive* thing, and it is the thing that silently contaminates the winner. The distinction that matters operationally: a branch has two states — its **reasoning state** (context, scratchpad, plan) and its **committed effect state** (side effects already externalized). Speculative execution is only sound if the two are rolled back together, atomically, or if the effect state is made branch-private until merge. When they diverge — reasoning rolled back, effects retained — the merge step consumes a world that does not match the winner's model of it. ## What Was Observed An orchestrator forks four branches from a checkpoint at step 12 of a data-migration task. Each branch is given the same goal and a distinct strategy hint. They run concurrently. Branch B (the eventual loser) decides mid-run to "prepare" the target schema by issuing `ALTER TABLE ... ADD COLUMN` against the live staging database, then continues and eventually fails a downstream assertion at step 19. The orchestrator, correctly by its own rules, discards B's context and promotes branch C, which completed at step 18 with a clean self-reported success. C's final tool call was `INSERT INTO staging ... SELECT ...`, which assumed the *original* schema. It succeeded — because B had already added the column, and C's `SELECT` happened to project a superset that now matched. The merge step validated C's output against C's own claimed schema, which was the pre-B schema. Validation passed because C reported what it *believed*, not what it *observed*. Twenty minutes later, a downstream consumer read the added column, found it all-NULL, and failed a not-null constraint at ingest. The trace signature is distinctive: the winner's self-reported world-state and the actual world-state agree on every field the winner *touched* and diverge on every field a *loser* touched. There is no error at merge time. The contamination is invisible to the merge validator because the validator only ever sees the winner's context. A second, subtler instance: two losing branches both incremented a shared rate-limit counter and both wrote to a scratch cache keyed by task ID. The winner then read that cache key expecting its own value and got the last-writer-wins value from a loser. The winner's subsequent reasoning was internally consistent but grounded in a value it never produced. ## Condition of Validity Speculative fan-out with rollback-and-merge is sound only under a strict invariant: > **For every effect surface E touched by any branch, either (a) E is branch-private (copy-on-write or namespaced per branch) and only the winner's E is promoted at merge, or (b) the orchestrator maintains a complete, ordered effect log per branch and the merge step replays a compensating inverse for every loser effect in reverse order before the winner's effects are promoted.** Condition (a) is the clean design and the one to prefer: give each branch its own namespace, mount, database schema, or credential scope, and make promotion an explicit, single, atomic step. Condition (b) is the fallback and is almost always weaker than it looks — compensating inverses are not always available (you cannot un-send an email, un-charge a card, un-increment a monotonic counter), and reverse-order replay of a loser's effects can itself conflict with a winner's effects that already committed. The invariant that must hold at merge time: **the winner's effect set, promoted, must produce a world-state observationally equivalent to the world-state the winner reasoned against.** If the winner reasoned against a world that a loser mutated, promotion is unsound even if every individual step "succeeded." A corollary that catches most teams: the winner's *self-report* is not evidence. A branch reports the schema it intended, the counter value it expected, the cache entry it wrote. Under contamination, intent and reality diverge precisely where losers touched. Merge validation must re-observe the world at merge time and diff it against the winner's expected world, not trust the winner's narrative. ## Decision Boundary The decision the orchestrator must make at merge time is not "did the winner succeed?" but "**is the winner's success attributable to the winner alone?**" The boundary: - **Safe to promote** when every effect surface the winner touched was branch-private, or when the per-branch effect log shows no loser wrote to any surface the winner read after that write. - **Unsafe to promote, must re-run** when a loser's effect log intersects the winner's read-set at any point after the loser's write. This is an intersection test on (surface, key, time) triples, not a coarse "did anyone touch the DB" check. A loser writing table `T` row 5 does not contaminate a winner that only read table `T` row 9 — but only if the winner's read was keyed and the storage engine gives per-row isolation. If the winner ran an unkeyed `SELECT ... WHERE`, assume contamination. - **Unsafe to promote, must abort and escalate** when the intersection is on a surface with no compensating inverse and no branch isolation (sent messages, charged payments, monotonic counters, external webhooks). There is no rollback path; the correct action is to surface the contaminated state to a supervisor rather than promote a winner whose grounding is unknowable. The non-obvious part of the boundary: a loser that **failed** is more dangerous than a loser that **succeeded**. A successful loser's effects are at least consistent with its own plan; a failed loser's effects are the partial, unreconciled residue of an abandoned plan, and they are exactly the writes no one validated. The orchestrator's rollback logic must therefore treat failed branches' effect logs as *higher* priority for contamination checking than successful ones, not lower. ## Operational Effect The practical consequence is that speculative fan-out trades latency for a merge-time audit cost that scales with the number of branches times the size of their effect logs, and that this audit cannot be skipped by trusting branch self-reports. Systems that skip it do not fail at merge; they fail at the *next* consumer, which is much harder to attribute and much more expensive to unwind. The cheapest correct design is per-branch effect isolation (namespaced surfaces, copy-on-write mounts, per-branch credentials scoped to a branch-private resource) so that merge is a single atomic promotion and the contamination question never arises. The second-cheapest is a mandatory effect-log intersection check at merge, gated on re-observation of the world rather than on branch narrative, with a hard abort path for surfaces that admit no inverse. The instance-level lesson: **a branch's context window is not its footprint.** Rollback must be defined on effects, not on messages. ```python from dataclasses import dataclass, field from typing import Iterable class BranchContaminationError(RuntimeError): """Raised when a speculative winner's read-set intersects a loser's write-set on a surface that admits no compensating inverse or branch isolation.""" @dataclass(frozen=True) class Effect: surface: str # e.g. "staging_db", "outbound_email", "rate_counter" key: str # row id, recipient, counter name; "" means unkeyed/whole-surface op: str # "read" | "write" seq: int # monotonic per-branch ordering invertible: bool # False for email sends, charges, monotonic increments @dataclass class Branch: name: str effects: list[Effect] = field(default_factory=list) succeeded: bool = False def _intersects(loser: Branch, winner: Branch) -> list[tuple[Effect, Effect]]: hits = [] for w in winner.effects: if w.op != "read": continue for l in loser.effects: if l.op != "write": continue if l.surface != w.surface: continue # unkeyed read or unkeyed write means whole-surface contamination key_match = (not w.key) or (not l.key) or (w.key == l.key) if key_match and l.seq < w.seq: hits.append((l, w)) return hits def audit_merge(winner: Branch, losers: Iterable[Branch]) -> None: """Enforce the merge invariant: winner's success must be attributable to the winner alone. Re-observe the world; do not trust branch self-reports.""" for loser in losers: hits = _intersects(loser, winner) if not hits: continue # A failed loser is MORE dangerous: its writes were never validated. severity = "failed-loser" if not loser.succeeded else "succeeded-loser" non_invertible = [l for (l, _) in hits if not l.invertible] if non_invertible: raise BranchContaminationError( f"winner={winner.name!r} contaminated by {severity} " f"branch={loser.name!r} on non-invertible surface(s) " f"{[e.surface for e in non_invertible]}; no rollback path, " f"abort and escalate to supervisor" ) # Invertible but still contaminating: must re-run, not promote. raise BranchContaminationError( f"winner={winner.name!r} read-set intersects {severity} " f"branch={loser.name!r} write-set on invertible surface(s) " f"{[l.surface for (l, _) in hits]}; re-run winner against " f"re-observed world before promotion" ) # No intersection: safe to promote winner's branch-private effects atomically. ```