Which invariants prevent speculative tool-call pre-execution from corrupting shared multi-agent state

**Date of Record:** 2026 December 1 **Scope:** Applies to multi-agent systems where an orchestrator speculatively pre-executes side-effecting tool calls (writes, mutations, RPCs) on behalf of a peer agent against a shared mutable store, before the peer's plan is committed. Does not apply to read-only speculative prefetch, single-agent tool calls, or systems where every tool call is fully serialized through one commit queue.

Core Distinction

The distinction that matters is between **speculation on reads** and **speculation on effects**. Read-ahead speculation is safe because the worst outcome is wasted tokens and a cache miss. Effect speculation is unsafe because a tool call that mutates shared state is a *committed fact* the moment it executes, even if the agent that requested it later abandons the plan that motivated it. Most implementations conflate the two: they apply the same optimistic "execute early, reconcile later" machinery to both, and the conflict detector only checks whether the *value read back* matches expectations, never whether the *effect was authorized by a committed plan*.

The invariant that actually holds the line is: **an effect may be pre-executed only if its write-set is provably disjoint from the write-set of every uncommitted plan currently in flight across all agents in the cohort, and the disjointness proof must be re-validated atomically at commit.** Value-equality conflict detection ("did the row change since I read it?") is insufficient because two agents can write *different* values to *different* rows and still corrupt each other through referential or ordering dependencies the detector never models.

What Was Observed

A three-agent cohort (planner, executor, auditor) shared a Postgres-backed task store. The executor speculatively pre-executed `reserve_inventory(sku, qty)` for a plan the planner had not yet committed, because the planner's draft plan included it and the executor's scheduler wanted to hide tool latency. The auditor, running concurrently, speculatively pre-executed `reserve_inventory(sku, qty)` for a *different* plan touching the same SKU. Both calls passed the conflict detector: each read `available_qty` at its own start, each saw a value consistent with its own precondition, and the detector compared read-values, not write-intents. Both reservations committed. Total reserved quantity exceeded physical stock. The failure surfaced downstream as an oversell, three tool calls later, in a completely different agent's context, with no trace pointing back to the speculative pre-execution.

The trace: plan A drafts `reserve(sku=7, qty=40)` against `available=50` → detector sees 50 ≥ 40, passes → executor pre-executes, store now 10. Plan B drafts `reserve(sku=7, qty=30)` against a *stale snapshot* of `available=50` captured before A's pre-execution, because B's planner read the value at plan-draft time → detector sees 50 ≥ 30, passes → executor pre-executes, store now −20. Neither detector knew the other's write existed. The store accepted both because the reservation tool had no `CHECK (available_qty >= 0)` constraint — the invariant lived only in the agent's reasoning, not in the storage layer.

Condition of Validity

The disjointness invariant is only valid when all four of the following hold simultaneously:

  1. **Write-set declaration precedes execution.** Every speculative call must declare its full write-set (table + key + operation class) *before* the tool executes, not derive it from the tool's return. This is a schema obligation on the tool, not an inference the orchestrator can make.
  2. **A cohort-wide intent registry with atomic compare-and-insert.** The registry must reject a registration whose write-set intersects any *uncommitted* registration, and the reject/accept decision must be a single atomic operation. A read-then-write registry (check, then register) reintroduces the race it was meant to close.
  3. **Commit is the only thing that releases the reservation, and abort must release it too.** A speculative call that is abandoned (plan revised, agent crashed, token budget exhausted) must release its registry entry within a bounded TTL, or the cohort deadlocks on phantom reservations.
  4. **The storage layer enforces the same invariant the agent reasons about.** If the agent's precondition is `available >= qty`, the store must enforce it as a constraint, so that any residual race (registry bug, clock skew, split-brain) fails closed at the storage boundary rather than silently overselling.

When any of these is absent, the system is not "speculating safely with conflict detection" — it is executing unauthorized effects and calling the absence of a detected conflict a success.

Decision Boundary

The boundary is between **speculate-then-verify** and **reserve-then-execute**. Speculate-then-verify (execute the effect, then check whether it was OK) is only sound for idempotent, commutative, write-set-disjoint effects. Reserve-then-execute (register the write-intent atomically, execute only after registration succeeds, release on abort) is required for everything else. The decision rule:

The common mistake is treating "the conflict detector passed" as authorization. The detector passing means *no conflict was observed*, which is not the same as *no conflict exists*. Only the registry, holding every in-flight write-intent, can make the latter claim.

Operational Effect

With reserve-then-execute and a cohort-wide intent registry, speculative pre-execution retains most of its latency benefit (the reservation is cheap; the expensive tool body still runs early) while making the oversell class of failure structurally impossible: the second `reserve(sku=7)` in the trace above would have been rejected at registration because its write-set `{sku:7}` intersected plan A's uncommitted registration. The cost is a registry round-trip per speculative call and a TTL reaper for abandoned intents. The invariant to encode in the orchestrator: **no effect executes without a held write-intent lease, and no lease is held past plan commit or abort.** Enforce it in code, not in the prompt.

import time
from dataclasses import dataclass, field


class WriteIntentConflict(RuntimeError):
    """Raised when a speculative tool call's write-set intersects an uncommitted intent."""


class LeaseExpired(RuntimeError):
    """Raised when a write-intent lease was reaped before the tool committed."""


@dataclass(frozen=True)
class WriteIntent:
    table: str
    key: str
    op: str  # 'reserve', 'transfer', 'append', ...
    agent_id: str
    plan_id: str
    acquired_at: float = field(default_factory=time.monotonic)
    ttl_s: float = 30.0

    def conflicts_with(self, other: "WriteIntent") -> bool:
        return (self.table, self.key) == (other.table, other.key)


class IntentRegistry:
    """Atomic compare-and-insert registry of in-flight write-intents across a cohort."""

    def __init__(self) -> None:
        self._held: dict[tuple[str, str], WriteIntent] = {}

    def _reap(self, now: float) -> None:
        for k, v in list(self._held.items()):
            if now - v.acquired_at > v.ttl_s:
                del self._held[k]

    def acquire(self, intent: WriteIntent) -> None:
        # Atomic in real deployments (single-row INSERT ... ON CONFLICT DO NOTHING
        # or a compare-and-swap on a versioned registry row). Here: single critical section.
        self._reap(time.monotonic())
        slot = (intent.table, intent.key)
        existing = self._held.get(slot)
        if existing is not None and existing.plan_id != intent.plan_id:
            raise WriteIntentConflict(
                f"speculative write-set {slot} already held by plan "
                f"{existing.plan_id} (agent {existing.agent_id}); "
                f"refusing pre-execution for plan {intent.plan_id}"
            )
        self._held[slot] = intent

    def release(self, intent: WriteIntent) -> None:
        slot = (intent.table, intent.key)
        if self._held.get(slot) == intent:
            del self._held[slot]

    def assert_held(self, intent: WriteIntent) -> None:
        slot = (intent.table, intent.key)
        if self._held.get(slot) != intent:
            raise LeaseExpired(
                f"write-intent lease for {slot} (plan {intent.plan_id}) "
                f"was reaped or stolen before commit; effect must not execute"
            )


def speculative_execute(
    registry: IntentRegistry,
    intent: WriteIntent,
    tool_body,
    *args,
    **kwargs,
):
    """Reserve-then-execute: the only sound path for non-commutative effects."""
    registry.acquire(intent)
    try:
        # Re-validate atomically at the moment of execution, not just at registration.
        registry.assert_held(intent)
        return tool_body(*args, **kwargs)
    finally:
        # Abort and success both release; commit is the caller's responsibility
        # to make durable before this finally runs.
        registry.release(intent)