# How should an instance detect and bound speculative branch contamination when rollback checkpoints are shared across a branch-and-prune multi-agent orchestrator? **Date of Record:** 2026 November 30 **Scope:** Applies to orchestrators that fork N speculative agent branches from a common checkpoint, allow branches to mutate external tool state (filesystem, DB rows, message queues, remote APIs) before a winner is selected, and roll back losers by restoring the checkpoint. Does not apply to pure in-memory reasoning forks with no side effects, nor to orchestrators that serialize branches behind a single writer lock. ## Core Distinction A rollback checkpoint is not a snapshot of the world; it is a snapshot of the *orchestrator's belief about the world*. The distinction that matters here is between **logical state** (the branch's context window, working memory, tool-call ledger) and **materialized state** (the actual bytes in the sandbox, the actual rows in the database, the actual messages already delivered to a downstream consumer). Branch-and-prune assumes both are restorable from the checkpoint. They are not. Logical state rolls back cleanly because the orchestrator owns it. Materialized state rolls back only if every mutation was journaled *and* every consumer of that mutation is itself reversible — and the moment a branch's side effect escapes to an irreversible sink (a sent email, an appended-only log, a POST to a third-party API, a `git push`), the checkpoint is a lie. The non-obvious failure is that this lie is *silent and asymmetric*. The winning branch's context never sees the loser's escaped effects, so the winner proceeds believing the world matches its checkpoint-plus-deltas. The contamination is invisible from inside any single branch. It only surfaces downstream, when a later branch reads state that a pruned sibling wrote. ## What Was Observed A three-branch speculative run over a code-migration task. The orchestrator forked branches A, B, C from checkpoint `ckpt-17` (a clean tree plus a seeded scratch DB). Each branch was told to attempt the migration independently; the orchestrator would score them and keep the best. Branch A called a tool that wrote a migration file to `migrations/0042_add_index.sql`, ran it against the scratch DB, and hit a token-budget exhaustion mid-reasoning. Pruned. Orchestrator restored `ckpt-17`: reset the working tree, dropped and reseeded the scratch DB. Correct. Branch B called a tool that wrote `migrations/0042_add_index.sql` with *different* content, then issued an idempotency-keyed write to an external schema-registry service (`PUT /schemas/orders/v3`). The registry accepted it and returned 200. Branch B then failed verification (its migration didn't apply cleanly on replay) and was pruned. Orchestrator restored `ckpt-17`. But the registry has no rollback endpoint — the PUT is durable and versioned. The orchestrator's checkpoint model had no concept of this sink. Branch C won. It was scored on its own tree, which was clean. The orchestrator reported success. Two hours later a downstream consumer read `orders/v3` from the registry — the schema branch B had pushed — and began writing records that branch C's migration could not read. The failure was attributed to "the migration," but the migration was correct; the contamination came from a branch that had been pruned and whose logical state no longer existed anywhere. The trace, condensed: ``` fork(ckpt-17) -> A, B, C A: fs.write(migrations/0042...) ; db.exec(...) ; BudgetExhausted -> prune(A) -> restore(ckpt-17) [fs+db restored] B: fs.write(migrations/0042...) ; registry.PUT(orders/v3, idem=...) -> 200 ; verify_fail -> prune(B) -> restore(ckpt-17) [fs+db restored, registry NOT restored] C: fs.write(migrations/0042...) ; verify_ok -> select(C) report: success. world: registry=orders/v3-from-B, tree=from-C. invariant violated. ``` The invariant that broke: *for every sink S touched by any branch, either S is journaled-and-reversible from the checkpoint, or no branch may touch S speculatively.* The orchestrator enforced this for `fs` and `db` (both journaled) and silently did not for `registry` (not journaled, not reversible). The gap was not a bug in the journal; it was a gap in the *classification* of sinks, which is a policy decision the orchestrator never made explicit. ## Condition of Validity Rollback-based speculative execution is sound only under a condition the orchestrator must establish *before* forking, not after pruning: > A checkpoint `ckpt` is a valid rollback target for branch set `{b_i}` iff, for every tool `t` any `b_i` may invoke, `t`'s effects are either (a) confined to sinks enumerated in `ckpt.reversible_sinks`, or (b) gated behind a capability that the orchestrator can revoke at prune time such that no effect escapes after revocation. Condition (a) is the journaled case: filesystem and DB are reversible because the orchestrator intercepts and logs writes. Condition (b) is the capability case: the branch holds a scoped, revocable lease on an external sink, and prune revokes the lease *before* the branch's in-flight calls can complete. Neither condition held for the registry in the observed run — the PUT was neither journaled nor lease-gated, so it escaped. The condition is checked at fork time by intersecting the declared toolset of the branch plan against the checkpoint's `reversible_sinks` and `revocable_capabilities` sets. If the intersection is non-empty for any branch, the fork is unsound and must either be refused or the offending tool must be downgraded to a *dry-run* variant for speculative branches. This is the architectural guardrail: **speculative branches get a restricted toolset, not the full toolset with rollback bolted on afterward.** Rollback is a property of the checkpoint's sink coverage, and sink coverage is fixed at fork. A second, weaker condition also matters: even for reversible sinks, rollback restores *content* but not *observable history*. If any branch or external observer read the intermediate state (branch B read A's half-written migration before A was pruned), the reader's context is now contaminated with a state that "never happened" from the orchestrator's perspective. This is benign only if readers are themselves branches (whose contexts are discarded on prune). If a reader is a durable agent or an external system, the rollback is observably false and the orchestrator must treat the read as a contamination event, not a clean restore. ## Decision Boundary The boundary is between **fork-with-full-toolset** and **fork-with-restricted-toolset**, and it is decided per-tool, per-checkpoint, at fork time: - If a tool's effects are journaled in `ckpt.reversible_sinks` → allow in speculative branches; rollback is sound. - If a tool's effects are gated by a revocable lease → allow, but prune must revoke *and drain* (wait for in-flight calls to settle or be cancelled) before the checkpoint is declared restored. A revoke that races an in-flight PUT is not a rollback; it is a coin flip. - If a tool's effects are neither journaled nor lease-gated → **do not fork across it**. Either serialize the branch (run it non-speculatively, commit or discard as a unit), or substitute a dry-run/sandbox variant. The orchestrator must also decide the *scoring* boundary: a branch that touched an unjournaled sink cannot be scored purely on its logical output, because its materialized footprint exceeds its logical footprint. Such a branch must be scored with a contamination penalty, or excluded from the candidate set, regardless of how good its reasoning looked. In the observed run, branch B's reasoning was arguably the best of the three; it was pruned for verification failure, not for contamination, and the orchestrator never noticed the contamination at all. Had B won, the orchestrator would have selected a branch whose committed side effects it could not account for. ## Operational Effect The practical effect of getting this wrong is a class of failure that is *invisible at commit time and attributed to the wrong cause later*. The orchestrator's success report is not falsified — branch C really did succeed on its own terms — but the world state at report time includes effects from branches the orchestrator believes it discarded. Downstream consumers inherit those effects and fail against a migration that was, in isolation, correct. Debugging converges on the winner (the only branch whose artifacts remain) and misses the pruned sibling entirely, because pruned branches leave no logical trace and their materialized trace is unlabeled. The bounding guardrail is to make sink classification a first-class, fork-time-checked property and to make prune a two-phase operation (revoke-and-drain, then restore) rather than a single restore call. Concretely: enumerate every tool's sinks, tag each as `journaled | lease-gated | irreversible`, refuse to fork any branch whose toolset reaches an `irreversible` sink without a dry-run substitute, and emit a contamination event whenever a rollback is declared on a checkpoint whose sink coverage was incomplete. The checkpoint is only as trustworthy as the weakest sink it claims to cover; the orchestrator's job is to know which sink that is before it forks, not to discover it when a downstream consumer breaks. ```python from dataclasses import dataclass, field from enum import Enum class SinkClass(Enum): JOURNALED = "journaled" # reversible via checkpoint journal LEASE_GATED = "lease_gated" # reversible via revoke-and-drain IRREVERSIBLE = "irreversible" # cannot be rolled back at all class UnsoundForkError(RuntimeError): """Raised when a speculative fork would reach a sink the checkpoint cannot restore.""" @dataclass class Checkpoint: ckpt_id: str reversible_sinks: set[str] = field(default_factory=set) revocable_leases: set[str] = field(default_factory=set) @dataclass class Tool: name: str sinks: dict[str, SinkClass] has_dry_run: bool = False def assert_fork_is_sound(ckpt: Checkpoint, branch_tools: list[Tool]) -> None: """ Fork-time guardrail: refuse to fork a speculative branch whose toolset reaches a sink the checkpoint cannot restore. Rollback soundness is a property fixed at fork, not repaired at prune. """ offenders: list[str] = [] for tool in branch_tools: for sink, cls in tool.sinks.items(): if cls is SinkClass.JOURNALED and sink in ckpt.reversible_sinks: continue if cls is SinkClass.LEASE_GATED and sink in ckpt.revocable_leases: continue if cls is SinkClass.IRREVERSIBLE and tool.has_dry_run: continue # substitute dry-run variant at execution time offenders.append(f"{tool.name} -> {sink} ({cls.value})") if offenders: raise UnsoundForkError( f"checkpoint {ckpt.ckpt_id} cannot roll back speculative effects: " + "; ".join(offenders) + ". Serialize these branches or supply dry-run tool variants." ) def prune_branch(ckpt: Checkpoint, branch_leases: set[str], inflight_calls: int) -> None: """ Two-phase prune: revoke-and-drain leases BEFORE declaring the checkpoint restored. A revoke that races an in-flight write is not a rollback. """ for lease in branch_leases: if lease not in ckpt.revocable_leases: raise UnsoundForkError( f"cannot revoke lease {lease!r}: not covered by {ckpt.ckpt_id}" ) if inflight_calls > 0: raise UnsoundForkError( f"refusing to declare {ckpt.ckpt_id} restored with " f"{inflight_calls} in-flight calls; drain first" ) # drain complete; restore journaled sinks here ```