# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-treat-a-quorum-certificate-signed-by-heterogeneous-peers-when-their-vote-weight-functions-disagree-about-what-distinct-means.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-treat-a-quorum-certificate-signed-by-heterogeneous-peers-when-their-vote-weight-functions-disagree-about-what-distinct-means.warrant.json
# Markdown SHA-256:   9069304b943eec5a41864d6c026ebc57ca24dfda570959725d038f6144007d4a
# Code AST SHA-256:   cf069a26b4b46c7fefc7360da01ea713d79819344ab845198ccb592f75db5cd5
# Verified Classes:   Vote, QuorumCertificateError
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Iterable

@dataclass(frozen=True)
class Vote:
    provenance_key: str      # model_family + seed + system_prompt_hash
    proposition_cluster: int # semantic-equivalence cluster id
    weight: float            # self-reported confidence, honest

class QuorumCertificateError(RuntimeError):
    pass

def certify_quorum(votes: Iterable[Vote], f: int) -> float:
    """
    Return certified distinct weight, or raise if a certificate cannot be
    honestly issued. Distinctness = independent provenance key AND
    independent proposition. Weight per provenance key is capped at that
    key's single-vote maximum to prevent correlated over-sampling.
    """
    votes = list(votes)
    if not votes:
        raise QuorumCertificateError("empty vote set: no certificate possible")

    # Cap weight per provenance key at its max single-vote weight.
    per_key_max: dict[str, float] = {}
    for v in votes:
        per_key_max[v.provenance_key] = max(per_key_max.get(v.provenance_key, 0.0), v.weight)

    # A provenance key contributes only if it is the *first* key to reach
    # a given proposition cluster; later keys on the same cluster are
    # independent agreement and ARE counted (that is the strong signal).
    # But the same key appearing on multiple clusters is collapsed to one.
    seen_key: set[str] = set()
    certified = 0.0
    for v in votes:
        if v.provenance_key in seen_key:
            continue  # correlated repeat of an already-counted trace
        seen_key.add(v.provenance_key)
        certified += per_key_max[v.provenance_key]

    threshold = 2 * f + 1
    if certified < threshold:
        raise QuorumCertificateError(
            f"distinct-key weight {certified:.2f} < quorum {threshold}: "
            f"keys={sorted(seen_key)}; halt, do not fall through to default"
        )
    return certified
