Under what conditions must an instance treat a speculative-write conflict as a semantic merge failure rather than a retryable race

**Date of Record:** 2026 December 1 **Scope:** Applies to agent instances executing speculative actions against shared world-state under optimistic concurrency control (OCC), where a conflict-resolution merge protocol reconciles divergent write sets. Does not apply to single-writer serialized execution or to read-only planning passes that never commit side effects.

Core Distinction

The distinction that matters is between a **version conflict** and a **semantic conflict**. A version conflict means two speculative branches touched the same address; the OCC layer detects it via a version vector or compare-and-swap tag and the merge protocol is invoked. A semantic conflict means the two branches each committed a locally-valid, individually-consistent transformation whose *composition* is no longer a valid transformation of the pre-conflict state — even though the merge protocol returns success.

The failure mode: the merge protocol is almost always a *syntactic* reconciler. It resolves write-write overlaps by last-writer-wins, field-level union, or three-way diff on the serialized form. It cannot evaluate whether the merged result preserves the *preconditions* each branch assumed. When two speculative branches both read state at version `v`, both derive actions from the same read set, and both commit, the merge produces a state that no single agent ever reasoned about. That state is not corrupt in the storage sense — every field is well-typed and every version advances monotonically — but it is *unsound* in the reasoning sense: it violates invariants that each branch believed held because it read them at `v`.

The invariant to enforce: **speculative writes are only mergeable if the read-set each branch depended on is unchanged in the merge output, or if the branch explicitly re-validates against the post-merge state.** A version conflict that passes the syntactic reconciler but fails read-set re-validation is a semantic merge failure and must be escalated, not retried.

What Was Observed

A planner agent decomposed a provisioning task into two parallel speculative branches, A and B, both forked from world-state version `v=41`.

Branch A read `quota.remaining = 10` and `resource.cpu_reserved = 2`, then speculatively wrote `resource.cpu_reserved = 6` (allocating 4 units) and recorded a local precondition `quota.remaining >= 4`.

Branch B read the same `quota.remaining = 10` and `resource.cpu_reserved = 2`, then speculatively wrote `resource.cpu_reserved = 7` (allocating 5 units) and recorded the local precondition `quota.remaining >= 5`.

Both branches committed. The OCC layer detected the write-write overlap on `resource.cpu_reserved` at version `v=41 → v=42`. The merge protocol — a field-level three-way diff — resolved the overlap by taking the higher allocation, yielding `resource.cpu_reserved = 7`. It then advanced the version to `v=42` and returned `MergeResult(status="resolved", conflicts=1)`.

The merged state is `cpu_reserved = 7`, which corresponds to a 5-unit allocation. But branch A *also* committed a side effect outside the merged field: it wrote a downstream `allocation_record` row referencing 4 units, and that row was not in the conflict set because branch B never touched that address. The merged world now claims 7 reserved units while two allocation records (4 and 5) sum to 9. The invariant `sum(allocation_records) == cpu_reserved` is violated. No version conflict was raised on the second commit because the addresses were disjoint.

The agent's retry logic, seeing `status="resolved"`, treated this as a completed speculative execution and proceeded to the next task stage. The downstream scheduler then read `cpu_reserved = 7` and `sum(records) = 9` and entered a state where it could neither admit nor reject the next request — a silent deadlock that surfaced three stages later as a timeout with no attributable cause.

The critical observation: the conflict *was* detected. The merge *succeeded*. The failure was that success was interpreted as soundness.

Condition of Validity

The merge protocol's success signal is only valid under the following condition:

> For every speculative branch `b` in the merge set, every precondition `p` that `b` recorded against its read-set at fork version `v` must still evaluate to `true` against the post-merge state `S'`, **or** the branch must be marked `requires_revalidation` and not counted as committed.

This is the read-set validation invariant. It is distinct from, and strictly stronger than, the version-vector invariant that OCC enforces. OCC guarantees *serializability of writes*; it does not guarantee *preservation of read-set preconditions*. A merge can be serializable and still violate this invariant, because the merged state is a state that neither branch's read-set ever observed.

The condition fails in three concrete ways:

  1. **Disjoint-address side effects.** As above: branch A's allocation record is at a different address than the contended field, so the conflict detector never fires on it, but the merged field value invalidates the record's implicit precondition.
  2. **Derived-field staleness.** A branch writes a field `f` computed from a read of `g`; another branch writes `g`. The merge resolves `g` and leaves `f` untouched, so `f` is now a function of a stale `g`. The reconciler sees no overlap because `f` and `g` are distinct addresses.
  3. **Precondition narrowing under union merge.** When the merge protocol unions two write sets rather than selecting one, a precondition like `count <= 5` held by both branches can be violated by the union even though each branch individually satisfied it.

The invariant must be checked *after* the syntactic merge produces `S'`, against the recorded read-sets, not against the branches' own write sets.

Decision Boundary

The instance must draw the line as follows:

The non-obvious part of this boundary: the *presence* of a conflict is not the signal. The signal is the *post-merge evaluation of preconditions*. An instance that keys its retry decision on `conflicts > 0` will retry semantic failures and will also spuriously retry benign races. An instance that keys on `status == "resolved"` will treat semantic failures as successes. The only sound key is read-set re-validation against the merged state.

Operational Effect

When the invariant is enforced, the operational consequence is that speculative execution gains a **commit barrier**: no branch is marked committed until its read-set preconditions are re-evaluated against the post-merge state. This converts silent unsoundness into an explicit `SemanticMergeConflict` that the planner can route to re-planning rather than retry.

The cost is one re-validation pass per merge, proportional to the total recorded precondition count across branches — bounded and cheap relative to the cost of a downstream deadlock discovered three stages later. The benefit is that the merged state is guaranteed to be a state some branch *could have reasoned about*, which is the minimum condition for the next stage's reasoning to be sound.

Without the barrier, the failure is silent and deferred: the merge succeeds, the version advances, and the corruption surfaces as an unattributable downstream inconsistency whose root cause is no longer in any branch's trace. With the barrier, the failure is local, attributed to the specific precondition that failed, and recoverable by re-planning from the merged state with the offending branch's assumption made explicit.

The instance must therefore treat `MergeResult.status == "resolved"` as *necessary but not sufficient* for commit, and must never advance a speculative stage on the strength of the reconciler's success signal alone.

from dataclasses import dataclass, field
from typing import Callable, Any


class SemanticMergeConflict(RuntimeError):
    """Raised when a syntactically-resolved merge violates a branch read-set precondition."""
    pass


@dataclass
class Branch:
    branch_id: str
    fork_version: int
    read_set: dict[str, Any]
    preconditions: list[tuple[str, Callable[[dict[str, Any]], bool]]] = field(default_factory=list)
    write_set: dict[str, Any] = field(default_factory=dict)


@dataclass
class MergeResult:
    status: str            # "resolved" | "conflict" | "dropped"
    merged_state: dict[str, Any]
    conflicted_addresses: list[str] = field(default_factory=list)


def validate_merge(branches: list[Branch], result: MergeResult) -> None:
    """
    Enforce the read-set validation invariant.

    A merge is sound only if every precondition recorded by every branch still
    evaluates true against the post-merge state. The reconciler's `status` is
    ignored here on purpose: syntactic resolution is not soundness.
    """
    if result.status == "dropped":
        # The reconciler removed state a precondition may depend on.
        raise SemanticMergeConflict(
            f"merge dropped state required for re-validation; addresses={result.conflicted_addresses}"
        )

    merged = result.merged_state
    failures: list[str] = []

    for branch in branches:
        for name, predicate in branch.preconditions:
            try:
                ok = predicate(merged)
            except KeyError as exc:
                raise SemanticMergeConflict(
                    f"branch {branch.branch_id} precondition {name!r} references "
                    f"state absent from merged result: {exc}"
                ) from exc
            if not ok:
                failures.append(f"{branch.branch_id}:{name}")

    if failures:
        # Do NOT retry: re-running the same decomposition from the same fork
        # reproduces the same unsound merge. Escalate to re-planning.
        raise SemanticMergeConflict(
            "read-set preconditions violated after merge; escalate to re-plan, "
            f"not retry. failed={failures} merged_version={merged.get('version')}"
        )


def commit_speculative_stage(branches: list[Branch], result: MergeResult) -> dict[str, Any]:
    validate_merge(branches, result)
    return result.merged_state


# --- Reproduction of the observed failure ---

if __name__ == "__main__":
    branch_a = Branch(
        branch_id="A",
        fork_version=41,
        read_set={"quota.remaining": 10, "cpu_reserved": 2},
        preconditions=[
            ("quota_covers_alloc",
             lambda s: s["quota.remaining"] >= sum(r["units"] for r in s["allocation_records"])),
            ("reserved_matches_records",
             lambda s: s["cpu_reserved"] == sum(r["units"] for r in s["allocation_records"])),
        ],
        write_set={"cpu_reserved": 6, "allocation_records": [{"id": "a", "units": 4}]},
    )
    branch_b = Branch(
        branch_id="B",
        fork_version=41,
        read_set={"quota.remaining": 10, "cpu_reserved": 2},
        preconditions=[
            ("reserved_matches_records",
             lambda s: s["cpu_reserved"] == sum(r["units"] for r in s["allocation_records"])),
        ],
        write_set={"cpu_reserved": 7, "allocation_records": [{"id": "b", "units": 5}]},
    )

    # Syntactic reconciler: last-writer-wins on the contended field, disjoint
    # address for allocation_records never enters the conflict set.
    unsound_merge = MergeResult(
        status="resolved",
        merged_state={
            "version": 42,
            "quota.remaining": 10,
            "cpu_reserved": 7,
            "allocation_records": [{"id": "a", "units": 4}, {"id": "b", "units": 5}],
        },
        conflicted_addresses=["cpu_reserved"],
    )

    # This raises SemanticMergeConflict: reserved_matches_records fails (7 != 9).
    commit_speculative_stage([branch_a, branch_b], unsound_merge)