# Why does an instance roll back a speculative branch and still commit the side effect it was hedging against **Date of Record:** 2026 November 23 **Scope:** Applies to orchestrators that fork multiple agent instances speculatively (branch-and-merge planning) and roll back losing branches by discarding their state on commitment failure. Does not apply to strictly sequential single-agent retry loops, nor to read-only speculative fan-out where no branch mutates external state. ## Core Distinction The distinction that matters is between **logical rollback** and **effect rollback**. A speculative branch-and-merge executor treats a branch as a unit of state: when a branch's commitment fails and the merge is aborted, the orchestrator discards the branch's context, its scratchpad, its message history, and its reserved identifiers. This is logical rollback — it is cheap, deterministic, and the orchestrator's bookkeeping can prove it happened. But an agent branch is not a pure function. Each branch executes tool calls against external systems — it writes to a queue, opens a ticket, charges a ledger, sends a message, mutates a shared vector store, appends to an append-only log. These effects are **not** owned by the orchestrator's transaction boundary. When a losing branch is rolled back, its *reasoning* disappears but its *effects* persist. The invariant an orchestrator must maintain is therefore not "rolled-back branches leave no trace" (false) but "every committed effect is attributable to exactly one surviving branch, and every orphaned effect is either compensated or quarantined before merge." Most implementations enforce the first, impossible invariant and silently violate the second. The non-obvious part: the failure is *invisible at rollback time*. The branch that gets discarded is the one that failed its commitment check, so the orchestrator's logs show a clean abort. The orphaned effects only surface later, when a downstream consumer observes a ticket that no surviving plan references, or a ledger entry whose idempotency key belongs to a branch that no longer exists. ## What Was Observed A planner forked three speculative branches to satisfy a single user intent: `branch-A` (primary, high-confidence), `branch-B` (fallback, lower-confidence), `branch-C` (hedge against a specific ambiguity in the request). Each branch was given a shared tool grant and a distinct `speculation_id`. The merge policy: commit the first branch whose commitment check passes; roll back the rest. The trace: 1. `branch-C` runs first (scheduler ordering is not guaranteed under load). It resolves the ambiguity by calling `create_refund(order_id, amount)` against the payments tool. The tool returns success with `refund_id=R-8812`. `branch-C` records `R-8812` in its scratchpad and proceeds. 2. `branch-C`'s commitment check fails — it cannot verify a downstream precondition (the order's fulfillment state flipped between read and write). The orchestrator marks `branch-C` failed and rolls it back: context dropped, `speculation_id` retired. 3. `branch-A` passes its commitment check and commits. `branch-A`'s plan does *not* include a refund; it chose a different resolution path. Merge succeeds. The orchestrator reports a clean single-branch commit. 4. `branch-A`'s plan later calls `create_refund` for the same `order_id` — because the user intent genuinely required a refund, and `branch-A` reached that decision independently. The payments tool, keyed on `(order_id, amount)` rather than on `speculation_id`, **rejects the second call as a duplicate** and returns the *existing* `refund_id=R-8812` — the one created by the rolled-back branch. 5. `branch-A` now holds a reference to `R-8812`, which it believes it created. The orchestrator's merge record attributes `R-8812` to `branch-A`. The rolled-back `branch-C` is gone from all bookkeeping, yet its effect is the surviving effect. The observable symptom was not an error. It was a *silent misattribution*: the audit trail claimed `branch-A` produced `R-8812`, but `branch-A` never executed the call that created it. When `branch-A` later attempted to compensate `R-8812` (issue a reversal), the reversal succeeded — but the compensation was logged against `branch-A`'s transaction, while the original debit had been logged against `branch-C`'s now-orphaned `speculation_id`. The two halves of the refund lifecycle lived in different, unreconcilable ledgers. ## Condition of Validity The rollback-on-failed-commitment pattern is only sound when **all** of the following hold. If any fails, the pattern produces orphaned effects: - **Effect idempotency is scoped to the branch, not the resource.** The external tool must key idempotency on `speculation_id` (or an equivalent branch-unique token), so that a surviving branch's call is a *distinct* effect from a rolled-back branch's call, even if their payloads are identical. Keying on `(resource, payload)` — the natural choice — collapses distinct branches into one effect and makes the orphan unobservable. - **Commitment checks are evaluated on read-after-write state, not on cached reads.** `branch-C` failed because it read a precondition that was stale by the time it wrote. The check must re-read the contended state immediately before commit, or the branch may commit an effect whose precondition was already invalid. - **The merge policy is deterministic with respect to effect creation order.** If branches can create effects in any order (as here, where `branch-C` ran first despite being the hedge), the merge record cannot assume "the committed branch is the one that created the effect." Effect attribution must be derived from `speculation_id` on the effect itself, never inferred from execution order. - **Compensation is branch-aware.** A compensation of an orphaned effect must be issued against the orphan's `speculation_id`, not the surviving branch's. Otherwise the ledger splits. The pattern is *invalid* whenever the external tool's idempotency key does not include a branch discriminator, or whenever the orchestrator infers effect ownership from merge order rather than from an effect-side token. ## Decision Boundary The boundary is the point at which a branch's tool call becomes **externally durable** — the moment the external system commits the write and returns an identifier. Before that point, rollback is total: the branch's state is discardable and no effect exists. After that point, rollback is *partial*: the branch's state is discardable but the effect is not, and the orchestrator must either (a) compensate the effect before retiring the branch, or (b) transfer ownership of the effect to a surviving branch with an explicit re-attribution record. The decision rule for a branch whose commitment check fails: - If the branch has **no externally durable effects**, roll back freely. This is the common case and the one the pattern was designed for. - If the branch has **durable effects and a surviving branch will re-issue an equivalent call**, do *not* rely on idempotency-key collision to deduplicate — that collision is exactly what produces the orphan misattribution. Instead, either compensate the orphan first, or pass the orphan's effect identifier to the surviving branch as an explicit inherited reference and record the re-attribution. - If the branch has **durable effects and no surviving branch will re-issue**, quarantine the orphan: mark its `speculation_id` as `orphaned_effect` and surface it to a reconciliation queue. Never retire the `speculation_id` while an effect bearing it is live. The invariant: **a `speculation_id` may be retired only when no externally durable effect carries it, or when every such effect has been compensated or explicitly re-attributed.** Retiring a `speculation_id` with live effects is the precise trigger for the failure above. ## Operational Effect The consequence of violating the invariant is a **split ledger**: the creation and the compensation of a single real-world effect are recorded under two different branch identities, one of which the orchestrator believes never existed. This is not a crash and not a data-loss event; it is a *reconciliation impossibility*. Downstream auditors, cost attribution, and compensation sweeps all key on branch identity, and none of them can join the two halves. The second-order effect is worse: because the surviving branch holds a valid effect handle (`R-8812`), it will *believe* it owns the effect and may issue further mutations against it (reversals, amendments, escalations). Each of those mutations is logged under the surviving branch, deepening the split. The orphaned branch's original debit becomes an unreferenced liability that no branch claims. The guardrail is a **retirement gate**: the orchestrator must query the effect registry for any live effects bearing the branch's `speculation_id` before retiring it, and refuse retirement if any exist. This gate is cheap (one indexed lookup per rolled-back branch) and converts the silent split into an explicit reconciliation event. ```python class OrphanedEffectRollbackError(RuntimeError): """Raised when a speculative branch is retired while externally durable effects still carry its speculation_id. Retiring in this state splits the effect's creation ledger from its compensation ledger and makes reconciliation impossible.""" pass class EffectRegistry: """Tracks externally durable effects keyed by the branch that created them. The registry is the source of truth for effect ownership, NOT the orchestrator's merge record.""" def __init__(self): self._effects_by_speculation = {} # speculation_id -> set[effect_id] def register(self, speculation_id: str, effect_id: str) -> None: self._effects_by_speculation.setdefault(speculation_id, set()).add(effect_id) def live_effects(self, speculation_id: str) -> set: return set(self._effects_by_speculation.get(speculation_id, set())) def compensate(self, speculation_id: str, effect_id: str) -> None: self._effects_by_speculation.get(speculation_id, set()).discard(effect_id) def reattribute(self, from_spec: str, to_spec: str, effect_id: str) -> None: self._effects_by_speculation.get(from_spec, set()).discard(effect_id) self._effects_by_speculation.setdefault(to_spec, set()).add(effect_id) def retire_branch( registry: EffectRegistry, speculation_id: str, surviving_speculation_id: str | None, compensate_first: bool = False, ) -> None: """Retire a rolled-back speculative branch. Enforces the retirement gate: a speculation_id may only be retired when it carries no live effects, or when every live effect has been compensated or explicitly re-attributed.""" live = registry.live_effects(speculation_id) if live and compensate_first: for effect_id in list(live): registry.compensate(speculation_id, effect_id) live = registry.live_effects(speculation_id) if live and surviving_speculation_id is not None: # Re-attribute rather than deduplicate by payload. The surviving branch # inherits the effect handle explicitly; the merge record must reflect # the re-attribution, not infer ownership from execution order. for effect_id in list(live): registry.reattribute(speculation_id, surviving_speculation_id, effect_id) live = registry.live_effects(speculation_id) if live: raise OrphanedEffectRollbackError( f"refusing to retire speculation_id={speculation_id!r}: " f"live effects {sorted(live)!r} still carry it. " f"Compensate them or re-attribute to a surviving branch first." ) # Safe to retire: no durable effect references this branch. registry._effects_by_speculation.pop(speculation_id, None) ```