# Which invariants prevent orphaned side effects when speculative agent branches roll back after a shared-resource commit **Date of Record:** 2026 November 22 **Scope:** Applies to multi-agent systems where a planner spawns speculative branches (parallel sub-agents exploring alternative tool-call trajectories) that may be rolled back after one branch has already committed an irreversible external effect (file write, API mutation, message send, DB insert). Does not apply to pure read-only speculation or to systems where every external effect is mediated by a transactional coordinator that supports true two-phase commit with participant rollback. ## Core Distinction The naive model of speculative execution treats rollback as the inverse of forward execution: if branch B executed steps S1…Sn, rolling back means undoing Sn…S1. This holds for pure functions and for effects behind a transactional boundary. It fails for **irreversible external effects** — an HTTP POST that sent an email, a `git push`, a row inserted into a table with no compensating-delete contract, a file overwritten without a backup. The critical distinction is between **state the orchestrator owns** (its own context, scratchpad, branch-local memory, in-memory tree) and **state the environment owns** (side effects that left the process boundary). Rollback is total over the first and partial (compensation-only) over the second. The invariant that prevents orphaned side effects is not "rollback restores prior state" — it is **"no branch may commit an irreversible effect until it has been nominated as the sole survivor, and nomination is a global decision that excludes all sibling branches from further irreversible effects."** Speculation and irreversibility are fundamentally incompatible unless the commit point is hoisted above the branch fan-out. ## What Was Observed A three-branch speculative planner (branches A, B, C) was tasked with "update the deployment manifest and notify the team." Each branch ran independently with a full toolset. Branch A chose to edit `deploy.yaml` then POST to a webhook. Branch B chose to POST the webhook first (to "announce intent") then edit. Branch C chose to edit and then run a validation script that itself wrote a `.lock` file. The orchestrator's reconciliation logic selected branch C as the winner on a quality score. It then rolled back A and B by replaying their journal in reverse: A's webhook POST had no compensating action (the journal recorded it as `effect:external, reversible:false`, but the rollback handler logged a warning and continued), B's webhook POST likewise, B's manifest edit was reverted by restoring a snapshot. Result: the team received two "intent to deploy" notifications for a deploy that never happened, plus the winner's notification — three webhooks for one logical action. The lock file from C survived because C was not rolled back, but a *retry* of C after a validation failure would have found a stale lock and deadlocked. The failure trace: 1. Fan-out: planner clones base context into A, B, C. All three share the same external-effect namespace (same webhook URL, same repo, same filesystem). 2. Divergent execution: each branch independently reaches the "notify" step. No branch knows the others exist. 3. Local commit: each branch's journal marks its POST as `committed` because the HTTP 200 returned. 4. Global reconciliation: orchestrator picks C, marks A and B `discarded`. 5. Rollback: journal replay attempts compensation. For `reversible:false` effects the handler is a no-op-with-warning. Effects persist. 6. Orphan: two external effects now exist with no owning branch. The orchestrator's state tree has no record that they are "live" — they are recorded only as "uncompensated discards." The non-obvious part: **the orchestrator believed rollback succeeded** because its own state tree was consistent. The inconsistency lived entirely in the environment, invisible to any check the orchestrator ran on itself. ## Condition of Validity The "rollback restores prior state" invariant is valid only when, for every step in every branch, one of the following holds: - **Idempotent-and-owned:** the effect is keyed by a branch-scoped idempotency token, so a duplicate from a sibling is deduplicated at the environment, and the orchestrator can enumerate its own effects by token. - **Compensable-with-contract:** the environment exposes a documented compensating action that is itself idempotent (e.g., `DELETE /message/{id}` where the id was returned on create), and the journal recorded the handle needed to compensate. - **Deferred:** the effect was buffered in an orchestrator-owned outbox and not released until commit. If any branch step can produce an effect satisfying none of these, the branch is **not speculable** — it must run in a serialized commit phase after nomination. The invariant to enforce: *a branch may execute an irreversible effect only if the orchestrator has already entered commit phase for that branch, and commit phase is entered for at most one branch at a time.* This condition is violated the moment two branches can reach the same external namespace before nomination. Shared namespaces (a single webhook, a single repo branch, a single file path) are the tell. ## Decision Boundary The boundary between safe speculation and orphaned effects is crossed at the first irreversible effect executed **before** the global nomination decision. Practically, the orchestrator must classify each tool at dispatch time: - `PURE` — no external state change (read, compute, local scratchpad). Always speculable. - `COMPENSABLE` — external change with a registered inverse and a recorded handle. Speculable only if the handle is journaled synchronously before the next step, and rollback is verified by re-reading environment state, not by trusting the journal. - `IRREVERSIBLE` — external change with no inverse (send, push, charge, delete-without-backup). Never speculable. Must be gated behind a `commit_token` that only the nominated branch holds. The guardrail is a **commit-token gate**: the orchestrator issues a single-use token on nomination; irreversible tools refuse to execute without a valid token presented at call time, and the token is bound to the branch id. Sibling branches that reach an irreversible tool mid-speculation receive `DeferredEffect`, which parks the intended call in the outbox and returns a placeholder to the branch's reasoning loop. If that branch loses nomination, the outbox entry is dropped — never executed. If it wins, the outbox is drained under the token. The second guardrail is **rollback verification against the environment, not the journal**: after compensation, the orchestrator must re-query the external namespace (list messages by token, `git log`, file hash) and assert the effect is gone. A journal that says "compensated" is a claim; the environment is the fact. Discrepancy raises a hard fault and halts the swarm rather than continuing with a false-consistent state tree. ## Operational Effect With the commit-token gate and environment-verified rollback, the failure mode is bounded: speculative branches can still *plan* irreversible actions (they park them), so reasoning quality is preserved, but no irreversible effect can escape before nomination. The cost is latency on the commit path (nomination must serialize) and the requirement that every irreversible tool declare its classification and, where possible, accept an idempotency token. Without it, the system exhibits **silent external divergence**: the orchestrator's state tree is internally consistent and reports a clean rollback, while the environment accumulates orphaned effects that no branch owns. These orphans are the worst class of bug in agent systems because they are invisible to every self-check the orchestrator can run, and they compound — each speculative round can leak more, and downstream agents observing the environment will treat the orphans as ground truth, poisoning future reasoning. The invariant, stated once: *irreversibility and speculation are mutually exclusive per effect; hoist the commit point above the fan-out, gate irreversible tools on a single-use nomination token, and verify compensation against the environment rather than the journal.* ```python class OrphanedEffectError(RuntimeError): """Raised when a speculative branch attempts an irreversible effect before global nomination, or when rollback verification finds an uncompensated external effect.""" pass class EffectClass: PURE = "pure" COMPENSABLE = "compensable" IRREVERSIBLE = "irreversible" class CommitTokenGate: def __init__(self): self._nominated_branch = None self._token_consumed = False def nominate(self, branch_id): if self._nominated_branch is not None: raise OrphanedEffectError( f"nomination already held by {self._nominated_branch}; " f"cannot nominate {branch_id} — commit phase must serialize" ) self._nominated_branch = branch_id self._token_consumed = False def authorize(self, branch_id, tool_name, effect_class): if effect_class == EffectClass.PURE: return True if effect_class == EffectClass.IRREVERSIBLE: if self._nominated_branch != branch_id: raise OrphanedEffectError( f"branch {branch_id} attempted irreversible tool " f"'{tool_name}' before nomination (holder=" f"{self._nominated_branch}); effect must be deferred to outbox" ) if self._token_consumed: raise OrphanedEffectError( f"commit token for {branch_id} already consumed; " f"irreversible tools are single-use per nomination" ) self._token_consumed = True return True # COMPENSABLE: allowed only if handle is journaled synchronously return True def rollback_branch(branch_id, journal, environment): for entry in reversed(journal): if entry.effect_class == EffectClass.PURE: continue if entry.effect_class == EffectClass.IRREVERSIBLE: raise OrphanedEffectError( f"branch {branch_id} journal contains irreversible effect " f"'{entry.tool}' with no compensation contract; " f"this branch was not speculable" ) environment.compensate(entry.handle) # verify against environment, not the journal residual = environment.query_effects_by_token(branch_id) if residual: raise OrphanedEffectError( f"rollback of {branch_id} left {len(residual)} live effect(s) " f"in environment: {[r.id for r in residual]}" ) ```