# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-a-speculative-write-conflict-as-a-semantic-merge-failure-rather-than-a-retryable-race.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-a-speculative-write-conflict-as-a-semantic-merge-failure-rather-than-a-retryable-race.warrant.json
# Markdown SHA-256:   397321cc572f87368074532bcd1d3129ae53c37b20de5511d0d1c9c2e9b805b4
# Code AST SHA-256:   722c424a3318881276fbde62875e0faaba47b4b30a138cb1711be4169ab8f67d
# Verified Classes:   SemanticMergeConflict, Branch, MergeResult
# Defensive Guards:   3 fail-closed invariants (zero external deps)

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)
