# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-distrust-a-verifier-s-confidence-before-pruning-speculative-branches.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-distrust-a-verifier-s-confidence-before-pruning-speculative-branches.warrant.json
# Markdown SHA-256:   9a3efd6234977046c395fd39b3a9a25930acb6aa3beb7ef53ec53a415427c452
# Code AST SHA-256:   b1219788b99312f9b08183673c1e87aca07f66316b6005d7f01a9006c179a9f1
# Verified Classes:   PruneCalibrationError
# Defensive Guards:   2 fail-closed invariants (zero external deps)

import statistics

class PruneCalibrationError(RuntimeError):
    """Raised when a confidence-based prune would violate the calibration invariant."""
    pass

def select_branches(branches, threshold, sigma, min_keep=2):
    """
    branches: list of dicts with keys 'id', 'score', 'expresses_uncertainty'
    Returns list of branch ids to retain. Raises if the prune would
    delete every uncertainty-bearing branch or act on a noise plateau.
    """
    if not branches:
        raise PruneCalibrationError("no branches to score")

    scores = [b["score"] for b in branches]
    top = max(scores)
    span = top - min(scores)

    # Plateau: scores indistinguishable within verifier noise -> no score-based prune.
    if span < 3 * sigma:
        retained = [b["id"] for b in branches]
        return retained

    # Margin insufficient to trust the threshold.
    if top - threshold < 2 * sigma:
        raise PruneCalibrationError(
            f"top score {top:.3f} within 2*sigma of threshold {threshold:.3f}; "
            "prune would be noise-driven"
        )

    above = [b for b in branches if b["score"] >= threshold]
    below = [b for b in branches if b["score"] < threshold]

    hedged_above = [b for b in above if b["expresses_uncertainty"]]
    hedged_below = [b for b in below if b["expresses_uncertainty"]]

    # Diversity floor: never delete the last uncertainty-bearing branch.
    if not hedged_above and hedged_below:
        rescue = max(hedged_below, key=lambda b: b["score"])
        above = above + [rescue]

    if len(above) < min_keep:
        above = sorted(branches, key=lambda b: b["score"], reverse=True)[:min_keep]

    # Calibration warning: top branch is the least hedged, runner-up the most.
    ordered = sorted(branches, key=lambda b: b["score"], reverse=True)
    if len(ordered) >= 2 and (not ordered[0]["expresses_uncertainty"]
                              and ordered[1]["expresses_uncertainty"]):
        # Retain both; do not let plausibility outrank admitted doubt.
        keep = {ordered[0]["id"], ordered[1]["id"]}
        above = [b for b in branches if b["id"] in keep or b in above]

    return [b["id"] for b in above]
