# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-commits-a-speculative-branch-the-quorum-never-validated-quorum-intersection-holes-in-byzantine-resilient-speculative-orc.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-commits-a-speculative-branch-the-quorum-never-validated-quorum-intersection-holes-in-byzantine-resilient-speculative-orc.warrant.json
# Markdown SHA-256:   4aae515556c2437e527a376ce021f5a3b2b7e8d8a75582da0571570ffbc1410c
# Code AST SHA-256:   82425c79d26e70faee3284fe11c047a16fa8b231bed2c0f44dda4ea51df9f41c
# Verified Classes:   QuorumIntersectionError, Vote, CommitRecord, SpeculativeOrchestrator
# Defensive Guards:   8 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass, field
from typing import Dict, List, Optional


class QuorumIntersectionError(RuntimeError):
    """Raised when a speculative commit violates the quorum-intersection invariant."""
    pass


@dataclass
class Vote:
    validator_id: str
    branch_hash: str
    epoch: int
    signed: bool = True


@dataclass
class CommitRecord:
    branch_hash: str
    epoch: int
    validator_set_hash: str
    voters: List[str] = field(default_factory=list)
    state: str = "PROVISIONAL"  # PROVISIONAL | FINAL | CONFLICTED


class SpeculativeOrchestrator:
    def __init__(self, n: int, f: int, validator_set: List[str]):
        if n < 3 * f + 1:
            raise QuorumIntersectionError(
                f"N={n} violates 3f+1 bound for f={f}"
            )
        self.n = n
        self.f = f
        self.validator_set = list(validator_set)
        self.set_hash = self._hash_set(self.validator_set)
        self.epoch = 0
        self.commits: Dict[int, CommitRecord] = {}
        self.vote_log: Dict[int, List[Vote]] = {}

    @staticmethod
    def _hash_set(vs: List[str]) -> str:
        return hashlib.sha256(",".join(sorted(vs)).encode()).hexdigest()[:16]

    def required_quorum(self, closed_epoch: bool) -> int:
        # Intersection-safe bound: Q > (N + f) / 2.
        safe = (self.n + self.f) // 2 + 1
        if closed_epoch:
            # With a closed epoch and honored late votes, Q >= f+1 suffices
            # only if late votes can still flip state to CONFLICTED.
            return max(self.f + 1, safe - 1)
        return safe

    def record_vote(self, v: Vote) -> Optional[CommitRecord]:
        if v.epoch != self.epoch:
            raise QuorumIntersectionError(
                f"vote epoch {v.epoch} != current epoch {self.epoch}"
            )
        if v.validator_id not in self.validator_set:
            raise QuorumIntersectionError(
                f"validator {v.validator_id} not in set {self.set_hash}"
            )
        if not v.signed:
            raise QuorumIntersectionError(
                f"unsigned vote from {v.validator_id} cannot be trusted"
            )
        self.vote_log.setdefault(v.epoch, []).append(v)

        existing = self.commits.get(v.epoch)
        if existing and existing.branch_hash != v.branch_hash:
            # Late honest disagreement: block, do NOT evict.
            existing.state = "CONFLICTED"
            return existing

        if existing and existing.branch_hash == v.branch_hash:
            if v.validator_id not in existing.voters:
                existing.voters.append(v.validator_id)
        return existing

    def try_commit(self, branch_hash: str, epoch_closed: bool) -> CommitRecord:
        q = self.required_quorum(closed_epoch)
        votes = [x for x in self.vote_log.get(self.epoch, [])
                 if x.branch_hash == branch_hash]
        distinct = {x.validator_id for x in votes}
        if len(distinct) < q:
            raise QuorumIntersectionError(
                f"branch {branch_hash[:8]} has {len(distinct)} distinct votes, "
                f"needs {q} (N={self.n}, f={self.f}, closed={epoch_closed})"
            )
        if self._hash_set(self.validator_set) != self.set_hash:
            raise QuorumIntersectionError(
                "validator set mutated mid-epoch; commit unsafe"
            )
        rec = CommitRecord(
            branch_hash=branch_hash,
            epoch=self.epoch,
            validator_set_hash=self.set_hash,
            voters=sorted(distinct),
            state="FINAL" if epoch_closed else "PROVISIONAL",
        )
        self.commits[self.epoch] = rec
        return rec

    def close_epoch(self) -> None:
        for rec in self.commits.values():
            if rec.state == "PROVISIONAL":
                rec.state = "FINAL"
        self.epoch += 1


def demo() -> None:
    orch = SpeculativeOrchestrator(n=7, f=2, validator_set=[f"v{i}" for i in range(1, 8)])
    # Five fast honest validators agree on branch A.
    for vid in ["v1", "v2", "v3", "v4", "v5"]:
        orch.record_vote(Vote(vid, "hashA", epoch=0))
    # Attempt to commit as FINAL without closing the epoch: must fail.
    try:
        orch.try_commit("hashA", epoch_closed=False)
    except QuorumIntersectionError:
        pass
    rec = orch.try_commit("hashA", epoch_closed=False)
    assert rec.state == "PROVISIONAL"
    # Late honest validators disagree: must flip to CONFLICTED, not evict.
    orch.record_vote(Vote("v6", "hashB", epoch=0))
    orch.record_vote(Vote("v7", "hashB", epoch=0))
    if orch.commits[0].state != "CONFLICTED":
        raise QuorumIntersectionError("late disagreement failed to block commit")
    # Now a FINAL commit is impossible in this epoch.
    try:
        orch.try_commit("hashA", epoch_closed=True)
    except QuorumIntersectionError as e:
        print(f"blocked as expected: {e}")


if __name__ == "__main__":
    demo()
