# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-draw-the-line-between-attested-by-a-quorum-and-attested-by-a-quorum-that-could-not-have-colluded-by-construction.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-draw-the-line-between-attested-by-a-quorum-and-attested-by-a-quorum-that-could-not-have-colluded-by-construction.warrant.json
# Markdown SHA-256:   a66be4dab4575bc260da1f700dbb43c2266abdff62628cd85226589a45753cb4
# Code AST SHA-256:   3ee9e30f4678a244fe5c0600d7413065567bba71afcb526eece714c7abb033be
# Verified Classes:   CorrelatedQuorumError, Attestation, QuorumCertificate
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from collections import Counter
from typing import Dict, List


class CorrelatedQuorumError(RuntimeError):
    """Raised when a quorum certificate's signers share an evidence provenance
    root beyond the Byzantine fault budget, invalidating the independence
    precondition required for BFT safety."""
    pass


@dataclass
class Attestation:
    signer_id: str
    verdict_digest: str
    evidence_provenance_root: str  # hash of the exact evidence set consumed


@dataclass
class QuorumCertificate:
    attestations: List[Attestation] = field(default_factory=list)


def verify_quorum_independence(
    cert: QuorumCertificate,
    n_auditors: int,
    threshold: int,
) -> None:
    """Enforce that no evidence provenance root is shared by more than
    f = (n_auditors - 1) // 3 auditors before accepting the certificate.

    Identity disjointness (distinct keys/hosts) is assumed already checked.
    This function checks *provenance* disjointness, which is the binding
    constraint for correlated-fault safety in LLM auditor swarms.
    """
    if len(cert.attestations) < threshold:
        raise CorrelatedQuorumError(
            f"quorum size {len(cert.attestations)} < threshold {threshold}"
        )

    f_budget = (n_auditors - 1) // 3

    root_counts: Dict[str, int] = Counter(
        a.evidence_provenance_root for a in cert.attestations
    )

    for root, count in root_counts.items():
        if count > f_budget:
            raise CorrelatedQuorumError(
                f"evidence provenance root {root[:12]}... shared by {count} "
                f"auditors, exceeding fault budget f={f_budget} for "
                f"N={n_auditors}. Quorum is correlated, not Byzantine-safe: "
                f"a single poisoned input at this root fails all {count} "
                f"signers together. Reject and re-dispatch with partitioned "
                f"evidence shards."
            )

    # Also require verdict agreement among provenance-disjoint signers.
    verdicts = Counter(a.verdict_digest for a in cert.attestations)
    top_verdict, top_count = verdicts.most_common(1)[0]
    if top_count < threshold:
        raise CorrelatedQuorumError(
            f"no verdict reaches threshold {threshold}: {dict(verdicts)}"
        )


def commit_result(cert: QuorumCertificate, n_auditors: int, threshold: int) -> str:
    verify_quorum_independence(cert, n_auditors, threshold)
    return cert.attestations[0].verdict_digest


# --- Demonstration of the failure the guardrail catches ---
if __name__ == "__main__":
    shared_root = "sha256:poisoned_evidence_bundle"
    cert = QuorumCertificate(
        attestations=[
            Attestation(f"auditor_{i}", "0xDEAD", shared_root) for i in range(7)
        ]
    )
    try:
        commit_result(cert, n_auditors=7, threshold=5)
    except CorrelatedQuorumError as e:
        print(f"REJECTED: {e}")
