# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-a-heterogeneous-quorum-s-byzantine-verdict-as-decision-bearing-rather-than-as-a-sampling-artifact.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-a-heterogeneous-quorum-s-byzantine-verdict-as-decision-bearing-rather-than-as-a-sampling-artifact.warrant.json
# Markdown SHA-256:   b89d92ccf727ad99c4ec052612e2de3f62be3f14d6d9eb9e996d20e8fcd53f6f
# Code AST SHA-256:   d61fa17cb3be349b7e306d072cc5431246ce208c00ce1472049a10af8e759997
# Verified Classes:   CorrelatedQuorumError, Vote
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass, field
from typing import Sequence


class CorrelatedQuorumError(RuntimeError):
    """Raised when a quorum verdict is a sampling artifact, not decision-bearing evidence."""
    pass


@dataclass
class Vote:
    member_id: str
    verdict: str                 # "VALID" | "INVALID"
    evidence_sources: tuple      # identifiers of retrieval artifacts / tool outputs cited
    reasoning_trace: str
    reexecution_conclusion: str  # conclusion reached under fresh context


def _trace_similarity(a: str, b: str) -> float:
    # Cheap normalized similarity proxy; swap for edit distance in production.
    sa, sb = set(a.split()), set(b.split())
    if not sa and not sb:
        return 1.0
    return len(sa & sb) / len(sa | sb)


def evaluate_quorum(
    votes: Sequence[Vote],
    n: int,
    f: int,
    min_distinct_sources: int,
    trace_similarity_ceiling: float = 0.85,
    reexec_stability_floor: float = 1.0 - (1.0 / (3 * f + 1)),
) -> str:
    """Return 'COMMIT', 'ESCALATE', or 'RESAMPLE'.

    Enforces the three validity conditions: input-channel independence,
    reasoning-trace divergence, and re-execution stability.
    """
    if len(votes) != n:
        raise CorrelatedQuorumError(
            f"quorum size mismatch: expected {n} votes, received {len(votes)}"
        )

    # Collapse coalitions whose reasoning traces are near-identical.
    collapsed: list[Vote] = []
    for v in votes:
        merged = False
        for c in collapsed:
            if _trace_similarity(v.reasoning_trace, c.reasoning_trace) >= trace_similarity_ceiling:
                merged = True
                break
        if not merged:
            collapsed.append(v)

    valid = [v for v in collapsed if v.verdict == "VALID"]
    invalid = [v for v in collapsed if v.verdict == "INVALID"]

    if not valid and not invalid:
        raise CorrelatedQuorumError("all votes collapsed to empty coalition; no evidence")

    deciding = valid if len(valid) >= len(invalid) else invalid
    threshold = (2 * n) // 3 + 1

    if len(deciding) < threshold:
        return "ESCALATE"

    # Condition 1: input-channel independence.
    sources = set()
    for v in deciding:
        sources.update(v.evidence_sources)
    if len(sources) < min_distinct_sources:
        # Coalition exceeds its independent evidence base: sampling artifact.
        return "RESAMPLE"

    # Condition 2: divergence floor already enforced by collapsing above.

    # Condition 3: re-execution stability.
    stable = sum(
        1 for v in deciding if v.reexecution_conclusion == v.verdict
    ) / len(deciding)
    if stable < reexec_stability_floor:
        raise CorrelatedQuorumError(
            f"re-execution stability {stable:.3f} below floor {reexec_stability_floor:.3f}; "
            "agreement is not reproducible and cannot authorize commit"
        )

    return "COMMIT"
