# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-speculative-branch-merges-from-violating-read-your-writes-across-federated-quorums.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-speculative-branch-merges-from-violating-read-your-writes-across-federated-quorums.warrant.json
# Markdown SHA-256:   b9f8aca8b3e9b90c4c73b501e8f80c7ab2ea3a530e4a71e694bcd0b89843c4ef
# Code AST SHA-256:   edcc9c3af73799e7b8ebe347ef9398ffbbe99a947f6c2aebce93a3a5c975078a
# Verified Classes:   MergeInvariantViolation, Observation, Branch, QuorumView
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional


class MergeInvariantViolation(RuntimeError):
    """Raised when a speculative branch merge would violate read-your-writes
    across the federated quorum's causal order."""
    pass


@dataclass(frozen=True)
class Observation:
    key: str
    value: object
    replica_id: str
    replication_cursor: int
    branch_id: str
    source: str  # "overlay" or "quorum"


@dataclass
class Branch:
    branch_id: str
    observations: list = field(default_factory=list)
    overlay_writes: dict = field(default_factory=dict)


@dataclass
class QuorumView:
    # replica_id -> (cursor, {key: value}) at commit time
    replicas: dict

    def read(self, replica_id: str, key: str):
        cursor, data = self.replicas[replica_id]
        return data.get(key), cursor

    def min_ack_cursor(self, ack_set: list) -> int:
        if not ack_set:
            raise MergeInvariantViolation("empty acknowledgment set")
        return min(self.replicas[r][0] for r in ack_set)


def merge_speculative_branch(
    branch: Branch,
    quorum: QuorumView,
    ack_set: list,
) -> dict:
    """Merge a surviving speculative branch into the quorum.

    Enforces: every fall-through observation cited by the branch must be
    cursor-dominated by the acknowledgment set, and must re-read to the
    same value at commit time. Overlay observations are exempt (they commit
    atomically with the branch).
    """
    ack_floor = quorum.min_ack_cursor(ack_set)

    for obs in branch.observations:
        if obs.source == "overlay":
            continue

        # Invariant 1: cursor domination. The replica that served the
        # observation must not be ahead of any acknowledging peer.
        if obs.replication_cursor > ack_floor:
            raise MergeInvariantViolation(
                f"branch {obs.branch_id} observation on {obs.key!r} served by "
                f"{obs.replica_id} at cursor {obs.replication_cursor}, which "
                f"exceeds ack floor {ack_floor}; peers {ack_set} cannot "
                f"validate the justification"
            )

        # Invariant 2: value stability. Re-read at commit time must match.
        current, _ = quorum.read(obs.replica_id, obs.key)
        if current != obs.value:
            raise MergeInvariantViolation(
                f"branch {obs.branch_id} cited {obs.key!r}={obs.value!r} but "
                f"commit-time value is {current!r}; justification is false, "
                f"re-fork required (not re-read)"
            )

    # Invariant 3: completeness. No acknowledging peer may hold a write to
    # a cited key that postdates the observation's cursor.
    cited_keys = {o.key for o in branch.observations if o.source == "quorum"}
    for peer in ack_set:
        peer_cursor, peer_data = quorum.replicas[peer]
        for key in cited_keys:
            if key in peer_data and peer_cursor > ack_floor:
                # Peer saw a later write to a key the branch reasoned about.
                # This is incompleteness, not staleness: re-fork.
                raise MergeInvariantViolation(
                    f"peer {peer} at cursor {peer_cursor} holds a post-"
                    f"observation write to {key!r}; branch {branch.branch_id} "
                    f"reasoned without information that existed at commit time"
                )

    return dict(branch.overlay_writes)
