# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-equivocation-in-a-byzantine-agent-quorum-when-signed-votes-are-replayed-across-epochs.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-equivocation-in-a-byzantine-agent-quorum-when-signed-votes-are-replayed-across-epochs.warrant.json
# Markdown SHA-256:   15cf998e1229a14a59c86cb815a7f108e488b344ca7938c5b77461166a7a16b2
# Code AST SHA-256:   02039aebec6a84e3cfba4c1e77151b817d8cc57e9bfd63acd1149136660c6846
# Verified Classes:   EquivocationDetected, Vote, SignedValueMemory
# Defensive Guards:   3 fail-closed invariants (zero external deps)

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


class EquivocationDetected(RuntimeError):
    """Raised when a signer has signed a conflicting value in an overlapping decision lineage."""
    pass


@dataclass(frozen=True)
class Vote:
    signer: str
    value: str          # e.g. hash of the proposal the vote endorses
    lineage: str        # content-addressed decision-context root; MUST be present
    epoch: int
    signature: str      # assumed verified upstream


@dataclass
class SignedValueMemory:
    # (signer, lineage) -> set of distinct values ever signed in that lineage
    history: Dict[Tuple[str, str], Set[str]] = field(default_factory=dict)

    def record_and_check(self, vote: Vote) -> None:
        if not vote.lineage:
            # No lineage => cannot prove non-equivocation => reject as unverifiable.
            raise EquivocationDetected(
                f"vote from {vote.signer} lacks lineage hash; non-equivocation unverifiable"
            )
        key = (vote.signer, vote.lineage)
        prior = self.history.get(key, set())
        if prior and vote.value not in prior:
            raise EquivocationDetected(
                f"signer {vote.signer} equivocated in lineage {vote.lineage}: "
                f"prior={sorted(prior)} new={vote.value} epoch={vote.epoch}"
            )
        self.history.setdefault(key, set()).add(vote.value)


def assemble_quorum(
    votes: list[Vote],
    memory: SignedValueMemory,
    threshold: int,
) -> Set[str]:
    accepted: Set[str] = set()
    for v in votes:
        try:
            memory.record_and_check(v)
            accepted.add(v.signer)
        except EquivocationDetected:
            # Reject the equivocating vote; do not count it toward quorum.
            continue
    if len(accepted) < threshold:
        raise EquivocationDetected(
            f"quorum not reached after equivocation filtering: "
            f"{len(accepted)}/{threshold} honest signers"
        )
    return accepted
