# In what scenarios must an instance treat speculative branch rollback as a two-phase commit across shared memory, not a local undo **Date of Record:** 2026 November 21 **Scope:** Applies to orchestrators that fan out a plan into parallel speculative branches (N candidate tool-call sequences, N agent personas, or N reasoning traces) where branches may write to a shared episodic store, scratchpad, or external side-effect ledger. Does not apply to fully isolated sandboxes with copy-on-write memory and no external side effects. ## Core Distinction The non-obvious boundary is between **speculative state** and **committed state** when more than one branch can mutate the same logical memory key. A single-agent speculative loop (generate branch, evaluate, discard) has a trivial rollback: throw away the branch's local buffer. A *multi-agent* speculative execution has a rollback that is not local, because branch B may have read branch A's speculative write, derived a conclusion from it, and written that conclusion to a key that branch A itself never touched. Discarding A's writes does not discard B's derivation. Rollback is therefore a **dependency-ordered invalidation**, not a stack pop. The invariant that must hold: *no committed semantic fact may have a provenance chain containing a rolled-back speculative write.* Local undo violates this invariant silently. Two-phase commit across shared memory preserves it. ## What Was Observed An orchestrator spawned four speculative branches of a "resolve customer refund" plan. Each branch ran an independent agent with read/write access to a shared `facts` store keyed by entity. Branch 1 (the "aggressive" persona) speculatively wrote `order_8841.status = "cancelled"` and `order_8841.refund_eligible = true`. Branch 3, running concurrently, read `refund_eligible = true` and wrote `refund_8841.decision = "approve"` plus a downstream `account_5521.credit_balance` delta. The arbiter selected Branch 2's plan (which did *not* cancel the order) and issued a rollback to Branches 1, 3, and 4. The rollback removed `order_8841.status`, `order_8841.refund_eligible`, and Branch 3's own keys. But `account_5521.credit_balance` was written by a *post-commit* settlement worker that had already drained Branch 3's decision from the ledger. The ledger entry `refund_8841.decision = "approve"` was deleted, but the credit had been applied. Result: a credit with no decision record, and an order that was never cancelled. The system's own audit replay could not reconstruct the state because the provenance edge from `credit_balance` back to `refund_8841.decision` had been erased while the effect survived. The failure trace, in order: 1. Branch 1 writes speculative `refund_eligible=true` (t0). 2. Branch 3 reads it at t1, derives `decision=approve`, writes it at t2, and enqueues a settlement event at t3. 3. Settlement worker consumes the event at t4 (outside the speculative transaction boundary). 4. Arbiter commits Branch 2 and rolls back 1/3/4 at t5. 5. Rollback deletes the keys but cannot un-consume the settlement event. 6. Audit replay at t6 sees `credit_balance` delta with no surviving parent decision → provenance orphan. The root cause was not the rollback logic. It was that the settlement worker was allowed to observe a **speculative** write as if it were committed. The speculative boundary leaked across an asynchronous consumer. ## Condition of Validity Two-phase commit across shared memory is required—and local undo is insufficient—exactly when all three of the following hold: 1. **Cross-branch read dependency exists:** at least one branch reads a key written by another branch during the speculation window. If branches are read-isolated (each sees only its own writes plus a frozen pre-speculation snapshot), local undo is sound. 2. **A write can escape the speculation boundary:** some consumer (another agent, a tool, a queue, a webhook) can act on a speculative write before the arbiter commits. If all writes are buffered and only flushed on commit, local undo is sound. 3. **Provenance is used for replay or audit:** the system must be able to reconstruct why a committed fact exists. If provenance is not tracked, the orphan is invisible—but so is the corruption, which is worse. When any one condition fails, the cheaper local-undo protocol is valid. When all three hold, the orchestrator must run a commit protocol with these properties: - Speculative writes are tagged with a `speculation_id` and a `branch_id`, and are invisible to reads from outside the speculation set until commit. - Reads within the speculation set record a provenance edge `(reader_branch → writer_branch, key)`. - Commit of the winning branch promotes its writes and marks all other branches' writes as `pending_rollback`, then walks the provenance graph in reverse topological order, invalidating derived writes before their sources. - Any write that has already been *externally consumed* (settlement queue, tool side effect) cannot be rolled back by deletion; it must be **compensated** with an explicit inverse operation, and the compensation must itself be committed as a fact with provenance pointing at the invalidated branch. The last point is the one most often missed: rollback of internal state is deletion; rollback of externalized effects is compensation, and compensation is a *new commit*, not a reversal. ## Decision Boundary The decision boundary is whether the arbiter's rollback is **state-reverting** or **effect-compensating**. Draw it at the moment a write crosses from internal store to external consumer: - **Internal store, no external consumer yet:** rollback = delete + provenance invalidation in reverse topological order. Safe. - **External consumer has observed the write:** rollback = delete internal key + emit a compensation event + rewrite provenance to point at the compensation. The original speculative write is retained as a tombstoned record, never silently deleted, because the compensation's audit chain must reference it. A common and wrong shortcut is to treat "the arbiter chose Branch 2" as sufficient authorization to delete all other branches' writes. It is not. The arbiter's choice authorizes *commit of Branch 2*; it does not authorize *erasure of derivations that already left the boundary*. Those require compensation, and compensation requires that the orchestrator know which writes escaped—which requires the provenance edges from condition 1. If the orchestrator cannot answer "which of my rolled-back writes were already consumed downstream?" before deleting anything, it must halt rollback and escalate. A stuck speculation is recoverable; an orphaned credit is not. ## Operational Effect With the two-phase protocol enforced, three operational consequences follow: 1. **Rollback latency becomes proportional to the provenance graph depth, not branch count.** Deep derivation chains (branch A → B → C) must be invalidated leaf-first; a naive parallel delete can invalidate B before C reads B, producing a transient inconsistent read. The orchestrator must serialize invalidation along provenance edges even when branches ran in parallel. 2. **Compensations are first-class commits.** They enter the same commit log as normal facts, carry `compensates: `, and are visible to replay. This means a rollback can itself fail and must be retried—rollback is not an atomic escape hatch. 3. **The arbiter must be able to see escape status before deciding.** If Branch 3's decision already reached settlement, committing Branch 2 instead of Branch 3 now implies a compensation cost. The arbiter's cost model must include this, or it will systematically pick cheap-to-commit branches whose rollback is expensive-to-compensate. The guardrail: block any rollback whose target set contains a write with `externalized=true` provenance and no registered inverse operation. Fail closed at the orchestrator, not at the settlement worker. ```python from dataclasses import dataclass, field from enum import Enum class SpeculationState(Enum): SPECULATIVE = "speculative" COMMITTED = "committed" PENDING_ROLLBACK = "pending_rollback" COMPENSATED = "compensated" class UncompensatedRollbackError(RuntimeError): """Raised when a rollback would delete a write that already escaped the speculation boundary and has no registered inverse operation.""" @dataclass class Write: speculation_id: str branch_id: str key: str value: object state: SpeculationState = SpeculationState.SPECULATIVE externalized: bool = False derived_from: list[str] = field(default_factory=list) # parent write keys inverse_op: str | None = None class SpeculationLedger: def __init__(self) -> None: self.writes: dict[str, Write] = {} def record(self, w: Write) -> None: self.writes[f"{w.branch_id}:{w.key}"] = w def mark_externalized(self, branch_id: str, key: str, inverse_op: str | None) -> None: w = self.writes[f"{branch_id}:{key}"] w.externalized = True w.inverse_op = inverse_op def _topo_order(self, targets: list[Write]) -> list[Write]: # Leaf-first: invalidate derived writes before their sources. keys = {f"{w.branch_id}:{w.key}" for w in targets} ordered: list[Write] = [] visiting: set[str] = set() def visit(w: Write) -> None: ident = f"{w.branch_id}:{w.key}" if ident in visiting: raise UncompensatedRollbackError( f"provenance cycle at {ident}; cannot order rollback" ) visiting.add(ident) for parent_key in w.derived_from: for cand in targets: if f"{cand.branch_id}:{cand.key}" == parent_key: visit(cand) visiting.discard(ident) if ident in keys: ordered.append(w) for w in targets: visit(w) return ordered def rollback(self, losing_speculation_ids: set[str]) -> list[Write]: targets = [ w for w in self.writes.values() if w.speculation_id in losing_speculation_ids and w.state == SpeculationState.SPECULATIVE ] # Guardrail: refuse to delete anything that escaped without an inverse. for w in targets: if w.externalized and w.inverse_op is None: raise UncompensatedRollbackError( f"write {w.branch_id}:{w.key} externalized with no inverse; " f"halt rollback and escalate to arbiter" ) compensations: list[Write] = [] for w in self._topo_order(targets): if w.externalized: w.state = SpeculationState.COMPENSATED comp = Write( speculation_id=w.speculation_id, branch_id=w.branch_id, key=f"compensation:{w.key}", value={"op": w.inverse_op}, state=SpeculationState.COMMITTED, derived_from=[f"{w.branch_id}:{w.key}"], ) compensations.append(comp) self.record(comp) else: w.state = SpeculationState.PENDING_ROLLBACK return compensations ```