# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-bound-the-equivocation-window-in-byzantine-agent-commitment-ledgers-before-quorum-certificates-become-forgeable.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-bound-the-equivocation-window-in-byzantine-agent-commitment-ledgers-before-quorum-certificates-become-forgeable.warrant.json
# Markdown SHA-256:   f74ff30df4a74020966aca430353787f32b72053bd7bfe26834150284f727122
# Code AST SHA-256:   54f711dcaffc6e8c1ee026b91695a1d85cf113cc76bbef9515a0e2f3d284fce8
# Verified Classes:   EquivocationWindowError, Signature
# Defensive Guards:   5 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass
from typing import Dict, List, Tuple


class EquivocationWindowError(RuntimeError):
    """Raised when a QC is assembled from signers whose attempt sequences
    are not consistent, indicating the equivocation window was open."""
    pass


@dataclass(frozen=True)
class Signature:
    signer_id: str
    task_id: str
    epoch: int
    attempt_seq: int
    plan_hash: str
    sig: bytes


def verify_quorum_certificate(
    qc_signatures: List[Signature],
    threshold: int,
    identity: Tuple[str, int],
) -> str:
    """Verify a QC binds exactly one plan_hash per (task_id, epoch) identity
    and that all signers report the maximal attempt_seq for that identity.

    Returns the committed plan_hash. Raises EquivocationWindowError if the
    window was open (mixed attempt_seq or divergent plan_hash).
    """
    task_id, epoch = identity
    if len(qc_signatures) < threshold:
        raise EquivocationWindowError(
            f"QC for {identity} has {len(qc_signatures)} < threshold {threshold}"
        )

    plan_hashes = {s.plan_hash for s in qc_signatures}
    attempt_seqs = {s.attempt_seq for s in qc_signatures}

    for s in qc_signatures:
        if (s.task_id, s.epoch) != identity:
            raise EquivocationWindowError(
                f"signer {s.signer_id} signed wrong identity {(s.task_id, s.epoch)}"
            )

    if len(plan_hashes) > 1:
        raise EquivocationWindowError(
            f"dual plan_hash {plan_hashes} under identity {identity}: "
            f"equivocation window was open between view_timeout and abort"
        )

    if len(attempt_seqs) > 1:
        raise EquivocationWindowError(
            f"mixed attempt_seq {attempt_seqs} under identity {identity}: "
            f"at least one signer re-signed after view change without "
            f"attempt-sequence monotonicity; QC unverifiable"
        )

    # Bind the QC to a deterministic digest over identity + attempt + plan.
    plan_hash = plan_hashes.pop()
    attempt_seq = attempt_seqs.pop()
    return hashlib.sha256(
        f"{task_id}:{epoch}:{attempt_seq}:{plan_hash}".encode()
    ).hexdigest()


def commit_task(
    qc_signatures: List[Signature],
    threshold: int,
    identity: Tuple[str, int],
    seen_identities: Dict[Tuple[str, int], str],
) -> str:
    """Commit a task only if the QC verifies and does not conflict with a
    previously committed QC for the same identity."""
    commitment_digest = verify_quorum_certificate(
        qc_signatures, threshold, identity
    )
    prior = seen_identities.get(identity)
    if prior is not None and prior != commitment_digest:
        raise EquivocationWindowError(
            f"identity {identity} already committed as {prior}, "
            f"new QC yields {commitment_digest}: dual-QC detected at executor"
        )
    seen_identities[identity] = commitment_digest
    return commitment_digest
