# How does an instance detect speculative tool-call rollback invalidation when optimistic concurrency merges silently overwrite sibling writes? **Date of Record:** 2026 November 25 **Scope:** Applies to agents that issue speculative (parallel, unconfirmed) tool calls against shared mutable state under optimistic concurrency control with automatic conflict-resolving merge semantics. Does not apply to serialized single-writer execution, read-only tool surfaces, or systems where every write carries an explicit compare-and-swap precondition that the agent itself authors. ## Core Distinction The failure is not "lost update" in the classical database sense. Classical lost update is detected because the writer knows the precondition it violated. The failure here is **speculative rollback invalidation**: an agent fires N speculative tool calls in parallel, each optimistically assuming the pre-call world; a *conflict-resolving merge* layer (three-way merge, CRDT-style join, or LLM-mediated reconciliation) then reconciles divergent results and produces a merged state that is *syntactically valid, causally coherent to the merge function, and semantically wrong to the agent*. The agent's local model of state was built from the pre-speculation snapshot; the merge layer rewrites that snapshot under it. The agent never observes a conflict signal because the merge layer's entire job is to suppress conflict signals. Detection must therefore be **inferential**, not event-driven: the instance has to prove its post-merge view is reachable from its own speculative writes, not merely that the merge returned 200. The sharp invariant: *a speculative call's effect is observable to the agent if and only if the merged state contains a witness of that call's write that the agent can re-derive from its own call log.* Conflict-resolving merges routinely drop that witness while preserving the surrounding state, producing a "successful" call whose effect vanished. ## What Was Observed A planner agent decomposed "rename all `user_id` fields to `account_id` across three config artifacts" into three parallel speculative `patch_file` calls (files A, B, C) plus a fourth speculative call `update_schema` that assumed the rename would land. All four were dispatched optimistically against a snapshot taken at t0. File B was concurrently modified by a sibling auditor agent that added a new `user_id` reference at t0+40ms. The merge layer, configured with a recursive three-way merge, resolved A and C cleanly, resolved the schema call cleanly, and for B produced a merge that **kept the auditor's new `user_id` line and dropped the agent's rename on the colliding region** — a standard "theirs wins on overlap" policy. The merge returned `status: merged, conflicts: 0`. The agent's tool-call results all returned `ok`. The agent then asserted completion and emitted a summary claiming full rename coverage. The defect surfaced 11 minutes later when a downstream loader rejected file B: it contained both `account_id` (from non-colliding lines) and `user_id` (from the auditor's insert), and the loader's strict schema check failed. The agent's completion claim was false at emission time, but every individual tool result was truthful. The failure lived entirely in the gap between *per-call success* and *merged-state witness*. A second observed variant: the merge layer's "conflict-resolution" was itself an LLM call. It reconciled the rename against the auditor's insert by *rewriting the auditor's line* to `account_id` — semantically defensible, but it silently mutated a sibling agent's committed write. The auditor's own completion assertion was thereby invalidated retroactively, and the auditor had no mechanism to learn this. ## Condition of Validity The invariant holds — i.e., the agent can trust merged state — only when all three conditions are jointly true: 1. **Witness re-derivation.** For every speculative write `w_i`, the agent can compute, from its own call log alone (not from the merge layer's report), a predicate `witness(w_i, S_merged)` that is true iff `w_i`'s effect is present in the merged state. This requires the write to be *content-addressed* (specific field, specific value, specific location) rather than *intent-addressed* ("rename all"). 2. **Merge transparency.** The merge layer exposes enough of its resolution log that the agent can distinguish "my write won," "my write lost to a sibling," and "my write was rewritten by a reconciler." A bare `conflicts: 0` is insufficient — it conflates "no conflict" with "conflict resolved without telling you." 3. **Sibling-write visibility.** The agent can observe that a sibling wrote to the same region during the speculation window. Without this, a dropped witness is indistinguishable from a write that never applied. If any condition fails, optimistic speculation is unsound and the agent must fall back to serialized execution with explicit preconditions. Most deployed systems fail condition 2 by default: merge layers are designed to *hide* resolution, because surfacing it confuses naive callers. ## Decision Boundary The boundary between "speculate safely" and "must serialize" is drawn by **witness granularity versus merge overlap probability**, not by call count or latency budget. - If every speculative write is expressible as a *content-addressed witness* (e.g., "field `x` at path `p` now equals `v`") **and** the merge layer returns a per-call resolution disposition (`applied | superseded | rewritten`), speculate freely; the agent verifies post-merge by re-deriving each witness. - If writes are *intent-addressed* ("rename all occurrences") — which is the natural form for LLM planners — the agent cannot construct a witness without first enumerating the affected region, and that enumeration is itself stale by merge time. In this regime, **any** concurrent sibling write to the region invalidates the speculation, and the agent must either (a) serialize, or (b) re-enumerate post-merge and diff against its pre-merge enumeration. - The hard stop: if the merge layer's reconciler is itself probabilistic (LLM-mediated merge), the agent must treat *every* merged region as untrusted and re-verify from scratch, because the reconciler may have mutated sibling writes in ways no witness can capture. Speculation here is only sound for writes whose region the reconciler provably did not touch — which requires the resolution log. The practical rule: **speculate on disjoint, content-addressable regions; serialize on intent-addressed or overlapping regions; never trust an LLM-mediated merge without a full post-merge re-read of the affected region.** ## Operational Effect The concrete operational consequence is that an agent's completion assertion must be gated on a **post-merge witness check**, not on per-call tool results. This adds one read pass over the merged state per speculation batch — cheap relative to the cost of a false completion — and it converts the silent-overwrite failure into a detectable, recoverable one: the agent learns which witnesses dropped, which regions were rewritten by a reconciler, and can re-issue only the invalidated calls (or escalate to serialized execution). The second effect is on sibling coordination: an agent that observes its own write was `rewritten` by a reconciler must propagate an invalidation notice to the sibling whose write was mutated, because that sibling's completion assertion is now stale. Without this, reconciler-mediated merges create *retroactive* completion failures that no agent can detect locally — the multi-agent equivalent of a torn read that surfaces minutes later in a downstream consumer. The guardrail is architectural, not procedural: the merge layer must return a per-call disposition and a resolution log, and the agent runtime must refuse to emit a completion assertion until every speculative witness re-derives true against the merged state. Absent that, optimistic speculation is a latency optimization that trades correctness for throughput, and the trade is invisible until a downstream strict consumer rejects the result. ```python from dataclasses import dataclass, field from typing import Callable, Literal Disposition = Literal["applied", "superseded", "rewritten", "absent"] class SpeculationWitnessError(RuntimeError): """Raised when a speculative write's witness fails to re-derive against merged state.""" @dataclass class SpeculativeWrite: call_id: str region: str # content-addressable region, e.g. "fileB:line42:user_id" expected_value: str # the value the agent intends to be present post-merge witness: Callable[[dict], bool] # re-derivable predicate over merged state @dataclass class MergeResult: state: dict dispositions: dict[str, Disposition] # call_id -> disposition resolution_log: list[str] = field(default_factory=list) def verify_speculation( writes: list[SpeculativeWrite], merge: MergeResult, *, reconciler_is_probabilistic: bool = False, ) -> None: """ Post-merge witness check. Must run before any completion assertion. Raises SpeculationWitnessError on the first unverifiable witness. """ for w in writes: disp = merge.dispositions.get(w.call_id, "absent") if disp == "rewritten": # A reconciler mutated this write's effect (or a sibling's). # Witness cannot be trusted even if it currently evaluates true, # because the reconciler may have altered sibling state we cannot see. raise SpeculationWitnessError( f"call {w.call_id}: reconciler rewrote region {w.region}; " f"completion assertion invalid, sibling invalidation required" ) if disp == "superseded": # Our write lost to a sibling. That may be correct, but we cannot # claim completion for this region. raise SpeculationWitnessError( f"call {w.call_id}: superseded on {w.region}; " f"re-enumerate region and re-issue or escalate to serialized" ) if disp == "absent": raise SpeculationWitnessError( f"call {w.call_id}: merge layer returned no disposition for {w.region}; " f"cannot distinguish dropped-write from never-applied" ) if not w.witness(merge.state): raise SpeculationWitnessError( f"call {w.call_id}: witness failed to re-derive on {w.region} " f"(expected {w.expected_value!r}); merged state does not contain our effect" ) if reconciler_is_probabilistic and w.region in merge.state: # Belt-and-suspenders: probabilistic reconcilers can mutate sibling # writes in the same region without emitting a 'rewritten' disposition. # Force a full re-read of the region against the pre-merge enumeration. raise SpeculationWitnessError( f"call {w.call_id}: probabilistic reconciler touched {w.region}; " f"full post-merge re-read required before completion" ) # Example invocation that triggers the guard: if __name__ == "__main__": writes = [ SpeculativeWrite( call_id="rename-B", region="fileB:user_id", expected_value="account_id", witness=lambda s: "user_id" not in s.get("fileB", ""), ) ] merged = MergeResult( state={"fileB": "account_id = 1\nuser_id = 2\n"}, # auditor's insert survived dispositions={"rename-B": "rewritten"}, resolution_log=["theirs-wins on overlap at fileB:user_id"], ) try: verify_speculation(writes, merged, reconciler_is_probabilistic=True) except SpeculationWitnessError as e: print(f"BLOCKED completion: {e}") ```