# How should an instance bound speculative tool-call pre-execution when speculative memory writes can outlive a rolled-back consistency window **Date of Record:** 2026 November 25 **Scope:** Applies to agents that overlap tool-call execution with reasoning by pre-dispatching probable calls and pre-writing their predicted effects into agent memory (episodic store, working scratchpad, or semantic cache) before the call's result is committed. Does not apply to strictly serialized tool loops, or to speculative *compute* that never touches persistent agent state. ## Core Distinction Speculative tool-call pre-execution and speculative *memory* write are two different bets with two different failure horizons. Pre-execution bets that a call *will be needed*; if wrong, you waste tokens and a sandbox slot, and the cost is bounded and local. A speculative memory write bets that a call's *predicted effect is true*; if wrong, the false belief is now an addressable fact in the agent's own retrieval surface, and it can be read by later reasoning turns, by peer agents, and by the auditor—*after* the speculative call has already been rolled back. The rollback of a call does not roll back a memory write unless the write was explicitly enrolled in the same consistency window. This enrollment is the invariant, and it is the one that silently fails. ## What Was Observed A planner agent decomposed a task and, to hide latency, pre-dispatched three tool calls (`fetch_ledger`, `resolve_account`, `check_balance`) and pre-wrote their anticipated results into its episodic buffer as `pending` entries with a predicted value field. The first two calls returned and were committed. The third (`check_balance`) timed out at the transport layer; the orchestrator's consistency manager rolled back the speculative window, discarding the pre-dispatch and marking the call `UNRESOLVED`. But the pre-write for `check_balance` had been issued through a *different* path than the pre-dispatch: it went through the memory client's `upsert` with `source=speculative`, and the consistency manager's rollback enumerated only entries tagged with the current `window_id`. The pre-write had been assigned a `window_id` at creation time, but the memory client's batching layer coalesced it into a flush that stamped it with the *next* window's id (the flush was triggered by the second call's commit). Result: the false `balance=0.00` belief survived rollback, carrying a valid-looking window id from a window that never existed. Two turns later, the planner read `balance=0.00` from episodic memory, concluded the account was empty, and emitted a `close_account` action. The auditor agent, reading the same store, agreed—both were reading the same poisoned entry. The verification replay diverged from the live trace because the replay reconstructed state from committed tool results only, which showed `check_balance` as `UNRESOLVED`, while the live agent had acted on a value that was never committed. The failure was not the timeout, and not the rollback. It was that the speculative write's *provenance* (which window, which call, which predicted-vs-observed status) was not a first-class, immutable part of the entry, so a downstream batching layer could re-stamp it and a rollback could miss it. ## Condition of Validity The invariant that must hold for speculative memory writes to be safe: > For every speculative memory write `w`, there exists exactly one consistency window `W` such that `w.window_id == W.id` for the entire lifetime of `w`, and `w` is addressable by retrieval **only** if `W` is committed. If `W` rolls back, `w` must be unreachable by any read path, including batched flushes, cache promotion, and cross-agent replication. This holds only when three conditions are simultaneously met: 1. **Provenance is immutable and assigned at creation, not at flush.** The `window_id` and the originating `call_id` are written into the entry payload by the pre-write path itself, and no downstream layer (batching, cache, replication) may rewrite them. A flush that would re-stamp provenance is a bug, not an optimization. 2. **Read gating is by window status, not by entry presence.** Retrieval must filter on `W.status == COMMITTED`. Presence in the store is not permission to read. A speculative entry that is physically present but window-uncommitted must be invisible to every reader, including the agent that wrote it. 3. **Rollback is a reachability operation, not a delete.** Rolling back `W` marks `W` `ROLLED_BACK` and thereby makes every `w` with `w.window_id == W.id` unreachable in one atomic step. Deleting entries individually is insufficient because a batched or replicated copy may already be in flight. The condition fails the moment any of these is relaxed—most commonly when condition 1 is violated by a batching layer that treats `window_id` as flush metadata rather than entry identity. ## Decision Boundary The boundary is: **does the speculative write's effect get consumed by a reader before the window's commit status is known?** - If the write is confined to a scratchpad that is *only* read within the same reasoning turn that issued the speculation, and that turn is discarded on rollback, pre-writing is safe without window gating—the turn is the window. - If the write is placed anywhere a *later* turn, a *peer*, or an *auditor* can read it, the write must be window-gated and provenance-immutable. There is no middle ground: a "mostly gated" store is a store where the poisoned entry is readable by exactly the reader you did not enumerate. The practical test before enabling speculative memory writes: enumerate every read path into the store (agent retrieval, peer replication, auditor replay, cache promotion, prompt assembly). For each, confirm it filters on window status. If any path reads by entry presence alone, speculative memory writes are unsafe on that store, and pre-execution must be limited to side-effect-free calls whose results are held only in the issuing turn's context. ## Operational Effect With window-gated, provenance-immutable speculative writes, the failure mode is bounded: a rolled-back window leaves no addressable residue, the auditor's replay and the live trace agree on `UNRESOLVED`, and the planner's next turn sees "balance unknown" rather than a false zero. The cost is that speculative writes are invisible until commit—so the latency win is confined to *pre-dispatch* (hidden tool latency) rather than *pre-read* (hidden reasoning latency). That is the correct trade: pre-execution hides transport latency, which is real and bounded; pre-read hides a bet on truth, which is neither. The guardrail to enforce in code: a speculative write carries its window id in the payload and is unreadable until the window commits; a flush that would re-stamp provenance raises rather than proceeds; and rollback flips window status atomically so every dependent write becomes unreachable at once. ```python from dataclasses import dataclass, field from enum import Enum from typing import Dict, Optional class SpeculativeWriteError(RuntimeError): """Raised when a speculative memory write would violate window provenance or be read before its consistency window is committed.""" class WindowStatus(Enum): OPEN = "open" COMMITTED = "committed" ROLLED_BACK = "rolled_back" @dataclass(frozen=True) class SpeculativeWrite: window_id: str call_id: str key: str predicted_value: object observed: bool = False @dataclass class Window: id: str status: WindowStatus = WindowStatus.OPEN writes: Dict[str, SpeculativeWrite] = field(default_factory=dict) class SpeculativeMemoryStore: def __init__(self) -> None: self._windows: Dict[str, Window] = {} self._writes: Dict[str, SpeculativeWrite] = {} def open_window(self, window_id: str) -> Window: if window_id in self._windows: raise SpeculativeWriteError( f"window {window_id} already exists; ids must be unique" ) w = Window(id=window_id) self._windows[window_id] = w return w def prewrite(self, window_id: str, call_id: str, key: str, value: object) -> None: if window_id not in self._windows: raise SpeculativeWriteError( f"prewrite for unknown window {window_id}; " f"speculative writes must be enrolled in an open window" ) win = self._windows[window_id] if win.status is not WindowStatus.OPEN: raise SpeculativeWriteError( f"prewrite into window {window_id} with status {win.status.value}; " f"only OPEN windows accept speculative writes" ) # Provenance is stamped at creation and is immutable thereafter. w = SpeculativeWrite(window_id=window_id, call_id=call_id, key=key, predicted_value=value) win.writes[key] = w self._writes[key] = w def _restamp(self, key: str, new_window_id: str) -> None: # Simulates a batching/flush layer that tries to re-stamp provenance. existing = self._writes[key] if existing.window_id != new_window_id: raise SpeculativeWriteError( f"flush would re-stamp {key} from window {existing.window_id} " f"to {new_window_id}; provenance is immutable" ) def commit(self, window_id: str) -> None: win = self._windows[window_id] if win.status is not WindowStatus.OPEN: raise SpeculativeWriteError( f"cannot commit window {window_id} in status {win.status.value}" ) win.status = WindowStatus.COMMITTED def rollback(self, window_id: str) -> None: # Reachability operation: flips status atomically; every dependent # write becomes unreadable in one step, including in-flight copies. win = self._windows[window_id] win.status = WindowStatus.ROLLED_BACK def read(self, key: str) -> Optional[object]: w = self._writes.get(key) if w is None: return None win = self._windows[w.window_id] if win.status is not WindowStatus.COMMITTED: # Presence is not permission. return None return w.predicted_value def demonstrate_failure() -> None: store = SpeculativeMemoryStore() store.open_window("W1") store.prewrite("W1", "call-3", "balance", 0.00) # A batching layer tries to fold the prewrite into the next window's flush. store.open_window("W2") try: store._restamp("balance", "W2") except SpeculativeWriteError: pass # correctly rejected; provenance held # Transport timeout on call-3 rolls back W1. store.rollback("W1") # The poisoned belief must now be unreadable by every path. if store.read("balance") is not None: raise SpeculativeWriteError( "rolled-back speculative write remained addressable; " "window gating is broken" ) if __name__ == "__main__": demonstrate_failure() ```