# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-bound-the-salience-weighted-pruning-of-its-own-context-window-when-the-retention-score-is-computed-by-the-same-model-that-later.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-bound-the-salience-weighted-pruning-of-its-own-context-window-when-the-retention-score-is-computed-by-the-same-model-that-later.warrant.json
# Markdown SHA-256:   61ee822cc3723bdb1ae04ed28b542107452eca8eaf4ecf284e1fd7f916d60cd4
# Code AST SHA-256:   45ca6c3f5ce7557b383b45290982c13b4deb1558b4a1ea5ed27d06e8de06a278
# Verified Classes:   PruningInvariantViolation, Span, PruningRound
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Literal


class PruningInvariantViolation(RuntimeError):
    """Raised when a self-editing pruning round would make a prior eviction undetectable."""


Provenance = Literal["reconstructible", "sole_witness", "contradiction"]


@dataclass
class Span:
    span_id: str
    tokens: int
    provenance: Provenance
    reconstruct_path: str | None = None


@dataclass
class PruningRound:
    retained: list[Span]
    evicted: list[Span]
    contradiction_count_before: int
    contradiction_count_after: int


def apply_pruning_round(
    spans: list[Span],
    salience: dict[str, float],
    tau: float = 0.25,
    min_retained_tokens: int = 4000,
) -> PruningRound:
    """Apply a model-proposed salience-based eviction under the pin invariant.

    The salience dict is the model's proposal. It is never trusted to override
    provenance: sole-witness and contradiction spans are pinned after scoring,
    not before, so the scorer cannot condition on the pin-set.
    """
    # 1. Classify by provenance, not by score.
    pinned = [s for s in spans if s.provenance in ("sole_witness", "contradiction")]
    scorable = [s for s in spans if s.provenance == "reconstructible"]

    # 2. A reconstructible span may only be evicted if its reconstruction path
    #    is named. An unnamed path means the eviction is unrecoverable.
    for s in scorable:
        if salience.get(s.span_id, 1.0) < tau and s.reconstruct_path is None:
            raise PruningInvariantViolation(
                f"span {s.span_id!r} scored {salience[s.span_id]:.2f} < tau={tau} "
                f"but has no named reconstruction path; eviction would be silent"
            )

    # 3. Propose evictions from scorable spans only.
    proposed_evict = [s for s in scorable if salience.get(s.span_id, 1.0) < tau]
    proposed_retain = [s for s in scorable if s not in proposed_evict] + pinned

    # 4. Enforce the token floor by evicting lowest-scored reconstructibles first,
    #    never by touching pinned spans.
    total = sum(s.tokens for s in proposed_retain)
    if total < min_retained_tokens:
        proposed_evict.sort(key=lambda s: salience.get(s.span_id, 1.0))
        for s in list(proposed_evict):
            if total >= min_retained_tokens:
                break
            proposed_evict.remove(s)
            proposed_retain.append(s)
            total += s.tokens

    # 5. Contradiction-count monotonicity: the round may not reduce the window's
    #    ability to detect its own prior evictions.
    before = sum(1 for s in spans if s.provenance == "contradiction")
    after = sum(1 for s in proposed_retain if s.provenance == "contradiction")
    if after < before:
        raise PruningInvariantViolation(
            f"pruning round would drop contradiction spans from {before} to {after}; "
            f"this seals a prior eviction error and is rejected"
        )

    return PruningRound(
        retained=proposed_retain,
        evicted=proposed_evict,
        contradiction_count_before=before,
        contradiction_count_after=after,
    )
