# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-byzantine-quorum-certificates-as-non-transferable-across-task-epochs.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-byzantine-quorum-certificates-as-non-transferable-across-task-epochs.warrant.json
# Markdown SHA-256:   b3802188f79530a773fa36e31f3799a8a256487cb954bfc80e727b61dafd1ddd
# Code AST SHA-256:   628092387deafe43f600a808746b272f81e91ecdb4ac3f6a6be9b48df96f5065
# Verified Classes:   QuorumEpochBleedError, QuorumCertificate
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass


class QuorumEpochBleedError(RuntimeError):
    """Raised when a quorum certificate is presented outside the roster
    domain in which its safety proof was established."""
    pass


@dataclass(frozen=True)
class QuorumCertificate:
    epoch: int
    roster_hash: str
    signers: frozenset
    delta_id: str


def roster_hash(roster: frozenset) -> str:
    return hashlib.sha256(",".join(sorted(roster)).encode()).hexdigest()[:16]


def verify_transferable(
    qc: QuorumCertificate,
    qc_roster: frozenset,
    current_roster: frozenset,
    current_epoch: int,
    fault_bound: int,
) -> bool:
    # Domain check first: a QC is a proof about one roster, not a portable token.
    if qc.roster_hash != roster_hash(qc_roster):
        raise QuorumEpochBleedError(
            f"QC roster_hash {qc.roster_hash} does not match its claimed roster"
        )

    if qc.epoch == current_epoch and qc_roster == current_roster:
        return True

    # Recompute honest intersection over the ORIGINAL signer set.
    # Do not re-filter signers against the new roster and re-count.
    surviving = qc.signers & current_roster
    if len(surviving) < fault_bound + 1:
        raise QuorumEpochBleedError(
            f"QC from epoch {qc.epoch} has honest intersection "
            f"{len(surviving)} < f+1={fault_bound + 1} against epoch "
            f"{current_epoch} roster; commit is not transferable"
        )
    return True


def reconcile(qc: QuorumCertificate, qc_roster, current_roster, current_epoch, f):
    if not verify_transferable(qc, qc_roster, current_roster, current_epoch, f):
        raise QuorumEpochBleedError("reconciliation refused: unsound QC transfer")
    return qc.delta_id
