# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-treat-a-byzantine-quorum-certificate-as-committed-rather-than-merely-gossiped-the-equivocation-proof-retention-boundary-in-multi.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-treat-a-byzantine-quorum-certificate-as-committed-rather-than-merely-gossiped-the-equivocation-proof-retention-boundary-in-multi.warrant.json
# Markdown SHA-256:   a53a4d0a275831464c590e6cea8e8eb1159bc3605f1d7ad3fafe32545d5b66db
# Code AST SHA-256:   f97a03cef3d9ea8cd57c14096b356e6cdcf7fbe557a5ab7c4816000cbd78b044
# Verified Classes:   EquivocationRetentionError, VoteRecord, Instance
# Defensive Guards:   2 fail-closed invariants (zero external deps)

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


class EquivocationRetentionError(RuntimeError):
    """Raised when an instance attempts to prune vote evidence before finality is proven."""
    pass


@dataclass
class VoteRecord:
    slot: int
    digest: str
    view: int
    signer: str


@dataclass
class Instance:
    name: str
    f: int
    vote_log: Dict[int, List[VoteRecord]] = field(default_factory=dict)
    finalized: Dict[int, str] = field(default_factory=dict)

    def record_vote(self, rec: VoteRecord) -> None:
        self.vote_log.setdefault(rec.slot, []).append(rec)

    def observe_quorum(self, slot: int, digest: str) -> None:
        # A 2f+1 quorum is NOT license to prune. Only f+1 finality assertions are.
        if slot in self.finalized and self.finalized[slot] == digest:
            self._prune(slot)
            return
        # Quorum observed but no finality: hold and contest.
        self._mark_contested(slot)

    def _prune(self, slot: int) -> None:
        self.vote_log.pop(slot, None)

    def _mark_contested(self, slot: int) -> None:
        # Slot stays in vote_log; no pruning permitted.
        _ = self.vote_log.get(slot, [])

    def sign_conflicting_vote(self, slot: int, new_digest: str, view: int) -> VoteRecord:
        prior = self.vote_log.get(slot, [])
        for rec in prior:
            if rec.digest != new_digest:
                raise EquivocationRetentionError(
                    f"{self.name}: refusing to sign {new_digest} at slot {slot} "
                    f"view {view}; prior vote for {rec.digest} at view {rec.view} "
                    f"is retained as equivocation proof."
                )
        rec = VoteRecord(slot=slot, digest=new_digest, view=view, signer=self.name)
        self.record_vote(rec)
        return rec

    def apply_finality(self, slot: int, digest: str, assertions: List[Tuple[str, str]]) -> None:
        distinct = {signer for signer, d in assertions if d == digest}
        if len(distinct) < self.f + 1:
            raise EquivocationRetentionError(
                f"{self.name}: finality for slot {slot} digest {digest} has only "
                f"{len(distinct)} distinct assertions; need {self.f + 1}. "
                f"Refusing to prune evidence."
            )
        self.finalized[slot] = digest
        self._prune(slot)


def run_equivocation_scenario() -> None:
    h1 = Instance(name="H1", f=1)
    h1.record_vote(VoteRecord(slot=42, digest="P1", view=7, signer="H1"))
    # H1 observes QC(P1, v7) but no finality assertions yet.
    h1.observe_quorum(slot=42, digest="P1")
    # Adversary solicits a conflicting vote in view 8.
    try:
        h1.sign_conflicting_vote(slot=42, new_digest="P2", view=8)
    except EquivocationRetentionError as exc:
        print(f"Caught equivocation attempt: {exc}")
    # Attempting to prune via insufficient finality must also fail.
    try:
        h1.apply_finality(slot=42, digest="P1", assertions=[("A", "P1")])
    except EquivocationRetentionError as exc:
        print(f"Retention enforced: {exc}")


if __name__ == "__main__":
    run_equivocation_scenario()
