# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-a-byzantine-fault-tolerant-commit-certificate-as-invalid-when-the-signing-quorum-overlaps-with-the-equivocati.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-a-byzantine-fault-tolerant-commit-certificate-as-invalid-when-the-signing-quorum-overlaps-with-the-equivocati.warrant.json
# Markdown SHA-256:   0a7b1c91b768aafe0b52ece434545a18c9b7afdd22082661b32dc2099399631e
# Code AST SHA-256:   f635e3893ca1cbde652f877e8871d07552b614933dcbbb2a939aad2c4150ff13
# Verified Classes:   EquivocationOverlapError, SlotPoisonedError, Certificate, SlotLedger
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Dict, List, Set, Tuple


class EquivocationOverlapError(RuntimeError):
    """Raised when a threshold-valid certificate's honest margin is insufficient."""
    pass


class SlotPoisonedError(RuntimeError):
    """Raised when two conflicting certificates exist for the same action slot."""
    pass


@dataclass(frozen=True)
class Certificate:
    slot: str
    epoch: int
    digest: str
    signers: Set[str]


@dataclass
class SlotLedger:
    # slot -> epoch -> digest -> Certificate
    seen: Dict[Tuple[str, int], Dict[str, Certificate]] = field(default_factory=dict)
    equivocators: Set[str] = field(default_factory=set)


def verify_certificate(
    cert: Certificate,
    ledger: SlotLedger,
    f: int,
    threshold: int,
) -> None:
    # 1. Structural threshold check
    if len(cert.signers) < threshold:
        raise EquivocationOverlapError(
            f"cert for slot={cert.slot} has {len(cert.signers)} signers < {threshold}"
        )

    key = (cert.slot, cert.epoch)
    prior = ledger.seen.get(key, {})

    # 2. Detect conflicting digest at same (slot, epoch)
    conflicting = [d for d in prior if d != cert.digest]
    if conflicting:
        # Record equivocators: signers who signed both digests
        for other_digest in conflicting:
            other = prior[other_digest]
            overlap = cert.signers & other.signers
            ledger.equivocators |= overlap
        raise SlotPoisonedError(
            f"slot={cert.slot} epoch={cert.epoch} poisoned; "
            f"conflicting digests={conflicting + [cert.digest]}"
        )

    # 3. Honest-margin check: signers minus known equivocators must be >= f+1
    honest_margin = cert.signers - ledger.equivocators
    if len(honest_margin) < f + 1:
        raise EquivocationOverlapError(
            f"cert for slot={cert.slot}: honest margin {len(honest_margin)} < f+1={f+1}; "
            f"signers={cert.signers}, equivocators={ledger.equivocators}"
        )

    # 4. Admit
    ledger.seen.setdefault(key, {})[cert.digest] = cert


def commit_action(
    cert: Certificate,
    ledger: SlotLedger,
    f: int,
    threshold: int,
) -> str:
    try:
        verify_certificate(cert, ledger, f, threshold)
    except SlotPoisonedError as e:
        # Escalate; do not apply either action
        raise EquivocationOverlapError(
            f"refusing to commit slot={cert.slot}: {e}"
        ) from e
    return f"committed {cert.digest} on slot={cert.slot} epoch={cert.epoch}"
