# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-distinguish-salience-score-saturation-from-genuine-context-exhaustion-during-in-place-rewriting-under-a-token-budget.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-distinguish-salience-score-saturation-from-genuine-context-exhaustion-during-in-place-rewriting-under-a-token-budget.warrant.json
# Markdown SHA-256:   b78482e6d66a51ffd0ead6ec77fc2ca37d7f6af411137ab96568ed1de5c2495f
# Code AST SHA-256:   a4de3ee391a05994a7b2427ecbdd7e8832c6ec490c59547d32615372e17f313b
# Verified Classes:   SalienceSaturationError, Span
# Defensive Guards:   1 fail-closed invariants (zero external deps)

import statistics
from dataclasses import dataclass


class SalienceSaturationError(RuntimeError):
    """Raised when a rewrite is requested but the salience scorer cannot
    separate retained from dropped spans, making in-place eviction unsafe."""


@dataclass
class Span:
    span_id: str
    tokens: int
    salience: float


RETAINED_SPREAD_FLOOR = 0.05   # internal spread of retained cluster
SEPARATION_FLOOR = 0.10        # gap between retained and dropped clusters


def plan_rewrite(spans: list[Span], token_budget: int) -> list[Span]:
    """Return the spans to retain. Refuses (raises) if the scorer is saturated."""
    ranked = sorted(spans, key=lambda s: s.salience, reverse=True)

    retained, used = [], 0
    for span in ranked:
        if used + span.tokens > token_budget:
            break
        retained.append(span)
        used += span.tokens

    dropped = [s for s in ranked if s not in retained]

    # Exhaustion is legitimate: nothing meaningful was dropped.
    if not dropped:
        return retained

    retained_scores = [s.salience for s in retained]
    dropped_scores = [s.salience for s in dropped]

    retained_spread = (
        statistics.pstdev(retained_scores) if len(retained_scores) > 1 else 0.0
    )
    separation = min(retained_scores) - max(dropped_scores)

    if retained_spread < RETAINED_SPREAD_FLOOR or separation < SEPARATION_FLOOR:
        raise SalienceSaturationError(
            f"rewrite not licensed: retained_spread={retained_spread:.4f} "
            f"(floor {RETAINED_SPREAD_FLOOR}), separation={separation:.4f} "
            f"(floor {SEPARATION_FLOOR}). Scorer saturated on "
            f"{len(retained)} spans; in-place eviction would fall back to "
            f"tie-break order. Widen candidate pool or re-weight scorer."
        )

    return retained


def rewrite_in_place(buffer: list[Span], token_budget: int) -> list[Span]:
    """Mutate the buffer to the licensed retained set, or raise untouched."""
    retained = plan_rewrite(buffer, token_budget)  # may raise
    buffer[:] = retained                           # only reached if licensed
    return buffer
