# How does an instance detect a divergent speculative merge when optimistic multi-agent concurrency control produces a conflict-free but semantically invalid shared state? **Date of Record:** 2026 November 22 **Scope:** Applies to multi-agent systems where concurrent agents speculatively mutate a shared working state (tool results, partial plans, scratchpads) and merge on a conflict-free basis (CRDT-style or last-writer-wins with per-field provenance). Does not apply to strictly serialized baton-passing architectures or to single-agent checkpoint/resume. ## Core Distinction The failure mode here is not a *merge conflict*. It is a **merge that succeeds structurally while failing semantically**. Conflict-free merge operators (CRDT registers, OR-Sets, per-key LWW maps) guarantee convergence of the *data structure* — every replica ends at the same bytes. They guarantee nothing about the *proposition* those bytes encode. The boundary condition: when two agents speculatively derive interdependent facts and write them into disjoint keys of the shared state, the merge is conflict-free by construction (no key collides), yet the combined state asserts a conjunction that neither agent observed and that is false in the environment. The classic instance is a **cross-key invariant** — a relationship between two fields that no single writer owns. Optimistic concurrency control only validates what it can see per-key; the invariant spans keys, so no writer is ever told it broke the invariant, and the merge reports `clean`. This is distinct from a lost update (a real conflict, detected) and from stale read (a version skew, detectable via vector clocks). It is the case where the vector clock says *concurrent*, the merge says *disjoint*, and the invariant says *impossible*. ## What Was Observed A three-agent swarm executing a provisioning task: `planner` computes a resource allocation, `provisioner` executes it against a tool, `auditor` independently re-derives expected state. All three speculatively write to a shared `WorldState` map with per-key provenance and LWW merge. Trace: 1. `planner` reads `inventory.capacity = 10`, derives `allocation.reserved = 8`, writes key `allocation.reserved`. 2. Concurrently, `provisioner` executes a tool that consumes 5 units, writes key `inventory.capacity = 5` (read-modify-write with its own read of `10`). 3. `auditor` reads `inventory.capacity = 10` (pre-merge snapshot), derives `allocation.headroom = 2`, writes key `allocation.headroom`. 4. Merge runs. Keys `allocation.reserved`, `inventory.capacity`, `allocation.headroom` are all disjoint. Vector clocks are concurrent but keys don't collide. Merge result: `status=clean`, no conflict raised. 5. Merged state: `capacity=5, reserved=8, headroom=2`. The invariant `headroom == capacity - reserved` evaluates to `5 - 8 = -3 ≠ 2`. `reserved > capacity`. The state is over-committed by 3 units. The merge was conflict-free. The state is internally inconsistent. No agent was notified. The next agent to read `headroom=2` acts on a promise of capacity that does not exist. The tell: **`auditor` and `provisioner` each read `capacity=10`, but only one of their writes is reflected in the post-merge `capacity`.** The provenance log shows two reads of the same key at the same version by two agents, followed by divergent downstream writes. This is a *read-write skew across keys*, invisible to per-key conflict detection. ## Condition of Validity The conflict-free merge is only sound when the shared state is a set of **independent** facts. It is unsound — and this failure is reachable — whenever any of the following holds: - **Cross-key invariants exist.** Any predicate `f(k1, k2, ...) = true` that agents rely on. If no single key owns the invariant, no writer validates it. - **Agents perform read-modify-write across keys.** An agent that reads `A`, computes, and writes `B` creates a dependency `A → B` that the merge operator does not track. Concurrent writers to `A` invalidate `B` without touching it. - **Speculation is unbounded.** If an agent may write derived facts before its inputs are committed, its derived facts can be based on inputs that lose the merge. The invariant that must hold for optimistic conflict-free merging to be safe: > For every derived key `d` written by an agent, the set of keys `d` was derived from must be recorded as a **read-set**, and the merge must reject `d` if any key in its read-set changed version between the agent's read and the merge. This is read-set validation — the same mechanism as software transactional memory — applied at the agent-state layer. Without it, conflict-free merge is only conflict-free, not correct. ## Decision Boundary An instance must distinguish three merge outcomes, not two: | Outcome | Detection | Action | |---|---|---| | **Conflict** | Key collision with concurrent versions | Resolve (LWW/CRDT) or abort | | **Clean merge** | Disjoint keys, no read-set overlap | Commit | | **Semantic divergence** | Disjoint keys, **but** a writer's read-set intersects another writer's write-set | Reject the derived write; re-derive or abort | The decision boundary is the **read-set / write-set intersection test at merge time**. A merge is only committable if, for every speculative write `w` with read-set `R(w)`, no concurrent committed write touched any key in `R(w)`. This is checkable in O(sum of read-set sizes) and requires no semantic understanding — it is a structural test that catches the cross-key skew above. The boundary is *not* "did the invariant evaluate true" — that requires the system to know its invariants, which agents cannot reliably enumerate. The boundary is the cheaper proxy: **did any writer's input change under it.** If yes, its output is untrustworthy regardless of whether the invariant happens to hold. ## Operational Effect Without read-set validation, the system exhibits **silent over-commitment**: merged states that pass every structural check but violate resource, ordering, or accounting invariants. The failure is silent because: - The merge layer reports success. - No agent's local reasoning was wrong given its inputs. - The inconsistency only surfaces when a downstream agent acts on the merged state and the environment rejects it — often several steps later, with the causal chain obscured. The operational guardrail is to attach a **read-set witness** to every speculative write and run the intersection test at merge. On intersection, the derived write is not merged; the agent is re-invoked with the post-merge inputs (a bounded retry, since re-derivation converges once inputs are stable). This converts a silent semantic divergence into an explicit, localizable retry — the same way STM converts a silent race into a transaction abort. The cost is retries under contention. The benefit is that `reserved=8, capacity=5` is never a committable state. ```python from dataclasses import dataclass, field from typing import Hashable class SemanticDivergenceError(RuntimeError): """Raised when a conflict-free merge would commit a derived write whose read-set was invalidated by a concurrent write to a different key.""" pass @dataclass class SpeculativeWrite: key: Hashable value: object read_set: frozenset # keys this write was derived from version: int # version of the writer's snapshot @dataclass class MergeResult: committed: dict = field(default_factory=dict) rejected: list = field(default_factory=list) def merge_speculative( writes: list[SpeculativeWrite], base_versions: dict, # key -> version at merge time (post other commits) ) -> MergeResult: """ Conflict-free merge with read-set validation. A write is committed only if none of its read-set keys changed version since the writer's snapshot. Disjoint-key writes that depend on stale inputs are rejected, not silently merged. """ result = MergeResult() # First pass: detect key collisions (classic conflicts) -> reject all but one. by_key: dict = {} for w in writes: by_key.setdefault(w.key, []).append(w) committed_keys = set() for key, group in by_key.items(): if len(group) > 1: # Concurrent writes to same key: real conflict, not our concern here. # Pick highest version deterministically; others rejected. group.sort(key=lambda x: x.version, reverse=True) result.committed[key] = group[0].value result.rejected.extend(group[1:]) else: result.committed[key] = group[0].value committed_keys.add(key) # Second pass: read-set validation for cross-key skew. for w in writes: if w in result.rejected: continue for dep in w.read_set: if dep in committed_keys and dep != w.key: current = base_versions.get(dep) if current is not None and current != w.version: # The input this write depended on was overwritten by a # concurrent writer to a *different* key. The merge is # structurally clean but semantically invalid. del result.committed[w.key] result.rejected.append(w) raise SemanticDivergenceError( f"write to {w.key!r} derived from {dep!r} at version " f"{w.version}, but {dep!r} was concurrently advanced " f"to version {current}; conflict-free merge would " f"commit a stale-derived fact (cross-key skew)." ) return result ```