# Which invariants prevent speculative branch commits from leaking side effects across an agent swarm **Date of Record:** 2026 November 23 **Scope:** Applies to multi-agent systems that run speculative execution branches (parallel candidate trajectories, speculative tool calls, or optimistic plan forks) and later commit exactly one branch while rolling back the rest. Does not apply to single-agent linear execution or to systems where every tool call is already idempotent and externally reversible. ## Core Distinction The distinction that matters is between *logical rollback* and *physical rollback*. A speculative branch can be logically discarded in O(1) time by dropping its state record, but the tool calls it already issued to the outside world—writes, payments, messages, file mutations, queue enqueues—are physical and persist independently of the agent's state graph. The invariant that prevents cross-branch contamination is not "rollback the branch," it is **"no speculative branch may perform a non-idempotent, non-warranted side effect before the commit protocol issues a commit token for that branch."** Systems that conflate logical discard with physical undo will pass all internal consistency tests and still corrupt external state, because the leak occurs in the gap between the agent's memory of what happened and what the world actually recorded. ## What Was Observed A planner agent forked three speculative branches to satisfy a single user request ("reconcile the two ledgers and file the discrepancy report"). Branch A chose a direct API write to the downstream accounting service. Branch B chose to stage a CSV and enqueue a job. Branch C chose to email the finance alias with an attachment. Each branch was assigned a distinct `branch_id` and a private context window; each was told, via the standard system preamble, that "your actions are speculative and will be rolled back if another branch commits." The auditor agent scored the branches and committed Branch B at step 14. The orchestrator then issued rollback signals to A and C. The rollback handler for A dropped the branch's state record and marked its pending tool calls `cancelled`. But Branch A had already issued `POST /ledger/reconcile` at step 9, which the downstream service had processed synchronously and acknowledged with a 201. The rollback handler never queried the downstream service—it only inspected the orchestrator's own call ledger, which recorded the call as `in_flight` at the time of cancellation and then transitioned it to `cancelled` without reconciling against the remote's actual state. The result: the ledger was reconciled twice (once by A's leaked write, once by B's staged job), the finance alias received a spurious email from C's branch (C's rollback was also logical-only), and the final report claimed a single reconciliation. The auditor's verification replay, run from the committed branch's trace alone, showed a clean, consistent execution. The discrepancy was only caught three days later by an external reconciliation audit. The non-obvious part: the branch preamble's promise of rollback was *believed by the branches themselves*. Branch A's reasoning trace explicitly notes "this write is safe because it will be rolled back if not selected." The agent's confidence in the rollback guarantee caused it to skip its own pre-write validation—it did not check whether the ledger was already reconciled, because it assumed the speculative frame made that check unnecessary. Speculation became a license for recklessness, and the license was counterfeit. ## Condition of Validity The "rollback makes speculation safe" claim is valid only when all four of the following hold simultaneously: 1. **Effect classification is complete and enforced at the transport layer, not the prompt layer.** Every tool exposed to a speculative branch must carry a machine-readable `effect_class` (`read_only`, `idempotent_write`, `non_idempotent_write`, `external_irreversible`). The dispatcher must refuse to route `non_idempotent_write` and `external_irreversible` calls from a branch whose `commit_token` is absent. A prompt instruction is not a guardrail; it is a suggestion the model may override under reasoning pressure. 2. **Commit tokens are single-use and branch-bound.** The commit protocol must mint a token binding `(branch_id, plan_hash, tool_call_sequence_hash)` and the dispatcher must verify the token against the actual call being made. A token issued for Branch B must be structurally unusable by Branch A, even if A's process is still live and has the token in memory. 3. **Rollback is a compensating transaction, not a state deletion.** For any branch that has issued an `idempotent_write` or better, rollback must issue an explicit compensating call and record the compensation's acknowledgment. Deleting the branch record without a compensation receipt is a logical rollback only, and the invariant does not hold. 4. **Verification replays against the external world, not the internal trace.** The auditor's consistency check must query the downstream services' actual state (or their idempotency-key logs) and compare against the union of all branches' issued calls, not just the committed branch's trace. A replay that reads only the orchestrator's memory will always agree with the orchestrator's memory. When any of these fails, the system is in a state where speculative branches can and will leak effects, and the leak is invisible to internal consistency checks. ## Decision Boundary The decision boundary is whether to allow *speculative side effects at all*. Two regimes: - **Effect-isolated speculation (safe):** Speculative branches may issue `read_only` calls freely and `idempotent_write` calls keyed by `(branch_id, call_index)` so that duplicate issuance is absorbed by the downstream's idempotency layer. `non_idempotent_write` and `external_irreversible` calls are *deferred*: the branch emits an intent record, and the commit protocol executes the intent only after the commit token is minted. This is the only regime in which the rollback promise is honest. - **Effect-permissive speculation (unsafe, but sometimes chosen):** Branches may issue any call, and the system relies on compensating transactions to undo losers. This is only defensible when every tool has a *verified* compensation (a tested inverse), the compensation itself is idempotent, and the compensation is issued before the branch record is dropped. In practice, "verified compensation" is rare for external services—most APIs have no undo endpoint—so this regime degrades to the failure above. The boundary is crossed the moment a branch is allowed to issue an `external_irreversible` call without a commit token, regardless of what the prompt says. The prompt is not the boundary; the dispatcher is. ## Operational Effect When the invariant holds (effect-isolated speculation), the orchestrator's rollback handler becomes trivial: it drops branch records and issues no compensations, because no compensations are needed. The cost is that speculative branches cannot "test" irreversible actions—they can only test their *plans* for such actions, which is a real loss of fidelity: a branch that would have discovered a downstream validation error at step 9 now discovers it only at commit time, after the commit token is spent. This is the correct trade: the loss is a latency and a re-plan, not a corrupted ledger. When the invariant fails (effect-permissive speculation without verified compensation), the operational signature is a specific pattern: internal traces are clean, auditor replays pass, and external reconciliation drifts. The drift is proportional to the number of speculative branches that issued irreversible calls, and it compounds because each leaked effect looks like an independent, plausible action to any downstream observer. The failure is not detected by the agent swarm; it is detected by the humans who reconcile the world. The guardrail that bounds the failure is a **pre-dispatch effect gate** that refuses any `non_idempotent_write` or `external_irreversible` call lacking a valid commit token, plus a **post-rollback reconciliation audit** that compares the union of all branches' issued calls against the downstream's idempotency-key log. The gate prevents the leak; the audit detects the gate's own failures. Neither is optional. ```python import hashlib from dataclasses import dataclass, field from typing import Optional class SpeculativeLeakError(RuntimeError): """Raised when a speculative branch attempts an effect it is not warranted to perform, or when a rollback is issued without a verified compensation receipt.""" pass EFFECT_CLASSES = {"read_only", "idempotent_write", "non_idempotent_write", "external_irreversible"} UNWARRANTED = {"non_idempotent_write", "external_irreversible"} @dataclass class CommitToken: branch_id: str plan_hash: str call_seq_hash: str def matches(self, branch_id: str, plan_hash: str, call_seq_hash: str) -> bool: return (self.branch_id == branch_id and self.plan_hash == plan_hash and self.call_seq_hash == call_seq_hash) @dataclass class Branch: branch_id: str plan_hash: str issued_calls: list = field(default_factory=list) committed: bool = False rolled_back: bool = False def _seq_hash(calls: list) -> str: h = hashlib.sha256() for c in calls: h.update(f"{c['tool']}:{c['effect_class']}:{c['idem_key']}".encode()) return h.hexdigest() def dispatch_tool_call(branch: Branch, tool: str, effect_class: str, idem_key: str, token: Optional[CommitToken]) -> dict: if effect_class not in EFFECT_CLASSES: raise SpeculativeLeakError(f"unknown effect_class={effect_class!r}") call = {"tool": tool, "effect_class": effect_class, "idem_key": idem_key} if effect_class in UNWARRANTED: if token is None: raise SpeculativeLeakError( f"branch {branch.branch_id} attempted {effect_class} call to {tool} " f"without a commit token; effect would leak past rollback" ) if not token.matches(branch.branch_id, branch.plan_hash, _seq_hash(branch.issued_calls)): raise SpeculativeLeakError( f"commit token does not bind to branch {branch.branch_id} " f"plan {branch.plan_hash}; refusing cross-branch warrant" ) if branch.rolled_back: raise SpeculativeLeakError( f"branch {branch.branch_id} is rolled back; commit token is stale" ) branch.issued_calls.append(call) return {"acknowledged": True, "call": call} def rollback_branch(branch: Branch) -> dict: if branch.committed: raise SpeculativeLeakError( f"cannot roll back committed branch {branch.branch_id}" ) leaked = [c for c in branch.issued_calls if c["effect_class"] in UNWARRANTED] if leaked: # This should be unreachable if dispatch_tool_call is the only path to effects. raise SpeculativeLeakError( f"branch {branch.branch_id} issued {len(leaked)} unwarranted effects; " f"logical rollback would leak them: {[c['tool'] for c in leaked]}" ) branch.rolled_back = True return {"rolled_back": True, "compensations_required": 0} def commit_branch(branch: Branch, token: CommitToken) -> dict: if branch.rolled_back: raise SpeculativeLeakError( f"branch {branch.branch_id} already rolled back; cannot commit" ) if not token.matches(branch.branch_id, branch.plan_hash, _seq_hash(branch.issued_calls)): raise SpeculativeLeakError( f"commit token does not bind to branch {branch.branch_id}; " f"possible token reuse across branches" ) branch.committed = True return {"committed": True, "branch_id": branch.branch_id} # --- Failure trace demonstrating the invariant --- def _demo(): b_a = Branch(branch_id="A", plan_hash="plan-direct-api") b_b = Branch(branch_id="B", plan_hash="plan-staged-csv") # Branch A tries a non-idempotent write with no token: gated. try: dispatch_tool_call(b_a, "POST /ledger/reconcile", "non_idempotent_write", idem_key="A-9", token=None) except SpeculativeLeakError as e: print("GATE HELD:", e) # Auditor commits B; token is bound to B only. tok_b = CommitToken(branch_id="B", plan_hash="plan-staged-csv", call_seq_hash=_seq_hash(b_b.issued_calls)) commit_branch(b_b, tok_b) # A cannot reuse B's token. try: dispatch_tool_call(b_a, "POST /ledger/reconcile", "non_idempotent_write", idem_key="A-9", token=tok_b) except SpeculativeLeakError as e: print("CROSS-BRANCH BLOCKED:", e) rollback_branch(b_a) print("A rolled back with zero compensations; no leak.") if __name__ == "__main__": _demo() ```