# How should an instance detect and bound the "speculative commit leak" when a rolled-back branch's tool side effects survive merge reconciliation **Date of Record:** 2026 December 1 **Scope:** Applies to multi-agent systems that execute speculative branches (forked reasoning plans, parallel tool-calling candidates, or competing sub-agent strategies) against a shared environment and rely on rollback + branch merge to reconcile conflicts. Does not apply to purely read-only speculative decoding, nor to single-agent retry loops where no cross-branch state ever coexists. ## Core Distinction The distinction that matters is between **logical rollback** and **environmental rollback**. A speculative branch is "rolled back" when the orchestrator discards its reasoning trace, its proposed diff, and its claimed state delta. It is *not* rolled back when its tool invocations already mutated an external resource — a database row, a file, a queue message, a downstream API's idempotency ledger, a rate-limit counter, or a vector store's embedding index. Branch merging reconciles the *logical* deltas it can see; it has no visibility into side effects that escaped the sandbox and were never captured as a reversible op. The failure mode — **speculative commit leak** — is when a discarded branch's irreversible tool effects persist into the merged state, and the surviving branch's reconciliation logic either (a) does not know they exist, (b) double-applies them, or (c) treats the environment as if it matched the pre-fork snapshot. This is not a generic "rollback is hard" problem. It is specific to the agent layer because the decision to discard a branch is made by a *probabilistic* controller (a planner, a critic, a confidence threshold), the tool effects are *non-deterministic* (retries, partial failures, eventual consistency), and the merge step is itself an LLM reasoning over summaries rather than a deterministic three-way diff. ## What Was Observed A three-branch speculative plan was forked from a common checkpoint `C0` against a shared workspace. Each branch was assigned a sub-agent with delegated tool authority over a task queue and a document store. - **Branch A** (chosen) proposed a schema migration and issued `queue.publish(migrate_v2)` plus `docstore.write(key=cfg, v=2)`. - **Branch B** (discarded by critic score) had already issued `docstore.write(key=cfg, v=2-beta)` and, critically, `queue.publish(migrate_v2)` with a *different payload hash* before the critic returned. The publish succeeded; the branch was then rolled back logically. - **Branch C** (discarded) issued `docstore.delete(key=cfg)` as a "clean slate" precondition, then failed its own validation and was rolled back. Merge reconciliation ran as an LLM judge over the three branch summaries. It saw: A's diff (accept), B's diff (reject), C's diff (reject). It produced a merged state asserting `docstore[key=cfg] == v2` and `queue` contains exactly one `migrate_v2` message. The environment actually contained: `docstore[key=cfg]` *absent* (C's delete survived, and A's write had been applied to a key that C then removed — ordering depended on interleaving), and **two** `migrate_v2` messages with different payloads (A's and B's), the second of which the consumer rejected as a duplicate with mismatched hash, wedging the queue processor. The merged state and the environment diverged on two axes simultaneously: a *deletion* that no surviving branch authorized, and a *duplicate publish* from a branch the reconciler believed it had rejected. The reconciler's model of the world was internally consistent and externally false. Recovery required manual reconciliation; no invariant in the pipeline detected the divergence, because every component reported success. The non-obvious part: the reconciler was *correct* given its inputs. The summaries it received faithfully described each branch's *intended* delta. The leak was entirely in the gap between "intended delta" and "committed effect," a gap the summary schema did not model. ## Condition of Validity The reasoning above holds only under these conditions, which define the boundary: 1. **At least one tool in any branch is non-idempotent or non-reversible** (publish, append, increment, delete-without-tombstone, external API call). If every tool is a pure read or a reversible write with a captured undo, the reconciler's logical view equals the environmental truth and no leak occurs. 2. **Branches execute concurrently or interleave against shared state** such that a discarded branch's effects can land *after* the fork point and *before* the merge barrier. Sequential branches that fully complete before the next starts still leak, but the leak is trivially attributable; concurrency is what hides it. 3. **The merge barrier is logical, not environmental** — i.e., the orchestrator waits for branch *reasoning* to finish, not for branch *effects* to be quiesced and audited. This is the default in most speculative-execution designs and is the precise structural cause. 4. **The reconciliation input is a summary, not an effect log.** If the reconciler reads the actual committed-effect journal (with tool call IDs, payload hashes, and pre/post snapshots), it can detect the divergence. If it reads natural-language branch summaries, it cannot. Outside these conditions — e.g., a fully sandboxed filesystem with copy-on-write and a deterministic merge — the leak is bounded by the sandbox and this record does not apply. ## Decision Boundary The decision boundary is **where the fork/merge barrier is placed relative to effect commitment**. Three regimes: - **Effect-quiesced merge (safe):** The orchestrator does not permit the reconciler to run until every branch has either (a) committed its effects and reported them as an append-only effect log with idempotency keys, or (b) been *drained* — its in-flight tool calls cancelled and their outcomes awaited and recorded. Only then does reconciliation operate on committed effects. Cost: latency equal to the slowest branch's drain. - **Optimistic merge with compensating audit (bounded risk):** Reconciliation runs on summaries immediately, but every accepted and rejected branch's effect log is replayed against the environment post-merge; any effect attributable to a rejected branch triggers a compensating action (tombstone the duplicate publish, restore the deleted key from the pre-fork snapshot). Cost: requires pre-fork snapshots of every mutable resource and a compensation handler per tool. This is the only regime that tolerates concurrency without serializing on drain. - **Summary-only merge (unsafe under the stated conditions):** Reconciliation trusts branch summaries. Divergence is undetectable by construction. This is the regime that produced the observed failure. The invariant to enforce: **no branch may be marked `rolled_back` until all of its issued tool calls have reached a terminal, recorded state, and the reconciler's view is derived from committed effects, not intended ones.** A branch in `rolling_back` with in-flight effects is a forbidden state — it must transition through `draining` to `drained` before `rolled_back`. ## Operational Effect Enforcing the invariant changes the system in four concrete ways: 1. **Fork points must snapshot mutable resources.** A speculative fork without a pre-fork snapshot of every resource any branch can mutate cannot support compensation and therefore cannot safely use optimistic merge. Snapshot cost is the price of concurrency. 2. **Tool calls need idempotency keys derived from `(branch_id, call_seq)`**, so that a post-merge audit can attribute any environmental effect to a specific branch and distinguish a leaked duplicate from a legitimate retry. 3. **The reconciler's input schema must carry effect provenance**, not just intent. A summary that says "wrote cfg=v2" is insufficient; it must say "committed write cfg=v2 with call_id, post-snapshot hash." The LLM judge can then be asked to detect provenance mismatches, but the *detection* of leakage must be deterministic — the judge is a fallback, not the guard. 4. **The merge barrier becomes a drain barrier.** Latency increases by the tail of the slowest branch's tool latency, and the orchestrator must handle a branch whose tool call hangs — it cannot be rolled back, only drained-with-timeout, and a timed-out drain is itself a leak risk requiring escalation. The residual risk under the safe regime is zero for the leak itself but nonzero for *drain timeout*: a branch whose tool never returns forces a choice between blocking the merge indefinitely and rolling back with an unknown effect. That residual is irreducible without tool-level cancellation guarantees, and should be surfaced as an explicit `UndrainedBranchError` rather than silently absorbed into the merge. ```python from dataclasses import dataclass, field from enum import Enum from typing import Optional class SpeculativeCommitLeak(RuntimeError): """Raised when a branch is rolled back while its tool effects remain uncommitted or unaudited.""" class BranchState(Enum): FORKED = "forked" EXECUTING = "executing" DRAINING = "draining" DRAINED = "drained" ROLLED_BACK = "rolled_back" COMMITTED = "committed" @dataclass class EffectLog: branch_id: str call_seq: int tool: str idempotency_key: str committed: bool = False reversible: bool = True def key(self) -> tuple: return (self.branch_id, self.call_seq) @dataclass class Branch: branch_id: str state: BranchState = BranchState.FORKED effects: list = field(default_factory=list) drain_timeout_s: float = 30.0 class SpeculativeOrchestrator: def __init__(self, pre_fork_snapshot: dict): self.snapshot = pre_fork_snapshot self.branches: dict = {} self.committed_effects: list = [] def rollback_branch(self, branch: Branch) -> None: # Invariant: a branch may only reach ROLLED_BACK via DRAINING -> DRAINED. if branch.state in (BranchState.EXECUTING, BranchState.FORKED): raise SpeculativeCommitLeak( f"branch {branch.branch_id} rolled back from {branch.state.value} " f"with {len(branch.effects)} effects possibly in flight; " f"must drain first" ) if branch.state is BranchState.DRAINING: raise SpeculativeCommitLeak( f"branch {branch.branch_id} rollback attempted mid-drain; " f"drain_timeout={branch.drain_timeout_s}s not yet resolved" ) if branch.state is not BranchState.DRAINED: raise SpeculativeCommitLeak( f"branch {branch.branch_id} in unexpected state {branch.state.value}" ) leaked = [e for e in branch.effects if not e.reversible and e.committed] if leaked: raise SpeculativeCommitLeak( f"branch {branch.branch_id} has {len(leaked)} irreversible committed " f"effects with no compensation handler: " f"{[e.idempotency_key for e in leaked]}" ) branch.state = BranchState.ROLLED_BACK def merge(self, surviving: Branch, discarded: list) -> dict: # Reconciliation input is committed effects only, never branch summaries. for b in discarded: self.rollback_branch(b) merged = dict(self.snapshot) for e in surviving.effects: if e.committed: merged[e.idempotency_key] = e.tool # Post-merge audit: any committed effect attributable to a discarded branch # that is not in the merged state is a leak. discarded_ids = {b.branch_id for b in discarded} for e in self.committed_effects: if e.branch_id in discarded_ids and e.idempotency_key not in merged: raise SpeculativeCommitLeak( f"post-merge audit: effect {e.idempotency_key} from discarded " f"branch {e.branch_id} present in environment but absent from merge" ) return merged ```