# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-a-byzantine-peer-s-equivocating-plan-commit-vote-as-a-liveness-fault-rather-than-a-safety-fault.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-a-byzantine-peer-s-equivocating-plan-commit-vote-as-a-liveness-fault-rather-than-a-safety-fault.warrant.json
# Markdown SHA-256:   a4d5414a5e7e3a908d0123aa1219ab588150745f9233eff816b35abb4f1f08d6
# Code AST SHA-256:   ab81c2681c2a8103668adc8dd517927dee541ff00a9de44db6da3d5d41a4156c
# Verified Classes:   PlanCommitSafetyError, PlanCommitLivenessError, Vote, VoteLog
# Defensive Guards:   6 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Dict, FrozenSet, List, Tuple


class PlanCommitSafetyError(RuntimeError):
    """Raised when equivocation intersects a quorum and commits must halt."""


class PlanCommitLivenessError(RuntimeError):
    """Raised when equivocation blocks progress but no quorum intersects; triggers view change."""


@dataclass(frozen=True)
class Vote:
    peer: str
    plan_hash: str
    view: int
    signature: str  # must be verifiable against signed membership


@dataclass
class VoteLog:
    # (plan_hash, view) -> set of peers who signed
    votes: Dict[Tuple[str, int], FrozenSet[str]] = field(default_factory=dict)
    # persisted negative certificates: (slot, view) -> observed plan hashes
    no_quorum: Dict[Tuple[str, int], FrozenSet[str]] = field(default_factory=dict)
    membership: FrozenSet[str] = frozenset()
    f_live: int = 0

    def threshold(self) -> int:
        n = len(self.membership)
        return (n + self.f_live + 1) // 2  # ceil((N+f+1)/2)

    def record(self, v: Vote) -> None:
        if v.peer not in self.membership:
            raise PlanCommitSafetyError(f"vote from non-member {v.peer}")
        if not v.signature:
            raise PlanCommitSafetyError(f"unsigned vote from {v.peer}")
        key = (v.plan_hash, v.view)
        self.votes[key] = self.votes.get(key, frozenset()) | {v.peer}


def classify_equivocation(
    log: VoteLog, slot: str, view: int, conflicting_plans: List[str]
) -> str:
    """Return 'safety', 'liveness', or 'benign' per the decision boundary."""
    thresh = log.threshold()
    quorate = [
        h for h in conflicting_plans
        if len(log.votes.get((h, view), frozenset())) >= thresh
    ]

    if len(quorate) >= 2:
        # Two distinct plans both reached quorum in the same view: true safety fault.
        raise PlanCommitSafetyError(
            f"quorum intersection on slot={slot} view={view}: {quorate}"
        )

    if len(quorate) == 1:
        # One plan has quorum; the equivocation did not threaten safety. Benign.
        return "benign"

    # No plan has quorum. Persist the negative certificate BEFORE any freeze.
    log.no_quorum[(slot, view)] = frozenset(conflicting_plans)
    raise PlanCommitLivenessError(
        f"non-quorum equivocation on slot={slot} view={view}; "
        f"persist NO_QUORUM and start view-change timer"
    )


def accept_stale_commit(log: VoteLog, slot: str, plan_hash: str, view: int) -> bool:
    """Reject a late COMMIT if a persisted NO_QUORUM certificate contradicts it."""
    cert = log.no_quorum.get((slot, view))
    if cert is not None and plan_hash not in cert:
        raise PlanCommitSafetyError(
            f"stale commit for {plan_hash} contradicts NO_QUORUM cert {cert}"
        )
    if cert is not None and plan_hash in cert:
        # The cert only proves absence of quorum, not presence; still require quorum.
        if len(log.votes.get((plan_hash, view), frozenset())) < log.threshold():
            raise PlanCommitSafetyError(
                f"commit for {plan_hash} lacks quorum despite NO_QUORUM cert"
            )
    return True
