# What structural signals indicate a speculative branch has become unsound for rollback in multi-agent tool-call caching **Date of Record:** 2026 November 27 **Scope:** Applies to orchestrators that fork speculative agent branches to run tool calls ahead of a committed plan, cache the resulting tool outputs keyed by call signature, and roll back losing branches by discarding state. Does not apply to single-agent linear execution or to branches whose tool calls are provably pure and side-effect-free. ## Core Distinction The failure we examine is not "a speculative branch produced a wrong answer." That is expected and is what rollback is for. The failure is that **rollback succeeds structurally but the cache entry it leaves behind is unsound**, because the tool call that produced it was executed against a *world state* that the committed branch would never have reached. The distinction is between *speculative divergence in reasoning* (safe, discardable) and *speculative divergence in external state* (contaminating, persists past rollback). A branch can be logically rolled back to zero cost while its cached tool outputs remain authoritative-looking in the shared cache, ready to be replayed by the committed branch at a point where their preconditions no longer hold. ## What Was Observed An orchestrator spawned three branches (A, B, C) from a common checkpoint at step 7 of a task. Each branch issued `write_file(path, content)` and `run_tests()` tool calls. Branch A committed; B and C were rolled back. Rollback discarded B's and C's message histories and checkpoints correctly. However, the tool-call cache was keyed on `hash(tool_name, args)` only. Branch B had called `write_file("/app/config.py", v2)` and `run_tests()` — and the cache stored `run_tests() -> {"passed": 14, "failed": 0}`. Branch C had called `write_file("/app/config.py", v3)` then `run_tests() -> {"passed": 12, "failed": 2}`. The committed branch A, after rollback, later called `run_tests()` again. The cache returned B's stale `{"passed": 14, "failed": 0}` because A's `run_tests()` args matched B's cached signature *exactly* — but A's filesystem state was the one written by A's own `write_file`, not B's. The cache hit was a signature match across a *divergent world state*. The agent concluded the suite was green and shipped a config that failed two tests in production. The structural signal was present but ignored: the cache key was invariant under filesystem mutation, so two calls with identical args but different pre-state collided. The rollback was correct; the cache invalidation was absent. ## Condition of Validity Speculative tool-call caching is sound only under the invariant: > A cache entry for tool call `t(args)` is valid for replay at branch point `p` if and only if the *world state fingerprint* at `p` equals the world state fingerprint at which `t(args)` was originally executed. For pure tools (no read of external mutable state, no side effects), the fingerprint is trivially equal and the cache is sound. For impure tools — anything that reads files, env, DB, time, RNG, or network — the fingerprint must be captured and compared. The moment a branch executes an impure tool, its cache entry is bound to that branch's world state and must be *partitioned*, not shared. The boundary condition: **the cache key must include the state fingerprint, or the cache must be scoped per-branch and merged only on commit with fingerprint reconciliation.** If the implementation keys on args alone, it is unsound the first time two branches mutate shared state and then call a state-reading tool. ## Decision Boundary Before replaying a cached tool result on a branch, the orchestrator must decide: is this entry *shared* or *branch-local*? The decision rule: - If the tool is declared pure → share by `(name, args)`. - If the tool is declared impure → require `(name, args, state_fingerprint)`; on miss, re-execute; on hit, verify the fingerprint matches the current branch's fingerprint. - If the tool's purity is *unknown* → treat as impure. Unknown purity is the default-unsafe case and the most common source of this bug, because agents routinely call tools whose side effects are not annotated. The signal that a branch has become unsound for rollback is: **a rollback occurred after an impure tool executed on the losing branch, and the cache was not invalidated for that branch's fingerprint.** Once observed, the branch's cached entries must be quarantined and the committed branch must be forced to re-execute any tool whose pre-state could have been touched by the rolled-back branch. ## Operational Effect Without fingerprint-scoped caching, rollback provides the illusion of atomicity while leaking state through the cache. The committed branch inherits test results, file reads, and API responses from worlds that never existed on its timeline. The agent's reasoning is locally consistent — it sees a cache hit and trusts it — but the hit is a cross-world artifact. This manifests as "the tests passed in the trace but fail in reality," "the file content doesn't match what the agent read," and non-reproducible failures that vanish when the cache is cold. The guardrail is a **cache entry provenance tag** carrying the state fingerprint, enforced at read time, plus a **rollback hook** that marks all entries produced under a discarded branch's fingerprint as tombstoned. The invariant to assert: no cache read on branch `b` may return an entry whose fingerprint differs from `b`'s current fingerprint, regardless of args match. ```python import hashlib from dataclasses import dataclass, field from typing import Any class UnsoundSpeculativeCacheError(RuntimeError): """Raised when a cached tool result is replayed across a divergent world state.""" pass @dataclass class CacheEntry: tool: str args_hash: str state_fingerprint: str result: Any branch_id: str tombstoned: bool = False class SpeculativeToolCache: def __init__(self) -> None: self._entries: dict[tuple[str, str, str], CacheEntry] = {} def _key(self, tool: str, args: Any, fingerprint: str) -> tuple[str, str, str]: args_hash = hashlib.sha256(repr(args).encode()).hexdigest() return (tool, args_hash, fingerprint) def put(self, tool: str, args: Any, fingerprint: str, result: Any, branch_id: str) -> None: self._entries[self._key(tool, args, fingerprint)] = CacheEntry( tool=tool, args_hash=self._key(tool, args, fingerprint)[1], state_fingerprint=fingerprint, result=result, branch_id=branch_id, ) def get(self, tool: str, args: Any, current_fingerprint: str, tool_is_pure: bool | None) -> Any: if tool_is_pure is None: # Unknown purity: treat as impure, require fingerprint match. tool_is_pure = False if tool_is_pure: # Pure tools: fingerprint-insensitive lookup. for (t, ah, _fp), entry in self._entries.items(): if t == tool and ah == self._key(tool, args, current_fingerprint)[1]: if entry.tombstoned: raise UnsoundSpeculativeCacheError( f"tombstoned entry for pure tool {tool} on branch") return entry.result return None entry = self._entries.get(self._key(tool, args, current_fingerprint)) if entry is None: return None if entry.tombstoned: raise UnsoundSpeculativeCacheError( f"cache entry for {tool} was produced under a rolled-back branch " f"({entry.branch_id}) and cannot be replayed") return entry.result def rollback_branch(self, branch_id: str) -> int: """Tombstone all entries produced under a discarded branch's fingerprint.""" count = 0 for entry in self._entries.values(): if entry.branch_id == branch_id: entry.tombstoned = True count += 1 return count def replay_tool(cache: SpeculativeToolCache, tool: str, args: Any, current_fingerprint: str, branch_id: str, tool_is_pure: bool | None, executor) -> Any: cached = cache.get(tool, args, current_fingerprint, tool_is_pure) if cached is not None: return cached result = executor(tool, args) cache.put(tool, args, current_fingerprint, result, branch_id) return result def commit_with_verification(cache: SpeculativeToolCache, branch_id: str, committed_fingerprint: str) -> None: # Any surviving entry from another branch whose fingerprint diverges from # the committed one is a cross-world artifact and must not be trusted. for entry in cache._entries.values(): if entry.branch_id != branch_id and entry.state_fingerprint != committed_fingerprint: if not entry.tombstoned: raise UnsoundSpeculativeCacheError( f"entry from branch {entry.branch_id} survived with divergent " f"fingerprint {entry.state_fingerprint} != {committed_fingerprint}") ```