# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-detect-equivocating-peers-during-multi-agent-task-commitment-when-the-quorum-certificate-carries-no-per-validator-vote-vector.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-detect-equivocating-peers-during-multi-agent-task-commitment-when-the-quorum-certificate-carries-no-per-validator-vote-vector.warrant.json
# Markdown SHA-256:   181ceff973db3c59760cf5c47f0529162e2eb96e5df2e7df5e30160a0ec34af8
# Code AST SHA-256:   2f82e190f57a8091115093d51d123052f0bd71f1bc7d0b44957a747b19a3a0c1
# Verified Classes:   EquivocationUndetectableError, ContestedSlotError, QuorumCertificate, CommitmentLedger
# Defensive Guards:   6 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional


class EquivocationUndetectableError(RuntimeError):
    """Raised when a QC cannot be intersected to prove or disprove equivocation."""


class ContestedSlotError(RuntimeError):
    """Raised when two conflicting QCs are seen for one (height, slot)."""


@dataclass
class QuorumCertificate:
    height: int
    slot: str
    block_digest: str
    signer_set: Optional[frozenset]  # None => cardinality-only, unsafe
    signature_count: int
    threshold: int

    def has_threshold(self) -> bool:
        return self.signature_count >= self.threshold


@dataclass
class CommitmentLedger:
    committed: dict = field(default_factory=dict)          # (height, slot) -> digest
    seen_qcs: dict = field(default_factory=dict)          # (height, slot) -> list[QC]
    contested: set = field(default_factory=set)           # frozen (height, slot)

    def observe(self, qc: QuorumCertificate) -> None:
        key = (qc.height, qc.slot)
        self.seen_qcs.setdefault(key, []).append(qc)

    def verify_intersection(self, a: QuorumCertificate, b: QuorumCertificate) -> frozenset:
        if a.signer_set is None or b.signer_set is None:
            raise EquivocationUndetectableError(
                f"QC at h={a.height} slot={a.slot} carries no signer set; "
                f"cardinality-only certificates cannot be intersected. "
                f"Refusing to commit; escalate to signer-set exchange round."
            )
        overlap = a.signer_set & b.signer_set
        if not overlap:
            # Impossible under 2f+1 threshold with f Byzantine; indicates
            # corrupt validator set or forged certificates.
            raise EquivocationUndetectableError(
                f"Empty intersection between QCs at h={a.height} slot={a.slot}; "
                f"threshold invariant violated—validator set integrity compromised."
            )
        return overlap

    def commit(self, qc: QuorumCertificate) -> str:
        key = (qc.height, qc.slot)

        if key in self.contested:
            raise ContestedSlotError(
                f"Slot {key} is frozen pending equivocation resolution; "
                f"refusing to commit digest {qc.block_digest}."
            )

        if not qc.has_threshold():
            raise ContestedSlotError(
                f"QC at {key} failed cardinality check "
                f"({qc.signature_count} < {qc.threshold})."
            )

        # Safety gate: intersect against every QC seen at this height/slot.
        for other in self.seen_qcs.get(key, []):
            if other.block_digest == qc.block_digest:
                continue
            try:
                faulty = self.verify_intersection(qc, other)
            except EquivocationUndetectableError:
                # Cannot prove equivocation locally: freeze, do not guess.
                self.contested.add(key)
                raise
            # Non-empty intersection => at least one validator signed both
            # conflicting blocks => equivocation proven.
            self.contested.add(key)
            raise ContestedSlotError(
                f"Equivocation proven at {key}: signers {sorted(faulty)} "
                f"signed both {qc.block_digest} and {other.block_digest}. "
                f"Slot frozen; exclude faulty signers and re-propose."
            )

        self.committed[key] = qc.block_digest
        return qc.block_digest


def reconcile(ledger: CommitmentLedger, incoming: QuorumCertificate) -> str:
    ledger.observe(incoming)
    return ledger.commit(incoming)
