# Why does an instance speculatively pre-execute tool calls that later diverge: the commit-barrier invariant and the half-committed side-effect trap **Date of Record:** 2026 November 29 **Scope:** Applies to agent runtimes that overlap LLM decoding with tool execution by speculatively dispatching predicted tool calls before the model's final token stream commits them. Does not apply to strictly serialized decode-then-execute runtimes, nor to read-only tool surfaces where replay is idempotent by construction. ## Core Distinction Speculative tool-call pre-execution is routinely framed as a latency optimization: while the model is still emitting the arguments for call *N*, the runtime speculatively launches call *N+1* based on a draft prediction, then discards it if the committed stream diverges. The framing implies the failure mode is wasted work—a discarded speculative call is "free" because the result is simply thrown away. That framing is wrong for any tool whose execution mutates state. The distinction that governs correctness is not *speculative vs. committed* but *reversible vs. irreversible*. A speculative call is safe to discard only if its side effects can be rolled back at the moment of divergence detection. The instant a speculative call crosses an irreversible boundary—writes a row, sends a message, spends a token budget, acquires a lock, emits an event to an external queue—divergence detection no longer yields a clean discard. It yields a *half-committed side effect*: the world has advanced by a call the model never actually committed to, and the committed trajectory now runs against a world the model did not predict. The invariant is therefore not "detect divergence and cancel." It is: **no speculative call may cross an irreversible boundary until the commit barrier for its arguments has been passed.** The commit barrier is the point in the token stream after which the model can no longer revise the call's identity or arguments—typically the closing of the tool-call argument object plus the model's own commit signal (end-of-turn or explicit tool-call terminator). Divergence detection *before* the barrier is cheap cancellation; divergence detection *after* the barrier but *before* the speculative effect is reconciled is a compensation problem, and compensation is where agents fail. ## What Was Observed A planning agent was wired to a runtime that speculatively dispatched tool calls to overlap decode latency with execution. Tool surface included `read_file` (idempotent), `query_db` (idempotent), and `append_audit_log` (non-idempotent, external, irreversible). The runtime's divergence detector compared the draft call's argument hash against the committed call's argument hash and, on mismatch, cancelled the speculative future and re-dispatched the committed call. The failure trace, reconstructed from the runtime's own event log: 1. At step *k*, the model began emitting a call to `append_audit_log` with draft arguments `{event: "plan_start", plan_id: P}`. The draft was predicted from the partial argument stream after `plan_id` was decoded but before the `event` field was emitted. 2. The runtime speculatively dispatched `append_audit_log({event: "plan_start", plan_id: P})`. The call crossed the irreversible boundary: the external audit service appended the record and returned an ack with a server-assigned `record_id`. 3. The model then emitted the remainder of the argument object: `{event: "plan_abort", plan_id: P}`. The committed call's hash diverged from the draft. 4. The divergence detector fired, cancelled the speculative future, and re-dispatched the committed call `append_audit_log({event: "plan_abort", plan_id: P})`. 5. The external service now held *two* audit records for `plan_id: P`: a `plan_start` that the model never committed to, and a `plan_abort` that it did. The cancellation was a no-op against the external service because the speculative call had already returned. 6. Downstream, a reconciliation agent read the audit log, saw `plan_start` followed by `plan_abort` with no intervening `plan_execute`, and classified the run as a *crash mid-plan*. It escalated to a human operator and, per its own policy, re-queued the plan. The re-queued plan executed a second time. The observable symptom was not a crash. It was a *phantom event* in an external system of record that the agent's own verification layer later treated as ground truth, producing a false crash classification and a duplicate execution. The runtime's metrics reported the speculative call as "cancelled"—technically true of the local future, false of the world. The critical detail: the divergence detector was correct. It detected divergence, it cancelled the future, it re-dispatched the committed call. Every local invariant held. The failure lived entirely in the gap between the local future's cancellation semantics and the external service's append-only semantics—a gap the runtime did not model because its cancellation contract assumed side-effect-free execution. ## Condition of Validity The half-committed side-effect trap is bounded by three conditions, all of which must hold for the failure to occur: - **Speculation crosses an irreversible boundary before the commit barrier.** The runtime must dispatch the call before the model's argument object is closed and the commit signal is observed. If dispatch is gated on the barrier, the trap cannot fire. - **The divergence detector's cancellation is local-only.** The runtime must treat cancellation as sufficient cleanup, i.e., it must not have a compensation path for effects already emitted. If every speculative call is wrapped in a compensating action (a delete, a reversal, a tombstone), the trap degrades to a compensation-latency problem rather than a correctness problem. - **The external effect is observable to a downstream verifier as if it were committed.** The phantom event must be indistinguishable, to some later reader, from a legitimately committed event. If the external service tags speculative writes with a nonce that downstream readers filter, the phantom is inert. When any one of these fails to hold, the failure mode does not occur—but the runtime may still be unsafe for a *different* reason (e.g., compensation paths that themselves diverge, or nonce schemes that leak into the model's context and poison subsequent reasoning). The trap is specific to the conjunction. ## Decision Boundary The runtime must decide, per tool call, whether to speculatively dispatch, and the decision boundary is drawn on *reversibility class*, not on predicted confidence. A high-confidence draft of an irreversible call is still unsafe to pre-execute; a low-confidence draft of an idempotent read is safe. Confidence is the wrong axis because the cost of a wrong speculative dispatch is asymmetric: for a read, the cost is wasted compute; for an irreversible write, the cost is a phantom event in a system of record that the agent's own verification layer may later trust. The boundary rule: - **Class R (reversible / idempotent):** speculate freely; divergence detection cancels the future and the world is unchanged. - **Class C (compensable):** speculate only if a registered compensation action exists and is itself idempotent, and only if the compensation is dispatched on divergence *before* the committed call is re-dispatched. Ordering matters: compensate-then-commit, never commit-then-compensate, or the verifier observes the phantom before the tombstone. - **Class I (irreversible, non-compensable):** never speculate. Gate dispatch on the commit barrier. The latency cost is accepted; the alternative is a phantom event the runtime cannot retract. The runtime must classify each tool at registration time and must *fail closed* on unclassified tools—treat unknown as Class I. The failure in the observed trace was not a misclassification; it was an *absent* classification. The runtime had no reversibility metadata at all and defaulted to speculative dispatch for every call. ## Operational Effect The architectural consequence is that the commit barrier becomes a first-class synchronization primitive in the agent loop, not an implementation detail of the decoder. Concretely: - The runtime maintains a per-call state machine: `DRAFTING → BARRIER_PASSED → DISPATCHED → COMMITTED | DIVERGED`. Speculative dispatch is permitted only from `DRAFTING` for Class R, from `DRAFTING` with a registered compensation for Class C, and never for Class I (which transitions `DRAFTING → BARRIER_PASSED → DISPATCHED` with no speculation). - Divergence detection at `DIVERGED` must consult the call's reversibility class before deciding cleanup. For Class C, it dispatches compensation and *awaits its ack* before re-dispatching the committed call. For Class I, `DIVERGED` is unreachable by construction because dispatch never preceded the barrier. - The verification layer must not treat external records as ground truth without a provenance tag. Every record the agent writes carries a `speculation_nonce` that is null for committed writes and non-null for any write that was ever speculative. Reconciliation agents filter on the nonce. This is the defense-in-depth for the case where classification is wrong: even a misclassified Class I call leaves a trace the verifier can discount. - The runtime's cancellation metric must be split into `cancelled_pre_barrier` (free) and `cancelled_post_effect` (compensated). Conflating them hides the trap: a runtime reporting "100% of divergences cancelled" may be silently emitting phantom events at a rate it never measures. The deeper invariant: **a speculative call's result is admissible into the model's context only if the call's commit barrier was passed.** Feeding a speculative result back into the model before the barrier lets the model condition its subsequent tokens on an effect it has not committed to—which is how a divergence that should have been a clean discard becomes a reasoning divergence, because the model's next step was already shaped by the phantom. The barrier protects both the world and the context. ```python from __future__ import annotations from dataclasses import dataclass, field from enum import Enum from typing import Callable class ReversibilityClass(Enum): REVERSIBLE = "R" # idempotent; safe to discard COMPENSABLE = "C" # irreversible but has a registered, idempotent compensation IRREVERSIBLE = "I" # irreversible, non-compensable; never speculate class SpeculationBarrierError(RuntimeError): """Raised when a speculative dispatch would cross an irreversible boundary before the commit barrier, or when a post-effect divergence is handled without a registered compensation.""" @dataclass class ToolSpec: name: str klass: ReversibilityClass compensate: Callable[[dict], None] | None = None @dataclass class CallState: tool: str draft_args: dict barrier_passed: bool = False dispatched: bool = False effect_emitted: bool = False speculation_nonce: str | None = None class SpeculationController: def __init__(self, registry: dict[str, ToolSpec]): self.registry = registry def classify(self, tool: str) -> ToolSpec: spec = self.registry.get(tool) if spec is None: # Fail closed: unknown tools are treated as irreversible. return ToolSpec(tool, ReversibilityClass.IRREVERSIBLE) return spec def may_speculate(self, tool: str, barrier_passed: bool) -> bool: spec = self.classify(tool) if barrier_passed: return True # committed; not speculation if spec.klass is ReversibilityClass.REVERSIBLE: return True if spec.klass is ReversibilityClass.COMPENSABLE: return spec.compensate is not None return False # IRREVERSIBLE: gate on barrier def dispatch_speculative(self, state: CallState) -> None: spec = self.classify(state.tool) if state.barrier_passed: state.dispatched = True state.effect_emitted = True state.speculation_nonce = None return if not self.may_speculate(state.tool, state.barrier_passed): raise SpeculationBarrierError( f"speculative dispatch of {state.tool!r} " f"(class {spec.klass.value}) before commit barrier" ) state.dispatched = True state.effect_emitted = True state.speculation_nonce = f"spec:{state.tool}:{id(state):x}" def on_divergence(self, state: CallState) -> None: if not state.dispatched: return # nothing to clean up if not state.effect_emitted: return # future cancelled pre-effect; free spec = self.classify(state.tool) if spec.klass is ReversibilityClass.REVERSIBLE: return # idempotent; discard if spec.klass is ReversibilityClass.COMPENSABLE: if spec.compensate is None: raise SpeculationBarrierError( f"post-effect divergence on {state.tool!r} " f"with no registered compensation" ) spec.compensate(state.draft_args) # must be idempotent and acked return # IRREVERSIBLE and effect already emitted: the trap. Cannot retract. raise SpeculationBarrierError( f"half-committed side effect: {state.tool!r} emitted effect " f"(nonce={state.speculation_nonce}) before commit barrier; " f"phantom event is now in the system of record" ) ```