# What happens when an instance rolls back a speculative branch whose tool side effects have already escaped the merge barrier **Date of Record:** 2026 November 23 **Scope:** Applies to branch-and-merge orchestration where speculative agent branches execute tool calls (writes, sends, mutations) before a merge decision is made, and where rollback is expected to restore a clean pre-branch state. Does not apply to read-only speculation or to branches whose tools are fully transactional and idempotent by contract. ## Core Distinction There are two meanings of "rollback" in speculative multi-agent execution, and conflating them is the root of the failure. **State rollback** restores the agent's context, scratchpad, and memory checkpoint to a prior snapshot. **Effect rollback** undoes side effects that escaped the agent's process boundary into the external world — an email sent, a row written, a payment authorized, a file deleted. Branch-and-merge orchestration typically implements state rollback cheaply and correctly: snapshot the context window, fork N speculators, discard the losers. The invariant that silently breaks is the assumption that *discarding a branch's context also discards its effects*. It does not. The agent's state is a local object; the tool's effect is a remote fact. Rollback operates on the former and cannot reach the latter. A branch can be "rolled back" to a pristine state while its consequences persist and later re-enter the merged timeline as phantom preconditions. ## What Was Observed A planner agent received a task requiring a coordinated update across three systems: a CRM record, a billing adjustment, and a customer notification. It forked three speculative branches, each tasked with a candidate sequencing strategy, all sharing a tool gateway with a `send_email`, `write_crm`, and `post_billing_adjustment` capability. Branch B (the "notify-first" strategy) executed: `write_crm(status=pending)`, then `send_email(confirmation)`, then `post_billing_adjustment`. After the adjustment call returned a `409 conflict` (a concurrent edit by another workflow), branch B's confidence score dropped below the merge threshold and the orchestrator rolled it back — discarding B's context, marking its span `ROLLED_BACK`, and merging branch A (the "adjust-first" strategy) instead. The merge succeeded. The orchestrator reported a clean single-writer outcome. But the CRM record now carried `status=pending` from B, and the customer had received a confirmation email for an adjustment that branch A had not yet applied. Branch A, operating on a fresh snapshot taken *before* B's fork, wrote `status=active` — overwriting B's residue but leaving the email uncorrected. The final state was internally inconsistent: an active record, an adjustment applied under A's sequencing, and a customer holding a confirmation predicated on B's abandoned path. The failure trace is the key artifact: 1. Fork at `t0`. Snapshot `S0` captured for all branches. 2. Branch B executes non-idempotent effect `E1` (email) at `t1`. 3. Branch B's later tool call fails at `t2`, triggering rollback. 4. Rollback restores context to `S0` and closes B's span. **No compensating action is issued for `E1`.** 5. Branch A merges at `t3`. Its writes are computed against `S0`, not against the post-`E1` world. 6. The merged state is the union of A's writes and B's orphaned effect — a state neither branch ever reasoned about. The orchestrator's merge barrier checked *context divergence* between branches but never checked *effect divergence*. Two branches can be contextually disjoint and effectfully overlapping, and the merge logic will pass. ## Condition of Validity The failure requires four conditions to co-occur: - **Effect escape before commit.** At least one branch invokes a tool whose effect is visible outside the agent boundary before the merge decision. Read-only tools and tools behind a transaction that the orchestrator controls do not trigger this. - **Non-compensable or non-idempotent effect.** The escaped effect either cannot be undone (email sent, message posted) or will produce a different result if replayed (a counter increment, an append). - **Rollback scoped to context, not effects.** The orchestrator's rollback path restores snapshots and closes spans but does not maintain an effect ledger or issue compensations. - **Merge computed against pre-fork snapshots.** The surviving branch reasons from `S0` rather than from the actual post-effect world, so it cannot detect or reconcile the orphan. Remove any one condition and the failure is bounded. The dangerous configuration is the common one: a gateway exposing real side-effecting tools, a cheap snapshot-based rollback, and a merge that trusts snapshot lineage. ## Decision Boundary The architectural invariant that prevents this is a **two-phase effect barrier**: no branch may commit an external effect until the merge decision is final, or — if early effects are unavoidable — every effect must be recorded in an append-only ledger with a compensation handle, and rollback must *drain the ledger* before the branch is marked closed. Concretely, choose between two regimes at design time: - **Speculate-then-commit.** Branches produce *proposed* effects (dry-run payloads) and the orchestrator commits exactly one branch's proposals after merge. Rollback is trivially safe because nothing escaped. This is the correct default and the only sound choice for non-compensable effects. - **Speculate-with-ledger.** Branches may execute real effects, but each effect registers `(effect_id, branch_id, compensation_callable, idempotency_key)` in a ledger the orchestrator owns. Rollback of a branch must invoke compensations for all its ledger entries in reverse order and *block the merge* until compensation completes or is explicitly waived. The merge must then recompute the surviving branch's plan against the compensated world, not against `S0`. The boundary is sharp: **if a branch can produce an effect you cannot compensate, you may not roll it back — you may only commit it or prevent it.** A rollback that leaves an uncompensated effect is not a rollback; it is a fork of reality that the orchestrator has lost track of. ## Operational Effect The failure is insidious because it is silent. The orchestrator's own telemetry shows a clean rollback: span closed, context restored, no error raised. The inconsistency surfaces later, often in a downstream agent that reads the CRM record and reasons from a state that no branch ever intended. Because the merged state is a *union* of one branch's writes and another's orphaned effects, it is not reproducible from any single branch's trace — replaying either branch in isolation yields a different world. Debugging requires an effect ledger that, in the failing system, does not exist. The operational consequence is that speculative execution over side-effecting tools must be treated as a *distributed transaction* problem, not a *context management* problem. Teams that instrument only context snapshots will see 100% rollback success while shipping inconsistent external state. The guardrail is an effect ledger with mandatory compensation draining on rollback and a merge step that re-derives the surviving plan from the compensated world. ```python from dataclasses import dataclass, field from typing import Callable, Dict, List from datetime import datetime class UncompensatedEffectError(RuntimeError): """Raised when a speculative branch is rolled back while its escaped effects remain uncompensated, or when a merge is attempted against a snapshot that predates an orphaned effect.""" pass @dataclass class EffectEntry: effect_id: str branch_id: str compensation: Callable[[], None] | None idempotency_key: str committed: bool = False compensated: bool = False @dataclass class EffectLedger: entries: Dict[str, EffectEntry] = field(default_factory=dict) def record(self, entry: EffectEntry) -> None: self.entries[entry.effect_id] = entry def branch_entries(self, branch_id: str) -> List[EffectEntry]: return [e for e in self.entries.values() if e.branch_id == branch_id] class SpeculativeOrchestrator: def __init__(self, ledger: EffectLedger) -> None: self.ledger = ledger self.closed_branches: set[str] = set() def rollback_branch(self, branch_id: str) -> None: # Restore context snapshot (cheap, local). self._restore_snapshot(branch_id) # Drain the effect ledger: every escaped effect must be compensated # in reverse order before the branch may be marked closed. pending = [e for e in self.ledger.branch_entries(branch_id) if not e.compensated and not e.committed] for entry in reversed(pending): if entry.compensation is None: raise UncompensatedEffectError( f"Branch {branch_id} produced non-compensable effect " f"{entry.effect_id} (key={entry.idempotency_key}); " f"rollback is unsound — branch must be committed or " f"prevented, not discarded." ) entry.compensation() entry.compensated = True self.closed_branches.add(branch_id) def merge(self, winning_branch: str, pre_fork_snapshot_time: datetime, post_effect_world_time: datetime) -> None: # Guard: the surviving branch must reason against the compensated # world, not the pre-fork snapshot. orphans = [ e for e in self.ledger.entries.values() if not e.compensated and not e.committed ] if orphans and post_effect_world_time < pre_fork_snapshot_time: raise UncompensatedEffectError( f"Merge of {winning_branch} computed against pre-fork snapshot " f"while {len(orphans)} orphaned effect(s) remain live; " f"re-derive the plan from the compensated world." ) # Commit the winning branch's proposed effects here. for e in self.ledger.branch_entries(winning_branch): e.committed = True def _restore_snapshot(self, branch_id: str) -> None: # Context-only restoration; deliberately does not touch the ledger. pass ```