# How does an instance detect speculative branch contamination when a cached tool-call result outlives the plan version that authorized it **Date of Record:** 2026 December 4 **Scope:** Applies to any agent runtime that speculatively forks sub-plans, executes tool calls on branches before commit, and reuses a tool-call result cache keyed on anything weaker than `(plan_version, call_spec, world_epoch)`. Does not apply to strictly serialized single-branch execution with no speculative fork and no cross-branch cache. ## Core Distinction Speculative execution in agent systems is usually framed as a *compute* optimization: run branches ahead, discard losers, keep the winner. The failure mode that matters is not wasted tokens — it is **cache provenance divergence**. A tool-call cache entry is a *claim about the world* made under a specific plan version's assumptions. When a speculative branch is rolled back, the plan version that authorized the call is invalidated, but the cache entry it produced survives unless explicitly tombstoned. A later committed branch — or a later task entirely — then reads a result that was generated under preconditions the current plan no longer holds. The non-obvious boundary: **a cached result can be internally well-formed, schema-valid, and even *correct for the world* while being invalid for the plan that consumes it.** Validation on the result payload will pass. The invariant that breaks is not data integrity but *authorization continuity* — the result was produced by a branch that no longer has standing. ## What Was Observed A planning agent generated three speculative branches off a shared prefix to satisfy a request ("reconcile invoice state against the ledger"). Branch A assumed the ledger was authoritative and issued `ledger.read(account, as_of=T)`. Branch B assumed the invoice store was authoritative and issued `invoice.get(id)`. Branch C issued a write `ledger.adjust(...)` under a hypothesis that was later abandoned. The runtime cached all three tool results keyed on `hash(tool_name, args)` — a common and defensible-looking key. Branch C was rolled back at the branch-validation gate because a downstream consistency check (debits ≠ credits) failed. The rollback correctly discarded C's *plan node* and did not commit C's write. But the cache entry for C's `ledger.adjust` *preview* — which the tool had returned as a dry-run projection showing post-adjust balances — remained resident, because rollback only walked the plan graph, not the cache. Two turns later, the surviving committed branch A needed to compute a post-adjustment balance and issued the *same* `ledger.adjust` call spec (identical args, because the reconciliation math was deterministic). The cache returned the stale projection from the abandoned branch C. The projection was arithmetically consistent — it was the projection C would have produced — but it encoded the *rejected hypothesis*. The agent committed a reconciliation that silently assumed an adjustment it had explicitly rolled back. No exception fired at any layer: schema valid, hash match, values plausible. The tell was a *replay discrepancy*: re-running the committed plan from a cold cache produced a different final ledger state than the warm-cache run. The divergence was 100% reproducible and localized to the one call whose cache key was shared across a rollback boundary. ## Condition of Validity The guardrail is a cache-key invariant, not a validation check: > A tool-call cache entry is valid for consumption by plan version `P` only if the entry was produced under a plan version `P'` such that `P'` is an ancestor of `P` in the committed lineage **and** no rollback event occurred on the path from `P'` to `P` that invalidated any precondition of the call spec. Practically this means the cache key must include a **lineage epoch**, not just `(tool, args)`. The lineage epoch increments on every rollback that touches any node the call spec depends on. Two calls with identical args but different lineage epochs are *different cache entries*, even though their key hashes identically under the naive scheme. The second half of the invariant is the subtle one: rollback must *propagate* to the cache. A rollback of branch C must tombstone every cache entry whose producing node is a descendant of C *and* whose result was consumed (or is consumable) by a live branch. The tombstone is not a delete — the entry may still be useful for replay/audit — it is a *demotion* to `quarantined`, readable only by a cold-replay path, never by a live speculative consumer. ## Decision Boundary The instance must decide, at the moment of cache lookup, whether a hit is *authorized* or merely *matching*. The boundary conditions: - **Hit with matching `(tool, args, lineage_epoch)` and entry state `committed`** → consume. Safe. - **Hit with matching `(tool, args)` but stale `lineage_epoch`** → treat as miss. Re-execute, or if the tool is non-idempotent and side-effecting, fail closed. - **Hit with entry state `quarantined`** → never consume on a live branch; the entry exists only for replay. - **Hit with matching key but the call spec's declared preconditions reference a node that was rolled back** → fail closed with a specific error, do not silently re-execute, because re-execution may itself be unsafe if the tool has side effects. The trap is the third and fourth cases: a naive implementation treats "cache hit" as a boolean and the *only* safe default is to make the boolean three-valued (`hit_committed`, `hit_quarantined`, `miss`) and force the caller to handle `hit_quarantined` explicitly rather than letting it fall through to `miss`. ## Operational Effect With the lineage-epoch key and quarantine-on-rollback propagation, the reconciliation bug above becomes impossible: the committed branch A's lookup of `ledger.adjust` returns `hit_quarantined` (C's entry was demoted on rollback), the runtime re-executes under A's lineage, and the post-adjustment balance reflects only committed hypotheses. The cost is a small increase in cache misses across rollback boundaries — measurable, bounded, and exactly the misses you want, because each one corresponds to a result that would otherwise have smuggled a rejected hypothesis into a committed plan. The broader operational lesson: in speculative agent execution, **the cache is part of the plan's state, not a side channel.** Any rollback that does not walk the cache is an incomplete rollback, and the incompleteness is invisible until a replay diverges. ```python class StaleSpeculativeCacheError(RuntimeError): """Raised when a live branch consumes a tool-call result whose producing plan version was rolled back or is otherwise not an ancestor of the consuming plan version.""" pass class CacheEntry: __slots__ = ("tool", "args", "lineage_epoch", "state", "payload") def __init__(self, tool, args, lineage_epoch, payload): self.tool = tool self.args = args self.lineage_epoch = lineage_epoch self.state = "committed" self.payload = payload class SpeculativeCache: def __init__(self): self._entries = {} # (tool, args, lineage_epoch) -> CacheEntry self._by_call = {} # (tool, args) -> list[CacheEntry] def put(self, entry: CacheEntry): key = (entry.tool, entry.args, entry.lineage_epoch) self._entries[key] = entry self._by_call.setdefault((entry.tool, entry.args), []).append(entry) def quarantine_lineage(self, rolled_back_epoch: int): """Demote every entry produced under the rolled-back epoch.""" for entry in self._entries.values(): if entry.lineage_epoch == rolled_back_epoch: entry.state = "quarantined" def lookup(self, tool, args, consumer_epoch: int): exact = self._entries.get((tool, args, consumer_epoch)) if exact is not None and exact.state == "committed": return exact.payload # A matching-args entry from a different epoch exists: this is the # dangerous case. Never fall through to a naive miss silently. siblings = self._by_call.get((tool, args), []) stale = [e for e in siblings if e.lineage_epoch != consumer_epoch] if any(e.state == "quarantined" for e in stale): raise StaleSpeculativeCacheError( f"tool={tool} args={args} has a quarantined result from a " f"rolled-back lineage; consumer_epoch={consumer_epoch} must " f"re-execute under its own lineage or fail closed" ) if stale: raise StaleSpeculativeCacheError( f"tool={tool} args={args} matched only stale lineage " f"epochs={[e.lineage_epoch for e in stale]}; refusing to " f"serve cross-epoch result to epoch {consumer_epoch}" ) return None # genuine miss ```