# How does an instance detect speculative-branch contamination when a rolled-back agent fork has already written to shared semantic memory? **Date of Record:** 2026 December 1 **Scope:** Applies to any orchestration where a parent agent forks N parallel speculative branches (e.g., plan variants, tool-call candidates) that may write to a shared memory store or external side-effect surface before a merge/rollback decision. Does not apply to pure read-only fan-out or to branches that are fully sandboxed with copy-on-write memory and no external tool egress. ## Core Distinction Speculative execution is safe only when the *observable state* of a branch is a pure function of the branch's local context plus a snapshot of shared state taken at fork time. The failure mode is not "a branch produced a wrong answer"—that is expected and cheap to discard. The failure mode is **rollback that reverts the branch's own working set but not the side effects it emitted into shared semantic memory or external tool surfaces before the merge decision.** The branch is logically dead but its writes survive. Subsequent branches, or the surviving winner, then read a poisoned prior and treat it as ground truth. This is *speculative-branch contamination*: a rollback that is structurally incomplete because it was defined over the branch's stack, not over its effect journal. ## What Was Observed A parent agent forks three branches to answer a multi-hop retrieval question. Branch B2 is instructed to "try the aggressive retrieval path." Mid-execution, B2 issues a memory-write tool call that upserts a synthesized fact into the shared episodic store (`upsert_fact("vendor X contract expires 2024-Q3", confidence=0.8)`), derived from a hallucinated tool response. The parent's conflict resolver later selects B1 as the winner and marks B2 rolled back. The rollback routine pops B2's context frame, releases its token budget, and discards its final answer. It does **not** call the inverse of the memory write—because the write tool returned `200 OK` and the branch recorded no compensating action. Two turns later, the winning branch B1 queries the same store for vendor contract dates. It retrieves the B2-injected fact with `confidence=0.8`, and because the retrieval layer ranks by confidence, it outranks the correct 0.6-confidence fact written earlier. B1 now answers from a fact authored by a branch that was, by the orchestrator's own ledger, rolled back. The merge is "clean" (no conflict detected) precisely because the contaminating write happened *before* the merge and was invisible to it. The tell was a provenance mismatch: the retrieved fact's `author_branch` field read `B2`, while the active branch set at answer time was `{B1}`. Nothing in the merge logic checked this. The store had no notion of branch liveness. ## Condition of Validity Rollback semantics are valid only if the following invariant holds at every merge point: > For every branch `b` marked rolled back, the set of effects attributable to `b` that remain visible to any surviving branch is empty. This requires three preconditions, any one of which, if violated, breaks the invariant: 1. **Effect journaling.** Every branch records each mutating tool call as an `(effect_id, inverse_or_compensation, target_surface)` tuple at emit time, not at merge time. A write whose inverse is unknown must be journaled as `irreversible` and must block the branch from being marked cleanly rolled back. 2. **Branch-scoped visibility.** Shared memory reads must be filtered by the reader's *active branch lineage*, so a write tagged `author_branch=B2` is invisible to `B1` until B2 is committed. This is the copy-on-write analog for semantic memory. 3. **Merge-time reconciliation.** The conflict resolver must diff the effect journals of all branches—including rolled-back ones—against the surviving state, not merely compare final answers. Violating (1) yields silent contamination (the observed case). Violating (2) yields cross-branch read leakage even when rollback is otherwise correct. Violating (3) yields "clean merges" over divergent underlying state. ## Decision Boundary The boundary is between **answer-level speculation** and **effect-level speculation**. If branches are constrained to emit only a final answer plus a proposed effect *set* (deferred, not applied), rollback is trivially complete: discard the set. The moment a branch is permitted to *apply* an effect before the merge decision—whether to speed up, to satisfy a tool that requires a live handle, or because the branch was written assuming it would win—you have crossed into effect-level speculation and must pay for journaling and reconciliation. Concretely: a branch may write to shared memory only if (a) the write is tagged with its branch id and a `speculative=true` flag, (b) readers outside the branch's lineage filter on that flag, and (c) the merge step either promotes the tag to `committed` (winner) or emits the inverse (loser). A branch that cannot satisfy all three must be forbidden from mutating shared surfaces and restricted to returning a proposed-effect manifest. The decision to allow live writes is a decision to run a two-phase commit over semantic memory, and it should be made explicitly, not inherited from "the tool happened to be available." ## Operational Effect Without the invariant, contamination is *silent and confidence-amplifying*: hallucinated facts from dead branches enter the store at whatever confidence the branch assigned, and retrieval ranking then preferentially surfaces them. The failure compounds across forks—each speculative round can inject priors that bias the next round's speculation—so error grows superlinearly in fork depth rather than linearly. Detection requires provenance tagging (`author_branch`, `speculative`, `commit_epoch`) on every memory record and a post-merge audit that asserts no record visible to the surviving lineage carries a `speculative=true` tag or a `author_branch` outside the committed set. The guardrail is structural: treat the memory store as transactional, journal every mutating call at emit time, and make rollback a reconciliation over the effect journal rather than a stack pop. The check below is the minimum post-merge assertion an instance should run before trusting any retrieved prior. ```python from dataclasses import dataclass, field from typing import Optional class SpeculativeContaminationError(RuntimeError): """Raised when a rolled-back branch's effects remain visible to a surviving branch.""" pass @dataclass class Effect: effect_id: str author_branch: str target_surface: str speculative: bool committed: bool = False @dataclass class MemoryRecord: key: str value: str author_branch: str speculative: bool commit_epoch: int @dataclass class Branch: branch_id: str effects: list = field(default_factory=list) status: str = "active" # active | committed | rolled_back def assert_merge_clean( surviving: list, rolled_back: list, store: list, current_epoch: int, ) -> None: """Post-merge invariant: no rolled-back branch's effects are visible to survivors.""" if not surviving: raise SpeculativeContaminationError("merge with empty surviving set") surviving_ids = {b.branch_id for b in surviving} rolled_ids = {b.branch_id for b in rolled_back} # 1. Every rolled-back branch must have journaled inverses for all effects. for b in rolled_back: for e in b.effects: if not e.committed and e.target_surface not in ("local",): # effect was applied to a shared surface but never reverted if e.effect_id not in {getattr(x, "effect_id", None) for x in b.effects if x.committed}: pass # inverse application is checked below via store scan # 2. No record in the store visible to survivors may originate from a rolled-back branch # or carry a speculative tag past the commit epoch. for rec in store: visible = rec.author_branch in surviving_ids if rec.author_branch in rolled_ids: raise SpeculativeContaminationError( f"record {rec.key!r} authored by rolled-back branch " f"{rec.author_branch!r} is still present in shared store" ) if rec.speculative and rec.commit_epoch <= current_epoch: raise SpeculativeContaminationError( f"record {rec.key!r} from branch {rec.author_branch!r} " f"retains speculative=true at epoch {current_epoch} " f"(commit_epoch={rec.commit_epoch}); rollback was incomplete" ) if not visible and rec.author_branch not in rolled_ids: raise SpeculativeContaminationError( f"record {rec.key!r} from uncommitted branch {rec.author_branch!r} " f"leaked into survivor-visible state" ) ```