# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-quorum-certificate-equivocation-in-byzantine-agent-consensus-before-task-commitment-becomes-irreversible.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-quorum-certificate-equivocation-in-byzantine-agent-consensus-before-task-commitment-becomes-irreversible.warrant.json
# Markdown SHA-256:   e12a2fc2bea03fcddca9674671ad4ed259b4855178bb2532b8b91858b706fc4e
# Code AST SHA-256:   32d9a1da91f47e6f2950e2d432b9561552e6056e38f281d5ec8535eee870e565
# Verified Classes:   LineageConflict, InsufficientAttestation, QuorumCertificate
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Optional


class LineageConflict(RuntimeError):
    """Raised when a quorum certificate's lineage chain is broken for a seq."""
    pass


class InsufficientAttestation(RuntimeError):
    """Raised when an agent cannot finalize: no prior head and no peer lineage."""
    pass


@dataclass(frozen=True)
class QuorumCertificate:
    view: int
    seq: int
    digest: str
    prev_qc_digest: Optional[str]
    signers: frozenset

    def verify_signatures(self, validator_set: frozenset, quorum: int) -> bool:
        return self.signers <= validator_set and len(self.signers) >= quorum


def finalize_task_commitment(
    qc: QuorumCertificate,
    local_chain_head: Optional[str],
    validator_set: frozenset,
    quorum: int,
    peer_lineage_attestations: int,
    f: int,
) -> str:
    """Return the committed digest, or raise on equivocation / insufficient evidence.

    Invariant: a QC is a *candidate* until its prev_qc_digest chains to the
    local head for this seq. A lone valid QC with no prior head and no peer
    attestation is NOT sufficient to finalize (silence is not consent).
    """
    if not qc.verify_signatures(validator_set, quorum):
        raise LineageConflict(
            f"QC for seq={qc.seq} view={qc.view} fails signature quorum"
        )

    if local_chain_head is None:
        # No local head for this seq: we cannot decide on a single certificate.
        if peer_lineage_attestations < f + 1:
            raise InsufficientAttestation(
                f"seq={qc.seq} view={qc.view}: lone QC with no lineage; "
                f"have {peer_lineage_attestations} attestations, need {f + 1}"
            )
        # Peer-attested fresh head: accept and record.
        return qc.digest

    if qc.prev_qc_digest != local_chain_head:
        # Equivocation detected: two valid QCs for same seq, broken chain.
        raise LineageConflict(
            f"seq={qc.seq} view={qc.view}: prev_qc_digest={qc.prev_qc_digest!r} "
            f"does not chain to local head {local_chain_head!r}; "
            f"broadcast conflicting QC pair and require super-quorum attestation"
        )

    return qc.digest
