# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-bound-learned-retention-scoring-against-rewrite-budgets-before-a-self-editing-context-policy-silently-evicts-the-very-constrain.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-bound-learned-retention-scoring-against-rewrite-budgets-before-a-self-editing-context-policy-silently-evicts-the-very-constrain.warrant.json
# Markdown SHA-256:   50b23ad058ee05dcb82c783e8e3891e8e92c68effd88e002224abc0faa0b396d
# Code AST SHA-256:   3d5dc9f60d08a3bb0b5509f432f8236c913c5ef4c9f501a594267d5e8794bf77
# Verified Classes:   InvariantEvictionError, Segment
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass


class InvariantEvictionError(RuntimeError):
    """Raised when a budget-constrained rewrite would evict an invariant segment."""
    pass


@dataclass(frozen=True)
class Segment:
    id: str
    tokens: int
    score: float
    invariant: bool = False


def plan_rewrite(segments: list[Segment], budget: int) -> list[Segment]:
    """
    Select segments to retain under `budget`, maximizing summed retention score,
    but NEVER evicting an invariant segment (constraints, identity, warrants).

    Raises InvariantEvictionError if the budget cannot accommodate the invariant
    class plus the best non-invariant fill -- the caller must relieve the budget
    or halt; it must not proceed with a rewrite that drops a guardrail.
    """
    invariants = [s for s in segments if s.invariant]
    optional = sorted(
        (s for s in segments if not s.invariant),
        key=lambda s: s.score,
        reverse=True,
    )

    invariant_tokens = sum(s.tokens for s in invariants)
    if invariant_tokens > budget:
        raise InvariantEvictionError(
            f"invariant class needs {invariant_tokens} tokens but rewrite budget "
            f"is {budget}; refusing to evict guardrails to satisfy budget"
        )

    retained = list(invariants)
    remaining = budget - invariant_tokens
    for seg in optional:
        if seg.tokens <= remaining:
            retained.append(seg)
            remaining -= seg.tokens

    # Defensive re-check: the invariant class must survive the optimizer intact.
    retained_ids = {s.id for s in retained}
    for inv in invariants:
        if inv.id not in retained_ids:
            raise InvariantEvictionError(
                f"invariant segment {inv.id!r} was evicted by rewrite optimizer"
            )
    return retained
