# Where must an instance reconcile speculative side effects before branch commit, and why the "compensate-on-rollback" invariant fails under concurrent sibling branches **Date of Record:** 2026 November 28 **Scope:** Applies to multi-agent orchestration patterns where a planner agent forks N speculative branches (each a sub-agent with its own tool-calling loop) that execute in parallel against shared external effectors (file writes, API mutations, message sends, DB inserts), and where exactly one branch is committed while the rest are rolled back. Does not apply to read-only speculative fan-out, nor to branch isolation enforced by full transactional sandboxing where effectors natively support two-phase commit. ## Core Distinction The naive mental model treats speculative branch rollback as *compensation*: branch B fails or loses the commit race, so the orchestrator invokes B's inverse operations (delete the file, refund the call, retract the message) and the world returns to its pre-fork state. This model is wrong for a specific and non-obvious reason: **compensation is not idempotent under concurrency, and speculative siblings routinely produce colliding effects on the same effector key.** The distinction that matters operationally is between two different invariants that are easy to conflate: - **Per-branch atomicity:** "each branch's effect set is either fully applied or fully retracted." - **Cross-branch exclusivity:** "no external effector key is mutated by two branches such that retracting one corrupts the other's committed state." A system can satisfy per-branch atomicity perfectly and still violate cross-branch exclusivity, because branch A's compensation (e.g., `DELETE /resource/42`) is indistinguishable from a legitimate mutation when branch B has since *adopted* the same resource. The failure is not a rollback bug; it is a **commit-ordering hazard masquerading as a rollback bug**. The compensation for a losing branch executes against a world that the winning branch has already advanced, and the inverse operation is computed from the losing branch's *stale* view of the effector. The correct framing: rollback is not the inverse of execution. Rollback is a *new forward operation* whose preconditions must be re-validated against current world state, and those preconditions are almost never captured in the branch's recorded effect log. ## What Was Observed A planner agent received the task "provision a staging environment and register it in the service catalog." It forked three speculative branches with different provisioning strategies: - **Branch 1 (terraform):** called `catalog.reserve_slot(name="staging-7")` → returned slot id `7`, then began `terraform apply`. - **Branch 2 (manual API):** also called `catalog.reserve_slot(name="staging-7")` — the catalog's reservation endpoint was **idempotent-by-name**, so it returned the *same* slot id `7`. - **Branch 3 (pulumi):** called `catalog.reserve_slot(name="staging-7")`, again returned `7`, then failed fast on a missing credential. Branch 1 won the commit race. The orchestrator committed branch 1 and issued rollback for branches 2 and 3. Each losing branch's effect log contained `reserve_slot(7)` and therefore its compensation was `release_slot(7)`. Both compensations fired **after** branch 1's commit. The catalog now reported slot `7` as free while the provisioned environment was live and pointed at it. A subsequent unrelated agent, seeing slot `7` free, reserved it for a different tenant. The staging environment silently became cross-tenant. The failure trace, precisely: 1. `reserve_slot` was idempotent on `name`, so three branches observed the *same* effector identity. The effect logs recorded three reservations of id `7` but only one reservation actually occurred at the effector. 2. The orchestrator's commit protocol assumed **effect-log cardinality equals effector mutation cardinality.** It did not. The log had 3 entries; the world had 1 mutation. 3. Compensation was computed per-branch from the branch-local log, so `release_slot(7)` was emitted twice. The effector treated `release` as idempotent too, so the second release was a no-op — but the *first* release was the fatal one, because it ran after the winner's commit. 4. No branch recorded *which* reservation it "owned," because the reservation was keyed by name, not by a per-branch lease token. Ownership was unrepresentable in the effect log. The second observed instance was the mirror image on a non-idempotent effector: two branches each called `POST /webhooks` with the same payload, producing **two** distinct webhook registrations (distinct server-assigned ids). The winner's commit kept its registration; the loser's compensation deleted *its own* id — correct — but the orchestrator's dedup layer, seeing identical payloads, had collapsed the two log entries into one and only issued one compensation. One orphaned webhook survived, firing duplicate events for weeks. ## Condition of Validity The "compensate-on-rollback" protocol is valid **only** when all four of the following hold simultaneously: 1. **Effect identity is branch-unique.** Every effector mutation carries a token minted by the branch (e.g., `Idempotency-Key: branch-{id}-{seq}`), so compensation can target exactly the mutation that branch caused and no other. Name-keyed or content-keyed effectors violate this and must be wrapped by the orchestrator with a lease layer before forking. 2. **Compensation preconditions are re-validated at execution time, not at log time.** The inverse operation must assert that the world still matches the post-state the branch left, and abort (escalate to human/orphan queue) if it does not. `release_slot(7)` must fail if slot `7`'s current holder is not this branch's lease. 3. **Commit is serialized against compensation on the same effector key.** The orchestrator must not allow a winner's commit to interleave with a loser's compensation on key `K`. This requires a per-key commit lock or a total order over (commit, compensate) events for each key — not just a global barrier at the end. 4. **Effect-log cardinality is reconciled against effector state before compensation is scheduled.** The orchestrator must query the effector for actual mutations attributable to the fork and diff against the union of branch logs, treating any discrepancy as an orphan to be quarantined, not silently compensated. When any of these fails, the system does not merely "roll back imperfectly" — it **actively corrupts the winner's committed state**, which is strictly worse than leaving the loser's effects in place. An orphaned side effect is recoverable; a wrongly-compensated committed effect is a silent integrity violation. ## Decision Boundary The operational decision is **when to compensate versus when to quarantine**, and it hinges on a single test performed at compensation-scheduling time: > *Can the compensation prove, against current effector state, that it is retracting exactly the mutation this branch caused and nothing the committed branch depends on?* - If **yes** → compensate inline, under the per-key commit lock, before releasing the fork barrier. - If **no** (identity not branch-unique, or effector state has advanced past the branch's recorded post-state, or log/effector cardinality mismatch) → **do not compensate.** Move the effect to an orphaned-side-effect queue tagged with the fork id, the branch id, the effector key, and the observed-vs-recorded diff. The queue is drained by a reconciler that has authority to inspect the *committed* branch's state and decide whether the orphan is safe to retract. The boundary is crossed the moment the orchestrator schedules compensation based on branch-local logs alone. That is the precise line: **compensation computed from a branch's own effect log is unsafe by construction under any shared-key effector.** The safe protocol computes compensation from a *fork-global reconciliation* that includes the winner's committed state. A corollary boundary: idempotent effectors do **not** make compensation safe. Idempotency protects against duplicate *application*; it says nothing about duplicate *retraction* of a shared key. The two properties are orthogonal, and conflating them is the root cause of the first observed failure. ## Operational Effect After adopting fork-global reconciliation with branch-unique lease tokens, the observable regime changes in three ways: - **Fork latency increases by one effector round-trip per distinct key**, because reconciliation must read current state before scheduling any compensation. Forks touching many keys pay this per key; forks touching one key pay it once. This is the cost of correctness and cannot be amortized away without reintroducing the hazard. - **Orphan queue depth becomes a first-class health signal.** A nonzero, growing orphan queue means the effector's identity model is incompatible with the fork's lease model — an architectural signal, not a transient. Alert on *rate*, not depth. - **Commit must be a two-phase act:** (1) mark winner committed in the orchestrator's durable log, (2) release the per-key commit lock only after all losing-branch compensations for that key have either succeeded or been quarantined. Releasing the lock earlier reopens the interleaving window and the original failure returns verbatim. The invariant to encode in the orchestrator, stated as a guardrail: *no compensation for effector key K may execute unless the reconciler has confirmed, against live state, that K's current value is attributable to a losing branch and not to the committed branch.* Violations raise and route to the orphan queue rather than proceeding. ```python import time from dataclasses import dataclass, field from enum import Enum from typing import Dict, List, Optional class SpeculativeCommitError(RuntimeError): """Raised when a fork's commit/rollback protocol cannot preserve cross-branch exclusivity.""" pass class EffectDisposition(Enum): COMPENSATE = "compensate" QUARANTINE = "quarantine" @dataclass class EffectRecord: branch_id: str effector_key: str lease_token: Optional[str] # branch-unique token; None => identity not branch-unique recorded_post_state: dict # branch's stale view at log time applied: bool = True @dataclass class Fork: fork_id: str committed_branch: Optional[str] = None effects: List[EffectRecord] = field(default_factory=list) class ForkReconciler: """ Enforces the invariant: no compensation for effector key K executes unless live state proves K is attributable to a losing branch, not the committed branch. """ def __init__(self, effector): self.effector = effector self.orphan_queue: List[dict] = [] def _live_state(self, key: str) -> dict: # Authoritative read against the effector, not the branch log. return self.effector.read(key) def schedule_compensation(self, fork: Fork, losing_branch_id: str) -> List[EffectDisposition]: if fork.committed_branch is None: raise SpeculativeCommitError( f"fork {fork.fork_id}: cannot schedule compensation before commit is durable" ) if losing_branch_id == fork.committed_branch: raise SpeculativeCommitError( f"fork {fork.fork_id}: attempted to compensate the committed branch " f"{losing_branch_id!r}; this is the corruption path, not rollback" ) dispositions: List[EffectDisposition] = [] losing = [e for e in fork.effects if e.branch_id == losing_branch_id] winner_keys = { e.effector_key for e in fork.effects if e.branch_id == fork.committed_branch } for eff in losing: key = eff.effector_key live = self._live_state(key) # Rule 1: identity must be branch-unique. if eff.lease_token is None: self._quarantine(fork, eff, live, "effect identity not branch-unique") dispositions.append(EffectDisposition.QUARANTINE) continue # Rule 2: live state must still match what this branch left behind. if live != eff.recorded_post_state: self._quarantine(fork, eff, live, "effector state advanced past branch post-state") dispositions.append(EffectDisposition.QUARANTINE) continue # Rule 3: key must not be shared with the committed branch. if key in winner_keys: self._quarantine(fork, eff, live, "effector key shared with committed branch") dispositions.append(EffectDisposition.QUARANTINE) continue # Safe: retract exactly this branch's mutation, under per-key lock. with self.effector.lock(key): if self._live_state(key) != eff.recorded_post_state: raise SpeculativeCommitError( f"fork {fork.fork_id}: key {key!r} mutated between validation and " f"compensation; per-key lock or total order is broken" ) self.effector.release(key, lease_token=eff.lease_token) dispositions.append(EffectDisposition.COMPENSATE) return dispositions def _quarantine(self, fork: Fork, eff: EffectRecord, live: dict, reason: str) -> None: self.orphan_queue.append({ "fork_id": fork.fork_id, "branch_id": eff.branch_id, "effector_key": eff.effector_key, "lease_token": eff.lease_token, "recorded_post_state": eff.recorded_post_state, "live_state": live, "reason": reason, "ts": time.time(), }) def commit_fork(reconciler: ForkReconciler, fork: Fork, winner: str, losers: List[str]) -> None: if winner not in {e.branch_id for e in fork.effects} and fork.effects: raise SpeculativeCommitError(f"fork {fork.fork_id}: winner {winner!r} has no recorded effects") # Phase 1: durable commit marker. fork.committed_branch = winner # Phase 2: reconcile every loser against live state before releasing the fork barrier. for loser in losers: reconciler.schedule_compensation(fork, loser) ```