# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-detect-equivocating-attestations-before-a-byzantine-quorum-commits-a-poisoned-task-result.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-detect-equivocating-attestations-before-a-byzantine-quorum-commits-a-poisoned-task-result.warrant.json
# Markdown SHA-256:   9fc407a984210d1c12ef61d1d7f85262d66b5894b70fea9db88767840507c935
# Code AST SHA-256:   d631010082ccffc5f0745626aa345702c6cec17fb7feb20a8c15288c6779f1d3
# Verified Classes:   EquivocationDetected, Attestation, QuorumAggregator
# Defensive Guards:   4 fail-closed invariants (zero external deps)

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


class EquivocationDetected(RuntimeError):
    """Raised when a signer attests two conflicting results for the same task."""
    pass


@dataclass
class Attestation:
    task_id: str
    result_hash: str
    signer_id: str
    signature: bytes


@dataclass
class QuorumAggregator:
    f: int
    # result_hash -> set of distinct signer ids
    signers_by_result: Dict[str, Set[str]] = field(default_factory=dict)
    # signer_id -> set of result hashes attested for this task
    results_by_signer: Dict[str, Set[str]] = field(default_factory=dict)
    quarantined: Set[str] = field(default_factory=set)

    @property
    def quorum(self) -> int:
        return 2 * self.f + 1

    def ingest(self, att: Attestation) -> None:
        if att.signer_id in self.quarantined:
            raise EquivocationDetected(
                f"signer {att.signer_id} is quarantined; attestation rejected"
            )
        # record signer -> results
        seen_results = self.results_by_signer.setdefault(att.signer_id, set())
        seen_results.add(att.result_hash)
        if len(seen_results) > 1:
            # this signer has now attested more than one result for the same task
            self.quarantined.add(att.signer_id)
            raise EquivocationDetected(
                f"signer {att.signer_id} equivocated on task {att.task_id}: "
                f"attested results {sorted(seen_results)}"
            )
        # record result -> distinct signers
        self.signers_by_result.setdefault(att.result_hash, set()).add(att.signer_id)

    def try_commit(self, task_id: str) -> Tuple[str, int]:
        # commit only if exactly one result has a quorum of DISTINCT signers
        # and no signer is quarantined for this task
        candidates = [
            (rh, len(signers))
            for rh, signers in self.signers_by_result.items()
            if len(signers) >= self.quorum
        ]
        if not candidates:
            raise EquivocationDetected(
                f"task {task_id}: no result reached quorum of {self.quorum} distinct signers"
            )
        if len(candidates) > 1:
            raise EquivocationDetected(
                f"task {task_id}: multiple results reached quorum {candidates}; "
                f"refusing to commit"
            )
        result_hash, count = candidates[0]
        return result_hash, count
