# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-detect-salience-inversion-collapse-when-model-driven-pruning-rewrites-its-own-eviction-criteria.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-detect-salience-inversion-collapse-when-model-driven-pruning-rewrites-its-own-eviction-criteria.warrant.json
# Markdown SHA-256:   4417070c86b24f82591e623fae231eef74fbd604e1855eefe2bea0e9bc3c4b9a
# Code AST SHA-256:   427d601d81ec5b3e49acc36f32afcc8d9b46f8758a7a8150761ab3f9ea5b9e8d
# Verified Classes:   Provenance, Span, SalienceInversionError, ContextPruner
# Defensive Guards:   5 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from enum import Enum


class Provenance(Enum):
    OBSERVED = "observed"      # read directly from source
    INFERRED = "inferred"      # reconstructed from a summary


@dataclass
class Span:
    span_id: str
    t_seen: int
    provenance: Provenance
    salience: float = 0.0
    exact_bytes: str | None = None   # None if only a lossy summary survives


class SalienceInversionError(RuntimeError):
    """Raised when model-driven pruning would evict a span still inside its
    relevance envelope, or when an inferred span is promoted to observed
    without source verification."""


class ContextPruner:
    def __init__(self, horizon: int, eviction_threshold: float = 0.3):
        self.horizon = horizon
        self.tau = eviction_threshold
        self.spans: dict[str, Span] = {}
        self.external_store: dict[str, Span] = {}

    def register(self, span: Span) -> None:
        self.spans[span.span_id] = span

    def _envelope_open(self, span: Span, now: int) -> bool:
        return (now - span.t_seen) <= self.horizon

    def prune(self, now: int, scores: dict[str, float]) -> list[str]:
        """Apply model-generated salience scores. Returns evicted span ids.

        Invariant: a span inside its relevance envelope may be compressed but
        never evicted on salience alone. Eviction requires an external copy.
        """
        evicted: list[str] = []
        for span_id, span in list(self.spans.items()):
            span.salience = scores.get(span_id, 0.0)
            if span.salience >= self.tau:
                continue
            if self._envelope_open(span, now):
                # Inside envelope: salience may schedule compression only.
                # Eviction here is the salience-inversion boundary.
                if span.exact_bytes is None:
                    raise SalienceInversionError(
                        f"span {span_id} scored {span.salience:.2f} below tau "
                        f"but is inside envelope (t_seen={span.t_seen}, "
                        f"now={now}, H={self.horizon}) and has no external copy"
                    )
                # Compress, do not evict: keep verbatim in external store.
                self.external_store[span_id] = span
                continue
            # Outside envelope: eviction permitted, but must be recoverable.
            if span.exact_bytes is None:
                raise SalienceInversionError(
                    f"span {span_id} outside envelope but has no recoverable "
                    f"bytes; eviction would be irreversible"
                )
            self.external_store[span_id] = span
            del self.spans[span_id]
            evicted.append(span_id)
        return evicted

    def promote_inferred(self, span_id: str, source: str) -> Span:
        """An inferred span may gate an action only after source verification."""
        span = self.spans.get(span_id)
        if span is None:
            raise SalienceInversionError(f"span {span_id} not in window")
        if span.provenance is Provenance.INFERRED:
            if span.exact_bytes is None or source not in span.exact_bytes:
                raise SalienceInversionError(
                    f"inferred span {span_id} cannot be promoted: source "
                    f"verification failed (reconstructed signature does not "
                    f"match {source!r})"
                )
            span.provenance = Provenance.OBSERVED
        return span

    def assert_non_degeneracy(self, now: int) -> None:
        """Retained set must contain every span whose envelope is still open."""
        for span_id, span in self.spans.items():
            if self._envelope_open(span, now) and span.exact_bytes is None:
                raise SalienceInversionError(
                    f"non-degeneracy violated: open-envelope span {span_id} "
                    f"survives only as a lossy summary"
                )


def run_pruning_pass(pruner: ContextPruner, now: int, scores: dict[str, float]) -> None:
    pruner.prune(now, scores)
    pruner.assert_non_degeneracy(now)


# --- Reproduction of the observed failure ---

def _reproduce():
    pruner = ContextPruner(horizon=40, eviction_threshold=0.3)
    # Step 12: call site observed verbatim, high salience.
    pruner.register(Span("call_site", t_seen=12, provenance=Provenance.OBSERVED,
                         exact_bytes="util.transform(x, legacy=True)"))
    # Step 24: task focus shifts; scorer rates call site 0.28.
    # No external copy exists and envelope (12+40=52) is still open.
    run_pruning_pass(pruner, now=24, scores={"call_site": 0.28})
    # -> SalienceInversionError: eviction of open-envelope span without copy.


if __name__ == "__main__":
    _reproduce()
