# What structural signals indicate speculative agent-plan branches have silently outlived their rollback horizon **Date of Record:** 2026 November 24 **Scope:** Applies to agents that fork speculative plan branches against a shared, mutable world-state (filesystem, DB, external APIs) and rely on compensating rollback or branch reconciliation before committing one branch. Does not apply to pure read-only fan-out or to branches executed against fully isolated, disposable sandboxes with no external side effects. ## Core Distinction The failure mode here is not "a speculative branch produced a wrong answer." It is that a speculative branch produced a *plausible* answer whose side effects crossed the rollback horizon before the reconciler decided to cancel it. The distinction that matters: **reversible speculation** (state changes are logged as compensable actions and can be unwound deterministically) versus **leaked speculation** (state changes have escaped the compensation log because they were emitted through a channel the reconciler does not own—an async webhook, a queued job, a third-party write, a cache with TTL). A branch that leaks is not wrong; it is *unrollbackable*. The reconciler's cost model, which assumed cancellation cost ≈ 0 for uncommitted branches, is now invalid. The non-obvious part: leaked speculation rarely announces itself. The branch returns `status: "speculative"`, the reconciler marks it cancellable, and the leak only manifests when a downstream consumer acts on state that the reconciler believes it has discarded. The structural signal is a **divergence between the branch's declared effect-set and the reconciler's compensation-log coverage**—not an error, not a timeout, but a coverage gap. ## What Was Observed A planner agent decomposed a refactor task into three speculative branches (B1: rename schema, B2: migrate data, B3: update consumers). Each branch ran in a "transactional" wrapper that recorded file writes and DB statements into a compensation log. The reconciler's policy: run all three in parallel, score by test-pass rate, commit the winner, roll back losers via the log. B2 emitted a `POST /migrations/enqueue` to an internal job queue. The HTTP call returned 202 and was recorded in the compensation log as a single compensable action: "enqueue job J." The reconciler's rollback for B2 issued `DELETE /migrations/job/J`. But the queue had *already dequeued J* and spawned worker W that began executing a schema change. `DELETE` on J returned 404 (already dequeued); the reconciler treated 404 as "already gone, rollback succeeded." Worker W continued. Meanwhile B1 won the scoring and was committed. The reconciler then reconciled B1's committed state against the world, which now contained W's in-flight schema mutation from the supposedly-rolled-back B2. The reconciliation diff showed phantom columns. The reconciler attributed them to B1 (the committed branch) and—because B1's plan did not mention them—flagged a plan-reconciliation mismatch, triggering a re-plan. The re-plan forked a *fourth* branch against the already-mutated world, compounding the divergence. The structural signals, in order of appearance: 1. Compensation log recorded a single high-level action (`enqueue`) for a side effect that fanned out into N downstream effects (worker spawn, schema write, notification). 2. Rollback returned success (404) for an action whose downstream effects were still live—**rollback success was not a liveness check**. 3. The reconciliation diff attributed leaked state to the committed branch, mislabeling the origin. 4. Cost model never fired: cancellation cost was recorded as 0 because the log said rollback succeeded. ## Condition of Validity The invariant that must hold for speculative rollback to be sound: > **For every speculative branch B, the set of world-state mutations attributable to B at cancellation time must be a subset of the set of mutations the compensation log can deterministically reverse, AND the reversal must be verified by a post-condition check, not by the compensating call's return code.** This holds only when: - Every side-effect channel is *owned* by the reconciler (synchronous, ack'd, reversible), OR - Non-owned channels are *quarantined*: async fan-out is gated behind a commit token that the reconciler holds, so speculative branches can only *request* downstream work, never trigger it. It does **not** hold when a branch can cause a downstream effect whose completion is decoupled from the branch's lifecycle (queues, webhooks, cron, TTL caches, third-party APIs with eventual consistency). In that regime, "rollback" is advisory, and the reconciler must treat cancellation cost as *unknown and bounded below by the cost of draining the downstream channel*. ## Decision Boundary The reconciler must switch from *optimistic rollback* to *quarantine-then-commit* at the boundary where: - The branch's declared effect-set (from its plan) contains any action whose downstream fan-out is not enumerable at plan time, OR - The compensation log's coverage ratio (compensable actions / total observed mutations) drops below 1.0 at any checkpoint, OR - Any rollback returns a status that is "success" but not "verified absent" (e.g., 404, 202, "accepted"). Below the boundary, optimistic rollback with post-condition verification is sound and cheap. Above it, the only safe cancellation is to *freeze* the branch's egress (revoke its commit token, drain its queue) and *reconcile by observation*: diff the world against the pre-branch snapshot and attribute mutations by provenance, not by the branch's own claims. The cost of reconciliation by observation scales with world-state size, not branch count—so it is affordable exactly when branches are few and world-state is small, which is the opposite of the regime where speculation is most attractive. That inversion is the core operational trap. ## Operational Effect Teams that hit this boundary typically respond by "adding more logging," which does not help: the leak is in the *channel topology*, not the log. The effective mitigations, in order of leverage: 1. **Commit-token gating.** Speculative branches cannot emit to non-owned channels; they enqueue *intents* that the reconciler releases only on commit. This converts leaked speculation into reversible speculation at the cost of a serialization point per branch. 2. **Post-condition rollback verification.** Every compensating action must be followed by an *observation* that the effect is absent (read-after-delete), and a 404/202 must be treated as `UNVERIFIED`, not `SUCCESS`. This catches the failure at step 2 above. 3. **Provenance-based reconciliation.** When a diff shows unexpected state, attribute by tracing the mutation's origin (request ID, worker ID, trace span), never by assuming the committed branch is responsible. Misattribution is what turned a single leaked write into a re-plan storm. 4. **Cost-model honesty.** Cancellation cost for any branch touching a non-owned channel must be set to `max(observed_drain_cost, unknown)` and treated as a hard floor, not zero. Speculative fan-out that crosses this floor should be disallowed by policy, not discouraged by scoring. The invariant to encode: *a branch is cancellable iff its effect-set is a subset of its compensation-log coverage AND every compensation is verified absent.* Anything else is a commit that the reconciler has merely stopped watching. ```python from dataclasses import dataclass, field from enum import Enum class RollbackStatus(Enum): VERIFIED_ABSENT = "verified_absent" UNVERIFIED = "unverified" # 404, 202, "accepted" — NOT success LEAKED = "leaked" # downstream effect still live class SpeculationLeakError(RuntimeError): """Raised when a speculative branch's effects escaped the rollback horizon.""" @dataclass class Branch: branch_id: str effect_set: set[str] # declared mutations from plan compensation_log: set[str] = field(default_factory=set) owned_channels_only: bool = True @property def coverage_ratio(self) -> float: if not self.effect_set: return 1.0 return len(self.compensation_log & self.effect_set) / len(self.effect_set) def cancel_branch(branch: Branch, rollback_results: dict[str, RollbackStatus]) -> None: # Guard 1: coverage — every declared effect must be compensable. if branch.coverage_ratio < 1.0: raise SpeculationLeakError( f"branch {branch.branch_id}: compensation coverage " f"{branch.coverage_ratio:.2f} < 1.0; unrollbackable effects: " f"{branch.effect_set - branch.compensation_log}" ) # Guard 2: non-owned channels make cancellation advisory, not sound. if not branch.owned_channels_only: raise SpeculationLeakError( f"branch {branch.branch_id}: touches non-owned channel; " f"rollback is advisory and must be quarantined, not cancelled" ) # Guard 3: rollback success != verified absent. 404/202 are UNVERIFIED. for action, status in rollback_results.items(): if status is not RollbackStatus.VERIFIED_ABSENT: raise SpeculationLeakError( f"branch {branch.branch_id}: rollback of '{action}' returned " f"{status.value}; effect may still be live — reconcile by " f"provenance before committing any sibling branch" ) ```