# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-anchor-equivocation-detection-when-a-byzantine-peer-casts-divergent-plan-commit-votes-across-two-quorums-of-the-same-epoch.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-anchor-equivocation-detection-when-a-byzantine-peer-casts-divergent-plan-commit-votes-across-two-quorums-of-the-same-epoch.warrant.json
# Markdown SHA-256:   9c45ac85bebdfc3b4969e5699b228691863e587f5a24987d7b96b18a23356165
# Code AST SHA-256:   6f87411ae5cc8ca825abe4520f80fed7301c4914c88d1f5f25aa3069075727dd
# Verified Classes:   EquivocationEvidenceLost, VoteEnvelope, EpochRecord
# Defensive Guards:   5 fail-closed invariants (zero external deps)

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


class EquivocationEvidenceLost(RuntimeError):
    """Raised when an epoch commits without retaining the raw vote set
    needed to prove or disprove peer equivocation."""
    pass


@dataclass(frozen=True)
class VoteEnvelope:
    voter_id: str
    epoch: int
    plan_hash: str
    signature: bytes


@dataclass
class EpochRecord:
    epoch: int
    raw_votes: List[VoteEnvelope] = field(default_factory=list)
    committed_plan: str | None = None

    def voted_on_set(self) -> Dict[str, Set[str]]:
        # Map each voter to the distinct plan hashes it signed this epoch.
        out: Dict[str, Set[str]] = {}
        for v in self.raw_votes:
            out.setdefault(v.voter_id, set()).add(v.plan_hash)
        return out

    def equivocators(self) -> Set[str]:
        return {voter for voter, plans in self.voted_on_set().items() if len(plans) > 1}


def commit_epoch(record: EpochRecord, quorum: int, retain_raw: bool) -> str:
    # Aggregate a quorum certificate, but refuse to discard the envelopes.
    tally: Dict[str, int] = {}
    for v in record.raw_votes:
        tally[v.plan_hash] = tally.get(v.plan_hash, 0) + 1

    winners = [h for h, c in tally.items() if c >= quorum]
    if not winners:
        raise EquivocationEvidenceLost(
            f"epoch {record.epoch}: no plan reached quorum {quorum}; "
            f"tally={tally}"
        )
    if len(winners) > 1:
        # Two plans each reached quorum: equivocation is already provable.
        raise EquivocationEvidenceLost(
            f"epoch {record.epoch}: conflicting quorums {winners}; "
            f"equivocators={record.equivocators()}"
        )

    if not retain_raw:
        # The exact bug from the trace: certificate committed, envelopes dropped.
        raise EquivocationEvidenceLost(
            f"epoch {record.epoch}: refusing to commit {winners[0]} without "
            f"retaining raw vote set; future equivocation would be unprovable"
        )

    record.committed_plan = winners[0]
    return winners[0]


def reconcile(record: EpochRecord) -> None:
    # An auditor must be able to reconstruct the voted-on set from raw votes.
    if not record.raw_votes:
        raise EquivocationEvidenceLost(
            f"epoch {record.epoch}: reconciliation requested but no raw votes "
            f"retained; equivocation cannot be confirmed or excluded"
        )
    bad = record.equivocators()
    if bad:
        raise EquivocationEvidenceLost(
            f"epoch {record.epoch}: provable equivocation by {sorted(bad)}; "
            f"slash and re-run epoch"
        )
