# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-commit-a-speculative-plan-draft-that-no-honest-quorum-ever-assembled.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-commit-a-speculative-plan-draft-that-no-honest-quorum-ever-assembled.warrant.json
# Markdown SHA-256:   07f7dd77af10ca3d107a32755264303d0325b0b43f9a664415e5f11fc2d7a32d
# Code AST SHA-256:   f9feec11aff85b535ebe6b98c5b2707cc64d55162c0d66def9b281932f0c82b3
# Verified Classes:   QuorumAssemblyError, DraftAttestation
# Defensive Guards:   2 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass


class QuorumAssemblyError(RuntimeError):
    """Raised when an attestation set is internally consistent but not epoch-homogeneous."""


@dataclass(frozen=True)
class DraftAttestation:
    epoch: int
    plan_digest: str
    signer: str


def compute_plan_digest(epoch: int, full_prefix: str, speculative_suffix: str) -> str:
    h = hashlib.sha256()
    h.update(str(epoch).encode())
    h.update(b"\x00")
    h.update(full_prefix.encode())
    h.update(b"\x00")
    h.update(speculative_suffix.encode())
    return h.hexdigest()


def commit_speculative_draft(
    epoch: int,
    full_prefix: str,
    speculative_suffix: str,
    attestations: list[DraftAttestation],
    fault_tolerance: int,
) -> str:
    threshold = 2 * fault_tolerance + 1
    expected_digest = compute_plan_digest(epoch, full_prefix, speculative_suffix)

    counted = []
    stale = []
    for att in attestations:
        if att.epoch != epoch:
            stale.append(att)
            continue
        if att.plan_digest != expected_digest:
            continue
        counted.append(att)

    if len(counted) < threshold:
        raise QuorumAssemblyError(
            f"epoch={epoch} counted={len(counted)} threshold={threshold} "
            f"stale_votes={len(stale)} — refusing to commit a mosaic quorum"
        )

    # Even with quorum, a stale vote in the set signals a drafter desync
    # that will poison downstream handoff; surface it.
    if stale:
        raise QuorumAssemblyError(
            f"epoch={epoch} quorum reached but {len(stale)} stale-epoch "
            f"attestations present (signers={[a.signer for a in stale]}); "
            f"re-solicit before commit"
        )

    return expected_digest
