# Which invariants prevent speculative branch-and-merge agent plans from committing orphaned side effects on rollback **Date of Record:** 2026 November 27 **Scope:** Applies to orchestrators that speculatively fork a plan into parallel agent branches, execute tool calls optimistically, and merge the winning branch while rolling back losers. Does not apply to strictly sequential single-agent execution or to branches whose tool calls are provably side-effect-free. ## Core Distinction A speculative branch-and-merge executor distinguishes between *logical rollback* (discarding a branch's reasoning state, message history, and intermediate artifacts) and *physical rollback* (undoing the external effects its tool calls already produced). The failure mode this record isolates is the silent divergence between these two: the orchestrator believes a losing branch was rolled back because its context was dropped and its checkpoint marked `ABORTED`, while the branch's already-issued tool calls have irreversibly mutated shared world state — a database row, a sent email, a provisioned resource, a pushed commit. The non-obvious part is that this is not a crash-recovery problem. The losing branch terminates *cleanly and correctly* by its own local logic. The bug lives in the merge arbiter's assumption that a branch's abort is a compensating action. It is not. Abort is a state transition on the branch's control flow; compensation is a separate, ordered set of inverse operations against the external systems the branch touched. Speculative execution conflates the two because in pure computation (CPU speculative execution, memoized futures) rollback *is* free — you discard the register file. In agent systems, tool calls are committed the instant they return, and the branch has no transactional handle to retract them. ## What Was Observed A planner agent received a task and, under a latency budget, forked three branches (`B0`, `B1`, `B2`) that each proposed a different migration strategy. Each branch was given a scoped tool grant including `db.execute`, `fs.write`, and `http.post`. The arbiter's policy was first-to-pass-verification wins; the others are rolled back. Trace of the failure: 1. `B0` and `B1` both begin optimistically. `B0` issues `http.post("/notify", {...})` at t=1.2s (customer notification). `B1` issues `db.execute("UPDATE accounts SET tier=...")` at t=1.4s. 2. `B2` completes verification first at t=2.0s and is selected. Arbiter emits `abort(B0)` and `abort(B1)` and merges `B2`. 3. `B0` and `B1` receive the abort signal, halt their reasoning loops, and write `status=ABORTED` checkpoints. Their in-flight tool calls, however, had already returned `200 OK` and `rows_affected=1`. 4. The merge commits `B2`'s plan, which *also* notifies the customer and *also* updates the tier — producing a duplicate notification and a tier transition applied twice (once by `B1`, once by `B2`), the second overwriting the first with a value computed against stale pre-`B1` state. The orchestrator's post-merge audit reported zero anomalies: all branches reached terminal states, all checkpoints were consistent, the merge was atomic from the arbiter's view. The divergence was invisible because the arbiter's rollback model only tracked *branch state*, never *effect state*. The invariant it assumed — "aborted branch ⇒ no external mutation" — was false the moment tool grants were optimistic. A second, subtler observation: the duplicate notification was not idempotent at the receiver, and `B2`'s tier update was computed by reading `accounts.tier` *before* `B1`'s write landed (read at t=1.1s, write by `B1` at t=1.4s, `B2`'s write at t=2.3s). This is a read-write hazard across speculative branches that no single branch could detect, because each branch saw a consistent snapshot at fork time. ## Condition of Validity The "abort ⇒ clean" assumption holds only under a conjunction that speculative executors rarely enforce: - **Effect isolation:** every tool call issued by a speculative branch is either (a) routed to a branch-private shadow namespace (transactional outbox, per-branch scratch schema, dry-run endpoint) or (b) explicitly declared idempotent and commutative with all sibling branches' effects. If neither holds, the branch is not safely speculable. - **Monotonic commit ordering:** a branch's effects become visible to the world only after the arbiter's merge decision, in a single ordered commit phase. Optimistic visibility before merge violates this. - **Compensation completeness:** for any non-isolated effect, the branch must have registered a compensating inverse at issue time, and the arbiter must execute compensations in reverse issue order before declaring rollback complete. A branch that cannot name its inverse is not rollback-able, only abandonable. - **Snapshot consistency across branches:** branches must read from a fork-point snapshot, and the merge must detect write-write and read-write conflicts against that snapshot (optimistic concurrency control), not merely pick a winner. First-to-verify is a *liveness* policy, not a *correctness* policy. When any conjunct fails, the system is outside the validity envelope and rollback is best-effort at the branch level with no guarantee at the effect level. ## Decision Boundary The boundary is whether the orchestrator treats the merge arbiter as a *selector* or as a *transaction manager*. A selector picks a winner and discards losers — correct only under full effect isolation. A transaction manager must additionally: - Maintain an **effect ledger** per branch, appended at tool-call issue time, recording `(tool, args_hash, idempotency_key, compensating_op, issued_at, returned_at)`. - Require every tool grant used in a speculative branch to carry an **idempotency key** derived from `(branch_id, logical_step, args_hash)`, so that a replayed or duplicated effect is deduplicated at the receiver rather than silently applied twice. - Run a **conflict check** at merge: if two branches' ledgers contain effects against the same key with non-commuting operations, or if any branch read a key another branch wrote after the fork snapshot, the merge must fail closed rather than pick a winner. - Execute **compensations before commit**, in reverse issue order, and only then mark rollback complete — with a hard invariant that no branch may be marked `ROLLED_BACK` while its ledger contains a non-compensated, non-isolated effect. The failure is triggered precisely when the arbiter advances a branch to `ROLLED_BACK` on the basis of control-flow termination rather than ledger emptiness. That single state transition is the bug. ## Operational Effect Systems that miss this boundary exhibit *phantom commits*: effects that survive their originating branch's abort and are misattributed to the merged branch during post-hoc audit, because the ledger that would disambiguate them was never written. The observable symptoms are duplicate non-idempotent actions (notifications, charges, resource provisioning), lost updates from cross-branch read-write hazards against the fork snapshot, and — most dangerously — a *clean* audit trail, because the orchestrator's own bookkeeping is internally consistent. The divergence is only detectable against external systems, and only if those systems logged enough to reconstruct which branch issued which effect. The architectural invariant that bounds the failure is the **ledger-before-effect rule**: no tool call may be dispatched by a speculative branch until its ledger entry, including its compensating operation and idempotency key, is durably recorded. Combined with fail-closed conflict detection at merge, this converts silent divergence into a detectable, recoverable abort — the orchestrator learns it cannot safely merge and escalates, rather than committing a plan that has already been partially executed by its losers. ```python class SpeculativeRollbackViolation(RuntimeError): """Raised when a branch is marked rolled back while non-isolated effects remain uncompensated in its effect ledger.""" pass def mark_rolled_back(branch, ledger): # Invariant: a branch may only reach ROLLED_BACK when its effect # ledger contains no non-isolated, non-compensated effects. uncompensated = [ e for e in ledger.for_branch(branch.id) if not e.isolated and not e.compensated ] if uncompensated: raise SpeculativeRollbackViolation( f"branch {branch.id} cannot be rolled back: " f"{len(uncompensated)} live effect(s) " f"{[e.tool for e in uncompensated]} were committed to shared " f"state and have no executed compensation; merge must fail closed" ) # Compensate in reverse issue order, then seal the ledger. for effect in sorted(ledger.for_branch(branch.id), key=lambda e: e.issued_at, reverse=True): if not effect.isolated: effect.compensating_op() effect.compensated = True ledger.seal(branch.id) branch.status = "ROLLED_BACK" return branch ```