# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-equivocation-in-a-bft-attested-agent-swarm-before-committing-to-a-task-result.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-equivocation-in-a-bft-attested-agent-swarm-before-committing-to-a-task-result.warrant.json
# Markdown SHA-256:   6066bf03269a23feb893f2a3a094eed6463d0a65ee2de31486a61312482d4c05
# Code AST SHA-256:   f5f30df740e6a26a32a59835071e9988227886ef8578bf34f958a7a5ea13957e
# Verified Classes:   EquivocationDetected, Attestation
# Defensive Guards:   1 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass
from typing import Iterable


class EquivocationDetected(RuntimeError):
    """Raised when a single signer produced contradictory verdicts over the
    same (task_id, result_hash, epoch) tuple. This is a safety violation, not
    a liveness fault: retrying aggregation cannot resolve it."""
    pass


@dataclass(frozen=True)
class Attestation:
    signer_id: str
    task_id: str
    result_hash: str
    epoch: int
    verdict: str  # "PASS" | "FAIL"
    signature: bytes

    def canonical_key(self) -> tuple:
        # Epoch is part of the key: cross-epoch signatures are NOT comparable.
        return (self.signer_id, self.task_id, self.result_hash, self.epoch)


def _canonical_hash(payload: dict) -> str:
    # Stable serialization so honest agents never appear to equivocate.
    import json
    return hashlib.sha256(
        json.dumps(payload, sort_keys=True, separators=(",", ":")).encode()
    ).hexdigest()


def aggregate_quorum(
    attestations: Iterable[Attestation],
    quorum_threshold: int,
) -> dict:
    """Aggregate signed attestations into a task commitment.

    Invariant: a quorum counts DISTINCT signers whose payloads are mutually
    consistent. A signer that signed two contradictory verdicts over the same
    canonical tuple poisons the quorum and must halt commitment.
    """
    by_key: dict[tuple, list[Attestation]] = {}
    for att in attestations:
        by_key.setdefault(att.canonical_key(), []).append(att)

    # Detect equivocation before any quorum arithmetic.
    for key, group in by_key.items():
        verdicts = {a.verdict for a in group}
        if len(verdicts) > 1:
            signer = key[0]
            raise EquivocationDetected(
                f"signer {signer} equivocated on task={key[1]} "
                f"result={key[2]} epoch={key[3]}: verdicts={sorted(verdicts)} "
                f"signatures={[a.signature.hex()[:16] for a in group]}"
            )

    # Count distinct consistent signers per (task, result, epoch).
    consistent_signers: dict[tuple, set[str]] = {}
    for key, group in by_key.items():
        consistent_signers.setdefault(key[1:], set()).add(key[0])

    committed = {}
    for (task_id, result_hash, epoch), signers in consistent_signers.items():
        if len(signers) >= quorum_threshold:
            committed[(task_id, result_hash, epoch)] = len(signers)
    return committed
