# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-commit-to-a-task-quorum-it-cannot-attest-equivocation-tolerant-consensus-and-the-attestation-commitment-gap-in-adversarial-multi.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-commit-to-a-task-quorum-it-cannot-attest-equivocation-tolerant-consensus-and-the-attestation-commitment-gap-in-adversarial-multi.warrant.json
# Markdown SHA-256:   3b33f45c4f4b17527b68fb57e284ea8ec2b71035e440a03252929c4aa5e3288e
# Code AST SHA-256:   21ac13e4e63fbabe53a3212c22ca87acb38f4cd82a02568b1bdfe283d40504ef
# Verified Classes:   AttestationSoundnessError, Attestation
# Defensive Guards:   6 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass


class AttestationSoundnessError(RuntimeError):
    """Raised when a BFT commit certificate cannot be independently replayed."""
    pass


@dataclass
class Attestation:
    task_id: str
    verdict: str          # "VALID" | "INVALID"
    confidence: float     # 0.0 .. 1.0
    evidence_root: str    # Merkle root over exact retrieved chunk IDs
    coverage_ratio: float # retrieved tokens / total trace tokens


ATTESTATION_FLOOR = 0.70
COVERAGE_FLOOR = 0.90
DIVERGENCE_UPPER_BOUND = 0.15  # measured honest-voter disagreement rate


def commit_hash(a: Attestation) -> str:
    # Confidence is bucketed so tiny sampling noise does not fracture the hash,
    # but the bucket boundary is part of the signed object.
    bucket = round(a.confidence * 10) / 10
    payload = f"{a.task_id}|{a.verdict}|{bucket}|{a.evidence_root}"
    return hashlib.sha256(payload.encode()).hexdigest()


def verify_quorum(attestations: list[Attestation], n: int, f: int) -> str:
    if len(attestations) != n:
        raise AttestationSoundnessError(
            f"expected {n} attestations, got {len(attestations)}"
        )

    eligible: list[Attestation] = []
    for a in attestations:
        if a.coverage_ratio < COVERAGE_FLOOR:
            # Voter reasoned over a truncated evidence set; cannot count.
            continue
        if a.confidence < ATTESTATION_FLOOR:
            # Below floor: must abstain, does not count toward quorum.
            continue
        eligible.append(a)

    # Quorum threshold must exceed the honest-divergence upper bound,
    # not merely f. With n=7, f=2, threshold=5 > ceil(7*0.15)=2.
    threshold = max(2 * f + 1, int(n * DIVERGENCE_UPPER_BOUND) + 1)
    if len(eligible) < threshold:
        raise AttestationSoundnessError(
            f"eligible voters {len(eligible)} < threshold {threshold}"
        )

    roots = {a.evidence_root for a in eligible}
    if len(roots) > 1:
        # Voters disagreed on the evidence set itself -> not evidence-closed.
        raise AttestationSoundnessError(
            f"evidence roots diverge across voters: {sorted(roots)}"
        )

    hashes = {commit_hash(a) for a in eligible}
    if len(hashes) != 1:
        raise AttestationSoundnessError(
            f"commit hash divergence across eligible voters: {sorted(hashes)}"
        )

    return hashes.pop()


def replay_audit(certificate_hash: str, auditor: Attestation) -> None:
    # Auditor must reason over the SAME evidence root; truncation is fatal.
    if auditor.coverage_ratio < COVERAGE_FLOOR:
        raise AttestationSoundnessError(
            "auditor retrieval truncated; replay invalid"
        )
    if commit_hash(auditor) != certificate_hash:
        raise AttestationSoundnessError(
            "replay mismatch: certificate not reproducible from closed evidence"
        )
