# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-speculative-branch-reconciliation-as-a-commit-barrier-rather-than-a-best-effort-merge.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-speculative-branch-reconciliation-as-a-commit-barrier-rather-than-a-best-effort-merge.warrant.json
# Markdown SHA-256:   3b019995140734dbe40dbca7f2cf5e75d29f3db937f9334deb1c4cf1f50e1549
# Code AST SHA-256:   8ce2c141263d5150247826fb5a54f87679a3f4559a155afaa4c864235c179201
# Verified Classes:   SpeculativeReplayViolation, LogEntry, Epoch
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import FrozenSet, List, Optional


class SpeculativeReplayViolation(RuntimeError):
    """Raised when a log entry's read-set intersects an unselected branch's write-set."""


@dataclass(frozen=True)
class LogEntry:
    seq: int
    epoch_id: str
    branch_id: Optional[str]  # None for coordinator/peer entries
    read_set: FrozenSet[str]
    write_set: FrozenSet[str]


@dataclass
class Epoch:
    epoch_id: str
    branch_writes: dict = field(default_factory=dict)  # branch_id -> set of keys
    selected: Optional[str] = None


def reconcile_epoch(epoch: Epoch, selected_branch: str, log: List[LogEntry]) -> None:
    """Mark an epoch committed to selected_branch, then verify no downstream
    entry depends on an unselected branch. Must run before releasing the log."""
    if selected_branch not in epoch.branch_writes:
        raise SpeculativeReplayViolation(
            f"epoch {epoch.epoch_id}: selected branch {selected_branch!r} produced no writes"
        )
    epoch.selected = selected_branch
    unselected_keys: FrozenSet[str] = frozenset().union(
        *(w for b, w in epoch.branch_writes.items() if b != selected_branch)
    ) if any(b != selected_branch for b in epoch.branch_writes) else frozenset()

    for entry in log:
        if entry.epoch_id == epoch.epoch_id:
            continue
        if entry.seq <= max((e.seq for e in log if e.epoch_id == epoch.epoch_id), default=-1):
            continue
        leaked = entry.read_set & unselected_keys
        if leaked:
            raise SpeculativeReplayViolation(
                f"entry seq={entry.seq} branch={entry.branch_id!r} read keys {sorted(leaked)} "
                f"written by unselected branch(es) in epoch {epoch.epoch_id}; "
                f"reconciliation must be a commit barrier, not a merge"
            )
