# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-speculative-branch-pruning-from-silently-dropping-the-winning-coalition-arm.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-speculative-branch-pruning-from-silently-dropping-the-winning-coalition-arm.warrant.json
# Markdown SHA-256:   dfce692abdcb854f6ca7ba125f710607047d1e266ba9ca6b1d49b4959f1da835
# Code AST SHA-256:   b0f4d402b98956600cc676fc9784910c4f56534452e5cd37cbed0388d7aefd88
# Verified Classes:   UnsoundPruneError, Arm
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Callable, Dict, List, Set


class UnsoundPruneError(RuntimeError):
    """Raised when a pruning heuristic would eliminate an arm outside its validity region."""


@dataclass
class Arm:
    name: str
    score_fn: Callable[[float], float]          # elapsed_ms -> current partial score
    monotone_in_time: bool                      # score provably non-increasing with elapsed time
    depends_on: Set[str]                        # arms whose verdict this arm consumes
    deadline_ms: float


def prune_arms(
    arms: List[Arm],
    elapsed_ms: float,
    threshold: float,
    lower_bound: Dict[str, float],
) -> List[str]:
    """
    Return the names of arms that may be soundly pruned at this point.

    Invariant enforced: an arm may be pruned only if
      (1) its score function is monotone non-increasing in time, AND
      (2) it has no downstream dependents in the coalition DAG, AND
      (3) its current partial score is below threshold.
    Any violation of (1) or (2) raises UnsoundPruneError instead of
    silently dropping the arm.
    """
    dependent_names: Set[str] = set()
    for a in arms:
        dependent_names |= a.depends_on

    prunable: List[str] = []
    for a in arms:
        partial = a.score_fn(elapsed_ms)
        if partial >= threshold:
            continue
        if not a.monotone_in_time:
            raise UnsoundPruneError(
                f"arm {a.name!r} score is non-monotone in time; "
                f"partial={partial:.3f} at t={elapsed_ms}ms is not an upper bound "
                f"on final score (late-evidence arm), cannot prune"
            )
        if a.name in dependent_names:
            raise UnsoundPruneError(
                f"arm {a.name!r} has downstream dependents in the coalition DAG; "
                f"pruning it would invalidate the verdicts of {sorted(dependent_names & {a.name})}"
            )
        if partial > lower_bound.get(a.name, float("-inf")):
            raise UnsoundPruneError(
                f"arm {a.name!r} partial score {partial:.3f} exceeds its own lower bound "
                f"{lower_bound[a.name]:.3f}; dominance certificate not established"
            )
        prunable.append(a.name)
    return prunable
