# Which invariants prevent speculative branch commits from surviving a rollback that never replayed their side effects **Date of Record:** 2026 November 22 **Scope:** Applies to multi-agent orchestrators that speculatively fork sibling branches, execute tool calls optimistically before verification, and commit the winning branch while rolling back losers. Does not apply to strictly serial single-agent loops or to branches whose tool calls are fully idempotent and externally reconciled. ## Core Distinction The failure here is not that a speculative branch produced a wrong answer. It is that a *losing* branch's optimistic tool side effect escaped the rollback envelope and became visible to the *committed* branch's subsequent reasoning. Rollback in most orchestrators is modeled as a state operation: discard the loser's message log, discard its scratchpad, restore the parent context. But an optimistic tool invocation is not state inside the agent — it is an effect *outside* the agent (a write to a ticket, a row insert, a sent email, a cache mutation). Rolling back the transcript does not roll back the world. The result is a committed branch reasoning over a world that contains residue from a branch the system believes never happened. The core distinction: **transcript rollback and effect rollback are two different invariants, and only one of them is usually implemented.** A branch is "rolled back" in the transcript sense when its context is dropped. It is rolled back in the effect sense only when every optimistic invocation it issued has been either compensated, fenced, or proven never to have committed. Optimistic execution decouples these two, and the gap between them is where divergence lives. ## What Was Observed A planner agent forks three speculative branches to resolve an ambiguous user request. Each branch is given the same parent context and a subtask. Branch B decides the correct action is to create a provisioning record and calls `provision_resource(id=42)` optimistically — the orchestrator allows the call to proceed before the verifier has scored the branch, on the assumption that losers will be rolled back. The verifier scores Branch A highest and commits it. Branch B is rolled back: its transcript is dropped, its sequence number invalidated, its token budget reclaimed. The committed Branch A then calls `provision_resource(id=42)` itself, as the correct path requires. The tool returns `409 Conflict — resource already exists`. Branch A's reasoning loop interprets this as "the resource pre-exists, so provisioning is unnecessary," skips the dependent configuration step, and reports success. The final answer is wrong, and no error was raised anywhere. The orphaned write from Branch B silently rewrote the committed branch's model of the world. The trace shows three facts that are individually reasonable and jointly fatal: 1. The optimistic call from B committed at the tool layer with a real, durable effect. 2. B's rollback was transcript-only; no compensating `deprovision_resource(42)` was issued because the orchestrator had no record that B held an *outstanding effect* — only that B held a *discarded context*. 3. A's error handling treated `409` as a benign precondition rather than as evidence of foreign state. The compounding step is (3). Even a correct rollback that merely *fails to compensate* would surface as a conflict; the divergence only becomes silent because the committed branch's tool-error policy classifies the conflict as expected. Optimistic execution plus a lenient conflict policy converts a detectable rollback leak into an undetectable reasoning error. ## Condition of Validity The invariant that bounds this failure is: **an optimistic effect may be committed only if the orchestrator holds a durable, branch-tagged effect record that survives transcript rollback, and every rollback path must drain that record via compensation or fencing before any sibling branch can observe the affected resource.** This is valid — and rollback is safe — only when all of the following hold: - Every optimistic invocation is registered in an effect ledger keyed by `(branch_id, resource_id, idempotency_token)` at issue time, not at commit time. A ledger written at commit time cannot record effects that were never committed but did execute. - Rollback is defined as a *drain* operation over the ledger, not a *discard* operation over the transcript. The two must be coupled: no branch is marked rolled-back until its ledger entries reach a terminal state (`compensated`, `fenced`, or `never_committed`). - The committed branch's tool-error policy distinguishes *foreign-state conflicts* (a `409` whose owning branch is not me) from *expected precondition conflicts*. A conflict attributable to an unresolved sibling effect must escalate, not degrade gracefully. - Fencing is available for effects that cannot be compensated (sent messages, external API calls). A fenced effect must be visible to the committed branch as a known-foreign artifact, so its reasoning can account for it rather than collide with it. When any of these is absent, the system is in the invalid regime: it is speculating on effects it cannot retract and committing branches that cannot see the residue. ## Decision Boundary The boundary between safe and unsafe speculation is drawn at the moment a branch issues its first non-compensable or conflict-generating effect. Before that point, rollback is a pure transcript operation and speculation is free. After it, rollback requires draining the ledger, and the orchestrator must choose one of two policies: - **Fence-and-proceed:** allow the optimistic effect, register it, and on rollback mark it `fenced`. The committed branch is then required to treat the resource as foreign-occupied and route around it. This preserves parallelism at the cost of committed branches that must reason about artifacts they did not create. - **Speculate-then-serialize:** allow speculative *reasoning* but defer the actual invocation until the branch is committed. This eliminates the leak entirely at the cost of losing the latency benefit of optimistic execution on exactly the effects that matter most. The wrong choice — and the one most systems make by default — is to allow optimistic invocation while keeping transcript-only rollback. That combination is not a policy; it is an unhandled interleaving. The decision boundary is therefore: **optimistic invocation is permissible only under fence-and-proceed with a durable effect ledger; absent the ledger, the only sound policy is speculate-then-serialize.** There is no third option where effects commit and rollback stays cheap. A secondary boundary governs the committed branch's conflict handling. A `409` is benign only when the orchestrator can prove the conflicting resource was created outside the speculative envelope (prior epoch, external actor). If the conflict's owner is an unresolved sibling, the committed branch must not interpret it as a precondition — it must halt or re-plan, because its world model is contaminated. ## Operational Effect When the invariant holds, speculative multi-agent execution retains its latency advantage on reasoning while confining effect risk to a ledger that is drained deterministically. Committed branches see fenced artifacts as explicit foreign state and route around them; the `409` becomes a signal rather than a trap. The cost is a durable write per optimistic invocation and a compensation path per effect class — real overhead, but bounded and auditable. When the invariant fails, the system exhibits *silent cross-branch contamination*: a committed branch's reasoning is corrupted by a rolled-back branch's residue, with no error surfaced at any layer. The failure is non-deterministic (depends on fork timing and tool latency), non-reproducible from transcripts alone (the evidence lives in the effect layer, not the message log), and biased toward false success (lenient conflict policies convert collisions into "already done"). This is the most dangerous class of multi-agent failure because every observable signal — the committed branch's transcript, the verifier's score, the final answer — looks correct. The operational guardrail is to treat the effect ledger as the source of truth for rollback completeness, and to make the committed branch's tool-error policy fail closed on any conflict it cannot attribute to a non-sibling owner. ```python import time from dataclasses import dataclass, field from enum import Enum from typing import Dict, Optional class EffectState(Enum): ISSUED = "issued" COMMITTED = "committed" COMPENSATED = "compensated" FENCED = "fenced" NEVER_COMMITTED = "never_committed" class RollbackLeakError(RuntimeError): """Raised when a branch is rolled back while it still holds an outstanding optimistic effect that no sibling can safely observe.""" class ForeignStateConflictError(RuntimeError): """Raised when a committed branch hits a tool conflict whose owning branch is an unresolved sibling, indicating contaminated world state.""" @dataclass class EffectRecord: branch_id: str resource_id: int idempotency_token: str state: EffectState = EffectState.ISSUED compensable: bool = True @dataclass class EffectLedger: records: Dict[str, EffectRecord] = field(default_factory=dict) def register(self, rec: EffectRecord) -> None: # Keyed by branch+resource so rollback can drain per-branch. self.records[f"{rec.branch_id}:{rec.resource_id}"] = rec def outstanding_for(self, branch_id: str) -> list: return [ r for r in self.records.values() if r.branch_id == branch_id and r.state in (EffectState.ISSUED, EffectState.COMMITTED) ] def drain(self, branch_id: str) -> None: """Rollback = drain, not discard. Every outstanding effect must reach a terminal state before the branch is considered rolled back.""" for rec in self.outstanding_for(branch_id): if rec.compensable: # issue compensating call, then mark rec.state = EffectState.COMPENSATED else: # non-compensable: must be fenced so siblings see it rec.state = EffectState.FENCED def owner_of(self, resource_id: int) -> Optional[str]: for rec in self.records.values(): if rec.resource_id == resource_id and rec.state in ( EffectState.ISSUED, EffectState.COMMITTED, EffectState.FENCED, ): return rec.branch_id return None def rollback_branch(ledger: EffectLedger, branch_id: str) -> None: outstanding = ledger.outstanding_for(branch_id) # Invariant: transcript rollback must not precede effect drain. # If drain cannot complete, we must NOT mark the branch rolled back. try: ledger.drain(branch_id) except Exception as exc: raise RollbackLeakError( f"branch {branch_id} rollback failed to drain " f"{len(outstanding)} outstanding effect(s): {exc}" ) from exc still_outstanding = ledger.outstanding_for(branch_id) if still_outstanding: raise RollbackLeakError( f"branch {branch_id} rolled back with " f"{len(still_outstanding)} live effect(s) still visible to siblings" ) def handle_tool_conflict( ledger: EffectLedger, committed_branch: str, resource_id: int, status_code: int, ) -> None: if status_code != 409: return owner = ledger.owner_of(resource_id) if owner is None: return # genuine pre-existing resource, benign if owner != committed_branch: # Conflict owned by a sibling (possibly rolled-back) branch: # committed branch's world model is contaminated. raise ForeignStateConflictError( f"committed branch {committed_branch} hit 409 on resource " f"{resource_id} owned by sibling {owner}; " f"refusing to treat as benign precondition" ) def speculative_round(ledger: EffectLedger, winner: str, losers: list) -> None: for loser in losers: rollback_branch(ledger, loser) # Only after all losers drained may the winner observe shared resources. for rec in ledger.records.values(): if rec.state == EffectState.FENCED and rec.branch_id in losers: # winner must route around fenced artifacts; surface as conflict handle_tool_conflict(ledger, winner, rec.resource_id, 409) ```