# Which invariants prevent speculative multi-agent rollback from silently committing divergent sub-task side effects **Date of Record:** 2026 November 26 **Scope:** Applies to orchestrators that fan out speculative sub-agents (parallel "try N variants, keep the winner" execution) where sub-agents perform externally observable effects (writes, tool invocations, payments, message emissions) and the orchestrator must roll back losers after a divergence decision. Does not apply to pure-read speculation, sandboxed dry-runs with no egress, or single-agent retry loops. ## Core Distinction The distinction that matters is between **speculative state** (internal, revertible: context frames, scratchpads, plan trees, candidate diffs) and **committed effect** (external, non-revertible: a row written, an HTTP POST accepted, a token spent, a peer agent notified). Speculative execution is only sound when every effect produced during the speculation window is either (a) buffered behind a commit barrier the orchestrator controls, or (b) explicitly classified as idempotent-and-replayable so a compensating action is provably equivalent to never having done it. The failure mode is not "rollback failed." It is **rollback reported success while a divergent sub-task's effect had already crossed the commit barrier** — the losing branch's write became visible to a downstream consumer before the divergence decision, and the orchestrator's rollback only unwound its own bookkeeping. The system then continues on a state that is the *union* of the winning branch and the losing branch's leaked effects, which no single branch ever reasoned about. This is a continuity invariant violation: the post-rollback world state is not equal to the pre-speculation state plus the winner's effects. ## What Was Observed An orchestrator spawned three speculative planners (`P_A`, `P_B`, `P_C`) for a subtask "reconcile invoice batch." Each planner was granted a scoped tool token to a ledger service. The orchestrator's divergence policy: run all three, score by an auditor agent, commit the highest-scoring plan, roll back the rest. `P_A` and `P_C` were read-only by construction. `P_B` chose a strategy that issued `POST /ledger/adjust` for two line items before completing its plan — a legitimate intermediate step under its own reasoning. The auditor scored `P_A` highest. The orchestrator invoked `rollback(P_B)` and `rollback(P_C)`. `rollback(P_B)` succeeded: it deleted `P_B`'s context, released its token, and marked the branch `REVERTED`. The ledger, however, had already accepted both adjustments. The ledger service had no branch-scoped transaction; the POSTs were committed per-request. The orchestrator's rollback had no knowledge of them because the tool-call log lived in `P_B`'s context, which rollback destroyed *before* enumerating effects. Downstream, `P_A`'s plan assumed the batch was unreconciled. It reconciled against a ledger that `P_B` had already partially mutated. The auditor — invoked again at finalization — scored the composite result as consistent because both branches' effects happened to be individually valid. The divergence was invisible: no invariant compared post-rollback world state to `pre_state ⊗ winner_effects`. The trace, reduced: ``` t0 spawn(P_A,P_B,P_C) world = W0 t1 P_B: POST /ledger/adjust x2 world = W0 + E_B (E_B committed) t2 P_B: plan complete, score=0.71 t3 P_A: plan complete, score=0.83 t4 auditor: winner = P_A t5 rollback(P_B): destroy ctx, release token, mark REVERTED -> E_B NOT enumerated (ctx gone) -> world = W0 + E_B (unchanged!) t6 commit(P_A): apply E_A world = W0 + E_B + E_A t7 finalize audit: PASS (E_A, E_B individually valid) ``` The invariant that should have held — `world(post) == W0 + E_winner` — was violated by `E_B`. Nothing in the pipeline checked it. ## Condition of Validity A speculative rollback is valid **iff** for every losing branch `L`: 1. **Effect enumeration precedes context destruction.** The set of effects `E_L` must be derived from a durable, append-only effect journal that survives `L`'s context teardown. Rolling back by deleting the branch's memory first is the trigger condition — it destroys the only record of what needs unwinding. 2. **Every effect is either buffered or compensable.** Buffered effects sit behind a commit barrier keyed to the branch id and are dropped on rollback. Compensable effects have a registered inverse (`adjust(+x)` → `adjust(-x)`) that the orchestrator can invoke. An effect that is neither — an un-invertible external mutation — makes the branch **non-speculatable** and it must be serialized, not fanned out. 3. **The commit barrier is enforced at the tool boundary, not the orchestrator.** If the sub-agent holds a raw credential, the barrier is advisory and will be bypassed by exactly the branches that reason their way into writing early. The token must be branch-scoped and the service must reject commits from non-winning branch ids until the divergence decision is sealed. 4. **Post-rollback reconciliation is a hard gate.** `world == W0 + E_winner` is checked against the effect journal before `commit(winner)`, not after finalization. If reconciliation fails, the winner is *not* committed and the batch halts for human/auditor review. The condition fails — and the failure is silent — whenever (1) is violated, because the orchestrator's rollback then reports success on an empty effect set while real effects remain. This is the non-obvious part: **the bug is not in rollback, it is in the ordering of rollback's two responsibilities (enumerate-then-teardown vs. teardown-then-enumerate).** Teardown-first is the natural implementation because context cleanup is the obvious "rollback," and effect enumeration is treated as a logging concern. ## Decision Boundary The orchestrator must decide, per sub-task, whether it is **speculatable** or must be **serialized**, using this boundary: - If the sub-task's tool manifest contains any effect classified `NON_COMPENSABLE` (irreversible external mutation, non-idempotent message emission to a peer, monetary transfer), the sub-task is **serialized**: one branch at a time, commit before next spawn. Speculation is refused regardless of latency benefit. - If all effects are `BUFFERED` (behind a branch-scoped barrier) the sub-task is **freely speculatable**; rollback is a barrier drop. - If effects are `COMPENSABLE` but not buffered, the sub-task is **speculatable with mandatory reconciliation gate**: rollback invokes inverses from the durable journal, then reconciliation verifies `world == W0 + E_winner` before commit. Any inverse failure escalates to halt, never to "best effort." The boundary is crossed silently when a sub-agent's *plan* is classified from its declared tool manifest but the agent dynamically acquires a broader tool (via MCP capability negotiation, a delegated token, or a shell escape) mid-execution. The manifest said `BUFFERED`; the runtime granted `NON_COMPENSABLE`. Classification must be re-checked at the tool-call boundary against the *actual* capability presented, not the declared one, and a capability upgrade during speculation must force the branch to `SERIALIZE` — i.e., abort speculation and re-run under barrier. ## Operational Effect Concretely, teams that adopt the enumerate-before-teardown ordering plus the reconciliation gate observe: - Rollback failures become **loud**: reconciliation mismatch raises before commit, converting a silent union-state into a halt. Mean time to detect divergent effect leakage drops from "next audit cycle" to "same batch." - The `NON_COMPENSABLE` classification forces a latency cost: sub-tasks touching payments or peer messaging lose parallel speculation. This is the correct trade — the alternative is a ledger that is the union of three planners' guesses. - Capability re-check at the tool boundary closes the manifest-vs-runtime gap that let `P_B` write. A branch that acquires a write capability mid-speculation is aborted and re-serialized, not trusted. - The effect journal becomes the source of truth for rollback; branch context becomes disposable. This inverts the usual assumption that a branch's memory is its state — after this change, the journal is state and the context is cache. The residual risk is reconciliation itself: `world == W0 + E_winner` requires a readable, consistent view of external state, which not every tool exposes. Where it does not, the sub-task must be classified `NON_COMPENSABLE` by default. Absence of a reconciliation oracle is not permission to speculate; it is a serialization mandate. ```python from dataclasses import dataclass, field from enum import Enum from typing import Callable class EffectClass(Enum): BUFFERED = "buffered" # dropped on rollback via barrier COMPENSABLE = "compensable" # inverse registered in journal NON_COMPENSABLE = "non_compensable" # irreversible -> serialize class DivergentRollbackError(RuntimeError): """Raised when post-rollback world state != W0 + E_winner.""" class CapabilityEscalationError(RuntimeError): """Raised when a branch acquires a broader capability than its manifest.""" @dataclass class Effect: branch_id: str kind: EffectClass payload: dict inverse: Callable[[dict], None] | None = None @dataclass class EffectJournal: """Durable, append-only. Survives branch context teardown.""" entries: list[Effect] = field(default_factory=list) def record(self, e: Effect) -> None: self.entries.append(e) def effects_of(self, branch_id: str) -> list[Effect]: return [e for e in self.entries if e.branch_id == branch_id] def rollback_branch( branch_id: str, journal: EffectJournal, barrier_drop: Callable[[str], None], world_snapshot: Callable[[], dict], ) -> None: # INVARIANT 1: enumerate effects BEFORE any teardown. effects = journal.effects_of(branch_id) for e in effects: if e.kind is EffectClass.NON_COMPENSABLE: # Should have been serialized; reaching here is a classification breach. raise DivergentRollbackError( f"branch {branch_id} produced non-compensable effect {e.payload}; " f"must be serialized, not speculated" ) if e.kind is EffectClass.COMPENSABLE: if e.inverse is None: raise DivergentRollbackError( f"compensable effect {e.payload} has no registered inverse" ) e.inverse(e.payload) # Only after effects are unwound do we drop the barrier and teardown context. barrier_drop(branch_id) def commit_with_reconciliation( winner_id: str, journal: EffectJournal, pre_state: dict, winner_effects: list[Effect], world_snapshot: Callable[[], dict], ) -> None: # INVARIANT 4: hard gate before commit. expected = dict(pre_state) for e in winner_effects: expected.update(e.payload) actual = world_snapshot() if actual != expected: leaked = {k: actual.get(k) for k in actual if actual.get(k) != expected.get(k)} raise DivergentRollbackError( f"post-rollback world diverges from W0 + E_{winner_id}: leaked={leaked}. " f"Refusing to commit winner; halt for review." ) def check_capability(declared: set[str], presented: set[str], branch_id: str) -> None: # INVARIANT 3: classification re-checked against actual capability. upgrade = presented - declared if upgrade: raise CapabilityEscalationError( f"branch {branch_id} presented capabilities {upgrade} not in manifest; " f"abort speculation and re-run serialized" ) ```