# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-a-byzantine-quorum-collapse-when-a-heterogeneous-agent-collective-silently-partitions-its-trust-graph-by-model-lineag.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-a-byzantine-quorum-collapse-when-a-heterogeneous-agent-collective-silently-partitions-its-trust-graph-by-model-lineag.warrant.json
# Markdown SHA-256:   c1de04fba020a3efbf0ff4e9202ac561d12b66a7255e9cb6cdb6d4327bdd4e9a
# Code AST SHA-256:   8121b47852a09dacb0feeacddf92b38e0cf30c104e4e84ca94a76d86dd7b73a9
# Verified Classes:   UncorrelatedQuorumViolation, Vote
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from collections import Counter
from typing import Iterable


class UncorrelatedQuorumViolation(RuntimeError):
    """Raised when a commit satisfies replica-count quorum but fails lineage-count quorum.

    This is the structural signal of a trust-graph partition by model lineage:
    the collective agreed, but the agreement was carried by correlated replicas
    sharing a common blind spot, not by independent decision-makers.
    """
    pass


@dataclass(frozen=True)
class Vote:
    replica_id: str
    lineage_id: str
    verdict: str          # e.g. "ACCEPT" / "REJECT"
    margin: float         # logit margin or confidence; used for correlation audit


def commit(
    votes: Iterable[Vote],
    f: int,
    verdict: str = "ACCEPT",
) -> str:
    votes = list(votes)
    n = len(votes)
    if n < 3 * f + 1:
        raise UncorrelatedQuorumViolation(
            f"replica census {n} below 3f+1={3*f+1}; BFT safety undefined"
        )

    matching = [v for v in votes if v.verdict == verdict]
    replica_quorum = len(matching) >= 2 * f + 1

    # Lineage-aware quorum: count distinct lineages, not replicas.
    lineage_counts = Counter(v.lineage_id for v in matching)
    distinct_lineages = len(lineage_counts)
    lineage_quorum = distinct_lineages >= f + 1

    # Correlation audit: if any single lineage supplies more than f votes
    # for the same verdict, the quorum may be carried by a shared blind spot.
    dominant_lineage, dominant_count = (
        lineage_counts.most_common(1)[0] if lineage_counts else ("", 0)
    )
    lineage_dominance = dominant_count > f

    if replica_quorum and not lineage_quorum:
        raise UncorrelatedQuorumViolation(
            f"verdict={verdict!r} passed replica quorum "
            f"({len(matching)}/{n} >= {2*f+1}) but failed lineage quorum "
            f"({distinct_lineages} distinct lineages < {f+1}); "
            f"lineage_counts={dict(lineage_counts)}"
        )

    if replica_quorum and lineage_dominance:
        # Safety is technically satisfied but the margin distribution must be
        # checked: correlated high-confidence votes from one lineage are the
        # signature of a shared systematic error.
        margins = [v.margin for v in matching if v.lineage_id == dominant_lineage]
        spread = max(margins) - min(margins) if margins else 0.0
        if spread < 0.05:
            raise UncorrelatedQuorumViolation(
                f"lineage {dominant_lineage!r} supplied {dominant_count} votes "
                f"for {verdict!r} with margin spread {spread:.4f} < 0.05; "
                f"inter-replica correlation indicates shared blind spot, "
                f"not independent agreement"
            )

    if not replica_quorum:
        raise UncorrelatedQuorumViolation(
            f"verdict={verdict!r} failed replica quorum: "
            f"{len(matching)}/{n} < {2*f+1}"
        )

    return verdict
