# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-equivocation-is-masquerading-as-slow-progress-in-a-bft-agent-commit-round.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-equivocation-is-masquerading-as-slow-progress-in-a-bft-agent-commit-round.warrant.json
# Markdown SHA-256:   2da0e98ca154179317f3a6b61fda943c20c4a804d41ea127e6aa0258a513cc96
# Code AST SHA-256:   c0104ac7df1098be83ad8689e1b019eb9c4f9d50035ba4da249c838e55cc0a96
# Verified Classes:   EquivocationDetected, QuorumCertificate, CommitStore
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Dict, FrozenSet, Tuple


class EquivocationDetected(RuntimeError):
    """Raised when two conflicting quorum certificates for the same slot
    share more than f signers, proving a Byzantine agent equivocated."""


@dataclass(frozen=True)
class QuorumCertificate:
    task_id: int
    view: int
    payload_hash: str
    signers: FrozenSet[str]

    def conflicts_with(self, other: "QuorumCertificate", f: int) -> bool:
        if (self.task_id, self.view) != (other.task_id, other.view):
            return False
        if self.payload_hash == other.payload_hash:
            return False
        return len(self.signers & other.signers) > f


class CommitStore:
    def __init__(self, f: int) -> None:
        self.f = f
        self._certs: Dict[Tuple[int, int], QuorumCertificate] = {}

    def accept(self, qc: QuorumCertificate) -> None:
        slot = (qc.task_id, qc.view)
        prior = self._certs.get(slot)
        if prior is None:
            self._certs[slot] = qc
            return
        if prior.payload_hash == qc.payload_hash:
            return  # idempotent re-delivery
        if prior.conflicts_with(qc, self.f):
            raise EquivocationDetected(
                f"task={qc.task_id} view={qc.view} "
                f"payloads={prior.payload_hash!r} vs {qc.payload_hash!r} "
                f"shared_signers={sorted(prior.signers & qc.signers)}"
            )
        # Disjoint-enough quorums: legitimate re-proposal, hold for full sets.
        raise EquivocationDetected(
            f"HOLD task={qc.task_id} view={qc.view}: "
            f"intersection={len(prior.signers & qc.signers)} <= f={self.f}, "
            f"requesting full signer sets before commit"
        )


def commit_gate(store: CommitStore, qc: QuorumCertificate) -> str:
    try:
        store.accept(qc)
    except EquivocationDetected as e:
        # Freeze the task; emit evidence; do not commit either value.
        return f"FROZEN: {e}"
    return f"COMMITTED task={qc.task_id} payload={qc.payload_hash}"
