# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-byzantine-quorum-certificates-as-invalid-when-agent-equivocation-is-hidden-by-per-view-signature-aggregation.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-byzantine-quorum-certificates-as-invalid-when-agent-equivocation-is-hidden-by-per-view-signature-aggregation.warrant.json
# Markdown SHA-256:   fcc7d3ebd394d2c17545ce612821dce9a9a2dc8e33ad61b7dee7f59008dcdc8c
# Code AST SHA-256:   3261c4bd5d13ffdedccc0f97ff089df013446eaeab9d721784fa5e1a53dc72c1
# Verified Classes:   EquivocationForkError, QuorumCertificate
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import FrozenSet, Iterable


class EquivocationForkError(RuntimeError):
    """Raised when two valid certificates with conflicting digests share a signer."""


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

    def verify(self) -> bool:
        # Per-view predicate: distinct signers, threshold met, view-bound.
        return len(self.signers) >= 3 and self.view >= 0


def commit_state(
    candidate: QuorumCertificate,
    retained: Iterable[QuorumCertificate],
    threshold: int = 3,
) -> str:
    """
    Commit only if `candidate` is admissible under the cross-view invariant:
    no retained certificate with a conflicting digest shares a signer,
    unless the candidate is dominated by a higher-view disjoint QC.
    """
    if not candidate.verify():
        raise EquivocationForkError(
            f"candidate QC at view {candidate.view} fails per-view verification"
        )

    retained = list(retained)

    for prior in retained:
        if prior.digest == candidate.digest:
            continue
        witness = prior.signers & candidate.signers
        if not witness:
            continue
        # A higher-view QC with a signer set disjoint from both supersedes the pair.
        dominator = next(
            (
                q
                for q in retained
                if q.view > max(prior.view, candidate.view)
                and not (q.signers & prior.signers)
                and not (q.signers & candidate.signers)
            ),
            None,
        )
        if dominator is not None:
            continue
        raise EquivocationForkError(
            f"fork evidence: views {prior.view} and {candidate.view} "
            f"carry conflicting digests {prior.digest!r} vs {candidate.digest!r} "
            f"with intersecting signers {sorted(witness)}; "
            f"quarantine both certificates and evict {sorted(witness)}"
        )

    if len(candidate.signers) < threshold:
        raise EquivocationForkError(
            f"candidate QC at view {candidate.view} has {len(candidate.signers)} "
            f"signers, below threshold {threshold}"
        )

    return candidate.digest
