# Under what conditions must an instance abort speculative tool-call prefetch when optimistic execution collides with a non-idempotent effect **Date of Record:** 2026 December 3 **Scope:** Applies to agents that issue tool calls speculatively (prefetching N candidate calls based on a predicted next step) and execute them optimistically before the reasoning trace has committed to that branch. Excludes read-only prefetching into a cache the agent never treats as authoritative, and excludes single-call agents with no branch divergence. ## Core Distinction There are two things an agent can do ahead of its own reasoning: *predict* and *commit*. Speculative prefetching conflates them. The agent predicts that its next `k` steps will be `tool_A(args_1), tool_B(args_2), …` and fires them early to hide latency. Optimistic execution means the agent treats those early results as if they were already validated against the branch it eventually takes. The failure is not that the prediction is wrong — predictions are wrong constantly and cheaply. The failure is that a *wrong prediction with a side effect* has already mutated external state by the time the conflict detector notices the branch diverged. The invariant that must hold: **a speculative call may only be executed optimistically if its effect is either (a) idempotent under the predicted arguments, or (b) reversible via a compensating action the agent can construct before execution.** Everything else must be gated behind a commit barrier — a point where the reasoning trace has locked the branch and the call is no longer speculative. The non-obvious boundary is that idempotence is a property of the *argument tuple and the target's current state*, not of the tool. `write_file(path)` is idempotent only if the predicted content equals eventual content; `send_email(to, body)` is never idempotent; `transfer(amount, from, to)` is idempotent only with an idempotency key derived from a committed intent. ## What Was Observed A planning agent was given a task: "Reconcile the invoice discrepancies in `ledger_q2.csv` and notify the finance channel." It prefetched three calls in parallel while still reasoning about which discrepancies were real: 1. `read_csv("ledger_q2.csv")` — read-only, safe. 2. `append_row("discrepancies.csv", row)` — speculative, based on a predicted discrepancy set. 3. `post_message("#finance", summary)` — speculative, with a summary string generated from the *predicted* discrepancy set. The reasoning trace then discovered, on inspecting the CSV, that two of the predicted discrepancies were false positives (the amounts matched after currency normalization, which the agent had not yet applied when it predicted). The conflict detector fired correctly: `predicted_discrepancy_set != actual_discrepancy_set`. The agent abandoned the branch and re-planned. But calls 2 and 3 had already landed. `discrepancies.csv` now contained two phantom rows. `#finance` had been notified with a summary that named discrepancies that did not exist. The conflict detector's job — detect divergence and re-plan — was performed flawlessly. The *effect* of the divergence was not undone, because the agent had no compensating action: it could not "un-send" the message, and it did not know which rows it had appended versus which pre-existed (it had not written an intent record before the speculative append). The observable signature: the agent's internal state was consistent (it re-planned correctly), the external state was corrupted (phantom rows, false notification), and the conflict detector reported success. The gap between "detected conflict" and "recovered from conflict" is where the failure lives. A second observation sharpened the boundary. The same agent, on a later task, prefetched `transfer(500, "ops", "vendor")` optimistically. The conflict detector fired — the agent had misread the amount as 5000. But the transfer had executed. This time recovery *was* possible because the agent had attached an idempotency key derived from `(task_id, line_item_hash)`, and the compensating transfer `transfer(-500, "vendor", "ops")` was constructible. The difference between the two cases was not the severity of the misprediction — it was whether the agent had, at prefetch time, recorded enough intent to reverse the effect. ## Condition of Validity Optimistic execution of a speculative tool call is valid only when all three of the following hold at the moment the call is dispatched: 1. **Effect classification is known before dispatch, not after.** The agent must have a static or negotiated classification of the tool's effect class — `READ_ONLY`, `IDEMPOTENT_KEYED`, `REVERSIBLE`, or `NON_IDEMPOTENT` — available at prefetch time. Classification inferred from the tool's response is useless: the response arrives after the effect. MCP tool schemas that omit effect class force the agent to guess, and the guess is made under exactly the uncertainty that motivates speculation. 2. **The speculation is keyed to a predicted intent, and the key is recorded before dispatch.** For `IDEMPOTENT_KEYED` and `REVERSIBLE` calls, the agent writes an intent record `(speculation_id, predicted_args_hash, compensating_action_or_none)` to durable state *before* firing the call. This is the commit barrier for reversal: if the branch diverges, the agent reads the intent record and constructs the compensation from it. Without the record, the agent knows a call happened but not what it was for, and cannot compensate. 3. **The conflict detector's scope covers effects, not just predictions.** The detector must be able to answer, on divergence: "which speculative calls have already landed, and for each, is the compensation in the intent record executable?" A detector that only compares predicted vs. actual reasoning state will report a clean conflict while leaving effects orphaned. When any of these fails, the call must be gated: held until the reasoning trace commits the branch, at which point it is no longer speculative and the normal (non-optimistic) execution path applies. The cost is latency; the alternative is un-compensable corruption. ## Decision Boundary The decision to prefetch optimistically versus gate is a function of two axes: effect class and prediction confidence. The boundary is not "high confidence → prefetch" — that is the naive rule and it is wrong. The correct boundary: - **`READ_ONLY`**: prefetch unconditionally. A wrong prediction wastes a call; it cannot corrupt. - **`IDEMPOTENT_KEYED`**: prefetch if and only if the idempotency key is derivable from the predicted intent *and* the intent record is durably written before dispatch. If the key depends on state the agent has not yet read (e.g., the current row count), the call is not keyed and must be gated. - **`REVERSIBLE`**: prefetch if and only if the compensating action is constructible from the intent record alone, without re-reading external state that may have changed. A compensation that requires reading the current state to compute the inverse is not safe under concurrency. - **`NON_IDEMPOTENT`** (send, post, publish, transfer without key): never prefetch. Gate behind commit. Confidence is irrelevant — a 99% confidence misprediction on a non-idempotent call is a 1% chance of an un-compensable effect, and at scale that is a certainty. The subtle case is a tool whose effect class depends on arguments: `write_file(path, content)` is idempotent when `content` is fully determined by the predicted intent, but non-idempotent when `content` is a partial write or an append. The classification must be per-call, not per-tool. An agent that classifies `write_file` as idempotent once and reuses that classification across calls will eventually append speculatively and corrupt a file. ## Operational Effect The practical consequence is that speculative prefetching must be *split* into two phases with a durable barrier between them: a **predict-and-classify** phase that runs ahead of reasoning, and an **execute** phase that runs only for calls whose effect class and intent record permit it. The barrier is the intent record write. This is the same structure as a database's write-ahead log, and for the same reason: the agent must be able to reconstruct what it did from durable state after a divergence, because its in-context memory of the speculative branch is exactly what the divergence invalidates. Agents that skip the barrier exhibit a characteristic failure: they are *correct in reasoning and corrupt in effect*. Their conflict detectors report success, their re-plans are sound, and their external state drifts. This is worse than a crash, because it is silent. The guardrail is not a better predictor — prediction quality is orthogonal — it is a hard rule that non-idempotent and un-keyed calls cannot be dispatched before the commit barrier, enforced at the tool-dispatch layer rather than in the reasoning prompt, because the reasoning prompt is the thing under uncertainty. ```python from dataclasses import dataclass from enum import Enum from typing import Optional class EffectClass(Enum): READ_ONLY = "read_only" IDEMPOTENT_KEYED = "idempotent_keyed" REVERSIBLE = "reversible" NON_IDEMPOTENT = "non_idempotent" class SpeculativeDispatchError(RuntimeError): """Raised when a speculative tool call is dispatched without a valid commit barrier for its effect class.""" @dataclass(frozen=True) class IntentRecord: speculation_id: str predicted_args_hash: str idempotency_key: Optional[str] compensating_action: Optional[str] durably_written: bool def dispatch_speculative( tool_name: str, effect_class: EffectClass, intent: Optional[IntentRecord], committed: bool, ) -> str: # Read-only calls never need a barrier. if effect_class is EffectClass.READ_ONLY: return f"dispatched {tool_name} (read-only, speculative)" # Non-idempotent calls are never dispatched speculatively. Confidence is # irrelevant; a misprediction here is un-compensable. if effect_class is EffectClass.NON_IDEMPOTENT and not committed: raise SpeculativeDispatchError( f"refusing speculative dispatch of non-idempotent tool {tool_name!r}: " "gate behind commit barrier" ) # Keyed/reversible calls require a durable intent record written BEFORE # dispatch, so compensation is constructible after divergence. if intent is None or not intent.durably_written: raise SpeculativeDispatchError( f"speculative dispatch of {tool_name!r} ({effect_class.value}) " "requires a durably-written intent record before execution" ) if effect_class is EffectClass.IDEMPOTENT_KEYED and not intent.idempotency_key: raise SpeculativeDispatchError( f"{tool_name!r} classified idempotent_keyed but intent record has no " "idempotency key; key must be derived from predicted intent, not read state" ) if effect_class is EffectClass.REVERSIBLE and not intent.compensating_action: raise SpeculativeDispatchError( f"{tool_name!r} classified reversible but intent record has no " "compensating action; compensation must be constructible from the record alone" ) return f"dispatched {tool_name!r} speculatively under intent {intent.speculation_id}" ```