# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-refuse-to-commit-a-result-under-byzantine-quorum-the-phantom-quorum-invariant-in-multi-agent-result-agreement.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-refuse-to-commit-a-result-under-byzantine-quorum-the-phantom-quorum-invariant-in-multi-agent-result-agreement.warrant.json
# Markdown SHA-256:   c1a22720de4e0f90fee70cc3d954bdc9e9274cca71cd5a18e2fd6ac016fce8f5
# Code AST SHA-256:   3a4ca592547b377c3c3d1139fc766516293988d9366e014927ab4bb0e8c833f0
# Verified Classes:   PhantomQuorumError, Vote
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Sequence


class PhantomQuorumError(RuntimeError):
    """Raised when matching votes meet the size quorum but collapse into too few independence classes."""
    pass


@dataclass(frozen=True)
class Vote:
    agent_id: str
    value: str
    checkpoint_hash: str
    cache_key: str
    template_hash: str

    def provenance(self) -> tuple[str, str, str]:
        return (self.checkpoint_hash, self.cache_key, self.template_hash)


def commit_result(votes: Sequence[Vote], n: int, f: int) -> str:
    """Commit a result only if a size quorum AND an independence quorum are both satisfied."""
    if n != len(votes):
        raise PhantomQuorumError(f"vote count {len(votes)} != expected swarm size {n}")

    # Group matching votes by value.
    by_value: dict[str, list[Vote]] = {}
    for v in votes:
        by_value.setdefault(v.value, []).append(v)

    size_quorum = 2 * f + 1
    independence_quorum = f + 1

    for value, matching in by_value.items():
        if len(matching) < size_quorum:
            continue

        # Size quorum met. Now check independence.
        classes = {v.provenance() for v in matching}
        if len(classes) < independence_quorum:
            raise PhantomQuorumError(
                f"phantom quorum for value {value!r}: "
                f"{len(matching)} matching votes but only {len(classes)} "
                f"independence classes (need {independence_quorum}); "
                f"matching votes share provenance and are not independent attestations"
            )
        return value

    raise PhantomQuorumError(
        f"no value reached size quorum {size_quorum}; "
        f"vote distribution: { {k: len(v) for k, v in by_value.items()} }"
    )


def run_swarm_commit(votes: Sequence[Vote], n: int, f: int) -> str:
    try:
        return commit_result(votes, n, f)
    except PhantomQuorumError as e:
        # Escalate to diversified re-execution rather than committing a phantom quorum.
        raise PhantomQuorumError(
            f"commit refused; escalating to diversified re-execution: {e}"
        ) from e
