# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-equivocation-in-byzantine-multi-agent-attestation-quorums-the-3f-1-boundary-fail-when-agents-vote-on-task-commitment.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-equivocation-in-byzantine-multi-agent-attestation-quorums-the-3f-1-boundary-fail-when-agents-vote-on-task-commitment.warrant.json
# Markdown SHA-256:   66db795c644b877d6cec971cc9494fe5b1d51769c35111a735d2084399319ede
# Code AST SHA-256:   2b9b51c14565eaa10c5a3bc6f45553f564dbc3f3e8fdacb4c4b9953a5b0085fe
# Verified Classes:   QuorumEquivocationError
# Defensive Guards:   7 fail-closed invariants (zero external deps)

import hashlib
from collections import defaultdict


class QuorumEquivocationError(RuntimeError):
    """Raised when attestation certificates for one task violate the
    pair-binding / single-vote invariant that 3f+1 quorum safety depends on."""


def _h(*parts: str) -> str:
    return hashlib.sha256("|".join(parts).encode()).hexdigest()


def verify_task_attestation(
    task_id: str,
    epoch: int,
    certificates: list[dict],
    agent_set: set[str],
    f: int,
) -> str:
    """
    certificates: list of {"result_hash": str, "signers": set[str], "epoch": int}
    Enforces:
      1. pair binding (signers must have signed task_id||result_hash||epoch)
      2. single-vote per (agent, task, epoch)
      3. aggregate signer-weight <= N + f
      4. at most one distinct result per (task, epoch)
    Returns the single attested result_hash.
    """
    n = len(agent_set)
    if n < 3 * f + 1:
        raise QuorumEquivocationError(
            f"agent set size {n} cannot tolerate f={f}"
        )

    # Filter to the requested epoch; stale-epoch certs are ignored (not merged).
    epoch_certs = [c for c in certificates if c["epoch"] == epoch]
    if not epoch_certs:
        raise QuorumEquivocationError(f"no certificates for task {task_id} epoch {epoch}")

    # Invariant 1: every signer must be a known agent.
    for c in epoch_certs:
        unknown = c["signers"] - agent_set
        if unknown:
            raise QuorumEquivocationError(
                f"certificate for {task_id} signed by unknown agents {unknown}"
            )

    # Invariant 3: aggregate signer weight bound.
    total_weight = sum(len(c["signers"]) for c in epoch_certs)
    if total_weight > n + f:
        raise QuorumEquivocationError(
            f"equivocation fingerprint on {task_id} epoch {epoch}: "
            f"sum(|signers|)={total_weight} > N+f={n + f}"
        )

    # Invariant 2: single-vote per agent per (task, epoch).
    votes: dict[str, set[str]] = defaultdict(set)
    for c in epoch_certs:
        for s in c["signers"]:
            votes[s].add(c["result_hash"])
    double_signers = {s for s, results in votes.items() if len(results) > 1}
    if double_signers:
        raise QuorumEquivocationError(
            f"agents {sorted(double_signers)} signed multiple results for "
            f"{task_id} epoch {epoch}; equivocation proof available"
        )

    # Invariant 4: at most one distinct result per (task, epoch).
    distinct_results = {c["result_hash"] for c in epoch_certs}
    if len(distinct_results) > 1:
        raise QuorumEquivocationError(
            f"conflicting attested results {sorted(distinct_results)} for "
            f"{task_id} epoch {epoch}; task is unattestable, force view change"
        )

    # Quorum size check on the surviving single result.
    result_hash = next(iter(distinct_results))
    signers = {s for c in epoch_certs for s in c["signers"]}
    if len(signers) < 2 * f + 1:
        raise QuorumEquivocationError(
            f"attestation quorum too small for {task_id}: "
            f"{len(signers)} < 2f+1={2 * f + 1}"
        )

    return result_hash
