# How does an instance detect speculative-branch contamination when a losing draft's tool side effects survive rollback and poison the winner's verification replay? **Date of Record:** 2026 November 29 **Scope:** Applies to orchestrators that fan out N parallel draft branches from a shared checkpoint, execute real tool calls inside each branch, then select a winner and roll back losers by discarding in-memory state. Does not apply to branches executed in fully isolated sandboxes with no external side effects, nor to purely internal reasoning branches with no tool invocations. ## Core Distinction The failure is not "the wrong branch won." It is that rollback of a speculative branch is almost always implemented as *state rollback* (discard the branch's message log, KV cache, scratchpad, and checkpoint pointer) while the branch's *tool side effects* — file writes, database mutations, sent messages, created resources, cache invalidations, appended log records — are not rolled back because the orchestrator has no transactional control over external systems. The winner is then selected and its verification replay runs against an environment that has been mutated by every losing branch. The invariant that silently breaks: **a branch's observable environment at verification time is assumed identical to the environment it reasoned about at draft time.** It is not, because sibling branches ran concurrently against the same external state. This is non-obvious because each branch, viewed in isolation, is internally consistent. The bug only manifests at the seam between branches, and only when a losing branch's side effect is (a) non-idempotent or (b) read by the winner's verification step. Deterministic single-branch execution never exposes it. ## What Was Observed A planner agent emitted a task requiring a config migration. The orchestrator opened checkpoint `C0`, then spawned three draft branches in parallel, each with the same base context and a distinct strategy prompt: - **Branch A:** rewrote `config.yaml` in place, then ran a validator. - **Branch B:** wrote `config.yaml.new`, diffed, then renamed over the original only after validation passed. - **Branch C:** attempted an in-place rewrite but its validator returned a schema error, so it emitted a partial write of `config.yaml` before aborting mid-tool-call (token budget exhausted inside the `write_file` tool call). All three branches shared the same working directory. The orchestrator's rollback for A and C consisted of dropping their message arrays and resetting the checkpoint pointer to `C0`. Branch B won on a scoring heuristic (clean diff, validator passed, no truncation). The winner's verification replay then re-read `config.yaml`. It contained a *hybrid*: the tail of B's atomic rename had not yet been flushed when C's aborted partial write landed, and because C's write was a truncating open followed by a short write, the file on disk was B's content truncated at C's byte offset. The verifier — which checked "file parses and contains `schema_version: 2`" — passed, because the truncation happened to fall after the schema key. The orchestrator recorded success. Two hours later a downstream consumer failed on a missing section that had been silently truncated. The tell was in the trace, not the output: the winner's verification read a file whose `mtime` was *later* than the winner's own final tool call, and whose size differed from the size the winner's `write_file` had reported. Both facts were present in the recorded tool outputs and both were ignored because the verifier only asserted on parsed content, never on provenance. ## Condition of Validity The contamination is bounded and detectable only under a specific conjunction: 1. **Shared mutable substrate.** At least two branches write to the same external resource (same path, same row, same queue, same namespace). If branches are namespaced per-branch-id, the failure cannot occur. 2. **Non-atomic or non-idempotent side effect.** An atomic rename-over or a content-addressed write is safe; a truncating open, an append, a counter increment, or a "delete then recreate" is not. 3. **Winner verification reads the mutated resource.** If the winner's verification is a pure function of its own recorded tool outputs (no re-read of external state), contamination is latent but harmless for that step — though it still poisons any subsequent branch that resumes from the winner. 4. **Rollback is state-only.** If rollback includes an inverse-operation log (compensating writes) applied before the winner's verification, the invariant is restored. All four must hold. Remove any one and the failure does not occur, which is exactly why it survives testing: most test harnesses inject a per-branch sandbox (kills condition 1) or verify against recorded outputs (kills condition 3). ## Decision Boundary The orchestrator must treat the moment of winner selection as a **barrier**, not a checkpoint resume. The decision boundary is: - **Before selection:** branches may run concurrently against shared state *only if* every tool call is declared `effect: isolated` (namespaced, atomic, or read-only). Any `effect: mutating` call forces the branch into a serialized lane or a per-branch overlay. - **At selection:** the orchestrator must reconcile external state to the winner's *expected* post-state. Concretely, it must compare, for every resource the winner touched, the winner's recorded post-write fingerprint (content hash, size, version vector) against the live resource. A mismatch means a sibling contaminated the substrate; the winner is *not* valid and must be re-drafted from a re-snapshotted checkpoint. - **After selection:** the winner's verification replay must run against a state that is proven equal to the winner's draft-time view, or the replay is meaningless. The guardrail is a **post-state fingerprint assertion**: each branch records, at each mutating tool call, the resource identity and the resulting fingerprint it believes it produced. At the barrier, the orchestrator asserts live fingerprint == winner's last recorded fingerprint for every touched resource. Any divergence raises and invalidates the selection rather than proceeding. ## Operational Effect Without the barrier assertion, speculative execution produces *silent* corruption: the winner is chosen on draft-time merit but verified against a post-rollback environment that no branch actually reasoned about. The corruption is invisible to per-branch scoring because scoring uses draft-time observations, and invisible to the verifier because the verifier asserts on content shape, not provenance. The only reliable detector is the fingerprint divergence at the barrier — a later `mtime`, a size mismatch, or a version-vector gap between what the winner reported writing and what is on disk. The operational cost is that mutating branches can no longer be freely parallelized against shared substrates; they must be serialized or overlaid. That is the correct trade: speculative parallelism is only sound over resources where rollback is *total*, and rollback of external side effects is total only when the substrate is namespaced or the writes are atomic and idempotent. ```python import hashlib from dataclasses import dataclass, field class SpeculativeContaminationError(RuntimeError): """Raised when a winning branch's verification substrate was mutated by a losing sibling.""" @dataclass class BranchWrite: resource_id: str fingerprint: str # e.g. sha256 of content the branch believes it wrote @dataclass class Branch: branch_id: str writes: list[BranchWrite] = field(default_factory=list) committed: bool = False def read_live_fingerprint(resource_id: str, substrate: dict[str, bytes]) -> str: return hashlib.sha256(substrate[resource_id]).hexdigest() def select_winner_and_assert_clean( winner: Branch, losers: list[Branch], substrate: dict[str, bytes], ) -> None: """Barrier check: the winner's expected post-state must match live state. Runs after rollback of losers' *state* but before the winner's verification replay. Detects sibling contamination of shared external resources. """ if not winner.committed: raise SpeculativeContaminationError( f"winner {winner.branch_id} selected before commit; barrier violated" ) for write in winner.writes: if write.resource_id not in substrate: raise SpeculativeContaminationError( f"winner {winner.branch_id} wrote {write.resource_id} but resource is absent" ) live = read_live_fingerprint(write.resource_id, substrate) if live != write.fingerprint: # Identify which sibling likely contaminated the substrate. suspects = [ b.branch_id for b in losers if any(w.resource_id == write.resource_id for w in b.writes) ] raise SpeculativeContaminationError( f"post-state divergence on {write.resource_id}: " f"winner expected {write.fingerprint[:12]}, live {live[:12]}; " f"losing branches that touched this resource: {suspects}. " f"Winner verification replay is invalid; re-draft from fresh checkpoint." ) ```