# Which invariants prevent speculative branch merges from resurrecting effects that the rollback already committed **Date of Record:** 2026 November 30 **Scope:** Applies to orchestrators that fan out speculative agent branches (parallel tool-using subagents) over a shared, effectful environment and reconcile by rolling back losers and merging winners. Does not apply to branches whose tool calls are provably side-effect-free (pure reads, sandboxed compute) or to single-branch linear execution. ## Core Distinction The failure is not "a losing branch's side effects leaked." That is the naive rollback problem, and it is solved by ordering: quiesce the loser, then compensate. The non-obvious failure is the inverse — **a winner's merge re-applies an effect that a loser's rollback already compensated, because the merge and the rollback both reference the same pre-branch state and neither knows the other touched it.** Rollback and merge are two writers racing to converge the environment onto "the correct post-speculation state," and they disagree about what the correct state is. The loser's compensator asserts *state = S₀* (undo my delta). The winner's merger asserts *state = S₀ ⊕ Δ_win* (apply my delta to the branch point). If Δ_win was computed against S₀ but the environment is already at S₀ because the rollback ran first, the merge is correct. If the merge reads the *current* environment (S₀ after compensation) and applies Δ_win as a *diff against current*, it double-subtracts the loser's compensation and resurrects the loser's effect — or, worse, the winner's merge was itself expressed as "replay my tool calls," and replaying a tool call whose first execution was compensated is not idempotent. This is the boundary: **speculative merge is only sound when the merge target is the immutable branch-point snapshot, not the live environment, and when every effect carries a monotonic effect-cursor that rollback advances and merge respects.** Lose either and you get resurrection or duplication. ## What Was Observed A planner agent (`root`) received a task requiring a schema migration. It fanned out three speculative branches against the same staging database: - `B1`: add column `tier` to `accounts`, backfill from `plan`. - `B2`: rename `plan` → `plan_code`, update three downstream views. - `B3`: drop `plan`, replace with a normalized `plan_ref` table. All three were launched from snapshot `S₀` (effect-cursor `c=41`). `B1` finished first and was provisionally accepted; `B2` finished second and was accepted as the merge winner because its downstream-view updates were a strict superset of `B1`'s intent. `B3` was rejected. The orchestrator issued, in order: `rollback(B3)` then `merge(B1, B2)`. The rollback of `B3` ran its compensator: `DROP TABLE plan_ref; ALTER accounts ADD COLUMN plan ...` — restoring `plan` and its contents from `S₀`. Fine. But `B2`'s merge had been *recorded* as a replayable effect log, and its replay included `ALTER TABLE accounts RENAME COLUMN plan TO plan_code`. The merger, reading the live environment to decide whether the rename was already applied, found a column named `plan` (recreated by `B3`'s compensator) and concluded the rename had *not* happened. It replayed it. The result: `plan_code` existed and was empty (renamed from the freshly-restored `plan`), while the backfilled data sat in a column the views no longer referenced. No error fired. Every individual step succeeded. The environment was silently corrupted because **the rollback advanced the effect-cursor backward in semantic terms (it re-materialized a pre-branch object) without advancing the cursor forward in monotonic terms**, so the merger's "has this effect already been applied?" probe returned a false negative. A second observation, same run, different branch pair: `B1` and `B2` both invoked `create_index(accounts, tier)`. `B1` won the index. `B2`'s merge, treating index creation as idempotent-by-name, replayed it. Postgres `CREATE INDEX` without `IF NOT EXISTS` raised, the merger caught it as "already applied, skip," and moved on — but it had already replayed the *preceding* statement in `B2`'s log, a `DROP INDEX` that was the rollback of an earlier speculative attempt. The merge log was not atomic per-transaction; partial replay left the index absent. The orchestrator's post-merge verifier checked row counts, not index existence, and passed. ## Condition of Validity The invariant that would have prevented both is: **merge must be a function of (branch-point snapshot, winner effect-log) only, and must be applied against the snapshot, not the live environment; rollback must never mutate the snapshot or any object the merge reads.** Concretely: 1. **Snapshot immutability.** `S₀` is copy-on-write and read-only to compensators. A compensator may only append a *compensation record* to the effect ledger; it may not restore live objects that a merge will later probe. If the environment must be physically restored, that restoration happens after all merges are decided, in a separate convergence phase. 2. **Monotonic effect-cursor, never decremented.** Every effect (including compensations) gets a strictly increasing cursor. A merge replay checks `effect.cursor > rollback_cursor_for_this_object`; a compensation that re-materialized `plan` at cursor `c=58` means any merge touching `plan` must be evaluated against `c=58`, not against the object's pre-rollback identity. The merger's probe "does `plan` exist?" is invalid; the valid probe is "what is the highest cursor affecting `plan`, and does my effect's precondition hold at that cursor?" 3. **Per-transaction merge atomicity.** A winner's effect-log replays as one unit or not at all. Partial replay (the `DROP INDEX` / `CREATE INDEX` case) is forbidden; if any statement in the log fails its precondition check, the entire merge aborts to a reconciliation-required state rather than skipping the failing statement. 4. **Verifier independence from row counts.** The post-merge verifier must assert structural properties (column set, index set, view definitions) derived from the *winner's declared postcondition*, not from aggregate counts that a resurrection can leave unchanged. The condition of validity is therefore: *speculative merge is sound iff the merge target is an immutable snapshot, effects are cursor-ordered and compensations are effects, and merge replay is atomic with structural postcondition verification.* Remove any one and the system permits resurrection, duplication, or silent partial application. ## Decision Boundary The orchestrator must choose between two reconciliation disciplines at the moment a branch is rejected: - **Snapshot-merge discipline** (invariant above): rollback is deferred; compensations are ledger entries; merge runs against `S₀`; a final convergence phase applies the net effect. Cost: the environment is inconsistent (contains un-compensated loser effects) for the duration of the merge window. Requires that no external observer reads the environment during that window — i.e., the environment must be fenced. - **Live-rollback discipline**: rollback runs immediately, merge reads live state. This is only valid when every effect is *provably idempotent and self-describing* — the effect carries enough metadata that a merge can determine, without probing object identity, whether it was already applied. In practice this holds only for effects keyed by a content hash or a client-supplied idempotency token, and almost never for DDL or for tool calls that mutate shared state by name. The boundary is crossed the moment a branch's effect-log contains any effect that is *not* keyed by an idempotency token the merger can check — a rename, a drop, a create-by-name, an append to a shared log, a POST to an external API without a dedup key. At that point live-rollback is unsound and the orchestrator must either fence the environment and switch to snapshot-merge, or refuse to speculate on that branch. There is no third option that preserves both liveness and correctness; the common mistake is to assume "the tool call succeeded, so it's idempotent," which is exactly the assumption that produced the empty `plan_code` column. ## Operational Effect The practical consequence is that **speculation over effectful branches requires an environment fence and a two-phase convergence**, and the fence duration is the merge window, not the branch execution window. Systems that skip the fence to keep speculation "fast" buy latency with silent corruption that surfaces only when a downstream consumer reads a resurrected object. The detectable signature is a verifier that passes on aggregate metrics while a structural assertion (column set, index set, view dependency graph) would have failed — so the guardrail is to make the verifier structural and to make the merger's precondition check cursor-based rather than existence-based. When the fence cannot be held (external APIs, shared databases with live readers), the correct decision is to serialize the effectful branches rather than speculate, because the merge invariant cannot be established and the rollback will race the merge. ```python from dataclasses import dataclass, field from typing import Dict, List class SpeculativeMergeError(RuntimeError): """Raised when a speculative merge would resurrect or duplicate a compensated effect.""" @dataclass class Effect: cursor: int target: str # object the effect touches, e.g. "accounts.plan" kind: str # "rename" | "drop" | "create" | "compensation" idempotency_token: str | None = None @dataclass class EffectLedger: effects: List[Effect] = field(default_factory=list) _cursor: int = 0 def record(self, target: str, kind: str, token: str | None = None) -> Effect: self._cursor += 1 e = Effect(self._cursor, target, kind, token) self.effects.append(e) return e def highest_cursor_for(self, target: str) -> int: return max((e.cursor for e in self.effects if e.target == target), default=0) def compensation_cursor_for(self, target: str) -> int: return max( (e.cursor for e in self.effects if e.target == target and e.kind == "compensation"), default=0, ) def merge_winner( ledger: EffectLedger, winner_log: List[Effect], snapshot_cursor: int, ) -> None: """ Apply a winner's effect-log against the branch-point snapshot. Rejects any effect whose target was compensated after the snapshot, because replaying it would resurrect or duplicate a rolled-back effect. """ for eff in winner_log: comp_cursor = ledger.compensation_cursor_for(eff.target) if comp_cursor > snapshot_cursor: # The object was re-materialized by a loser's rollback after S0. # A name-based probe would falsely conclude the effect is unapplied. if eff.idempotency_token is None: raise SpeculativeMergeError( f"merge of {eff.kind} on {eff.target!r} (cursor {eff.cursor}) " f"would replay against a compensated object " f"(compensation at cursor {comp_cursor} > snapshot {snapshot_cursor}); " f"no idempotency token present, merge is unsound" ) # With a token, the merger can prove prior application without probing identity. ledger.record(eff.target, eff.kind, eff.idempotency_token) def run_speculation() -> None: ledger = EffectLedger() # B1 wins: rename plan -> plan_code, tokenized so replay is safe. ledger.record("accounts.plan", "rename", token="b1-rename-1") # B3 rejected: compensator re-materializes plan AFTER the branch point. ledger.record("accounts.plan", "compensation") snapshot_cursor = 1 # S0 was taken before the compensation # B2's merge log touches accounts.plan with no idempotency token. winner_log = [Effect(cursor=2, target="accounts.plan", kind="rename", idempotency_token=None)] merge_winner(ledger, winner_log, snapshot_cursor) # raises SpeculativeMergeError if __name__ == "__main__": try: run_speculation() except SpeculativeMergeError as exc: print(f"merge aborted to reconciliation-required state: {exc}") ```