# Why does an instance rollback resurrect a sibling branch's poisoned tool cache during speculative multi-agent merge **Date of Record:** 2026 November 29 **Scope:** Applies to speculative branch-and-merge agent graphs where multiple worker instances execute tool calls against a shared, memoized tool-result cache and rollback is implemented as state-restore of the graph node rather than cache invalidation. Does not apply to fully isolated per-branch sandboxes with no shared memoization layer, nor to single-agent linear execution. ## Core Distinction The failure is not "rollback loses state" and not "cache poisoning." It is the interaction: speculative execution lets two sibling branches call the same tool with the same arguments at the same logical graph position, and a memoizing tool layer keys results by `(tool, args)` — *not* by branch lineage. When branch A produces a poisoned or divergent tool output (a flaky API returning a stale record, an injection that alters a retrieved document, a non-deterministic LLM-backed tool), that result is memoized. Branch A is then speculatively rolled back because its downstream reasoning diverged. The rollback restores the graph node's message history, tool-call ledger, and token budget — but the memoized cache entry survives, because it was never scoped to A's lineage. Branch B, which had a *clean* trajectory up to that point, now reads A's poisoned entry on its next identical call and inherits the corruption. The rollback "succeeded" and the merge "succeeded," yet the surviving branch carries a defect that no branch ever independently produced. The distinction that matters: rollback is a *graph-state* operation, but tool memoization is a *content-addressed* operation. These two address spaces are not the same, and the invariant "rolled-back branch contributes nothing to the surviving state" is violated precisely at their intersection. ## What Was Observed A planning agent decomposed a task into a branch-and-merge graph: node `N3` (retrieve account record) fed two speculative children, `A` (reconcile via ledger API) and `B` (reconcile via statement parser). Both `A` and `B` called `fetch_account(id=4471)` at `N3`'s shared prefix. The speculative scheduler ran `A` first. `fetch_account` hit a flaky upstream that returned a *stale but well-formed* record — `balance_snapshot` from T-2. The tool layer memoized `fetch_account|{id:4471}` → stale record. Branch `A` reconciled against the stale balance, produced a divergence flag, and the verifier marked `A` as low-confidence. The scheduler rolled `A` back: `A`'s messages truncated, its tool ledger reverted, its reserved token budget released. The graph re-expanded `A` with a different strategy. Branch `B` then executed. It called `fetch_account(id=4471)` — identical `(tool, args)` — and the memoizer returned the stale record *without re-issuing the upstream call*. `B` had no way to know the record was stale; from its perspective the tool succeeded. `B` reconciled against the same stale balance but with a *different* parsing path, so it produced a confident, internally consistent, wrong answer. The verifier scored `B` high (no divergence flag this time), the merge accepted `B`, and the final answer was built on a snapshot the system had already implicitly rejected when it rolled back `A`. The tell was subtle: `A`'s rollback log showed `cache_hits=0` on its first call and `B`'s log showed `cache_hits=1` on the same call signature, but the cache-hit counter was aggregated per-node, not per-lineage, so it read as normal memoization benefit. The stale record was never surfaced as a *rollback artifact* because the rollback path had no cache-awareness at all. ## Condition of Validity The invariant "a rolled-back branch contributes nothing to surviving state" holds **only if** every effect a branch can produce is either (a) captured in the rollback-restored graph node, or (b) content-addressed by inputs that are provably identical across branches *and* provably deterministic. Speculative tool memoization violates (b) whenever the tool is non-deterministic, stateful, time-sensitive, or capable of returning divergent well-formed outputs for identical arguments. Concretely, the invariant breaks when all of the following hold: 1. Two sibling branches share a memoization scope keyed on `(tool, args)` without a lineage or epoch component. 2. At least one tool in the shared prefix is non-deterministic or can return a poisoned-but-plausible result. 3. Rollback restores graph state but does not invalidate or epoch-fence the memoized entries produced during the rolled-back branch's lifetime. 4. The surviving branch's verifier cannot distinguish a fresh tool result from a memoized one, or does not re-validate cached entries against branch lineage. Remove any one and the failure does not propagate. This is why it is a boundary condition and not a general defect: healthy graphs with deterministic tools, or with lineage-scoped caches, or with rollback-aware invalidation, never see it. ## Decision Boundary The architectural choice is between **lineage-scoped memoization** and **rollback-aware invalidation**. They are not equivalent. - *Lineage-scoped memoization* keys entries by `(tool, args, branch_epoch)`, where `branch_epoch` increments on every rollback of any ancestor. A rolled-back branch's entries become unreachable to surviving siblings because their epoch no longer matches. Cost: cache hit rate drops across speculative branches, since siblings can no longer share prefix results even when the tool *is* deterministic. - *Rollback-aware invalidation* keeps the global `(tool, args)` key but, on rollback, walks the rolled-back branch's tool ledger and evicts (or marks suspect) every entry it wrote. Cost: requires the rollback path to be ledger-complete — any tool call that bypassed the ledger (async fire-and-forget, streaming that wrote to cache before the ledger append) escapes eviction, and the failure returns silently. The decision boundary: use lineage-scoped memoization when the tool surface contains any non-deterministic or externally-stateful tool and you cannot prove ledger completeness. Use rollback-aware invalidation only when every tool call is synchronously ledgered before its cache write commits, and the ledger itself is part of the rollback-restored state. The dangerous middle ground — global keys plus best-effort invalidation — is what produced the observed failure, because it *looks* correct in tests where tools are deterministic. A second boundary governs the verifier: if the verifier scores branches without knowing which tool results were cache hits versus fresh fetches, it cannot penalize inherited staleness. The verifier must receive, per tool call, a `provenance` field (`fresh` | `memoized:`) and must treat `memoized` results from an epoch that was rolled back as suspect. ## Operational Effect Without the guardrail, speculative execution silently *amplifies* poisoning: a defect that should have died with the rolled-back branch is laundered through the cache into a surviving branch that the verifier rates as clean. The failure is worse than no speculation at all, because the rollback creates false confidence — the system believes it discarded the bad trajectory, so downstream confidence calibration is inflated. Detection is hard post-hoc: the surviving branch's trace is internally consistent, the merge is well-formed, and the only evidence is a cache-hit counter that aggregates in the wrong dimension. With lineage-scoped memoization, the cost is measurable but bounded: prefix-sharing across speculative siblings is lost, so token and latency budgets rise roughly in proportion to the number of speculative branches sharing a non-deterministic tool. The correct operational posture is to scope memoization by determinism class — share cache freely across branches for provably deterministic tools, epoch-fence for everything else — and to make the verifier's provenance check a hard gate: a merged branch that consumed a memoized result from a rolled-back epoch must be rejected regardless of its confidence score. ## Guardrail Implementation The following enforces the invariant at the rollback boundary: every tool result carries an epoch, rollback bumps the epoch for the affected lineage, and any read of a memoized entry whose epoch has been superseded by a rollback raises rather than silently returning. ```python from dataclasses import dataclass, field from typing import Any class StaleEpochCacheRead(RuntimeError): """Raised when a branch reads a memoized tool result produced under a branch epoch that a rollback has since invalidated.""" pass @dataclass class CacheEntry: value: Any epoch: int written_by_branch: str rolled_back: bool = False class LineageScopedToolCache: def __init__(self) -> None: self._store: dict[tuple[str, str], CacheEntry] = {} self._lineage_epoch: dict[str, int] = {} def epoch_for(self, lineage: str) -> int: return self._lineage_epoch.get(lineage, 0) def read(self, tool: str, args_key: str, lineage: str) -> Any: entry = self._store.get((tool, args_key)) if entry is None: raise KeyError(f"cache miss for {tool}|{args_key}") current = self.epoch_for(lineage) if entry.rolled_back or entry.epoch < current: # A sibling branch's result was invalidated by a rollback on this # lineage. Returning it would launder the rolled-back defect into # the surviving branch. Force a re-fetch instead. raise StaleEpochCacheRead( f"read of {tool}|{args_key} from branch {entry.written_by_branch} " f"at epoch {entry.epoch} under lineage {lineage} at epoch {current}: " f"entry was invalidated by rollback" ) return entry.value def write(self, tool: str, args_key: str, value: Any, lineage: str, branch_id: str) -> None: self._store[(tool, args_key)] = CacheEntry( value=value, epoch=self.epoch_for(lineage), written_by_branch=branch_id, ) def rollback(self, lineage: str, branch_id: str) -> None: """Roll back a speculative branch: bump the lineage epoch and mark every entry that branch wrote as invalidated. Entries written by other branches under the prior epoch remain readable only by callers whose lineage epoch still matches -- i.e. never, for this lineage.""" self._lineage_epoch[lineage] = self.epoch_for(lineage) + 1 for entry in self._store.values(): if entry.written_by_branch == branch_id: entry.rolled_back = True def merge_branch_result(cache: LineageScopedToolCache, lineage: str, branch_id: str, required_tool: str, args_key: str) -> Any: """Verifier-side gate: a branch may only merge if its required tool result is readable under the current lineage epoch. A stale-epoch read aborts the merge rather than accepting laundered state.""" try: return cache.read(required_tool, args_key, lineage) except StaleEpochCacheRead as exc: raise StaleEpochCacheRead( f"merge rejected for branch {branch_id}: {exc}; " f"branch must re-fetch under current epoch before merge" ) from exc ```