# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-s-attestation-quorum-silently-collapse-when-byzantine-agents-equivocate-across-distinct-result-hashes-that-are-each-individually.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-s-attestation-quorum-silently-collapse-when-byzantine-agents-equivocate-across-distinct-result-hashes-that-are-each-individually.warrant.json
# Markdown SHA-256:   4b4cab4da33d5aab0a7664a5b2391a7bcb1a520610fe424d19168db670d8e7d2
# Code AST SHA-256:   362a0cf93e723b177dc6eb94d53bd9f65672949fa41fbdde291ebd186e2cea48
# Verified Classes:   QuorumInvariantViolation, Attestation
# Defensive Guards:   6 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass


class QuorumInvariantViolation(RuntimeError):
    """Raised when a commit/attest quorum is counted over a non-convergent key."""


@dataclass(frozen=True)
class Attestation:
    agent_id: str
    task_id: str
    round: int
    view: int
    commitment_hash: str   # H(task_id || round || input_digest || schema)
    result_hash: str       # agent-produced artifact hash (NON-deterministic)
    accept: bool
    signature: bytes


def count_quorum(attestations, n, f, key):
    """Count matching attestations under `key`. Refuses to count over result_hash."""
    if key == "result_hash":
        raise QuorumInvariantViolation(
            "Counting quorum over result_hash is unsound in probabilistic swarms: "
            "honest agents emit distinct hashes, so 2f+1 is unreachable and the "
            "plurality fallback becomes Byzantine-decisive."
        )
    threshold = 2 * f + 1
    buckets = {}
    for a in attestations:
        k = (getattr(a, key), a.round, a.view)
        buckets.setdefault(k, []).append(a)
    for k, group in buckets.items():
        if len(group) >= threshold:
            return k, group
    return None, []


def detect_equivocation(attestations):
    """Flag any agent that signed the same commitment across different views."""
    seen = {}
    for a in attestations:
        key = (a.agent_id, a.commitment_hash, a.round)
        seen.setdefault(key, set()).add(a.view)
    equivocators = [k[0] for k, views in seen.items() if len(views) > 1]
    if equivocators:
        raise QuorumInvariantViolation(
            f"Equivocation detected across views by agents: {equivocators}; "
            f"slash before finalizing."
        )
    return True


def commit(attestations, n, f):
    try:
        detect_equivocation(attestations)
        key, group = count_quorum(attestations, n, f, key="commitment_hash")
        if key is None:
            raise QuorumInvariantViolation(
                "No 2f+1 commitment-hash quorum; abort and re-dispatch (never plurality)."
            )
        accepts = sum(1 for a in group if a.accept)
        if accepts < 2 * f + 1:
            raise QuorumInvariantViolation(
                f"Content attestation quorum failed: {accepts} accepts < {2*f+1}."
            )
        return key
    except QuorumInvariantViolation:
        raise
    except Exception as e:
        raise QuorumInvariantViolation(f"Unexpected attestation failure: {e}") from e
