# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-a-byzantine-quorum-as-invalid-when-signed-votes-arrive-through-a-lossy-mcp-transport.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-a-byzantine-quorum-as-invalid-when-signed-votes-arrive-through-a-lossy-mcp-transport.warrant.json
# Markdown SHA-256:   45d6dc0a8e601b888fdd881644b3f355f2ad74f3099f166d1acfe5fc183bd576
# Code AST SHA-256:   6670117d83d9dee93f28003f379f0463355a5c6ba3d03a6c520717ac3cb980aa
# Verified Classes:   QuorumInflationError, Vote
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Iterable


class QuorumInflationError(RuntimeError):
    """Raised when a purported quorum is assembled from fewer distinct signers
    than the threshold, typically because envelope identity was used as the
    dedup key instead of the signature-recovered signer."""


@dataclass(frozen=True)
class Vote:
    envelope_agent_id: str   # controlled by relay / transport, UNTRUSTED
    payload: bytes
    signature: bytes


def recover_signer(payload: bytes, signature: bytes) -> str:
    # Placeholder for real signer-recovering verification (e.g. secp256k1 recover).
    # Must return the identity derived from the signature bytes, never a claimed field.
    raise NotImplementedError


def assemble_quorum(votes: Iterable[Vote], n: int, f: int) -> frozenset[str]:
    threshold = 2 * f + 1
    signers: set[str] = set()
    for v in votes:
        recovered = recover_signer(v.payload, v.signature)
        # Envelope identity is deliberately ignored for set membership.
        signers.add(recovered)

    if len(signers) < threshold:
        raise QuorumInflationError(
            f"quorum set has {len(signers)} distinct signers "
            f"(threshold {threshold}); envelope metadata may have inflated the count"
        )
    return frozenset(signers)


def commit_if_quorate(votes: Iterable[Vote], n: int, f: int, reported_signers: Iterable[str]) -> frozenset[str]:
    actual = assemble_quorum(votes, n, f)
    # Independent attestation: the coordinator's own accounting must match the recomputed set.
    if set(reported_signers) != set(actual):
        raise QuorumInflationError(
            "coordinator-reported signer set diverges from signature-recovered set: "
            f"reported={sorted(reported_signers)} recovered={sorted(actual)}"
        )
    return actual
