# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-bound-speculative-branch-fan-out-before-byzantine-merge-quorum-collapses-into-silent-majority-poisoning.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-bound-speculative-branch-fan-out-before-byzantine-merge-quorum-collapses-into-silent-majority-poisoning.warrant.json
# Markdown SHA-256:   68dc548b69bd33ad2d5dc71e4d0e39ff4f2563fe4fa53ea0d9dbf45382f712ba
# Code AST SHA-256:   65d8aa5dee47d479029ab4d2ccc3a69be41459e6430c7ecf56f629608ac261c9
# Verified Classes:   InadmissibleQuorumError, BranchVerdict, MergePolicy
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Iterable


class InadmissibleQuorumError(RuntimeError):
    """Raised when a merge quorum is reached by a coalition that is not admissible."""


@dataclass(frozen=True)
class BranchVerdict:
    branch_id: str
    verdict: str          # e.g. normalized value
    state_hash: str       # commits to full observation: endpoint, epoch, response bytes
    dependency_edges: frozenset[str]  # shared upstream deps (cache id, endpoint id, seed)


@dataclass(frozen=True)
class MergePolicy:
    quorum_k: int
    freshness_epoch: str
    correctness_fields: frozenset[str]  # fields the task's predicate references


def merge_speculative_verdicts(
    verdicts: Iterable[BranchVerdict],
    policy: MergePolicy,
    canonicalized_fields: frozenset[str],
) -> str:
    verdicts = list(verdicts)

    # Invariant 1: canonicalization must be injective on correctness-relevant fields.
    dropped = policy.correctness_fields - canonicalized_fields
    if dropped:
        raise InadmissibleQuorumError(
            f"canonicalizer drops correctness-relevant fields {sorted(dropped)}; "
            "merge would be plurality vote over a lossy projection"
        )

    # Group by verdict, then by state_hash, to expose correlated coalitions.
    by_verdict: dict[str, list[BranchVerdict]] = {}
    for v in verdicts:
        by_verdict.setdefault(v.verdict, []).append(v)

    for verdict, coalition in by_verdict.items():
        if len(coalition) < policy.quorum_k:
            continue

        # Invariant 2: winning coalition must not share a stale-dependency edge.
        # A shared edge collapses correlated branches into one effective voter.
        edge_counts: dict[str, int] = {}
        for v in coalition:
            for edge in v.dependency_edges:
                edge_counts[edge] = edge_counts.get(edge, 0) + 1
        shared = [e for e, c in edge_counts.items() if c > 1]
        if shared:
            raise InadmissibleQuorumError(
                f"quorum for verdict {verdict!r} reached by coalition sharing "
                f"dependency edges {shared}; effective independent voters "
                f"{len(coalition) - sum(edge_counts[e] - 1 for e in shared)} "
                f"< k={policy.quorum_k}"
            )

        # Invariant 3: every member's state_hash must attest the freshness epoch.
        for v in coalition:
            if policy.freshness_epoch not in v.state_hash:
                raise InadmissibleQuorumError(
                    f"branch {v.branch_id} state_hash {v.state_hash!r} does not "
                    f"attest freshness epoch {policy.freshness_epoch!r}"
                )

        return verdict

    raise InadmissibleQuorumError(
        "no admissible coalition reached quorum; re-fan-out with offending "
        "dependency bypassed rather than relaxing k"
    )
