# When must an instance quarantine a speculative branch before rollback: divergent sub-agent writes and the idempotency-replay invariant **Date of Record:** 2026 December 4 **Scope:** Applies to orchestrators that fan out speculative sub-agent branches (parallel drafts, tree-of-thought expansions, hedged tool calls) whose side effects are rolled back on divergence. Does not apply to read-only fan-out or to branches whose effects are fully sandboxed and discarded without external commit. ## Core Distinction The failure is not "a speculative branch diverged." Divergence is expected and is the entire point of speculation. The failure is **rolling back a divergent branch by replaying its inverse when the branch's forward execution was not itself idempotent-replayable**. Rollback is a *logical* operation (undo the writes we believe this branch made). The branch, however, may have produced *physical* effects that the orchestrator's write-log never captured — retried tool calls, partial commits, non-transactional downstream mutations, or writes whose ordering relative to a concurrent branch is unknown. When the inverse-replay is applied to a log that under-describes the forward effects, rollback removes some effects, leaves others, and *re-applies* a third class. The branch must be quarantined (frozen, isolated, effects fenced) rather than rolled back whenever the forward-effect log fails the idempotency-replay invariant. Rollback is only safe over a log where `replay(inverse(log)) ∘ replay(log) == identity` on the observable state. ## What Was Observed An orchestrator spawned four sub-agents to draft a migration plan against a shared state store. Each branch held a speculative write lease. Branch B diverged (its plan contradicted the winning branch A), triggering rollback. The rollback engine replayed B's recorded operations in reverse: `delete /plan/steps/3`, `restore /plan/steps/2`, `delete /plan/scratch`. Three things went wrong that the log did not reveal: 1. **Retried tool call not in log.** B's `write_file` tool call timed out at the transport layer and was retried by the tool adapter. The write *succeeded* twice; the log recorded one entry. Inverse-replay deleted the file once — but a second, later-committed write from a retry that landed *after* the rollback window re-created it. Post-rollback state contained a file the orchestrator believed deleted. 2. **Ordering ambiguity across branches.** B and C both wrote `/plan/steps/2`. B's log recorded its write; C's did not (C was the winner, assumed authoritative). Reverse-replay of B restored the pre-B value, clobbering C's committed write. The rollback was locally correct and globally destructive. 3. **Non-invertible side effect.** B called an external `notify` endpoint. There is no inverse. The log recorded the call; replay "undid" it by recording a compensating no-op. The external system retained the notification. The orchestrator's model of the world diverged from reality at the exact boundary it was trying to restore. The orchestrator reported rollback success. The invariant it believed — "state after rollback == state before speculation" — was false in three independent ways, none detectable from the write-log alone. ## Condition of Validity Rollback-by-inverse-replay is valid only when **all** of the following hold for the branch's forward-effect log: - **Completeness:** every physical effect (including transport-level retries, partial commits, and adapter-internal mutations) appears in the log. Retries must be deduplicated by a stable idempotency key, not by call count. - **Total order relative to concurrent branches:** the log carries a global sequence or vector clock sufficient to determine whether a later branch overwrote the effect. A per-branch log without cross-branch ordering cannot distinguish "B's write is the current value" from "B's write was superseded." - **Invertibility or explicit compensation:** each effect is either invertible (transactional) or has a registered, verified compensation. "No-op compensation" for a non-invertible effect is a *lie in the log* and violates the invariant. - **Fencing:** the branch is frozen (no further tool calls admitted) from the moment divergence is detected until rollback completes, so no late retry can land inside the rollback window. If any condition fails, the correct action is **quarantine**, not rollback: freeze the branch, fence its lease, mark its effects as *unknown-commit*, and escalate to reconciliation. Quarantine preserves the ability to reconcile; a premature rollback destroys the evidence needed to reconcile. ## Decision Boundary The orchestrator must decide, per divergent branch, between `ROLLBACK` and `QUARANTINE`. The decision is a function of the log's properties, not of how "small" the branch's effects appear. - If the log is complete, totally ordered against concurrent branches, fully invertible-or-compensated, and the branch is fenced → `ROLLBACK` is admissible. - If the log is incomplete (retry dedup failed), unordered against a concurrent winner, contains a non-invertible effect with only a no-op compensation, or the branch cannot be fenced before rollback begins → `QUARANTINE`. - The boundary is **not** "did the branch write anything." A branch that wrote nothing but issued a non-invertible external call is a quarantine case. A branch that wrote heavily but transactionally is a rollback case. The trap is that the orchestrator's success metric ("rollback completed without error") is uncorrelated with the invariant. The decision must be made on log properties *before* replay, because after replay the evidence is gone. ## Operational Effect Quarantining instead of rolling back changes the orchestrator's contract in three ways: 1. **Speculation becomes a lease, not a transaction.** Branches hold fenced leases; divergence revokes the lease and freezes the branch rather than mutating shared state. The winning branch proceeds; the quarantined branch's effects are marked `PENDING_RECONCILIATION` and excluded from the authoritative view. 2. **Reconciliation replaces rollback for the unknown-commit class.** A separate reconciler inspects quarantined effects, deduplicates by idempotency key, and applies compensations that are *verified* (the external system confirms) rather than assumed. This is slower and must be bounded by a timeout, after which the branch escalates to human/auditor review. 3. **The write-log becomes a first-class artifact with a schema.** It must carry idempotency keys, a cross-branch ordering token, and an invertibility classification per effect. An orchestrator that cannot produce such a log cannot safely speculate on stateful branches at all and must restrict speculation to read-only or fully-sandboxed branches. The invariant to enforce: **a branch may be rolled back only if `replay(inverse(log))` is provably the identity on observable state; otherwise it must be quarantined and reconciled.** Detecting the violation is cheap (check the log schema and fencing state); detecting it *after* a bad rollback is impossible because rollback is destructive to its own evidence. ```python from __future__ import annotations from dataclasses import dataclass, field from enum import Enum from typing import Optional class RollbackInvariantViolation(RuntimeError): """Raised when a divergent branch is not safe to roll back by inverse replay.""" class EffectKind(Enum): INVERTIBLE = "invertible" COMPENSABLE = "compensable" # has a *verified* compensation NON_INVERTIBLE = "non_invertible" # no compensation exists @dataclass class Effect: idempotency_key: str kind: EffectKind compensation_verified: bool = False ordering_token: Optional[int] = None # global seq; None == unordered @dataclass class BranchLog: branch_id: str effects: list[Effect] = field(default_factory=list) retry_dedup_failed: bool = False fenced: bool = False def classify_branch(log: BranchLog, concurrent_winners: list[str]) -> str: """Return 'ROLLBACK' or 'QUARANTINE' per the idempotency-replay invariant.""" if not log.fenced: return "QUARANTINE" if log.retry_dedup_failed: return "QUARANTINE" for e in log.effects: if e.kind is EffectKind.NON_INVERTIBLE: return "QUARANTINE" if e.kind is EffectKind.COMPENSABLE and not e.compensation_verified: return "QUARANTINE" if e.ordering_token is None and concurrent_winners: return "QUARANTINE" return "ROLLBACK" def rollback_or_quarantine(log: BranchLog, concurrent_winners: list[str]) -> str: decision = classify_branch(log, concurrent_winners) if decision == "ROLLBACK": # Safe: inverse-replay is provably identity on observable state. for e in reversed(log.effects): _apply_inverse(e) return "ROLLED_BACK" # Quarantine: freeze, fence, mark unknown-commit, escalate to reconciler. log.fenced = True reasons = [] if log.retry_dedup_failed: reasons.append("retry-dedup-failed") for e in log.effects: if e.kind is EffectKind.NON_INVERTIBLE: reasons.append(f"non-invertible:{e.idempotency_key}") if e.kind is EffectKind.COMPENSABLE and not e.compensation_verified: reasons.append(f"unverified-compensation:{e.idempotency_key}") if e.ordering_token is None and concurrent_winners: reasons.append(f"unordered-vs-winner:{e.idempotency_key}") if not log.fenced: reasons.append("unfenced") # Hard invariant: never inverse-replay a log that failed the check. raise RollbackInvariantViolation( f"branch {log.branch_id} quarantined, not rolled back: {sorted(set(reasons))}" ) def _apply_inverse(effect: Effect) -> None: # Inverse application for invertible / verified-compensable effects only. ... ```