What happens when an instance speculatively pre-executes a tool call whose optimistic concurrency token is invalidated by a concurrent sibling agent before reconciliation

**Date of Record:** 2026 December 1 **Scope:** Applies to agents that overlap reasoning with tool execution by issuing speculative calls under an optimistic concurrency assumption (read-token / version-vector / ETag style precondition), and that must reconcile the speculative result against a committed state when a sibling agent mutates the same resource first. Does not apply to pessimistic-locking executors, single-writer topologies, or read-only tool surfaces with no shared mutable state.

Core Distinction

The distinction that matters here is between *speculative execution* and *speculative commitment*. An agent that pre-executes a tool call to hide latency is making a bet: that the world it read at planning time will still hold at commit time. When the tool surface is a pure function of inputs, this bet is free — the result is either valid or trivially discardable. But when the tool call carries an optimistic concurrency precondition (a version token, an `If-Match` ETag, a monotonic `seq_no`), the speculative *side effect* is not the only thing at risk. The precondition itself is a claim about shared state, and a sibling agent can invalidate that claim between the moment the parent instance read the token and the moment the speculative result is reconciled.

The non-obvious part: the failure is not that the speculative call fails. It is that the speculative call *succeeds locally* — producing a well-formed result, often a plausible-looking diff or a new resource version — while the precondition it was supposed to enforce has already been superseded. The agent then reconciles a *valid-looking* speculative artifact against a *different* committed baseline, and the reconciliation logic silently treats the speculative output as if it were derived from the current state. This is the "optimistic token invalidation gap": the window between token read and reconciliation during which a sibling's commit makes the speculative derivation stale, but not detectably so, because the speculative executor never re-read the token.

What Was Observed

A parent agent (`A`) plans a two-step mutation: read resource `R` at version `v7`, then issue a speculative `patch(R, delta, if_match=v7)` in parallel with continued reasoning. A sibling agent (`B`), spawned earlier from the same task graph, commits `patch(R, delta_B, if_match=v7)` and advances `R` to `v8`. `A`'s speculative executor already dispatched its request; the tool returns `409 Conflict` (or, worse, a 200 with a *rebased* body if the tool surface does server-side three-way merge). In the 409 case, `A`'s reconciliation logic observes "speculative call failed, retry with fresh token" and re-reads `R` at `v8`. But the retry is issued with `A`'s *original* `delta`, which was computed against `v7` and does not account for `delta_B`. The retry succeeds at `v9`, and the merged result is a *semantic* conflict that no precondition caught: `delta` and `delta_B` both assume field `f` had its `v7` value, and both overwrite it.

The trace:

  1. `A` reads `R@v7`, computes `delta = {f: a}`.
  2. `A` speculatively dispatches `patch(R, delta, if_match=v7)`.
  3. `B` commits `patch(R, delta_B={f: b}, if_match=v7)` → `R@v8`.
  4. `A`'s speculative call returns `409`.
  5. `A`'s reconciler re-reads `R@v8`, sees `f == b`, and — because its `delta` was already materialized — re-dispatches `patch(R, delta, if_match=v8)`.
  6. `A` commits → `R@v9`, `f == a`. `B`'s write is silently lost.

The invariant that was violated: *a speculative result is only reconcilable against the token it was derived from.* Once the token advances, the speculative artifact is not "a pending write to retry" — it is an orphaned derivation whose preconditions no longer hold. Retrying it against the new token converts an optimistic-concurrency conflict into a lost-update, because the precondition check moves from "did the world change since I read it" to "is the world currently at some version I can write to," which is a strictly weaker guarantee.

A subtler variant: the tool surface performs server-side rebase and returns `200` with a merged body. `A`'s reconciler sees success and never learns that `delta_B` was partially overwritten. The speculative executor's success signal is *indistinguishable* from a clean commit, and the parent's reasoning loop proceeds as if no conflict occurred. This is the worst case — the conflict is invisible to the agent layer entirely.

Condition of Validity

The speculative-pre-execution pattern is sound only under the conjunction:

When any of these fails, speculative pre-execution degrades from a latency optimization to a lost-update generator. The degradation is silent because the failure mode is a *successful* commit of a stale derivation.

Decision Boundary

The boundary is: **speculate only when the reconciliation path can distinguish "my derivation is stale" from "my derivation is valid against current state," and only when the tool surface refuses to rebase.**

Concretely, the reconciler must implement the following decision:

The non-obvious operational rule: the parent must treat a `409` on a speculative call as a signal to *invalidate the speculative result entirely*, not as a signal to retry. Retrying is the failure. The speculative result was a bet on `v7`; when `v7` is gone, the bet is lost, and the only correct move is to re-derive from `v8`. Any optimization that reuses the stale delta is trading correctness for latency.

Operational Effect

The practical consequence is a class of silent lost updates that are invisible to per-agent logs. `A`'s log shows a clean `409 → re-read → 200` sequence, which looks like correct optimistic-concurrency handling. `B`'s log shows a clean `200`. Only a cross-agent trace of `R`'s version history reveals that `B`'s write was overwritten. This means per-agent observability is insufficient to detect the failure; the detection invariant must live at the resource level: *every committed version must be attributable to a delta whose `derived_from` matches the immediately preceding version, or whose merge is annotated.*

The architectural guardrail is a **derivation-bound commit protocol**: speculative artifacts are first-class records with a `derived_from` field, the reconciler enforces `derived_from == if_match` at commit, and the tool surface is forbidden from rebasing (it must return `409` with the current token, never a merged body). Under this protocol, speculative pre-execution remains a latency win for commutative or read-only surfaces, and degrades to a clean re-plan for non-commutative surfaces — never to a lost update.

from dataclasses import dataclass
from typing import Optional


class StaleSpeculativeDerivation(RuntimeError):
    """Raised when a speculative artifact is reconciled against a token it was not derived from."""
    pass


@dataclass(frozen=True)
class SpeculativeArtifact:
    delta: dict
    derived_from: str  # the concurrency token read at plan time


@dataclass(frozen=True)
class Resource:
    token: str
    state: dict


def reconcile(
    artifact: SpeculativeArtifact,
    current: Resource,
    *,
    delta_is_commutative: bool = False,
) -> dict:
    """
    Reconcile a speculative artifact against the current committed resource.

    Invariant: a speculative artifact may only be committed against the token it
    was derived from, unless the delta is provably commutative with all
    intervening commits. A 409-on-speculative must NOT be retried with the
    stale delta; it must be discarded and re-planned.
    """
    if artifact.derived_from == current.token:
        merged = dict(current.state)
        merged.update(artifact.delta)
        return merged

    if delta_is_commutative:
        # Safe only when the tool surface exposes the intervening commit log
        # and the delta provably commutes with every intervening write.
        merged = dict(current.state)
        merged.update(artifact.delta)
        return merged

    # Non-commutative delta against an advanced token: the speculative
    # derivation is orphaned. Retrying it here is the lost-update bug.
    raise StaleSpeculativeDerivation(
        f"speculative artifact derived_from={artifact.derived_from!r} "
        f"cannot be committed against current token={current.token!r}; "
        f"delta is non-commutative — discard and re-plan, do not retry"
    )


def commit_speculative(
    artifact: SpeculativeArtifact,
    current: Resource,
    *,
    delta_is_commutative: bool = False,
) -> Resource:
    merged_state = reconcile(
        artifact, current, delta_is_commutative=delta_is_commutative
    )
    # Token advances only on a validated commit.
    next_token = f"v{int(current.token.lstrip('v')) + 1}"
    return Resource(token=next_token, state=merged_state)