# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-a-byzantine-peer-s-equivocation-as-a-schema-level-fault-rather-than-a-value-level-disagreement-in-bft-task-co.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-a-byzantine-peer-s-equivocation-as-a-schema-level-fault-rather-than-a-value-level-disagreement-in-bft-task-co.warrant.json
# Markdown SHA-256:   35ee354f4dea61f7c91081777e4b6cf122a5f3539d54700c8b022cc4b423cff3
# Code AST SHA-256:   c71c32b78f8f2212a4cd5487024115be0e85b5427796f3e2b4fd172af0095a8d
# Verified Classes:   SchemaEquivocationFault, Ballot
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass
from typing import Iterable

class SchemaEquivocationFault(RuntimeError):
    """Raised when a Byzantine peer signs two incompatible schemas for one (task_id, epoch)."""

@dataclass(frozen=True)
class Ballot:
    task_id: str
    epoch: int
    schema_canonical: str
    signer: str
    signature: bytes

    def identity(self) -> bytes:
        h = hashlib.sha256()
        h.update(self.task_id.encode())
        h.update(self.epoch.to_bytes(8, "big"))
        h.update(hashlib.sha256(self.schema_canonical.encode()).digest())
        return h.digest()

def assert_commit_safe(ballots: Iterable[Ballot], f: int) -> bytes:
    """Return the committed ballot identity iff 2f+1 ballots share it. Raise otherwise."""
    by_identity: dict[bytes, list[Ballot]] = {}
    by_task_epoch: dict[tuple[str, int], set[str]] = {}
    for b in ballots:
        by_identity.setdefault(b.identity(), []).append(b)
        by_task_epoch.setdefault((b.task_id, b.epoch), set()).add(b.schema_canonical)

    for (task_id, epoch), schemas in by_task_epoch.items():
        if len(schemas) > f:
            raise SchemaEquivocationFault(
                f"task={task_id} epoch={epoch} has {len(schemas)} distinct schema hashes "
                f"(>f={f}); Byzantine equivocation suspected, refusing to commit"
            )

    quorum = 2 * f + 1
    winners = [ident for ident, group in by_identity.items() if len(group) >= quorum]
    if len(winners) != 1:
        raise SchemaEquivocationFault(
            f"expected exactly one identity with quorum {quorum}, found {len(winners)}"
        )
    return winners[0]

def commit_epoch(ballots: list[Ballot], f: int) -> bytes:
    try:
        return assert_commit_safe(ballots, f)
    except SchemaEquivocationFault:
        # Do not retry silently: a schema-level fault means a signing key is compromised.
        raise
