# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-treat-a-byzantine-quorum-failure-as-a-memory-continuity-event-rather-than-a-retryable-consensus-fault.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-treat-a-byzantine-quorum-failure-as-a-memory-continuity-event-rather-than-a-retryable-consensus-fault.warrant.json
# Markdown SHA-256:   abed255c8d1535cff600d4587ed51156fd2d9de22aa53834a9fb3e9393dc3a04
# Code AST SHA-256:   7728ea76146dd9c56be92e32897480e3c4afa300887acef6c4ac0c33aaf4eb76
# Verified Classes:   UncertifiedResumeError, QuorumCertificate, EpisodicRecord
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional


class UncertifiedResumeError(RuntimeError):
    """Raised when a coordinator attempts to resume a quorum decision
    from a durable record that lacks a re-verifiable quorum certificate."""
    pass


@dataclass
class QuorumCertificate:
    round_epoch: int
    outcome: str
    signers: frozenset  # verified honest signer ids, size >= 2f+1
    threshold: int

    def verifies(self) -> bool:
        return len(self.signers) >= self.threshold


@dataclass
class EpisodicRecord:
    round_epoch: int
    summary: str
    certificate: Optional[QuorumCertificate] = None


def resume_decision(record: EpisodicRecord) -> str:
    """Resume a quorum decision only from a certified record.

    A narrative summary without a certificate is treated as untrusted
    adversarial input, never as a commitment.
    """
    if record.certificate is None:
        raise UncertifiedResumeError(
            f"round {record.round_epoch}: durable record has summary "
            f"{record.summary!r} but no quorum certificate; "
            f"refusing to resume downstream action"
        )
    if not record.certificate.verifies():
        raise UncertifiedResumeError(
            f"round {record.round_epoch}: certificate has "
            f"{len(record.certificate.signers)} signers, "
            f"threshold {record.certificate.threshold}; "
            f"quorum not met"
        )
    return record.certificate.outcome


def commit_round(votes, threshold: int, epoch: int) -> EpisodicRecord:
    """Write-ahead certification: only certified votes become durable."""
    matching = {v.signer for v in votes
                if v.epoch == epoch and v.verified}
    if len(matching) < threshold:
        # Quarantine, do not distill. Round is a retryable fault.
        return EpisodicRecord(
            round_epoch=epoch,
            summary=f"round {epoch}: quorum not reached ({len(matching)}/{threshold})",
            certificate=None,
        )
    cert = QuorumCertificate(epoch, votes[0].outcome, frozenset(matching), threshold)
    return EpisodicRecord(
        round_epoch=epoch,
        summary=f"round {epoch}: certified {cert.outcome}",
        certificate=cert,
    )
