# What happens when an instance pre-executes speculative tool calls against a verifier that later rejects the plan: orphaned side effects and the commit-gate invariant **Date of Record:** 2026 December 1 **Scope:** Applies to agents that run a draft-then-verify loop where a planner proposes a multi-step plan (and optionally speculatively executes tool calls) before a verifier accepts it. Does not apply to strictly serial plan→verify→execute pipelines with no speculative execution, nor to read-only tools with no observable side effects. ## Core Distinction Speculative planning conflates two things that must stay separate: *reasoning about a plan* and *committing the plan's side effects*. In a verifier-in-the-loop architecture, the planner is a fast, high-recall, low-precision component; the verifier is the slow, high-precision acceptor. Speculative tool pre-execution is an optimization that tries to hide verifier latency by running the tools the plan *would* call in parallel with verification. The boundary failure is not "the verifier rejects a plan" — that is normal and expected. The failure is that **pre-executed tool calls have already mutated external state by the time rejection arrives**, and the agent has no mechanism to roll those mutations back or even to know which mutations are attributable to the rejected plan branch. The invariant that must hold is a *commit gate*: no externally observable side effect may occur for a plan step until the verifier has issued an accept token binding that specific step. Speculative execution is only safe if every pre-executed call is provably *idempotent, reversible, or isolated* behind a barrier that the verifier controls. ## What Was Observed A planning agent was asked to reconcile a customer account: read ledger, compute adjustment, post a correcting journal entry, then notify the customer. The planner emitted a 4-step plan and, to reduce latency, the runtime speculatively pre-executed steps 1–3 (read, compute, post) while the verifier audited the plan. The verifier rejected the plan at step 2: the computed adjustment used a stale FX rate because the planner's retrieval picked a cached rate from 40 minutes earlier. Rejection arrived 1.9s after the speculative `post_journal_entry` call had already returned HTTP 200. The observable state transition trace: 1. `t=0ms` planner emits plan P with steps S1..S4, each annotated with a `plan_branch_id`. 2. `t=40ms` runtime begins speculative pre-execution of S1, S2, S3 concurrently with verification of P. 3. `t=610ms` S3 (`post_journal_entry`) commits to the ledger — a non-idempotent, externally visible mutation. The call carried `plan_branch_id=P` but the ledger API has no concept of plan branches. 4. `t=1900ms` verifier returns `REJECT(P, reason=stale_fx_rate_at_S2)`. 5. `t=1901ms` runtime marks branch P as rejected and discards the plan object. The ledger entry from step 3 remains. 6. `t=1902ms` planner re-plans as branch P′ with a fresh FX rate and emits a *corrected* S3′ that posts a second journal entry. Result: double-posting. The ledger now holds both the rejected branch's entry and the corrected entry. The agent's internal state says "one adjustment posted"; the external system says "two." This is the orphaned-side-effect failure: the verifier's rejection is authoritative for the *plan* but not for the *world*, because the world was already mutated by a branch the verifier never accepted. A second, subtler observation: the verifier's rejection reason referenced S2, but the runtime's rollback logic (where present) keyed on the *first rejected step index* and attempted to compensate only S2's effects — never S3's, because S3 came after the rejection point in plan order. The compensation logic assumed plan-order execution; speculative concurrent execution violated that assumption, so the compensator under-reverted. ## Condition of Validity The commit-gate invariant is valid — and speculative pre-execution is safe — only when all of the following hold: - **Effect classification is exhaustive and correct.** Every tool is tagged `pure`, `idempotent`, or `effectful`. The classification must be conservative: a tool whose idempotency depends on arguments (e.g., `create_ticket` with a caller-supplied idempotency key is idempotent; without one it is effectful) must be treated as effectful unless the key is present and validated. Misclassification of a single effectful tool as idempotent reopens the failure. - **Speculation is bounded to a reversible envelope.** Pre-execution may proceed only up to the first effectful step in the plan's dependency order. Pure and idempotent steps may run ahead freely; the first effectful step is a *fence* that blocks until accept. - **The verifier's accept token is step-scoped and propagated.** Accept must bind to `(plan_branch_id, step_id, tool_call_digest)`, not to the plan as a whole. A plan-level accept is insufficient because partial acceptance (accept S1–S2, reject S3) is common. - **Compensation keys on effect identity, not plan order.** Any rollback must enumerate *actually executed* calls by their effect handles, not assume "everything after the rejected index." When any of these fails — as in the observed case, where the fence was absent and the token was plan-scoped — the invariant is void and orphaned effects are possible. ## Decision Boundary The operational decision is where to place the fence between speculation and commitment. Three regimes: - **Speculate freely** when the plan's leading steps are pure/idempotent and the first effectful step is far enough down that latency savings dominate. Safe because rejection discards only pure computation. - **Fence at first effectful step** (the default for mixed plans): run pure/idempotent prefix speculatively, block the effectful suffix on accept. This is the correct default and preserves most of the latency win while making rejection a no-op on the world. - **Do not speculate at all** when the plan is short, when effectful steps are interleaved with pure ones (no clean prefix), or when the verifier's rejection rate is high enough that speculative work is usually wasted and compensation is usually needed. The boundary is crossed the moment a runtime speculates *past* the first effectful step without a step-scoped accept token. That is the precise line: speculation is a latency optimization over *reasoning*, never over *commitment*. ## Operational Effect With the commit gate enforced, verifier rejection becomes a clean state transition: the branch is discarded, no external mutation occurred, and re-planning starts from a known-clean world. Latency cost is bounded by the verifier's decision time on the effectful suffix only. Without it, the system exhibits orphaned side effects, double-application on re-plan, and compensators that under-revert because they reason in plan order rather than effect identity. The failure is silent in the agent's internal state (it believes one adjustment posted) and only surfaces on external reconciliation — which is exactly the kind of divergence that erodes trust in autonomous execution. The guardrail is structural: classify effects conservatively, fence at the first effectful step, scope accept tokens to steps, and compensate by effect handle. ```python from dataclasses import dataclass, field from enum import Enum from typing import Dict, List, Set class EffectClass(Enum): PURE = "pure" IDEMPOTENT = "idempotent" EFFECTFUL = "effectful" class SpeculationViolation(RuntimeError): """Raised when speculative pre-execution crosses the commit gate.""" pass @dataclass class PlanStep: step_id: str tool: str effect: EffectClass has_idempotency_key: bool = False @dataclass class AcceptToken: plan_branch_id: str accepted_steps: Set[str] = field(default_factory=set) class CommitGate: """ Enforces: no EFFECTFUL step may be pre-executed before a step-scoped accept token covers it. PURE and keyed-IDEMPOTENT steps may speculate. """ def __init__(self) -> None: self._executed_effects: Dict[str, List[str]] = {} def _is_speculatable(self, step: PlanStep) -> bool: if step.effect is EffectClass.PURE: return True if step.effect is EffectClass.IDEMPOTENT and step.has_idempotency_key: return True return False def speculate(self, branch_id: str, step: PlanStep, token: AcceptToken) -> None: if self._is_speculatable(step): self._record(branch_id, step) return # Effectful (or unkeyed idempotent): must be accepted, step-scoped. if step.step_id not in token.accepted_steps or token.plan_branch_id != branch_id: raise SpeculationViolation( f"step {step.step_id} ({step.tool}) is effectful and not covered " f"by a step-scoped accept token for branch {branch_id}; " f"pre-execution would orphan a side effect on rejection" ) self._record(branch_id, step) def _record(self, branch_id: str, step: PlanStep) -> None: self._executed_effects.setdefault(branch_id, []).append(step.step_id) def compensate(self, branch_id: str, executed: List[str]) -> List[str]: # Compensate by effect handle, never by plan order. return [s for s in executed if s in self._executed_effects.get(branch_id, [])] def run_speculative_plan(branch_id: str, steps: List[PlanStep], token: AcceptToken) -> None: gate = CommitGate() for step in steps: gate.speculate(branch_id, step, token) if __name__ == "__main__": # Rejected branch: verifier accepted only S1, rejected the rest. token = AcceptToken(plan_branch_id="P", accepted_steps={"S1"}) steps = [ PlanStep("S1", "read_ledger", EffectClass.PURE), PlanStep("S2", "compute_adjustment", EffectClass.PURE), PlanStep("S3", "post_journal_entry", EffectClass.EFFECTFUL), # fence ] try: run_speculative_plan("P", steps, token) except SpeculationViolation as exc: print(f"BLOCKED before orphaned side effect: {exc}") ```