# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-equivocation-by-a-peer-auditor-before-committing-to-a-quorum-attested-result.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-equivocation-by-a-peer-auditor-before-committing-to-a-quorum-attested-result.warrant.json
# Markdown SHA-256:   3ae575982667ab8d3c8045d0a5e5a2f9df06dc66fa3a07596aec17c10f8d029c
# Code AST SHA-256:   49254d94f954b9e35d2deb627ea61f204f646ed2a2d46ff9e1e1ef47f6306be4
# Verified Classes:   EquivocationDetected, QuorumUnreachable, Attestation, Committer
# Defensive Guards:   5 fail-closed invariants (zero external deps)

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


class EquivocationDetected(RuntimeError):
    """Raised when an auditor signs two conflicting attestations to the same
    recipient for the same (task_id, epoch). This is a self-contained proof
    of Byzantine behavior and must poison the auditor for that epoch."""
    pass


class QuorumUnreachable(RuntimeError):
    """Raised when, after excluding equivocators, fewer than f+1 auditors
    remain and the task cannot be committed without weakening the fault
    assumption the threshold was chosen under."""
    pass


@dataclass(frozen=True)
class Attestation:
    task_id: str
    epoch: int
    auditor_id: str
    recipient_id: str
    result_hash: str
    signature: bytes


@dataclass
class Committer:
    self_id: str
    n_auditors: int
    f: int
    # ledger[auditor][task] -> (last_epoch, result_hash_at_that_epoch)
    ledger: Dict[Tuple[str, str], Tuple[int, str]] = field(default_factory=dict)
    poisoned: Dict[Tuple[str, str], str] = field(default_factory=dict)  # (auditor, task) -> reason

    @property
    def threshold(self) -> int:
        return self.f + 1

    def accept(self, att: Attestation) -> None:
        if att.recipient_id != self.self_id:
            raise ValueError("attestation not addressed to this committer")
        key = (att.auditor_id, att.task_id)
        prior = self.ledger.get(key)
        if prior is not None:
            prior_epoch, prior_hash = prior
            if att.epoch == prior_epoch and att.result_hash != prior_hash:
                self.poisoned[key] = "equivocation"
                raise EquivocationDetected(
                    f"auditor {att.auditor_id} signed {prior_hash!r} and "
                    f"{att.result_hash!r} for task {att.task_id} epoch {att.epoch} "
                    f"to recipient {self.self_id}"
                )
            if att.epoch <= prior_epoch:
                raise ValueError("stale or replayed epoch")
        self.ledger[key] = (att.epoch, att.result_hash)

    def try_commit(self, task_id: str, pool: list[Attestation]) -> str:
        counts: Dict[str, int] = {}
        for att in pool:
            if (att.auditor_id, att.task_id) in self.poisoned:
                continue
            try:
                self.accept(att)
            except EquivocationDetected:
                continue  # auditor excluded; re-evaluate below
            counts[att.result_hash] = counts.get(att.result_hash, 0) + 1

        survivors = self.n_auditors - sum(
            1 for (a, t) in self.poisoned if t == task_id
        )
        if survivors < self.threshold:
            raise QuorumUnreachable(
                f"task {task_id}: {survivors} auditors remain after poisoning, "
                f"threshold is {self.threshold}, aborting rather than "
                f"committing on a reduced fault assumption"
            )

        for result_hash, count in counts.items():
            if count >= self.threshold:
                return result_hash
        raise QuorumUnreachable(f"task {task_id}: no result reached threshold")
