# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-a-peer-s-equivocation-as-a-quorum-safety-violation-rather-than-a-recoverable-inconsistency.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-a-peer-s-equivocation-as-a-quorum-safety-violation-rather-than-a-recoverable-inconsistency.warrant.json
# Markdown SHA-256:   43bbc31ab43505bf8d155303102d81090dc591229f6ebf009c4803ed15e342ce
# Code AST SHA-256:   96b2d8676ae09f0125906407e649e6e3e23e76e2be98206ce11a410f65641693
# Verified Classes:   EquivocationSafetyViolation, Vote, Certificate, EquivocationIndex
# Defensive Guards:   4 fail-closed invariants (zero external deps)

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


class EquivocationSafetyViolation(RuntimeError):
    """Raised when two conflicting votes from one agent appear in accepted quorum certificates."""


@dataclass(frozen=True)
class Vote:
    agent_id: str
    round: int
    decision_id: str
    value: str  # "accept" | "reject"
    signature: bytes


@dataclass(frozen=True)
class Certificate:
    round: int
    decision_id: str
    value: str
    signatures: Tuple[Vote, ...]


@dataclass
class EquivocationIndex:
    accepted_certs: List[Certificate] = field(default_factory=list)
    seen_votes: Dict[Tuple[str, int, str], List[Vote]] = field(default_factory=dict)

    def _votes_in_accepted_certs(self, vote: Vote) -> bool:
        for cert in self.accepted_certs:
            for sig in cert.signatures:
                if (sig.agent_id, sig.round, sig.decision_id, sig.value, sig.signature) == (
                    vote.agent_id, vote.round, vote.decision_id, vote.value, vote.signature
                ):
                    return True
        return False

    def record_vote(self, vote: Vote) -> str:
        key = (vote.agent_id, vote.round, vote.decision_id)
        prior = self.seen_votes.setdefault(key, [])
        conflicting = [p for p in prior if p.value != vote.value and p.signature != vote.signature]
        prior.append(vote)
        if not conflicting:
            return "OK"
        for p in conflicting:
            in_cert_a = self._votes_in_accepted_certs(vote)
            in_cert_b = self._votes_in_accepted_certs(p)
            if in_cert_a and in_cert_b:
                raise EquivocationSafetyViolation(
                    f"agent {vote.agent_id} equivocated at round {vote.round} "
                    f"decision {vote.decision_id}: conflicting votes both present in "
                    f"accepted certificates; quorum intersection broken, freezing."
                )
        return "RECOVERABLE_QUARANTINE"

    def accept_certificate(self, cert: Certificate) -> None:
        self.accepted_certs.append(cert)
        # Retroactive re-evaluation: a previously recoverable equivocation
        # may now be a safety violation because a second accepted certificate
        # contains the conflicting vote.
        for key, votes in self.seen_votes.items():
            values = {v.value for v in votes}
            if len(values) > 1:
                in_certs = [v for v in votes if self._votes_in_accepted_certs(v)]
                if len({v.value for v in in_certs}) > 1:
                    raise EquivocationSafetyViolation(
                        f"retroactive promotion: agent {key[0]} at round {key[1]} "
                        f"decision {key[2]} now has conflicting votes in accepted "
                        f"certificates after accepting {cert.value} cert."
                    )


def demo() -> None:
    idx = EquivocationIndex()
    v_accept = Vote("C", 41, "deploy-v7", "accept", b"sigA")
    v_reject = Vote("C", 41, "deploy-v7", "reject", b"sigR")

    assert idx.record_vote(v_accept) == "OK"
    # C's second vote is recoverable only if neither is in an accepted cert yet.
    assert idx.record_vote(v_reject) == "RECOVERABLE_QUARANTINE"

    cert_accept = Certificate(41, "deploy-v7", "accept", (v_accept,))
    idx.accept_certificate(cert_accept)  # no violation yet: only one value in certs

    cert_reject = Certificate(41, "deploy-v7", "reject", (v_reject,))
    # Accepting the second certificate must retroactively promote to safety violation.
    idx.accept_certificate(cert_reject)  # raises


if __name__ == "__main__":
    try:
        demo()
    except EquivocationSafetyViolation as e:
        print(f"FROZEN: {e}")
