# What happens when an instance merges a speculative branch whose tool side-effects were already committed downstream **Date of Record:** 2026 November 22 **Scope:** Applies to orchestrators that fork parallel agent branches to hedge against non-deterministic tool outcomes, then merge the winning branch and roll back losers. Does not apply to strictly linear single-agent loops or to branches that touch only read-only tools. ## Core Distinction The failure is not "rollback failed." Rollback of *state* almost always succeeds because state is the thing the orchestrator owns. The failure is that rollback was scoped to the branch's *local* context and working memory, while the branch's *tool effects* had already propagated into a downstream surface the orchestrator does not checkpoint: a message queue, an external API that isn't idempotent, a shared scratchpad another live agent is reading, or a side-effect chain where branch A's tool call produced an artifact that branch B's tool call consumed before the merge decision was made. Speculative branch-and-merge is safe only under an invariant we will call **effect isolation**: no branch's externally observable tool effects may become an input to any other branch, or to any non-branch consumer, until the merge is committed. When that invariant is violated, the merge is not a selection among hypotheses — it is a selection among *already-materialized histories*, and discarding the loser does not un-materialize its consequences. The non-obvious part: the violation is usually invisible at the branch boundary. Each branch looks locally consistent. The corruption appears in the *winner*, because the winner inherited a stale or contaminated input produced by a loser that was later garbage-collected. ## What Was Observed A planner agent decomposed a task into "resolve target resource identity" followed by "apply configuration." Because identity resolution was flaky (two candidate endpoints, non-deterministic DNS resolution and a rate-limited registry), the orchestrator forked two speculative branches: - **Branch A** resolved the resource to `res-7f3a` and wrote a claim record to a shared coordination table (`claimed_by=A`) as a precondition for the apply step. - **Branch B** resolved the same resource to `res-7f3a` as well but, due to a retry, wrote a *second* claim record (`claimed_by=B`) before the merge arbiter ran. The arbiter scored Branch A higher on resolution confidence and committed A, rolling back B. Rollback restored B's context window, deleted B's scratchpad, and marked B's task row `ABORTED`. But B's claim row in the coordination table had already been read by a *third*, concurrent agent (a reconciler) that used it to derive "resource is contended" and dispatched a quarantine action. That quarantine fired against `res-7f3a` — the resource Branch A then proceeded to configure. Trace, compressed: 1. `fork(A, B)` at decision point; both branches share the coordination table as an un-isolated resource. 2. `A.tool(claim, res-7f3a, owner=A)` → row inserted. 3. `B.tool(claim, res-7f3a, owner=B)` → second row inserted (tool was not idempotent on `(resource, owner)`; it appended). 4. `reconciler.observe(coord_table)` → sees two owners → emits `quarantine(res-7f3a)`. 5. `arbiter.commit(A)`, `rollback(B)` → B's context and task row reverted; **the two claim rows and the quarantine event are not reverted** because they live outside the branch checkpoint domain. 6. `A.tool(apply_config, res-7f3a)` → fails against a quarantined resource, or worse, succeeds partially. The winner A was correct in its own reasoning and still executed against a world that a discarded branch had mutated. The merge report said `committed=A, rolled_back=B, status=ok`. That report was a lie about the world, not about the branches. ## Condition of Validity The merge-and-rollback protocol is sound **iff** all of the following hold at the instant the arbiter commits: - **Effect isolation:** every tool invoked by any branch is either (a) read-only, (b) idempotent and commutative on its key, or (c) buffered in a branch-private staging area that is only flushed on commit. - **Single-writer on shared surfaces:** no non-branch consumer (reconciler, monitor, peer agent) can observe a branch's staged effects before commit. This means the coordination table must be partitioned per branch or versioned with a `visible_after_commit` marker. - **Rollback domain ⊇ effect domain:** the set of things rollback restores must be a superset of the set of things the branch could have touched. If a branch can write to a surface the checkpoint doesn't cover, the invariant is already broken. - **Merge determinism:** the arbiter's scoring function must be a pure function of branch-local state, not of shared state that branches themselves mutated (otherwise the loser can bias the winner's score). If any of these fails, you do not have speculative execution. You have **concurrent execution with a post-hoc vote**, and the vote cannot undo the votes' side-effects. ## Decision Boundary The operative question is not "did rollback run?" but "could any committed effect have been *observed* by a consumer outside the rollback domain before the commit barrier?" - If **no** — proceed with fork/merge. Cheap, safe. - If **yes, and the effect is idempotent/commutative** — proceed, but require the arbiter to reconcile duplicates (e.g., collapse two claim rows into one with a deterministic winner key) rather than assume rollback cleaned them. - If **yes, and the effect is non-idempotent or observable** — you must either (1) serialize the branches behind a staging buffer flushed only on commit, or (2) forbid forking across that tool and instead resolve the nondeterminism with a single retrying branch. Speculation across a non-idempotent, externally observable effect is unsound regardless of how good the arbiter is. A useful test: for each tool in the branch's reachable set, ask "if this fires twice and one firing is later declared void, is the world still consistent?" If the answer depends on the arbiter's decision, the tool is not speculatable. ## Operational Effect The practical consequence is a class of bugs where the *committed* branch fails or corrupts state for reasons that trace to a *discarded* branch, and the audit trail blames the winner. Post-mortems chase the wrong agent. Retries re-fork and re-poison. The system appears to have a nondeterministic flakiness that correlates with concurrency but not with any single branch's logic. The guardrail is to make the commit barrier the *only* point at which branch effects become world-visible, and to assert at commit time that no staged effect from a losing branch has escaped. That assertion must be enforced in code, not in the arbiter's prompt. ```python from dataclasses import dataclass, field from typing import Literal class SpeculativeIsolationViolation(RuntimeError): """Raised when a branch's tool effect escaped the rollback domain before commit.""" @dataclass class Branch: branch_id: str staged_effects: list[str] = field(default_factory=list) committed: bool = False def stage_effect(self, effect_key: str) -> None: self.staged_effects.append(effect_key) @dataclass class SharedSurface: # Effects that have become visible to non-branch consumers. visible: set[str] = field(default_factory=set) def observe(self, effect_key: str) -> None: self.visible.add(effect_key) def commit_branch( winner: Branch, losers: list[Branch], surface: SharedSurface, non_idempotent_keys: set[str], ) -> None: # Pre-commit invariant: no losing branch may have leaked an effect # onto a surface observable by non-branch consumers. for loser in losers: for effect in loser.staged_effects: if effect in surface.visible: raise SpeculativeIsolationViolation( f"branch {loser.branch_id} effect {effect!r} was observed " f"before commit; rollback cannot un-materialize it" ) # Second invariant: winner must not depend on a non-idempotent effect # that any branch (including itself) may have fired more than once. fired_counts: dict[str, int] = {} for b in [winner, *losers]: for effect in b.staged_effects: fired_counts[effect] = fired_counts.get(effect, 0) + 1 for effect, count in fired_counts.items(): if count > 1 and effect in non_idempotent_keys: raise SpeculativeIsolationViolation( f"non-idempotent effect {effect!r} fired {count} times across " f"speculative branches; merge cannot reconcile" ) # Safe to flush: effects become world-visible only now. for effect in winner.staged_effects: surface.observe(effect) winner.committed = True ```