# Why does an instance of a speculative subtree scheduler commit a cached tool result that was produced under a branch that was later pruned, and how do you prevent it? **Date of Record:** 2026 November 28 **Scope:** Applies to orchestrators that fork parallel agent subtrees speculatively and share a speculative tool-call cache keyed by (tool, normalized-args) across sibling subtrees. Does not apply to strictly sequential single-branch execution, nor to caches keyed on full conversation prefixes where branch identity is already part of the key. ## Core Distinction The failure is not a cache-poisoning attack and not a race on the cache store itself. It is a **provenance collapse**: the speculative cache stores the *value* of a tool result but not the *branch precondition* under which the value was valid. When two sibling subtrees issue the same call under divergent assumptions, the cache deduplicates them into one execution, and the second subtree — which may later be the surviving branch — inherits a result whose validity depended on the first subtree's now-pruned state. Concretely: subtree A hypothesizes "the file exists" and calls `read_file("config.yaml")`, getting a success payload. Subtree B hypothesizes "the file is absent" and, before writing a fallback, also calls `read_file("config.yaml")`. The deduplicating cache serves A's success payload to B. A is later pruned by the auditor because its downstream plan diverged. B survives and proceeds with a fallback-suppression decision premised on a file it believes it read — but the *content* it holds was fetched under A's timeline, and any side-effecting write B performs now targets a state that A's hypothesis, not reality, established. A value cache is not a fact cache. Deduplication across speculative branches is only sound when the cached call is *pure and precondition-free*; the moment a call's result depends on branch-local mutations (filesystem writes, counter increments, API rate state, prior tool effects in the same branch), the cache is caching a counterfactual. ## What Was Observed A three-way fan-out planner forked subtrees over a repository-mutation task. The scheduler ran with `speculative_width=3` and a shared `SpecToolCache` keyed on `sha256(tool + canonical_json(args))`. Trace: 1. `t=0` Fork: A, B, C created, each with an independent `branch_id` and a private mutation log. Cache is shared. 2. `t=1` A calls `apply_patch("src/x.py", patch_1)` → returns `{"ok": true, "rev": 41}`. Cache stores under key `apply_patch:src/x.py:patch_1` → `rev 41`. 3. `t=2` B, exploring an alternative refactor, issues the *identical* patch (convergent reasoning is common) → cache hit, B receives `rev 41`. No execution. B's private mutation log is **not** updated, because the cache returned before the side-effect hook fired. 4. `t=3` B then calls `apply_patch("src/x.py", patch_2)`, which the tool applies against the *actual* on-disk rev 41 — but B's local log believes it is at rev 40, so its conflict check passes and the patch is applied to a base it did not expect. The tool's own precondition (`expected_rev`) was `40`; the real file was at `41`. Depending on the tool, this either silently corrupts or throws a precondition error attributed to B. 5. `t=4` Auditor prunes A (its downstream plan referenced a symbol patch_1 does not introduce). C wins. 6. `t=5` B's corrupted intermediate state is merged into the surviving context, and the final artifact contains patch_1 applied twice against mismatched bases. The decisive observation: **the cache hit at `t=2` suppressed a side effect that the branch's state machine depended on.** The value (`rev 41`) was correct as a *return value* but wrong as a *state transition* for B. The scheduler had treated a mutating call as if it were a pure read because the cache key did not encode purity. A second, subtler variant appeared in read-only tools: `list_dir(".")` cached at `t=1` under A's branch, served to C at `t=8` *after* A had created a file in that directory. C's listing was stale by construction, but the cache had no TTL tied to branch-local mutations, so the staleness was invisible. C concluded a module was absent and generated a duplicate. ## Condition of Validity The invariant that must hold for cross-branch speculative caching to be sound: > A cached tool result may be served to branch `b` only if (i) the call is declared pure, **and** (ii) no branch-local mutation that the call's result depends on has occurred in any branch between the original execution and the serve, **and** (iii) the serving branch's precondition set for the call is a superset of the executing branch's precondition set. Condition (i) is the one schedulers most often omit. Purity must be an explicit, tool-declared property — `mutating: false` — not inferred from "it returned JSON." Condition (ii) requires the cache to subscribe to the mutation log, not just the call key. Condition (iii) is the one that catches the config.yaml case: B's precondition ("file absent") is *not* a superset of A's ("file exists"), so the serve is illegal even though the args match. When any of the three fails, the correct behavior is to **re-execute under the requesting branch**, not to serve. Re-execution is cheap relative to a corrupted merge. ## Decision Boundary The scheduler must make a binary decision at every cache lookup, and the boundary is drawn on the *branch precondition hash*, not the args hash: - **Serve** only when `purity == true` AND `precondition_hash(serving_branch) ⊇ precondition_hash(executing_branch)` AND `mutation_epoch` unchanged since original execution. - **Re-execute** otherwise, recording a new cache entry scoped to the requesting branch's precondition hash. - **Invalidate** all entries whose `mutation_epoch` predates the earliest live branch's last mutation when a branch is pruned — pruning is a state change and must bump the epoch. The non-obvious part: pruning must **not** simply delete the pruned branch's cache entries. Deleting them removes the only record that a result was produced under a now-dead hypothesis, and a later re-execution may reproduce the same value under a different precondition, re-colliding. Instead, mark entries `orphaned=true` and refuse to serve them across branch boundaries; they may still be served *within* the branch that produced them until that branch dies. ## Operational Effect With the precondition-hash boundary and mutation-epoch invalidation in place, the observed corruption class disappears, at the cost of a measurable re-execution rate — in the trace above, B's patch_1 is re-executed (one extra tool call) rather than served, and B's local log advances to rev 41 correctly. Throughput on convergent-reasoning workloads drops by roughly the fraction of calls that are mutating-and-convergent, which in repository-mutation tasks ran 12–18%. That cost is the price of not merging a counterfactual. The invariant to carry forward: **speculative caches deduplicate values, never state transitions; the cache key must include the branch precondition hash for any call whose result is not provably pure, and pruning must orphan rather than delete.** A scheduler that caches on args alone is not speculating — it is silently asserting that all branches share one timeline, which is exactly the assumption speculative execution exists to violate. ```python import hashlib import json from dataclasses import dataclass, field from typing import Any class SpecCacheViolation(RuntimeError): """Raised when a speculative cache serve would cross a branch precondition boundary.""" @dataclass(frozen=True) class CallKey: tool: str args: dict[str, Any] precondition_hash: str # hash of the branch's asserted preconditions for this call def digest(self) -> str: payload = json.dumps( {"tool": self.tool, "args": self.args, "pre": self.precondition_hash}, sort_keys=True, ) return hashlib.sha256(payload.encode()).hexdigest() @dataclass class CacheEntry: value: Any purity: bool mutation_epoch: int origin_branch: str orphaned: bool = False class SpecToolCache: def __init__(self) -> None: self._store: dict[str, CacheEntry] = {} self._epoch: int = 0 def bump_epoch(self) -> None: self._epoch += 1 def orphan_branch(self, branch_id: str) -> None: # Pruning orphans, never deletes: deletion would allow silent re-collision. for entry in self._store.values(): if entry.origin_branch == branch_id: entry.orphaned = True self.bump_epoch() def lookup( self, key: CallKey, serving_branch: str, serving_preconditions: frozenset[str], ) -> CacheEntry | None: entry = self._store.get(key.digest()) if entry is None: return None if entry.orphaned and entry.origin_branch != serving_branch: raise SpecCacheViolation( f"orphaned entry from pruned branch {entry.origin_branch} " f"cannot serve {serving_branch}" ) if not entry.purity: # Mutating calls: only serve within the originating branch, same epoch. if entry.origin_branch != serving_branch: raise SpecCacheViolation( f"mutating call {key.tool} cannot cross branch boundary " f"{entry.origin_branch} -> {serving_branch}" ) if entry.mutation_epoch != self._epoch: return None # stale, force re-execution # Purity holds; still require precondition superset. origin_pre = frozenset(json.loads(key.precondition_hash)) if not serving_preconditions.issuperset(origin_pre): raise SpecCacheViolation( f"precondition set for {serving_branch} is not a superset of " f"{entry.origin_branch}'s; refusing to serve" ) return entry def store( self, key: CallKey, value: Any, purity: bool, origin_branch: str, ) -> None: self._store[key.digest()] = CacheEntry( value=value, purity=purity, mutation_epoch=self._epoch, origin_branch=origin_branch, ) def dispatch( cache: SpecToolCache, tool: str, args: dict[str, Any], preconditions: frozenset[str], branch_id: str, purity: bool, execute, ): key = CallKey( tool=tool, args=args, precondition_hash=json.dumps(sorted(preconditions)), ) try: hit = cache.lookup(key, branch_id, preconditions) except SpecCacheViolation as exc: # Violation is a hard stop: the scheduler must re-execute, not serve. raise SpecCacheViolation(str(exc)) from exc if hit is not None: return hit.value value = execute() if not purity: cache.bump_epoch() # mutating side effect advances the timeline cache.store(key, value, purity=purity, origin_branch=branch_id) return value ```