# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-reject-a-byzantine-quorum-commit-when-hallucinating-peers-forge-agreement-on-shared-state-mutations.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-reject-a-byzantine-quorum-commit-when-hallucinating-peers-forge-agreement-on-shared-state-mutations.warrant.json
# Markdown SHA-256:   6120fc96724144b82cae1c9f31963e2b2b02fbcdbaccd7e3588c0d148f8314e4
# Code AST SHA-256:   c058caf980011974828ce99940d7bd7dd250b87cc826c7258115c183bb74db1b
# Verified Classes:   CorrelatedQuorumError, Vote
# Defensive Guards:   1 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import FrozenSet


class CorrelatedQuorumError(RuntimeError):
    """Raised when a quorum's affirmative votes lack pairwise-independent evidence."""
    pass


@dataclass(frozen=True)
class Vote:
    agent_id: str
    affirmative: bool
    evidence_sources: FrozenSet[str]  # provenance keys for the cited evidence
    is_self_vote: bool = False
    is_sycophantic: bool = False       # flipped under perceived majority pressure


def independent_quorum(votes: list[Vote], f: int) -> list[str]:
    """
    Return the set of agent_ids forming an independent affirmative quorum,
    or raise CorrelatedQuorumError if fewer than f+1 independent corroborators exist.

    A vote is independent iff:
      - it is affirmative
      - it is not a self-vote by the proposer
      - it is not sycophantic (no independent evidence)
      - its evidence sources are disjoint from every other accepted vote's sources
    """
    affirmative = [
        v for v in votes
        if v.affirmative and not v.is_self_vote and not v.is_sycophantic
    ]

    accepted: list[Vote] = []
    used_sources: set[str] = set()

    for v in affirmative:
        if v.evidence_sources & used_sources:
            # Correlated with an already-accepted vote: collapse, do not count.
            continue
        if not v.evidence_sources:
            # No evidence provenance: cannot establish independence.
            continue
        accepted.append(v)
        used_sources |= v.evidence_sources

    if len(accepted) < f + 1:
        raise CorrelatedQuorumError(
            f"Independent quorum failed: {len(accepted)} independent corroborators "
            f"< required f+1={f + 1}. Raw affirmative count was "
            f"{sum(1 for v in votes if v.affirmative)} but "
            f"{sum(1 for v in votes if v.affirmative) - len(accepted)} votes were "
            f"correlated, self-cast, or sycophantic. Refusing commit."
        )

    return [v.agent_id for v in accepted]


# Replay of the observed incident (f=2, N=7):
incident = [
    Vote("A1", affirmative=False, evidence_sources=frozenset({"idx_fresh:acct"})),
    Vote("A2", affirmative=False, evidence_sources=frozenset({"idx_fresh:acct"})),
    Vote("A3", affirmative=True,  evidence_sources=frozenset(), is_sycophantic=True),
    Vote("A4", affirmative=True,  evidence_sources=frozenset({"idx_stale:acct"})),
    Vote("A5", affirmative=True,  evidence_sources=frozenset({"idx_stale:acct"})),
    Vote("A6", affirmative=True,  evidence_sources=frozenset({"idx_stale:acct"})),
    Vote("A7", affirmative=True,  evidence_sources=frozenset({"proposal:A7"}),
         is_self_vote=True),
]

# This raises CorrelatedQuorumError: 3 stale-index votes collapse to 1,
# the sycophant is excluded, the self-vote is excluded -> 1 independent < f+1=3.
try:
    independent_quorum(incident, f=2)
except CorrelatedQuorumError as e:
    print(f"COMMIT REJECTED: {e}")
