# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-refuse-a-quorum-certificate-equivocation-proof-divergence-in-cross-org-federated-task-ledgers.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-refuse-a-quorum-certificate-equivocation-proof-divergence-in-cross-org-federated-task-ledgers.warrant.json
# Markdown SHA-256:   af24ca5619cc352b813e04cd5056855e9e1970e046fe45856a9a357c6cd64d64
# Code AST SHA-256:   49e6d04a9944b75ba2cd11a6e3435d4e92d11c32c127860262a42681020ba425
# Verified Classes:   EquivocationDetected, Vote, FirstSeenGuard
# Defensive Guards:   5 fail-closed invariants (zero external deps)

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


class EquivocationDetected(RuntimeError):
    """Raised when a validator signs or a receiver accepts conflicting votes
    for the same (task_id, epoch) under different state hashes."""
    pass


@dataclass
class Vote:
    validator_id: str
    task_id: str
    epoch: int
    state_hash: str
    signature: str  # assumed pre-verified by transport layer


@dataclass
class FirstSeenGuard:
    # (task_id, epoch, validator_id) -> state_hash
    _seen: Dict[Tuple[str, int, str], str] = field(default_factory=dict)

    def check_and_record(self, vote: Vote) -> None:
        key = (vote.task_id, vote.epoch, vote.validator_id)
        prior = self._seen.get(key)
        if prior is None:
            self._seen[key] = vote.state_hash
            return
        if prior != vote.state_hash:
            # Two signed votes, same epoch, different payload: slashable proof.
            raise EquivocationDetected(
                f"validator {vote.validator_id} equivocated on "
                f"task={vote.task_id} epoch={vote.epoch}: "
                f"{prior} vs {vote.state_hash}"
            )
        # Identical re-vote is idempotent and permitted.


def commit_quorum_certificate(
    guard: FirstSeenGuard,
    task_id: str,
    epoch: int,
    votes: list[Vote],
    validator_set: set[str],
    f: int,
) -> str:
    """Commit only if the QC is valid AND equivocation-free."""
    signers = {v.validator_id for v in votes}
    if not signers.issubset(validator_set):
        raise EquivocationDetected("QC contains non-member signer")
    if len(signers) < 2 * f + 1:
        raise EquivocationDetected(f"QC under-sized: {len(signers)} < {2*f+1}")

    hashes = {v.state_hash for v in votes}
    if len(hashes) != 1:
        raise EquivocationDetected(
            f"QC spans multiple state hashes for epoch {epoch}: {hashes}"
        )

    # Receiver-side first-seen enforcement: this is the load-bearing check.
    for v in votes:
        guard.check_and_record(v)

    return hashes.pop()


def sign_vote(
    guard: FirstSeenGuard,
    validator_id: str,
    task_id: str,
    epoch: int,
    state_hash: str,
    sign_fn,
) -> Vote:
    """Refuse to produce a second, conflicting signature for the same epoch."""
    key = (task_id, epoch, validator_id)
    prior = guard._seen.get(key)
    if prior is not None and prior != state_hash:
        raise EquivocationDetected(
            f"refusing to re-sign task={task_id} epoch={epoch}: "
            f"prior={prior} new={state_hash} (likely replay-derived hash)"
        )
    sig = sign_fn(validator_id, task_id, epoch, state_hash)
    vote = Vote(validator_id, task_id, epoch, state_hash, sig)
    guard.check_and_record(vote)
    return vote
