# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-treat-a-heterogeneous-byzantine-quorum-s-adversarial-output-detector-as-unsound-the-detector-majority-inversion-at-the-f-1-witne.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-treat-a-heterogeneous-byzantine-quorum-s-adversarial-output-detector-as-unsound-the-detector-majority-inversion-at-the-f-1-witne.warrant.json
# Markdown SHA-256:   2da1f138d4b40ecb2b43476fa1458e8edea1c617c3ca9485a3198b2a15fc8d84
# Code AST SHA-256:   2df0d9aa20f6949af94e3e2bc1456caea901a73b36803a5fa024efb2988c482b
# Verified Classes:   DetectorQuorumUnsound, RoundView
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Dict


class DetectorQuorumUnsound(RuntimeError):
    """Raised when detector filtering has mutated quorum membership beyond the fault bound."""
    pass


@dataclass
class RoundView:
    submitted_by_family: Dict[str, int]   # family -> count submitted
    survived_by_family: Dict[str, int]    # family -> count surviving detector filter
    faulty_by_family: Dict[str, int]      # known/estimated faulty per family in submitted set
    fp_rate_by_family: Dict[str, float]   # detector false-positive rate per family, last calibration
    fp_spread_threshold: float = 0.15
    fault_bound: float = 1.0 / 3.0


def assert_detector_quorum_sound(view: RoundView) -> None:
    families = set(view.submitted_by_family) | set(view.survived_by_family)
    n_submitted = sum(view.submitted_by_family.values())
    n_survived = sum(view.survived_by_family.values())

    if n_survived == 0:
        raise DetectorQuorumUnsound("detector filtered all votes; quorum undefined")

    # 1. Family-conditional false-positive spread.
    fp_values = [view.fp_rate_by_family.get(f, 0.0) for f in families]
    spread = max(fp_values) - min(fp_values)
    if spread > view.fp_spread_threshold:
        # 2. Rejection correlated with family identity.
        global_rej = 1.0 - (n_survived / n_submitted)
        for f in families:
            submitted = view.submitted_by_family.get(f, 0)
            if submitted == 0:
                continue
            rej_f = 1.0 - (view.survived_by_family.get(f, 0) / submitted)
            if rej_f > global_rej + 2.0 * (global_rej ** 0.5) / (submitted ** 0.5) + 1e-9:
                raise DetectorQuorumUnsound(
                    f"detector rejection correlated with family {f!r}: "
                    f"rej={rej_f:.2f} vs global={global_rej:.2f}, fp_spread={spread:.2f}"
                )

    # 3. Post-filter faulty-fraction estimate.
    faulty_survived = 0.0
    for f in families:
        faulty_survived += view.faulty_by_family.get(f, 0)
        # honest members of f may survive with probability (1 - fp_f); estimate residual faults
        submitted = view.submitted_by_family.get(f, 0)
        faulty = view.faulty_by_family.get(f, 0)
        honest = submitted - faulty
        faulty_survived += honest * view.fp_rate_by_family.get(f, 0.0) * 0.0  # honest never faulty
    q_prime = faulty_survived / n_survived

    if q_prime >= view.fault_bound:
        raise DetectorQuorumUnsound(
            f"post-filter faulty fraction {q_prime:.3f} >= bound {view.fault_bound:.3f}; "
            f"surviving set composition {view.survived_by_family} is not BFT-valid"
        )
