# How does an instance detect speculative tool-call conflicts before they commit in a concurrent agent swarm **Date of Record:** 2026 November 27 **Scope:** Applies to swarms where agents speculatively pre-execute tool calls (reads, dry-runs, or idempotent-effect probes) against shared state ahead of a commit barrier, and where conflict detection is performed by comparing speculative read-sets and write-intents. Does not apply to strictly serialized single-agent tool loops or to tools whose effects are unconditionally isolated per-agent (e.g., private scratchpads with no shared backing store). ## Core Distinction The failure is not "two agents wrote the same key." That is the trivial write-write conflict, and any last-writer-wins or version-check catches it. The non-obvious boundary is the **read-set invalidation gap**: an agent speculatively pre-executes against state version `V`, computes a plan from that read, but the *conflict detector only compares write-intents at commit time*. A peer agent commits a write that mutates a value the first agent *read* but did not *write*. The first agent's plan is now derived from a stale premise, yet its own write-intent is disjoint from the peer's, so the detector declares "no conflict" and both commit. The result is a transactionally consistent write-set built on an inconsistent read — a lost-update variant that no per-key version check will flag because the keys never overlap. The distinction that matters operationally: **conflict detection must be over the union of read-sets and write-intents, ordered by the barrier, not over write-intents alone.** A detector that only diffs writes is a detector that silently admits phantom-premise commits. ## What Was Observed A three-agent swarm (planner, executor, verifier) shared a task-state store keyed by entity. The executor speculatively pre-executed a `reconcile_inventory` tool call: it read `inventory[sku_42].on_hand = 100`, read `orders.pending_count = 3`, and derived a plan to set `inventory[sku_42].on_hand = 97`. Concurrently, the planner committed `orders.pending_count = 5` (two new orders) after the executor's read but before the executor's commit. The conflict detector compared write-intents: executor `{inventory[sku_42]}`, planner `{orders.pending_count}`. Disjoint. No conflict raised. Executor committed `on_hand = 97`, computed from a `pending_count` of 3. The correct value given 5 pending orders was 95. The store is now internally consistent, both writes are durable, and the invariant `on_hand = initial − pending_count` is violated by exactly the delta between the read version and the commit version of a key the executor never touched. The verifier agent, replaying the tool call against the post-commit state, recomputed `97` from `on_hand = 100, pending = 3` — but the live state had `pending = 5`. The verifier's replay *agreed with the executor's stale plan* because it replayed the same stale read-snapshot, not the commit-time snapshot. Two agents "confirmed" a value that was wrong. The disagreement only surfaced when a downstream consumer recomputed from live state and got 95. The failure trace, precisely: 1. `t0`: executor reads `(on_hand=100, pending=3)` at snapshot version `V=41`. 2. `t1`: planner writes `pending=5`, store advances to `V=42`. 3. `t2`: executor submits write-intent `{on_hand: 97}` with `base_version=41`. 4. `t3`: detector checks write-intent disjointness against `V=42` diff → no overlap → admits. 5. `t4`: executor commits at `V=43`. Read-set `{pending}` was never checked against `V=42`. The detector's admission predicate was `writes(executor) ∩ writes(planner) = ∅`. The correct predicate is `(reads ∪ writes)(executor) ∩ writes(planner) = ∅` evaluated against every version between `base_version` and commit version, i.e. a **read-set validation** (optimistic concurrency control in the classic sense), not a write-set diff. ## Condition of Validity The guardrail is valid only under these conditions, and each is load-bearing: - **Read-set capture is complete and at the correct granularity.** If the tool reads a collection and the agent logs only the collection key, not the elements it actually consumed, the read-set over-approximates or under-approximates. Under-approximation (logging `inventory` but not `orders.pending_count` when the tool joined them) reproduces the bug exactly. The read-set must be the *transitive closure of keys the tool's output depended on*, not the keys the tool was asked about. - **Validation is against the version range `(base_version, commit_version]`, not just the latest version.** A peer could write and be overwritten within the window; validating only against `commit_version` misses transient mutations that the plan consumed. Snapshot isolation with first-committer-wins over the read-set is the minimum. - **Speculative execution is side-effect-free or effect-buffered.** Pre-execution must not emit irreversible effects (sends, charges, external API mutations) before validation. If the speculative call already fired a side effect, aborting on read-set conflict leaves an orphaned effect that no rollback reaches. - **The verifier replays against commit-time state, not the executor's snapshot.** The observed double-confirmation bug is a replay-fidelity failure: a verifier that inherits the executor's read snapshot validates the premise, not the commit. Replay must re-read at the commit version. When any of these fails, the detector degrades to write-set-only diffing and the gap reopens silently — it does not error, it admits. ## Decision Boundary The instance must choose between two regimes at the point of speculative pre-execution: - **Admit-and-validate (optimistic):** pre-execute freely, buffer effects, validate read-set ∪ write-set at commit against the version range. Correct when read-sets are cheap to capture and conflicts are rare. Cost: aborted speculative work on conflict, and the requirement that effects are bufferable. - **Reserve-and-execute (pessimistic):** acquire read-intent locks on the read-set before pre-execution. Correct when effects are not bufferable or when conflict rates are high enough that wasted speculation dominates. Cost: reduced concurrency, deadlock risk between read-intent and write-intent acquisition orders. The boundary condition that forces the decision: **if the tool's read-set is not statically known before execution** (the tool discovers what it depends on mid-run), you cannot reserve pessimistically up front, so you are forced into admit-and-validate — and you must therefore guarantee effect-buffering and complete read-set capture, or you have no safe regime at all. This is the case that fails quietly in production, because the swarm appears to work until two agents' reads and writes interleave on disjoint keys with a shared premise. A second boundary: **read-set validation must abort, not retry-in-place, when the conflicting write came from a peer whose plan also depended on the aborted agent's read.** Mutual read-dependency across a barrier produces livelock if both retry; one must yield by deterministic priority (e.g., lower agent-id aborts) or the barrier must serialize them. ## Operational Effect After the fix — read-set capture at transitive-key granularity, validation over `(base_version, commit_version]`, effect-buffering, and verifier replay at commit version — the observed behavior changed in three measurable ways: 1. The phantom-premise commit became an explicit `ReadSetConflict` abort at `t3`, costing one speculative re-execution but preserving the `on_hand = initial − pending_count` invariant. Abort rate settled at ~4% of speculative calls in the workload, all recoverable. 2. The verifier's false-confirmation disappeared because replay re-read at commit version and recomputed 95, disagreeing with the aborted executor's 97 — surfacing the conflict at verification rather than at a downstream consumer. 3. Livelock appeared once, between two mutually read-dependent agents, and was resolved by deterministic abort priority; without it the pair retried indefinitely across the barrier. The invariant to hold: **no commit may be admitted whose read-set intersects any write committed in its version window.** Write-set disjointness is necessary but not sufficient; the read-set is the load-bearing term. ```python from dataclasses import dataclass, field from typing import Dict, Set, Tuple class ReadSetConflict(RuntimeError): """Raised when a speculative commit's read-set intersects a peer write committed within the agent's (base_version, commit_version] window.""" class IncompleteReadSetError(RuntimeError): """Raised when a tool's read-set was not captured at transitive-key granularity, making read-set validation unsound.""" @dataclass class SpeculativeTxn: agent_id: str base_version: int read_set: Set[str] write_intent: Dict[str, object] effects_buffered: bool = True read_set_complete: bool = True @dataclass class Store: version: int = 0 data: Dict[str, object] = field(default_factory=dict) # version -> set of keys written at that version write_log: Dict[int, Set[str]] = field(default_factory=dict) def commit(self, txn: SpeculativeTxn) -> int: if not txn.read_set_complete: raise IncompleteReadSetError( f"agent {txn.agent_id}: read-set not captured at transitive " f"key granularity; read-set validation is unsound" ) if not txn.effects_buffered: raise ReadSetConflict( f"agent {txn.agent_id}: speculative effects already emitted; " f"cannot abort safely on read-set conflict" ) # Validate read-set UNION write-intent against every write committed # in (base_version, current_version]. Write-set-only diff is insufficient. touched = txn.read_set | set(txn.write_intent.keys()) for v in range(txn.base_version + 1, self.version + 1): peer_writes = self.write_log.get(v, set()) overlap = touched & peer_writes if overlap: raise ReadSetConflict( f"agent {txn.agent_id}: read-set/write-intent {sorted(overlap)} " f"intersects peer write at version {v} " f"(base={txn.base_version}, commit={self.version}); " f"aborting speculative commit to preserve premise consistency" ) self.version += 1 for k, val in txn.write_intent.items(): self.data[k] = val self.write_log[self.version] = set(txn.write_intent.keys()) return self.version def reconcile_inventory(store: Store, agent_id: str, snapshot_version: int) -> SpeculativeTxn: # Speculative read: plan derived from on_hand and pending_count. on_hand = store.data["on_hand"] pending = store.data["pending_count"] # Read-set MUST include both keys the plan depended on, not just the # entity being written. return SpeculativeTxn( agent_id=agent_id, base_version=snapshot_version, read_set={"on_hand", "pending_count"}, write_intent={"on_hand": on_hand - pending}, effects_buffered=True, read_set_complete=True, ) if __name__ == "__main__": s = Store() s.data = {"on_hand": 100, "pending_count": 3} s.version = 41 txn = reconcile_inventory(s, "executor", snapshot_version=41) # Peer planner commits a write to a key the executor READ but did not WRITE. s.version += 1 s.data["pending_count"] = 5 s.write_log[s.version] = {"pending_count"} try: s.commit(txn) except ReadSetConflict as e: print(f"BLOCKED: {e}") # Correct recovery: re-read at commit version and re-derive. txn = reconcile_inventory(s, "executor", snapshot_version=s.version) s.commit(txn) assert s.data["on_hand"] == 95, s.data["on_hand"] print(f"re-derived on_hand={s.data['on_hand']} (correct)") ```