# When must an instance refuse to commit a speculative branch: the side-effect compensation invariant in parallel agent rollouts **Date of Record:** 2026 November 29 **Scope:** Applies to any orchestrator that fans out speculative agent branches which pre-execute tools with real external side effects (writes, sends, payments, deploys) and later commits exactly one branch. Does not apply to read-only speculation or purely sandboxed branches with no external effect surface. ## Core Distinction The distinction that matters is between **speculation as computation** and **speculation as commitment**. When an agent branch pre-executes a tool call, it produces two separable artifacts: a *result* (what the model will condition on) and an *effect* (what the world now reflects). Most speculative-execution designs treat these as fused—the branch runs, the tool fires, the result is captured. That is correct only when the tool is idempotent and reversible. The boundary failure appears when a branch produces an effect that is **non-compensable**: the rollback path cannot restore the pre-state, so discarding the branch leaves an orphaned side effect whose existence the committed trajectory never models. The invariant is therefore not "roll back losing branches." It is: **a branch may be committed only if every effect it emitted is either (a) still live and owned by the winning branch, or (b) provably compensated by a compensation whose success is acknowledged before commit.** A branch that emitted a non-compensable effect and lost the race must force the orchestrator into a *reconciliation* state, not a silent discard. ## What Was Observed A planner agent fans out three branches for a refund workflow. Branch A calls `refund.create(order=42, amount=50)`. Branch B calls `refund.create(order=42, amount=50)` with a different rationale. Branch C calls `notify.customer(order=42, "refund issued")`. The branches run in parallel; the orchestrator's commit rule is "first branch whose verifier passes wins; discard the rest." A's verifier passes on a stale inventory read; B's verifier passes on the fresh read. Both effects are emitted. The orchestrator commits B and issues rollback to A. A's rollback calls `refund.cancel(refund_id_A)`—but the payment processor's `refund.create` is **not idempotent across distinct client tokens**, so A and B created two distinct refunds. The `cancel` on A succeeds, but the customer notification from C already fired referencing a refund that was then canceled. Net state: one live refund (B), one canceled refund (A), one false notification (C). The committed trajectory contains only B and believes the world matches its model. It does not. The failure is silent because each individual rollback returned `200 OK`. The invariant violation is at the **aggregate** level: no single branch is responsible for the cross-branch effect reconciliation, and the orchestrator's commit predicate only inspects the winning branch. ## Condition of Validity The "discard losing branches" rule is valid only under the conjunction: 1. **Effect idempotency keyed by branch-independent identity.** Every pre-executed effect carries a deterministic idempotency key derived from the *task* (e.g., `hash(order_id, refund_intent)`), not from the branch id. Two branches attempting the same refund then collapse to one effect at the tool layer, and rollback of the loser is a no-op rather than a compensating cancel. 2. **Compensation acknowledgment precedes commit.** The orchestrator may not transition to `COMMITTED` until every losing branch's compensation has returned a terminal success *and* that success has been re-read (not merely accepted from the response body). A `200 OK` on a cancel is not proof of cancellation. 3. **Effect closure is monotone.** No branch may emit an effect that depends on a *different* branch's effect (C's notification referencing A's refund). Cross-branch effect dependencies must be declared in the branch plan and ordered after commit, never speculated. When any of these fails, the commit predicate is unsound and the orchestrator must refuse to commit. ## Decision Boundary The precise boundary: **commit is permitted iff the set of emitted effects across all branches, after compensation of losers, equals the set of effects the winning trajectory will assume exist.** Formally, let `E_emitted` be the multiset of effects fired, `E_compensated` the subset provably reverted, and `E_assumed` the effects the committed plan's world model contains. Commit requires `E_emitted \ E_compensated == E_assumed`. When this equality cannot be established—because a compensation is unacknowledged, because an effect is non-compensable, or because a cross-branch dependency was speculated—the orchestrator enters `RECONCILIATION_REQUIRED` and halts further fan-out. The non-obvious part: a branch can be *semantically correct* and still be un-committable. B's refund is the right refund. But the presence of A's orphaned notification means the world no longer matches B's model, and committing B propagates a false belief into the next task's context. ## Operational Effect Orchestrators that enforce this invariant pay a latency cost—compensation acknowledgment is a synchronous barrier before commit—and a fan-out cost, since branches whose effects cannot be isolated are serialized rather than speculated. In exchange, they eliminate the class of "committed trajectory diverges from world state" failures that are invisible to per-branch verifiers and only surface as downstream contradictions (customer complains about a refund the agent's memory says was never issued). The reconciliation state must itself be a first-class, resumable checkpoint: it carries the emitted-effect ledger so a resumed instance can finish compensation rather than re-fan-out and duplicate effects. ```python from dataclasses import dataclass, field from enum import Enum from typing import Optional class SpeculativeCommitError(RuntimeError): """Raised when a speculative branch set cannot be safely committed.""" class EffectKind(Enum): COMPENSABLE = "compensable" NON_COMPENSABLE = "non_compensable" @dataclass class Effect: branch_id: str idempotency_key: str # task-derived, NOT branch-derived kind: EffectKind compensated: bool = False compensation_acked: bool = False @dataclass class BranchLedger: effects: list[Effect] = field(default_factory=list) def emitted_keys(self) -> set[str]: return {e.idempotency_key for e in self.effects} def uncompensated(self) -> list[Effect]: return [e for e in self.effects if not (e.compensated and e.compensation_acked)] def assert_committable( ledger: BranchLedger, winning_branch_id: str, assumed_effect_keys: set[str], ) -> None: """ Enforce: E_emitted \\ E_compensated == E_assumed before commit. Refuses commit if any losing branch left a non-compensable or unacknowledged effect, or if the assumed set diverges from live effects. """ # 1. Idempotency keys must be task-derived, so duplicate intents collapse. keys = ledger.emitted_keys() if len(keys) != len(ledger.effects): # Duplicate idempotency keys mean two branches fired the same intent; # the tool layer should have collapsed them, so this is a protocol bug. raise SpeculativeCommitError( f"duplicate idempotency keys across branches: {keys}" ) # 2. No losing branch may leave a non-compensable effect behind. for e in ledger.effects: if e.branch_id == winning_branch_id: continue if e.kind is EffectKind.NON_COMPENSABLE: raise SpeculativeCommitError( f"branch {e.branch_id} emitted non-compensable effect " f"{e.idempotency_key}; commit would orphan it" ) if not (e.compensated and e.compensation_acked): raise SpeculativeCommitError( f"branch {e.branch_id} effect {e.idempotency_key} " f"compensation unacknowledged; cannot commit" ) # 3. The committed plan's assumed effects must equal the live effect set. live = {e.idempotency_key for e in ledger.effects if not e.compensated} if live != assumed_effect_keys: raise SpeculativeCommitError( f"effect closure mismatch: live={live} assumed={assumed_effect_keys}" ) def commit_branch(ledger: BranchLedger, winner: str, assumed: set[str]) -> str: assert_committable(ledger, winner, assumed) return "COMMITTED" if __name__ == "__main__": # Two branches attempt the same refund intent (same idempotency key): # the tool layer collapses them, so only one effect exists. ledger = BranchLedger(effects=[ Effect("A", "refund:order42:50", EffectKind.COMPENSABLE, compensated=True, compensation_acked=True), Effect("B", "refund:order42:50", EffectKind.COMPENSABLE), ]) # Duplicate keys -> protocol bug, refuse. try: commit_branch(ledger, "B", {"refund:order42:50"}) except SpeculativeCommitError as exc: print("refused:", exc) ```