# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-refuse-to-treat-a-2f-1-quorum-certificate-as-sufficient-evidence-of-task-commitment-when-the-committing-peers-s.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-refuse-to-treat-a-2f-1-quorum-certificate-as-sufficient-evidence-of-task-commitment-when-the-committing-peers-s.warrant.json
# Markdown SHA-256:   c4f53230fcde0e0aebee3321800cc5e289a65bb88f52ad4978c957cbaa8f6ca1
# Code AST SHA-256:   2cb3ecda1da90c52a81f2fe0522970650ed2b33046c51be9713f590acf3e9055
# Verified Classes:   CorrelatedEvidenceCommitError, Vote
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Iterable


class CorrelatedEvidenceCommitError(RuntimeError):
    """Raised when a signature quorum is satisfied but lineage-deduped support is below f+1."""


@dataclass(frozen=True)
class Vote:
    voter_id: str
    evidence_hash: str
    verdict: str
    premise_snapshot: int


def resolve_lineage_root(evidence_hash: str) -> str | None:
    # In production: look up the index's chunk-lineage map. Returns the source
    # document ID (lineage root) or None for orphan/fabricated hashes.
    return LINEAGE_MAP.get(evidence_hash)


def verify_commitment(
    votes: Iterable[Vote],
    f: int,
    premise_snapshot: int,
) -> str:
    votes = list(votes)
    quorum = 2 * f + 1
    if len(votes) < quorum:
        raise CorrelatedEvidenceCommitError(
            f"signature quorum not met: {len(votes)} < {quorum}"
        )

    # Resolve each vote to a lineage root; orphans are untrustworthy provenance.
    rooted: list[tuple[Vote, str]] = []
    for v in votes:
        if v.premise_snapshot > premise_snapshot:
            # Evidence drawn from a snapshot newer than the task premise.
            continue
        root = resolve_lineage_root(v.evidence_hash)
        if root is None:
            continue
        rooted.append((v, root))

    # Count distinct lineage roots, excluding the f voters with maximal overlap.
    # Overlap proxy: number of peers sharing the same root.
    from collections import Counter
    root_counts = Counter(root for _, root in rooted)
    # Drop the f voters belonging to the most-shared roots.
    excluded = 0
    surviving_roots: set[str] = set()
    for v, root in sorted(rooted, key=lambda x: -root_counts[x[1]]):
        if excluded < f and root_counts[root] > 1:
            excluded += 1
            continue
        surviving_roots.add(root)

    independent_support = len(surviving_roots)
    if independent_support < f + 1:
        raise CorrelatedEvidenceCommitError(
            f"lineage-deduped support {independent_support} < f+1={f + 1}; "
            f"signature quorum {len(votes)} is not independent evidence"
        )

    approvals = sum(1 for v, _ in rooted if v.verdict == "approve")
    return "commit" if approvals >= f + 1 else "abort"


LINEAGE_MAP = {
    "h1": "doc-7",  # voter A and B both resolve to doc-7 via different chunkings
    "h2": "doc-7",
    "h3": "doc-99",
}

# A, B honest-but-correlated; C is the adversary. Three signatures, one logical source.
votes = [
    Vote("A", "h1", "approve", premise_snapshot=10),
    Vote("B", "h2", "approve", premise_snapshot=10),
    Vote("C", "h3", "approve", premise_snapshot=10),
]
verify_commitment(votes, f=1, premise_snapshot=10)  # raises CorrelatedEvidenceCommitError
