# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-byzantine-quorum-agreement-on-a-task-commitment-as-void-when-the-committing-view-was-assembled-across-a-recon.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-byzantine-quorum-agreement-on-a-task-commitment-as-void-when-the-committing-view-was-assembled-across-a-recon.warrant.json
# Markdown SHA-256:   fd1218059cacdeab06cd798c8739a752b3886f7be70a7d9c571f817e19a88432
# Code AST SHA-256:   560585184438902c8c58c5ca6d9ff847ab0b2d1f49b051612d49e4ee20b859da
# Verified Classes:   EpochBoundaryConflict, CommitmentQC, ValidatorSet, LocalView
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import FrozenSet


class EpochBoundaryConflict(RuntimeError):
    """Raised when a commitment QC cannot be proven to belong to a single epoch's quorum."""
    pass


@dataclass(frozen=True)
class CommitmentQC:
    task_id: str
    plan_hash: str
    epoch: int
    signers: FrozenSet[str]
    parent_commit_hash: str


@dataclass(frozen=True)
class ValidatorSet:
    epoch: int
    members: FrozenSet[str]

    def quorum(self) -> int:
        return (2 * len(self.members) + 1) // 3 + 1


@dataclass(frozen=True)
class LocalView:
    synced_epoch: int
    head_commit_hash: str
    validator_sets: dict  # epoch -> ValidatorSet


def verify_commitment(qc: CommitmentQC, view: LocalView) -> None:
    # Rule 1: epoch monotonicity / state-transfer completeness.
    if qc.epoch > view.synced_epoch:
        raise EpochBoundaryConflict(
            f"QC epoch {qc.epoch} exceeds synced epoch {view.synced_epoch}; "
            f"task {qc.task_id} pending state transfer"
        )

    # Rule 2: quorum must be epoch-scoped, not unioned across epochs.
    vs = view.validator_sets.get(qc.epoch)
    if vs is None:
        raise EpochBoundaryConflict(f"no validator set known for epoch {qc.epoch}")
    epoch_signers = qc.signers & vs.members
    if len(epoch_signers) < vs.quorum():
        raise EpochBoundaryConflict(
            f"task {qc.task_id}: signers {sorted(qc.signers)} do not form a quorum "
            f"of epoch {qc.epoch} (need {vs.quorum()}, have {len(epoch_signers)}); "
            f"QC likely assembled across an epoch boundary"
        )

    # Rule 3: causal linkage to receiver's current head.
    if qc.parent_commit_hash != view.head_commit_hash:
        raise EpochBoundaryConflict(
            f"task {qc.task_id}: parent {qc.parent_commit_hash} != head "
            f"{view.head_commit_hash}; view-change proof required before execution"
        )


def execute_task(qc: CommitmentQC, view: LocalView) -> str:
    verify_commitment(qc, view)
    return f"executed {qc.task_id}:{qc.plan_hash}"
