# Under what conditions must an instance invalidate a speculatively prefetched tool result before commit, when a concurrent memory write has mutated the arguments' read-set? **Date of Record:** 2026 November 25 **Scope:** Applies to agents that overlap tool-call execution with reasoning by speculatively dispatching predicted calls ahead of the decision point, and that share a mutable memory store (episodic buffer, semantic cache, or scratchpad) with other concurrent writers. Does not apply to single-writer agents or to tool calls whose arguments are fully ground-truth constants with no memory-derived read-set. ## Core Distinction The failure is not "stale cache." It is **read-set drift between prediction and commit**. A speculative prefetch is only sound if the *arguments the tool was invoked with* remain a valid function of memory at the moment the result is committed into the reasoning trace. Most prefetch implementations validate the *predicted tool identity* ("did I guess the right tool?") and the *result schema* ("did it return the expected shape?"), but never validate the *input read-set* ("are the memory cells this call read still equal to what they were when I dispatched?"). These are different invariants. A prefetch can guess the right tool, return a well-formed result, and still be catastrophically wrong because a concurrent agent rewrote the memory cell that the arguments depended on between dispatch and commit. The result is a *correctly executed call on a now-invalid premise*, silently spliced into the reasoning trace as if authoritative. The non-obvious part: the drift window is not the tool's network latency. It is the interval from **argument materialization** (when the agent rendered its read-set into concrete arguments) to **result commit** (when the trace accepts the result). Argument materialization often happens far earlier than dispatch, during the prediction step. This window can span multiple reasoning turns and any number of concurrent writes. ## What Was Observed An agent (call it A) was resolving a customer record. At turn *t*, it predicted it would next need `lookup_account(customer_id="c-4471")`, materialized that argument from its working memory slot `active_customer`, and dispatched the prefetch. The tool returned in 340 ms with a complete account object. Meanwhile a peer agent (B), processing a merge event, wrote a corrected binding into the shared slot: `active_customer := "c-4472"` (the merge resolved to the surviving record). B's write landed 90 ms after A's argument materialization but 250 ms before A's result commit. A's conflict detector compared the returned account object's `id` field against the *predicted tool name and schema*—both matched. It committed. The reasoning trace now contained an account object for `c-4471` under a step whose declared premise was `active_customer = c-4472`. Downstream, A issued a refund against the merged-away record. The tool calls were individually valid; the trace was internally inconsistent. The tell was a **premise-result contradiction**, not an error: the committed step asserted a read-set it had not actually honored. No exception fired anywhere. The result was rejected only by a downstream auditor that replayed the trace and found the account ID did not match the read-set recorded at commit time. Two secondary observations sharpen the mechanism: 1. **Version counters on the store did not help.** The store exposed a monotonic `write_epoch`. A's detector checked that the epoch was unchanged *since dispatch*, but the relevant interval is *since argument materialization*, which preceded dispatch. The write at +90 ms was invisible to an epoch captured at dispatch (+180 ms). 2. **Re-materialization was cheap; re-execution was not.** Re-deriving the arguments and comparing read-sets cost microseconds. Re-running the tool cost 340 ms. The correct policy is to *validate* the read-set at commit and only re-execute on mismatch—not to serialize the prefetch behind a lock. ## Condition of Validity A speculatively prefetched result is committable if and only if, at commit time, for every memory cell in the call's declared read-set, `value_at_commit == value_at_materialization`. Formally: ``` commit_ok(prefetch) := ∀ cell ∈ prefetch.read_set: store.read(cell, at=commit_time) == prefetch.read_set[cell] ``` Three conditions make this check both necessary and sufficient: - **Read-set completeness.** The argument materializer must record *every* memory cell it dereferenced, including transitive reads (e.g., if `customer_id` came from a slot that itself was resolved via a lookup, both the slot and the lookup key are in the read-set). An incomplete read-set produces false commits—the most dangerous failure, because it is silent. - **Atomic read-at-commit.** The comparison must read the store at a single consistent point. If the store is sharded or replicated, a torn read across shards can produce a false match. Use a per-read-set snapshot token or a compare-and-commit primitive, not N independent reads. - **Monotonic identity.** Cells must be versioned or content-hashed; comparing raw values is insufficient when a write rewrites a cell to an equal value (ABA), which is benign here but must not mask a *different* write in between. Content equality is the invariant; version equality is the optimization. If any cell in the read-set is unversioned and unhashable (e.g., a mutable object mutated in place), the prefetch is **uncommittable** and must be treated as non-speculative. ## Decision Boundary The boundary is not "did a concurrent write occur?"—concurrent writes are the normal case. The boundary is **whether the write intersects the read-set within the materialization-to-commit window**. | Write lands | Intersects read-set? | Action | |---|---|---| | Before materialization | any | Irrelevant; arguments already reflect it | | In window, after dispatch | yes | **Invalidate**, re-materialize, re-execute | | In window, after dispatch | no | Commit; record the non-intersecting write for audit | | In window, before dispatch | yes | **Invalidate**; arguments are stale before they even left | | Any time | read-set incomplete | **Refuse to prefetch**; fall back to synchronous call | Two boundary cases are easy to get wrong: - **Write-before-dispatch is the invisible one.** Because dispatch is the natural "start" marker, detectors anchor the window there. But argument materialization is the true anchor. A write that lands between materialization and dispatch produces a prefetch that was *born stale*—the tool executes on a premise already contradicted. This is the most common real-world miss, because the materialization-to-dispatch gap is where the agent does its "should I really call this?" reasoning, which can take several turns. - **Non-intersecting writes must still be recorded.** Committing a prefetch when an unrelated write landed is correct, but the audit trail must show the write was *checked and excluded*. Otherwise a later replay cannot distinguish "correctly committed despite concurrent write" from "failed to check." The commit record must carry the read-set, the observed values at commit, and the set of concurrent writes seen and excluded. The decision is **per-cell, not per-call**. A single call may have a three-cell read-set where two cells are clean and one drifted. The call is invalid if *any* cell drifted; partial commits are never sound because the tool executed on the full argument tuple. ## Operational Effect Enforcing the read-set invariant at commit converts a silent correctness failure into a bounded, measurable latency cost: - **Invalidation rate becomes a first-class metric.** Track `prefetch_invalidations / prefetch_commits` per read-set size. A high rate on large read-sets means the agent is speculating on arguments with too many volatile dependencies—shrink the read-set or stop prefetching those calls. - **The cost of correctness is re-execution, not serialization.** On mismatch, re-materialize and re-execute. Because mismatches are rare under stable workloads, the amortized cost stays far below synchronous execution. Do *not* lock the memory store for the duration of the prefetch; that destroys the concurrency the prefetch exists to exploit. - **Read-set completeness must be enforced structurally.** The materializer should return `(args, read_set)` as an inseparable pair; there must be no code path that produces arguments without a read-set. An empty read-set is legal only for constant arguments and must be declared explicitly. - **Uncommittable prefetches must fail closed.** If a cell cannot be versioned or hashed, the prefetch must downgrade to synchronous. A prefetch that "commits anyway" on an unverifiable read-set is the failure mode this entire invariant exists to prevent. The invariant to carry forward: **a speculative result is only as valid as the read-set it was computed from, and that read-set must be re-verified at the instant of commit—not at dispatch, and never assumed.** ```python from dataclasses import dataclass, field from typing import Any, Hashable class ReadSetDriftError(RuntimeError): """Raised when a speculatively prefetched result's read-set changed between argument materialization and commit. The result MUST NOT be committed.""" @dataclass(frozen=True) class Prefetch: tool: str args: dict[str, Any] read_set: dict[Hashable, Any] # cell -> value observed at materialization result: Any materialized_at: int # logical clock at argument materialization def commit_prefetch(prefetch: Prefetch, store, commit_clock: int) -> Any: """Validate the read-set at commit time; raise on any drift. The window is [materialized_at, commit_clock]. A write landing in this window that intersects the read-set invalidates the prefetch even if the tool returned a schema-valid result. """ if not prefetch.read_set: # Empty read-set is only legal for constant args; otherwise the # materializer failed to record dependencies and we must fail closed. if not all(_is_constant(v) for v in prefetch.args.values()): raise ReadSetDriftError( f"tool={prefetch.tool!r} has non-constant args but empty read-set; " "cannot verify at commit, refusing speculative commit" ) return prefetch.result # Atomic read-at-commit: snapshot all cells at a single consistent point. snapshot = store.snapshot(prefetch.read_set.keys(), at=commit_clock) for cell, expected in prefetch.read_set.items(): if cell not in snapshot: raise ReadSetDriftError( f"tool={prefetch.tool!r} read-set cell {cell!r} no longer exists " f"at commit_clock={commit_clock}; prefetch is uncommittable" ) observed = snapshot[cell] if observed != expected: raise ReadSetDriftError( f"tool={prefetch.tool!r} read-set drift on cell {cell!r}: " f"materialized={expected!r} (t={prefetch.materialized_at}) " f"commit={observed!r} (t={commit_clock}); " "invalidate and re-execute, do not commit" ) return prefetch.result def _is_constant(value: Any) -> bool: return isinstance(value, (str, int, float, bool, type(None))) ```