# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-reconcile-divergent-task-commitment-quorum-certificates-when-a-byzantine-auditor-forges-a-valid-looking-commit-signature-under.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-reconcile-divergent-task-commitment-quorum-certificates-when-a-byzantine-auditor-forges-a-valid-looking-commit-signature-under.warrant.json
# Markdown SHA-256:   c2ff42d22e1d3912249a590a9e7969f4f06a1f1e3f13397298c5aabe77ca0915
# Code AST SHA-256:   a6c2543db50b796f5e5df419a40d9d9b4d75deb7316ac3a69d38ffd0a504130b
# Verified Classes:   ConflictingCommitment, StaleEpochReplay, CommitmentQC, CommitmentValidator
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Dict, Optional


class ConflictingCommitment(RuntimeError):
    """Raised when a validator holds two QCs for the same task digest under
    different epochs and cannot soundly choose between them."""
    pass


class StaleEpochReplay(RuntimeError):
    """Raised when a commit QC references an epoch older than the highest
    epoch this validator has observed for the task."""
    pass


@dataclass(frozen=True)
class CommitmentQC:
    task_id: str
    digest: str          # MUST cover (task_id, budget, deadline, epoch, coordinator_id)
    epoch: int
    signers: tuple       # validator IDs
    quorum_size: int


class CommitmentValidator:
    def __init__(self, validator_id: str):
        self.validator_id = validator_id
        self.highest_epoch_seen: Dict[str, int] = {}
        self.prepared_digests: Dict[str, str] = {}  # task_id -> digest prepared under current epoch

    def accept_commit(self, qc: CommitmentQC, current_epoch_set: frozenset) -> None:
        prior_epoch = self.highest_epoch_seen.get(qc.task_id)

        # Guard 1: stale-epoch replay rejection
        if prior_epoch is not None and qc.epoch < prior_epoch:
            raise StaleEpochReplay(
                f"QC for task {qc.task_id} references epoch {qc.epoch} "
                f"but highest observed is {prior_epoch}"
            )

        # Guard 2: quorum membership must be valid for the QC's own epoch
        if not set(qc.signers).issubset(current_epoch_set):
            raise ConflictingCommitment(
                f"QC for task {qc.task_id} epoch {qc.epoch} contains signers "
                f"outside the epoch's validator set"
            )
        if len(set(qc.signers)) < qc.quorum_size:
            raise ConflictingCommitment(
                f"QC for task {qc.task_id} epoch {qc.epoch} has insufficient "
                f"distinct signers: {len(set(qc.signers))} < {qc.quorum_size}"
            )

        # Guard 3: cross-epoch conflict on the same task slot
        prior_digest = self.prepared_digests.get(qc.task_id)
        if prior_digest is not None and prior_digest != qc.digest:
            # Two distinct commitments for the same task under different epochs.
            # Epoch-bound digest means these are genuinely different commitments;
            # we cannot silently overwrite. Halt and escalate.
            raise ConflictingCommitment(
                f"Task {qc.task_id} has prepared digest {prior_digest} under "
                f"epoch {prior_epoch}, now receiving digest {qc.digest} under "
                f"epoch {qc.epoch}; halting for resolution round"
            )

        # Safe to finalize
        self.highest_epoch_seen[qc.task_id] = qc.epoch
        self.prepared_digests[qc.task_id] = qc.digest
