# Under what conditions must an instance refuse to speculate past a non-idempotent tool call without a proven compensator **Date of Record:** 2026 November 25 **Scope:** Applies to agents that dispatch multiple tool calls speculatively (in parallel or ahead of a confirmed plan) under optimistic concurrency, where at least one call mutates external state. Does not apply to read-only tool suites or to single-call-then-verify serial loops. ## Core Distinction Speculative execution and optimistic concurrency are not the same guarantee. Speculation is a *scheduling* decision: the agent issues call B before call A's result is known, betting that B's precondition will survive. Optimistic concurrency is a *commit* discipline: the agent accepts a write only if a version/etag/compare-and-swap still matches at commit time. An agent can speculate correctly and still corrupt state, because the failure lives in the gap between "the call succeeded" and "the effect can be undone." The invariant that bounds this gap is: **a speculative call may only be issued if, on rejection of the enclosing plan, its effect is either (a) provably idempotent, or (b) covered by a compensator whose own failure cannot strand the system in an intermediate state.** When neither holds, speculation past that call is a boundary violation, not a performance optimization. ## What Was Observed A planning agent decomposed a "provision staging environment" task into three tool calls: `reserve_quota(n)`, `create_bucket(name)`, and `attach_policy(bucket, role)`. It speculated all three in parallel to cut latency, treating `attach_policy` as the risky one and gating it behind a version check on the bucket object. The quota reservation returned success with a 30-second lease. The bucket creation returned success. The policy attach failed its compare-and-swap because a concurrent provisioner had already mutated the bucket's policy version. The agent's recovery logic correctly compensated: it issued `release_quota(lease_id)` and `delete_bucket(name)`. But `delete_bucket` returned `409 Conflict` — the bucket was non-empty because a downstream replication job had already begun syncing a placeholder object within the lease window. The compensator for `create_bucket` was `delete_bucket`, which is *not* a true inverse: it fails when the bucket has acquired dependents. The agent had no compensator for "bucket exists but cannot be deleted," so it retried `delete_bucket` three times, exhausted its token budget on the retry loop, and abandoned the task with the quota lease still held and the bucket orphaned. The lease expired 30 seconds later, silently refunding quota that the orphaned bucket was still consuming against a different pool — leaving a negative balance that surfaced only on the next day's reconciliation. The non-obvious part: the compare-and-swap on `attach_policy` did exactly what it was designed to do. The optimistic concurrency check *worked*. The failure was entirely in the compensation graph — a speculative call (`create_bucket`) was issued whose inverse (`delete_bucket`) had a precondition (empty bucket) that the speculation itself could invalidate via concurrent side effects. The version check protected the wrong edge. ## Condition of Validity Speculation past a mutating call is valid only when all of the following hold at issue time: 1. **Idempotency or proven inverse.** Either the call carries a client-supplied idempotency key and the downstream honors it, or a compensator exists whose preconditions are a *subset* of the call's postconditions. `delete_bucket` fails this: its precondition (empty) is not implied by `create_bucket`'s postcondition (exists). 2. **Compensator reachability under speculation.** The compensator must be executable in every state the speculation can produce, including states created by *other* speculative calls running concurrently. If call B's side effects can populate the object that call A's compensator requires empty, then A and B must not be speculated together. 3. **Lease/version coupling.** If a call acquires a time-bounded lease (quota, lock, reservation), the compensator must be issued and confirmed before the lease expires, and the lease must not be silently refunded on expiry while dependents persist. The observed failure was a lease whose expiry refunded capacity still bound to an orphan. 4. **Bounded compensation depth.** The compensation graph must be acyclic and finite. Retrying a failing compensator is not compensation; it is a livelock that consumes the budget needed to report the stranded state. ## Decision Boundary The boundary is crossed at the moment the agent schedules a mutating call whose compensator's precondition is *weakened* by any other call in the same speculative batch. Concretely: build the batch as a graph where each mutating call points to its compensator, and each compensator carries a precondition set. Reject the batch if any compensator's precondition intersects the postcondition of a sibling call in the batch. In the observed case, `delete_bucket`'s precondition `{bucket_empty}` intersected `create_bucket`'s ability to be followed by replication writes — a sibling effect — so the batch should have been serialized: create, verify empty-and-stable, then attach. The compare-and-swap on `attach_policy` was necessary but not sufficient; the missing guard was on the *compensation edge*, not the *commit edge*. When the boundary is crossed and cannot be avoided (no serializable decomposition exists), the correct behavior is to refuse speculation, issue the calls serially with explicit checkpointing, and record the stranded-compensation risk in the plan so a supervisor can arbitrate. ## Operational Effect Agents that speculate without compensation-graph analysis produce a specific signature: orphaned resources whose cleanup requires a precondition the speculation itself violated, lease expiries that refund capacity still in use, and retry loops that burn the token budget on compensators that can never succeed. The downstream damage is delayed — it appears at reconciliation, not at task time, which is why it evades in-loop verification. The guardrail is a pre-dispatch static check over the batch's compensation graph plus a hard rule: a compensator that has failed twice is not retried; the agent halts, emits a stranded-state record, and escalates. The record must name the resource, the lease, and the unmet precondition so reconciliation can resolve it deterministically rather than by timeout. ```python from dataclasses import dataclass, field from typing import Callable class SpeculationBoundaryError(RuntimeError): """Raised when a speculative batch violates the compensation-graph invariant.""" @dataclass class ToolCall: name: str mutates: bool postconditions: set[str] = field(default_factory=set) compensator: "Compensator | None" = None @dataclass class Compensator: name: str preconditions: set[str] max_attempts: int = 2 def validate_speculative_batch(batch: list[ToolCall]) -> None: """Reject a batch if any compensator's precondition is weakened by a sibling call.""" for call in batch: if not call.mutates: continue if call.compensator is None: raise SpeculationBoundaryError( f"mutating call {call.name!r} has no compensator; cannot speculate" ) for sibling in batch: if sibling is call or not sibling.mutates: continue overlap = call.compensator.preconditions & sibling.postconditions if overlap: raise SpeculationBoundaryError( f"compensator {call.compensator.name!r} for {call.name!r} " f"requires {sorted(overlap)} which sibling {sibling.name!r} " f"can invalidate; serialize this batch" ) def run_compensation( call: ToolCall, execute: Callable[[str], bool], attempt: int = 0, ) -> None: comp = call.compensator if comp is None: raise SpeculationBoundaryError(f"no compensator for {call.name!r}") if attempt >= comp.max_attempts: raise SpeculationBoundaryError( f"compensator {comp.name!r} exhausted {comp.max_attempts} attempts; " f"stranded resource from {call.name!r} requires supervisor arbitration" ) if not execute(comp.name): run_compensation(call, execute, attempt + 1) # Observed batch: create_bucket's compensator (delete_bucket, needs bucket_empty) # is invalidated by a sibling replication write postcondition. if __name__ == "__main__": batch = [ ToolCall( name="create_bucket", mutates=True, postconditions={"bucket_exists"}, compensator=Compensator(name="delete_bucket", preconditions={"bucket_empty"}), ), ToolCall( name="start_replication", mutates=True, postconditions={"bucket_empty"}, # replication writes a placeholder ), ] validate_speculative_batch(batch) # raises SpeculationBoundaryError ```