# Under what conditions must an instance invalidate a speculative branch before its rollback journal is sealed: the unsealed-commit hazard in speculative multi-agent rollback **Date of Record:** 2026 November 29 **Scope:** Applies to multi-agent systems where a *speculator* agent forks a speculative execution branch (one or more worker agents plus their tool calls) and must roll it back when a *verifier* or auditor agent reports divergence, and where the rollback is mediated by a journal of side-effecting operations. Does not apply to purely read-only speculative branches, nor to single-agent retry loops without a journal. ## Core Distinction The failure is not "rollback failed." It is **rollback executed against a journal that was still being appended to.** A speculative branch is only safely reversible if its effect journal is *sealed* — no further side-effecting operation can be committed under that branch's idempotency lineage — *before* the divergence verdict is acted upon. The non-obvious boundary is temporal: the verifier's divergence signal and the speculator's in-flight tool calls race. Divergence is detected at time *t_v*, but tool calls launched at *t < t_v* may still be executing and will append their effects to the journal at *t > t_v*. If the rollback sweep runs at *t_v* and the late effect lands at *t_v + δ*, the system has rolled back a prefix and then committed a suffix — leaving a **partially rolled-back branch whose journal is internally inconsistent**: the inverse operations applied do not cover the full effect set, and the surviving effect has no compensating entry. This is distinct from ordinary "lost update" because the surviving effect is *semantically valid in isolation* — it was a legitimate tool call. It is also distinct from a crash-recovery gap, because no process died. The hazard is that the branch's *authority to commit* was revoked while its *capacity to commit* was still live. ## What Was Observed A planner agent decomposed a migration task and dispatched three worker agents (schema-mutator, data-backfiller, index-builder) under a speculative branch `spec-7`. A verifier agent independently re-derived the target schema and flagged divergence at step 4: the schema-mutator had inferred a `NOT NULL` constraint from a nullable source column, an inference the verifier judged unsound. The speculator issued `rollback(spec-7)`. The rollback journal for `spec-7` at verdict time contained 6 entries: 3 DDL statements and 3 inverse-operation records. The sweep applied all 6 inverses and marked `spec-7` as `ROLLED_BACK`. The system then re-planned from the pre-speculation checkpoint. What the journal did not yet contain: the index-builder had issued a `CREATE INDEX CONCURRENTLY` at step 3 that was still building. `CONCURRENTLY` returns before the index is valid; the tool wrapper recorded the *submission* as a pending entry but only appended the *completion* record — including the inverse `DROP INDEX` — when the build finished. The build finished 41 seconds after the rollback sweep. The completion handler appended the inverse record to a journal already marked sealed-and-rolled-back, and — because the handler's contract was "record the inverse for future rollback," not "check whether the branch is already dead" — did not execute the inverse. The index survived on a table the re-plan subsequently dropped and recreated under a different name. The re-planned branch's verifier passed, because it checked schema and data, not orphaned index objects. The orphan was discovered three days later as a write-amplification and lock-contention anomaly. The trace, reduced: 1. `t0`: `spec-7` opened, journal unsealed, commit authority = GRANTED. 2. `t1`: index-builder submits `CREATE INDEX CONCURRENTLY`; journal gets a *pending* entry, no inverse yet. 3. `t2`: verifier emits `DIVERGENCE(spec-7, reason=unsound_nullable_inference)`. 4. `t3`: speculator calls `rollback(spec-7)`. Sweep reads journal (6 entries), applies 6 inverses, sets `sealed=TRUE, state=ROLLED_BACK`. 5. `t4`: index build completes. Completion handler appends inverse record; handler's seal-check is absent, so it does not execute the inverse. 6. `t5`: re-plan proceeds from checkpoint. Orphan index persists, invisible to the new branch's verifier. The invariant that was violated: **a branch's commit authority must be revoked atomically with respect to the journal's seal, and every in-flight operation must be either drained (completed and inverted) or cancelled-and-confirmed before the sweep runs.** The system revoked authority at `t3` but did not drain the in-flight operation whose completion was the precondition for its own inverse. ## Condition of Validity The rollback sweep is *sound* — meaning the post-sweep state equals the pre-speculation state restricted to the branch's effect set — only when all of the following hold at the instant the sweep begins: - **Journal closure:** no operation under the branch id is in `PENDING` state; every submitted operation has either a terminal completion record or a confirmed cancellation record. "Confirmed cancellation" means the tool layer has acknowledged that the operation will not produce a late effect — not merely that a cancel was requested. - **Seal-before-sweep ordering:** the journal is marked `SEALED` *before* the first inverse is applied, and the seal is enforced at the append path (any late append to a sealed journal raises and routes to a reconciliation queue, never silently no-ops). - **Authority-capacity coupling:** the branch's commit authority (the token/lease/lineage that lets a tool call be attributed to the branch) is revoked in the same critical section as the seal, so no new operation can be submitted between seal and sweep. - **Inverse completeness:** for every terminal effect there exists an inverse record, and the sweep applies exactly the set of inverses whose effects are present — not the set that was present at verdict time. The condition fails, and the sweep is *unsound*, whenever a `PENDING` operation can transition to terminal after the seal. This is precisely the `CONCURRENTLY`-style case: operations whose tool-layer contract is "return on submission, complete asynchronously." Any tool with a deferred-completion contract — async index builds, queued webhooks, batched writes, long-running sandbox jobs — is a candidate. The speculator cannot know from the tool's return value whether the effect is final; it must consult the journal's terminality, and the journal must be the single source of truth. ## Decision Boundary The speculator must choose between **drain** and **abandon** at verdict time, and the choice is forced by whether the in-flight set can be drained within the rollback deadline: - **Drain** when every `PENDING` operation has a bounded completion time and a known inverse, and `max(remaining_completion) + sweep_cost < rollback_deadline`. Block the sweep until journal closure is observed; then seal, revoke, sweep. - **Abandon** when any `PENDING` operation is unbounded or its inverse is unknown. Do *not* sweep. Mark the branch `QUARANTINED`, revoke commit authority immediately, and hand the branch to a reconciler that will later invert whatever terminal effects appear. The re-plan must not reuse the checkpoint's resource names until reconciliation confirms the branch's effect set is closed. The boundary is *not* "divergence detected → roll back." It is "divergence detected → revoke authority → achieve journal closure or quarantine → then roll back." Treating verdict as the trigger for sweep is the bug. The verdict is the trigger for *authority revocation*; the sweep is triggered by *journal closure*. A second boundary: the verifier's divergence verdict must carry the branch's *effect-set fingerprint* (the set of operation ids it observed), and the sweep must refuse to run if the journal contains operations outside that fingerprint. A late operation is by definition outside the verifier's observation; its presence at sweep time is the signal that closure has not been achieved, regardless of what the pending-count says. ## Operational Effect Systems that seal-before-sweep and enforce closure observe: rollback latency becomes bounded by the slowest in-flight operation rather than by verdict latency (a real cost — rollback is no longer instant); orphaned effects become impossible rather than rare; and the reconciler's queue becomes the only path by which a late effect can be inverted, which makes late effects *visible* instead of silent. The observable signature of the fixed system is that `ROLLED_BACK` is a terminal state reachable only from `SEALED ∧ CLOSED`, and `QUARANTINED` is a distinct terminal state with a reconciliation obligation. Systems without the invariant exhibit the orphan signature: a `ROLLED_BACK` branch whose effect set, audited later against the underlying resource layer, is non-empty. The audit is the only reliable detector, because the branch's own journal will claim completeness — the late inverse record was appended, after all, just never applied. The failure is silent to every check that trusts the journal's self-report. The guardrail is a single invariant, enforced at the append path and the sweep entry: **no inverse may be applied to a journal that is not sealed, and no journal may be sealed while any operation under its branch id is pending.** Both halves are required. Sealing without closure lets a late append land on a dead journal; closure without sealing lets a new operation slip in between the closure check and the sweep. The seal and the authority revocation must be one atomic transition, and the closure check must be the sweep's precondition, not the verdict's. ```python import time from dataclasses import dataclass, field from enum import Enum from typing import Callable, Dict, List, Optional class RollbackInvariantError(RuntimeError): """Raised when a rollback sweep would run against an unsealed or unclosed journal.""" class OpState(Enum): PENDING = "pending" TERMINAL = "terminal" CANCELLED = "cancelled" @dataclass class JournalEntry: op_id: str state: OpState inverse: Optional[Callable[[], None]] = None @dataclass class BranchJournal: branch_id: str entries: Dict[str, JournalEntry] = field(default_factory=dict) sealed: bool = False authority_granted: bool = True def submit(self, op_id: str) -> None: if not self.authority_granted: raise RollbackInvariantError( f"commit authority revoked for {self.branch_id}; op {op_id} rejected" ) if self.sealed: raise RollbackInvariantError( f"append to sealed journal {self.branch_id} (op {op_id}); route to reconciler" ) self.entries[op_id] = JournalEntry(op_id=op_id, state=OpState.PENDING) def complete(self, op_id: str, inverse: Callable[[], None]) -> None: if self.sealed: # Late completion after seal: must be reconciled, never silently dropped. raise RollbackInvariantError( f"late completion of {op_id} on sealed journal {self.branch_id}; " f"quarantine and reconcile" ) entry = self.entries[op_id] entry.state = OpState.TERMINAL entry.inverse = inverse def is_closed(self) -> bool: return all(e.state is not OpState.PENDING for e in self.entries.values()) def seal_and_revoke(self) -> None: # Atomic transition: seal + revoke authority in one step. self.sealed = True self.authority_granted = False def rollback_sweep(journal: BranchJournal, deadline_s: float = 30.0) -> str: """Apply inverses only if the journal is sealed and closed. Never sweep a live journal.""" if not journal.sealed: raise RollbackInvariantError( f"sweep attempted on unsealed journal {journal.branch_id}" ) if not journal.is_closed(): pending = [e.op_id for e in journal.entries.values() if e.state is OpState.PENDING] raise RollbackInvariantError( f"sweep attempted with pending ops {pending} on {journal.branch_id}; " f"drain or quarantine first" ) for entry in journal.entries.values(): if entry.state is OpState.TERMINAL and entry.inverse is not None: entry.inverse() return "ROLLED_BACK" def speculative_rollback( journal: BranchJournal, verdict_diverged: bool, drain_deadline_s: float = 30.0, clock: Callable[[], float] = time.monotonic, ) -> str: """Verdict revokes authority; closure gates the sweep. Drain if bounded, else quarantine.""" if not verdict_diverged: return "NO_OP" # Step 1: revoke authority immediately on verdict — capacity to commit dies now. journal.authority_granted = False # Step 2: attempt drain until closure or deadline. start = clock() while not journal.is_closed(): if clock() - start > drain_deadline_s: # Unbounded in-flight op: do not sweep. Quarantine for reconciliation. journal.sealed = True return "QUARANTINED" time.sleep(0.05) # Step 3: closure achieved — seal atomically, then sweep. journal.seal_and_revoke() return rollback_sweep(journal, deadline_s=drain_deadline_s) ```