# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-commit-to-a-task-quorum-that-no-longer-exists-byzantine-quorum-certificate-divergence-under-membership-churn-in-agent-consensus.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-commit-to-a-task-quorum-that-no-longer-exists-byzantine-quorum-certificate-divergence-under-membership-churn-in-agent-consensus.warrant.json
# Markdown SHA-256:   b57b812ea9246ebec612f0142fd7a95085b23ad1caafa6d916074ba30a4a77f7
# Code AST SHA-256:   4b69e22d3e5a977a40d3cfacfb2bec26b9c7400d9d978d2b1101f6d30e5e9983
# Verified Classes:   QuorumCertificateDivergence, ValidatorSet, QuorumCertificate
# Defensive Guards:   5 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass, field


class QuorumCertificateDivergence(RuntimeError):
    """Raised when a QC's epoch-relative validity cannot be reconciled
    with the verifier's current epoch under the retention horizon."""
    pass


@dataclass
class ValidatorSet:
    epoch: int
    members: frozenset

    @property
    def threshold(self):
        n = len(self.members)
        return (2 * n + 1) // 3 + ((2 * n + 1) % 3 > 0)


@dataclass
class QuorumCertificate:
    task_id: str
    state_root: str
    view: int
    epoch: int
    validator_set_hash: str
    signers: frozenset
    epoch_change_chain: list = field(default_factory=list)


def _hash_set(vs: ValidatorSet) -> str:
    return hashlib.sha256(
        repr(sorted(vs.members)).encode()
    ).hexdigest()


def verify_qc(
    qc: QuorumCertificate,
    current_set: ValidatorSet,
    known_sets: dict,
    retention_horizon: int,
) -> bool:
    """Verify a QC under the epoch it was formed in, not the current epoch.

    Raises QuorumCertificateDivergence when the QC's epoch is outside the
    retention horizon and no epoch-change chain bridges it to current_set.
    """
    if qc.epoch == current_set.epoch:
        target = current_set
    else:
        if qc.epoch < current_set.epoch - retention_horizon:
            raise QuorumCertificateDivergence(
                f"QC epoch {qc.epoch} is {current_set.epoch - qc.epoch} "
                f"epochs behind current {current_set.epoch}; "
                f"retention horizon is {retention_horizon}. "
                f"Cannot re-evaluate signers against current set without "
                f"epoch-change chain — refusing to treat as invalid "
                f"(that path causes split-brain finality)."
            )
        # Walk the epoch-change chain from qc.epoch to current_set.epoch.
        chain = {c["from_epoch"]: c for c in qc.epoch_change_chain}
        e = qc.epoch
        while e < current_set.epoch:
            link = chain.get(e)
            if link is None:
                raise QuorumCertificateDivergence(
                    f"Missing epoch-change cert for transition {e} -> "
                    f"{e + 1}; cannot establish that evictions were "
                    f"certified under epoch {e}."
                )
            if link["certified_by"] != _hash_set(known_sets[e]):
                raise QuorumCertificateDivergence(
                    f"Epoch-change cert for {e} -> {e + 1} not signed by "
                    f"the epoch-{e} validator set."
                )
            e += 1
        target = known_sets[qc.epoch]

    if qc.validator_set_hash != _hash_set(target):
        raise QuorumCertificateDivergence(
            f"QC {qc.task_id} claims validator_set_hash "
            f"{qc.validator_set_hash[:12]} but epoch {qc.epoch} set hashes "
            f"to {_hash_set(target)[:12]}; QC was formed against a "
            f"different membership than claimed."
        )

    effective = qc.signers & target.members
    if len(effective) < target.threshold:
        # Under the QC's OWN epoch this is a genuine failure, not a
        # cross-epoch artifact — safe to reject.
        return False
    return True


def commit_task(
    qc: QuorumCertificate,
    current_set: ValidatorSet,
    known_sets: dict,
    retention_horizon: int,
) -> str:
    if not verify_qc(qc, current_set, known_sets, retention_horizon):
        raise QuorumCertificateDivergence(
            f"QC for {qc.task_id} failed threshold under its own epoch "
            f"{qc.epoch}; refusing to commit."
        )
    return f"committed:{qc.task_id}@epoch{qc.epoch}"
