# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-speculative-branch-pruning-from-silently-discarding-the-only-viable-plan-under-miscalibrated-confidence.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-speculative-branch-pruning-from-silently-discarding-the-only-viable-plan-under-miscalibrated-confidence.warrant.json
# Markdown SHA-256:   e27509bf706c3cfd16d583d6f848256d1f1ff724826b25918a2440494ec9ebd9
# Code AST SHA-256:   99282e2d2b34654e4d20f5c9907ba826ed20adaf9bec4fdb9bc0c1d8f8bf30fe
# Verified Classes:   InadmissiblePruneError, Branch
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import math
from dataclasses import dataclass


class InadmissiblePruneError(RuntimeError):
    """Raised when a branch is pruned on scalar EV without adequate calibration evidence."""
    pass


@dataclass
class Branch:
    name: str
    self_confidence: float      # model self-report, NOT used directly for pruning
    calibrated_posterior: float | None  # P(success | family, artifact_class); None if uncalibrated
    payoff: float
    cost: float                 # measured critical-path cost, not cache-biased estimate
    family: str
    has_artifact: bool = False


def expected_value(b: Branch) -> float:
    conf = b.calibrated_posterior if b.calibrated_posterior is not None else b.self_confidence
    return (conf * b.payoff) / max(b.cost, 1e-9)


def prune(branches: list[Branch], calibration_uncertainty: dict[str, float],
          keep_k: int = 2) -> list[Branch]:
    """
    Prune only when:
      - calibration posterior exists for the branch family, AND
      - at least one branch has produced a verifiable artifact, AND
      - EV gap between survivor and pruned exceeds calibration uncertainty * payoff.
    Otherwise retain (defer to first artifact).
    """
    if not any(b.has_artifact for b in branches):
        # Step-0 pruning is inadmissible: defer.
        return branches

    ranked = sorted(branches, key=expected_value, reverse=True)
    survivors = ranked[:keep_k]
    pruned = ranked[keep_k:]

    for p in pruned:
        if p.calibrated_posterior is None:
            raise InadmissiblePruneError(
                f"branch {p.name} in family {p.family!r} has no calibrated posterior; "
                f"self-report {p.self_confidence} is not admissible for pruning"
            )
        u = calibration_uncertainty.get(p.family)
        if u is None:
            raise InadmissiblePruneError(
                f"no calibration uncertainty recorded for family {p.family!r}; "
                f"cannot bound EV gap for branch {p.name}"
            )
        ev_gap = expected_value(survivors[-1]) - expected_value(p)
        if ev_gap <= u * p.payoff:
            raise InadmissiblePruneError(
                f"branch {p.name} EV gap {ev_gap:.3f} does not exceed "
                f"calibration uncertainty {u:.3f} * payoff {p.payoff:.3f}; "
                f"prune is statistically unjustified"
            )
    return survivors
