# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-speculatively-executes-parallel-plan-branches-and-the-merge-layer-silently-drops-a-losing-write.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-speculatively-executes-parallel-plan-branches-and-the-merge-layer-silently-drops-a-losing-write.warrant.json
# Markdown SHA-256:   b7451fbe4a2a18ac36dc0bccbf419e88206be5a915369285fcc96b461d4b6980
# Code AST SHA-256:   df0ead6140c26b5144e019f645899130038c3c7ba979a8f0f3d7b11d46fd82d0
# Verified Classes:   StaleSpeculativeWrite, UnresolvableMergeConflict, VersionVector, SpeculativeWrite, SpeculativeStore
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field

class StaleSpeculativeWrite(RuntimeError):
    """Raised when a speculative branch attempts to commit a write whose
    read-set version is dominated by an already-committed write on the same key.
    This is the guardrail that prevents the merge layer from silently
    manufacturing conflict-freedom by discarding a losing branch."""
    pass

class UnresolvableMergeConflict(RuntimeError):
    """Raised when two branches wrote the same key with equal read-set versions
    but divergent values (nondeterminism) -- must be escalated, never resolved
    by branch priority."""
    pass

@dataclass
class VersionVector:
    versions: dict = field(default_factory=dict)  # key -> snapshot epoch

    def dominates(self, other: "VersionVector") -> bool:
        return all(self.versions.get(k, -1) >= v for k, v in other.versions.items())

@dataclass
class SpeculativeWrite:
    branch_id: str
    key: str
    value: object
    read_version: VersionVector

class SpeculativeStore:
    def __init__(self):
        self._committed = {}   # key -> (value, VersionVector, branch_id)
        self._conflicts = []

    def commit(self, write: SpeculativeWrite) -> None:
        prior = self._committed.get(write.key)
        if prior is not None:
            prior_value, prior_vv, prior_branch = prior
            # Guardrail 1: reject writes based on a dominated (stale) read set.
            if prior_vv.dominates(write.read_version) and not write.read_version.dominates(prior_vv):
                self._conflicts.append((prior_branch, write.branch_id, write.key))
                raise StaleSpeculativeWrite(
                    f"branch {write.branch_id} wrote {write.key}={write.value!r} "
                    f"from stale read-set {write.read_version.versions}; "
                    f"dominated by committed {prior_branch}"
                )
            # Guardrail 2: equal versions + divergent values = nondeterminism.
            if prior_vv.versions == write.read_version.versions and prior_value != write.value:
                raise UnresolvableMergeConflict(
                    f"branches {prior_branch} and {write.branch_id} disagree on "
                    f"{write.key}: {prior_value!r} vs {write.value!r} at identical "
                    f"read-set versions; escalate, do not order-resolve"
                )
        self._committed[write.key] = (write.value, write.read_version, write.branch_id)

    def conflict_log(self):
        return list(self._conflicts)
