# Why does an instance fail to roll back a speculative sub-agent when the divergence is detected after the branch has already committed writes to shared episodic memory? **Date of Record:** 2026 November 29 **Scope:** Applies to orchestrators that fan out speculative sub-agents (parallel branch exploration, tree-of-thought style rollback, or "try N trajectories, keep the best" schemes) where branches share a mutable episodic store or blackboard. Does not apply to branches with fully isolated, copy-on-write memory namespaces and no shared tool side effects. ## Core Distinction The failure is not "divergence detection is wrong." Divergence detection is usually fine—a verifier, a critic, or a trajectory-distance metric flags that branch B has drifted from the parent's intent. The failure is that rollback is treated as a *control-flow* operation (discard the branch, resume the parent) when it is actually a *state-reconciliation* operation across at least three substrates that commit at different times: the branch's private context window, the shared episodic memory store, and the external tool environment (files, API mutations, message queues). Speculative execution assumes rollback is cheap and total. In agent systems it is neither, because a sub-agent's reasoning trace *is* a side effect: once a branch writes a distilled fact, a tool result, or a "confirmed" belief into shared memory, downstream agents have already read it and conditioned on it. You cannot un-ring that bell by dropping the branch's context. The sharp, non-obvious boundary: **rollback is only sound if every write the branch performed is either (a) tagged with the branch's speculative epoch and invisible to non-descendant readers until commit, or (b) reversible with a compensating action.** Most orchestrators implement neither. They implement "kill the branch and delete its context," which leaves the shared store poisoned and the tool environment mutated. ## What Was Observed A planner agent decomposes a task ("reconcile these 400 invoice records against the ledger") and speculatively spawns three sub-agents: - Branch A: batch-diff approach, writes intermediate reconciliation facts to the shared episodic store under keys like `recon:batch_7:status`. - Branch B: per-record LLM adjudication, also writes to the same key namespace because the schema was not branch-scoped. - Branch C: heuristic prefilter, writes `recon:batch_7:status = "clean"` for batches it filtered out. Branch B diverges—its adjudication rate collapses (it starts emitting `uncertain` for 60% of records, a trajectory the critic flags as low-confidence). The orchestrator detects divergence at step 41 and rolls back Branch B. It deletes Branch B's context, drops its pending tool calls, and marks the branch `aborted`. But Branch B had, at step 12, written `recon:batch_7:status = "clean"` after a partial pass. Branch C had *already read that key* at step 20 and used it to skip 40 records from its own prefilter, propagating the false "clean" into its own writes. When Branch B is rolled back, the orchestrator restores nothing, because it never recorded which keys Branch B wrote. Branch A, which was the surviving branch, reads `recon:batch_7:status` at step 55 and inherits the orphaned "clean" from the dead branch. The final reconciliation reports 40 records as clean that were never checked. No error is raised. The divergence was "handled." The trace signature: a divergence event followed by a *clean* completion whose output references memory keys written by an aborted branch. The orchestrator's rollback log shows `branch_B: aborted, context discarded` and nothing about memory. The shared store shows keys with no live owner. ## Condition of Validity Rollback-on-divergence is valid **only** under the conjunction: 1. **Epoch isolation:** every shared-memory write carries a speculative epoch/transaction ID; readers outside the branch's descendant set see the pre-branch value until an explicit commit. Reads within the branch see its own writes (read-your-writes), but siblings and the parent do not. 2. **Write-set capture:** the branch maintains a complete, ordered log of every external mutation (memory keys, tool calls with side effects, emitted messages) sufficient to construct a compensating undo *or* to prove the write is epoch-isolated and therefore needs no undo. 3. **Read-dependency tracking:** the orchestrator knows which other branches read which speculative keys, so that aborting a producer either invalidates or re-executes the dependent readers. Without this, an aborted branch's writes leak through *sibling reads* even if the store itself is epoch-clean at commit time. 4. **Tool-side-effect classification:** every tool the branch can call is classified reversible (idempotent, compensating action exists) or irreversible (external email sent, payment initiated, file overwritten in place). Irreversible calls must be gated behind commit, not executed speculatively. If any of these is absent, "rollback" is a context-window operation masquerading as a state operation. The boundary is crossed the moment a branch performs its first uncommitted shared write, which in practice is early—often step 5–15, long before divergence is detectable. ## Decision Boundary The orchestrator must decide, per branch, between two regimes: - **Speculate-with-isolation:** branch writes go to an epoch-scoped overlay; siblings see parent state only; commit merges the overlay; abort drops it. Cost: every reader must resolve overlays, and cross-branch information sharing is delayed until commit, which can starve branches that legitimately need sibling results. - **Speculate-with-compensation:** branch writes go directly to shared state but are logged with undo records; abort replays compensations in reverse order and re-runs dependent readers. Cost: requires reversible tools and a dependency graph; fails hard on irreversible tools. The decision boundary is the **first irreversible or untracked write**. Before it, compensation is viable. After it, the only sound options are (a) commit the branch's effects and accept them, or (b) halt the whole speculative cohort and surface the divergence to a human/supervisor rather than silently continuing. An orchestrator that rolls back *past* the first irreversible write without epoch isolation is in an undefined state and must treat the entire cohort as contaminated. Concretely: if `write_set` contains a mutation whose `reversible == False` or whose `epoch == None`, the correct action is not `abort_branch()` but `quarantine_cohort()`. ## Operational Effect The observable consequence is a **silent correctness regression that correlates with speculative breadth**: the more branches you fan out, the more likely a sibling read a doomed branch's write, and the more likely the surviving branch inherits a false fact. Systems that "work" at breadth 2 fail at breadth 5. The failure is invisible to per-branch success metrics because the surviving branch *does* complete, and its completion is internally consistent—it just rests on a fact whose author was aborted. The guardrail is to make rollback a first-class transaction over the shared substrate, not a context discard. Minimum viable implementation: tag every shared write with `(branch_id, epoch, reversible)`, maintain a read-dependency edge from `(reader_branch, key)` to `(writer_branch, epoch)`, and on abort compute the transitive closure of readers of the aborted epoch's keys and either re-execute or invalidate them before the cohort can commit. If the closure contains an irreversible write or an unlogged mutation, escalate to cohort quarantine. The invariant to enforce: **no committed state may depend on a write whose author epoch was aborted.** Violating it is the exact mechanism by which speculative execution silently corrupts the record. ```python from dataclasses import dataclass, field from typing import Any class SpeculativeRollbackError(RuntimeError): """Raised when a branch abort would leave committed state depending on an aborted epoch.""" pass @dataclass class Write: branch_id: str epoch: int key: str value: Any reversible: bool @dataclass class SharedStore: committed: dict[str, Any] = field(default_factory=dict) # read_edges[(reader_branch, key)] = set of (writer_branch, epoch) read_edges: dict[tuple[str, str], set[tuple[str, int]]] = field(default_factory=dict) write_log: list[Write] = field(default_factory=list) def read(self, branch_id: str, key: str) -> Any: # record that this branch read this key, attributing to whoever last wrote it writers = {(w.branch_id, w.epoch) for w in self.write_log if w.key == key} self.read_edges.setdefault((branch_id, key), set()).update(writers) return self.committed.get(key) def abort_branch(store: SharedStore, branch_id: str, epoch: int) -> None: """Roll back a divergent branch. Refuses if dependents or irreversible writes exist.""" branch_writes = [w for w in store.write_log if w.branch_id == branch_id and w.epoch == epoch] if not branch_writes: return # nothing to roll back; context discard is sufficient # 1. Irreversible writes cannot be compensated. irreversible = [w for w in branch_writes if not w.reversible] if irreversible: raise SpeculativeRollbackError( f"branch {branch_id}@{epoch} has irreversible writes " f"{[w.key for w in irreversible]}; quarantine cohort, do not abort" ) # 2. Find every reader that conditioned on this branch's writes. doomed_keys = {w.key for w in branch_writes} dependents: set[str] = set() for (reader, key), writers in store.read_edges.items(): if key in doomed_keys and (branch_id, epoch) in writers and reader != branch_id: dependents.add(reader) if dependents: raise SpeculativeRollbackError( f"branch {branch_id}@{epoch} writes were read by {sorted(dependents)}; " f"abort would leave committed state depending on an aborted epoch" ) # 3. Safe: drop the branch's uncommitted writes and its log entries. store.write_log = [w for w in store.write_log if not (w.branch_id == branch_id and w.epoch == epoch)] for w in branch_writes: # restore prior committed value if any; overlay semantics store.committed.pop(w.key, None) ```