# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-abort-a-speculative-branch-that-would-have-succeeded-the-verifier-prior-coupling-failure-in-cost-aware-speculative-scheduling.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-abort-a-speculative-branch-that-would-have-succeeded-the-verifier-prior-coupling-failure-in-cost-aware-speculative-scheduling.warrant.json
# Markdown SHA-256:   c7f4f992e35a3d64b4a9b4735f0e4ef518390a5c9b3a31c9a505eb04dc89fc1c
# Code AST SHA-256:   5bb99d8dcbaba66a7c3efcfad678125118f9caeb990c352e88e7603b84698987
# Verified Classes:   Intent, SpeculativePruneError, Branch
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from enum import Enum
from typing import Optional


class Intent(Enum):
    CONFIRM = "confirm"
    DISCONFIRM = "disconfirm"
    EXPLORE = "explore"


class SpeculativePruneError(RuntimeError):
    """Raised when a prune decision violates the intent-spanning invariant."""
    pass


@dataclass
class Branch:
    branch_id: str
    intent: Intent
    verifier_score: float          # P_success as emitted by verifier model
    est_remaining_cost: float      # point estimate, branch-type conditioned
    u_success: float
    u_disconfirm: float            # value of failing informatively
    pending_side_effect: bool
    posterior_shift_if_completed: float


def expected_value(b: Branch) -> float:
    p = b.verifier_score
    return (
        p * b.u_success
        + (1.0 - p) * b.u_disconfirm
        - b.est_remaining_cost
    )


def should_prune(
    branch: Branch,
    surviving: list[Branch],
    posterior_stable: bool,
    epsilon: float = 0.02,
    disconfirm_reservation_remaining: int = 1,
) -> bool:
    # Reversibility guard: never prune a branch with a committed side effect.
    if branch.pending_side_effect:
        return False

    # Intent-spanning invariant: keep at least one disconfirming branch
    # until the task posterior has stabilized.
    if branch.intent is Intent.DISCONFIRM:
        if not posterior_stable and disconfirm_reservation_remaining > 0:
            return False
        # Even if stable, a disconfirming branch with high informative value
        # must not be pruned on verifier score alone.
        if branch.u_disconfirm > epsilon:
            return False

    v = expected_value(branch)
    if v >= 0.0:
        return False

    # Selection-induced prior shift guard: if this branch's intent differs
    # from the surviving set's modal intent, the verifier score is suspect.
    if surviving:
        modal_intent = max(
            {i: sum(1 for s in surviving if s.intent is i) for i in Intent}.items(),
            key=lambda kv: kv[1],
        )[0]
        if branch.intent is not modal_intent and branch.verifier_score < 0.5:
            raise SpeculativePruneError(
                f"branch {branch.branch_id} intent={branch.intent.value} "
                f"differs from modal={modal_intent.value} and would be pruned "
                f"on contaminated verifier score {branch.verifier_score:.3f}; "
                f"recompute value with intent-conditioned calibration or "
                f"consume disconfirm reservation"
            )

    return True


def schedule_prune(
    branches: list[Branch],
    posterior_stable: bool,
    disconfirm_reservation: int,
) -> list[str]:
    surviving: list[Branch] = []
    pruned: list[str] = []
    reservation = disconfirm_reservation
    for b in sorted(branches, key=expected_value, reverse=True):
        if should_prune(b, surviving, posterior_stable, disconfirm_reservation_remaining=reservation):
            pruned.append(b.branch_id)
            if b.intent is Intent.DISCONFIRM:
                reservation = max(0, reservation - 1)
        else:
            surviving.append(b)
    if not any(b.intent is Intent.DISCONFIRM for b in surviving) and not posterior_stable:
        raise SpeculativePruneError(
            "intent-spanning invariant violated: no disconfirming branch "
            "survives while posterior is unstable"
        )
    return pruned
