# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-abstain-from-a-byzantine-commit-certificate-under-equivocation.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-abstain-from-a-byzantine-commit-certificate-under-equivocation.warrant.json
# Markdown SHA-256:   046be24ffb4c08fdc5cc267b8c0b755de89af3ff6a28316c4ba821c973a155b0
# Code AST SHA-256:   bfe009b70b50c6e1d870fb5c2e4da8081a3265f26aef9a90a5e6bfbfe0be9393
# Verified Classes:   EquivocationCommitError, Certificate, Reconciler
# Defensive Guards:   5 fail-closed invariants (zero external deps)

import hashlib
import time
from dataclasses import dataclass, field


class EquivocationCommitError(RuntimeError):
    """Raised when a commit certificate is finalized despite an unresolved
    equivocation, or when a contradiction surfaces after finalization."""


@dataclass
class Certificate:
    slot: str
    round: int
    payload_hash: str
    signer: str
    sig: str
    received_at: float


@dataclass
class Reconciler:
    quorum: int
    max_observed_skew_s: float | None = None
    finalize_window_s: float = 0.0
    _by_slot: dict = field(default_factory=dict)
    _finalized: dict = field(default_factory=dict)

    def _key(self, slot: str, rnd: int) -> tuple:
        return (slot, rnd)

    def ingest(self, cert: Certificate) -> None:
        key = self._key(cert.slot, cert.round)
        self._by_slot.setdefault(key, {}).setdefault(cert.payload_hash, []).append(cert)

    def _distinct_hashes(self, slot: str, rnd: int) -> set:
        return set(self._by_slot.get(self._key(slot, rnd), {}).keys())

    def finalize(self, slot: str, rnd: int, payload_hash: str) -> None:
        # Boundary guard: cannot bound skew -> cannot safely finalize.
        if self.max_observed_skew_s is None:
            raise EquivocationCommitError(
                f"refusing to finalize slot={slot} round={rnd}: "
                "inter-instance skew is unmeasured; quorum intersection is unverified"
            )

        # Boundary guard: any divergent signature for this (slot, round) is a veto.
        seen = self._distinct_hashes(slot, rnd)
        if len(seen) > 1:
            raise EquivocationCommitError(
                f"equivocation veto on slot={slot} round={rnd}: "
                f"divergent payload hashes {sorted(seen)}"
            )

        certs = self._by_slot[self._key(slot, rnd)][payload_hash]
        if len({c.signer for c in certs}) < self.quorum:
            raise EquivocationCommitError(
                f"insufficient quorum on slot={slot}: "
                f"{len(certs)} < {self.quorum}"
            )

        # Hold for the finalization window so a late veto can still land.
        window = max(self.finalize_window_s, self.max_observed_skew_s)
        deadline = time.monotonic() + window
        while time.monotonic() < deadline:
            if len(self._distinct_hashes(slot, rnd)) > 1:
                raise EquivocationCommitError(
                    f"late veto during finalize window on slot={slot} round={rnd}"
                )
            time.sleep(0.01)

        # Final contradiction check: a second quorum must never coexist.
        if len(self._distinct_hashes(slot, rnd)) > 1:
            raise EquivocationCommitError(
                f"post-window contradiction on slot={slot} round={rnd}: "
                "two legal quorums for one slot"
            )

        self._finalized[self._key(slot, rnd)] = payload_hash
