# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-speculative-agent-branch-pruning-has-silently-discarded-the-winning-branch-under-consensus-derived-confidence.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-speculative-agent-branch-pruning-has-silently-discarded-the-winning-branch-under-consensus-derived-confidence.warrant.json
# Markdown SHA-256:   fcb8f00762e4469f3f8978f6887cf9ce9f7272b4ceb2eb8805f2f32584f1b846
# Code AST SHA-256:   2d101a49a3520b3c8f18a73ba62d6c8a955cbe8454b2ec5e82ee40993d07a0d3
# Verified Classes:   PruningInvariantViolation, Branch
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from statistics import mean, variance


class PruningInvariantViolation(RuntimeError):
    """Raised when a rank-based prune would discard a high-variance or
    uncertified branch, breaking sibling-independence of the pruner."""


@dataclass
class Branch:
    id: int
    votes: list[float]          # per-auditor confidence in [0, 1]
    certified: bool = False     # absolute, population-free admissibility

    @property
    def score(self) -> float:
        return mean(self.votes)

    @property
    def vote_variance(self) -> float:
        return variance(self.votes) if len(self.votes) > 1 else 0.0


def prune_speculative_branches(
    branches: list[Branch],
    keep: int,
    theta: float = 0.75,        # absolute acceptance floor
    sigma2_max: float = 0.16,   # cross-auditor variance ceiling
    k_min: int = 2,
) -> list[Branch]:
    if keep < k_min:
        raise PruningInvariantViolation(
            f"keep={keep} below k_min={k_min}; survivors cannot be certified"
        )

    ranked = sorted(branches, key=lambda b: b.score, reverse=True)
    survivors, pruned = ranked[:keep], ranked[keep:]

    certified = [b for b in survivors if b.certified or b.score >= theta]
    if len(certified) < k_min:
        raise PruningInvariantViolation(
            f"only {len(certified)} survivor(s) clear theta={theta}; "
            f"fork more branches instead of pruning (max_s={survivors[0].score:.3f})"
        )

    for b in pruned:
        if b.vote_variance > sigma2_max:
            raise PruningInvariantViolation(
                f"branch {b.id} pruned at variance {b.vote_variance:.3f} "
                f"> sigma2_max={sigma2_max}; future unsampled, re-score at "
                f"next checkpoint instead"
            )

    survivor_scores = [b.score for b in survivors]
    margin = max(survivor_scores) - sorted(survivor_scores)[len(survivor_scores) // 2]
    if margin < 0.10 and max(survivor_scores) < theta:
        raise PruningInvariantViolation(
            f"survivor margin compressed to {margin:.3f} with max_s "
            f"{max(survivor_scores):.3f} < theta; consensus is mutually "
            f"reinforcing near-duplicates, not confirmation"
        )

    return survivors
