# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-self-editing-context-policies-from-evicting-the-load-bearing-observation-during-a-budgeted-rewrite.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-self-editing-context-policies-from-evicting-the-load-bearing-observation-during-a-budgeted-rewrite.warrant.json
# Markdown SHA-256:   e0e399fda7192bb6e298d15108c1058a22a8a63ab519c59108ff6c6c223edfda
# Code AST SHA-256:   a5d06441a93b5a9cbb6f12ff2307c9a3bdee6980a9d194247a148cf5274ca121
# Verified Classes:   EvictionInvariantViolation, Provenance, Span, ContextPolicy
# Defensive Guards:   5 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from enum import Enum
from typing import Optional


class EvictionInvariantViolation(RuntimeError):
    """Raised when a rewrite pass would evict a non-reconstructible span."""
    pass


class Provenance(Enum):
    RECONSTRUCTIBLE = "reconstructible"   # idempotent read of immutable resource
    SIDE_EFFECTING = "side_effecting"     # mutation / non-idempotent call
    EPHEMERAL = "ephemeral"               # time-sensitive, non-reproducible


@dataclass
class Span:
    span_id: str
    tokens: int
    provenance: Provenance
    salience: float = 0.0                 # model-assigned, advisory only
    pinned: bool = False


@dataclass
class ContextPolicy:
    budget: int
    pinned: list[Span] = field(default_factory=list)
    evictable: list[Span] = field(default_factory=list)

    def ingest(self, span: Span) -> None:
        if span.provenance is Provenance.RECONSTRUCTIBLE:
            self.evictable.append(span)
        else:
            # Provenance, not salience, decides pinning.
            span.pinned = True
            self.pinned.append(span)

    def rewrite(self, target_tokens: int) -> list[str]:
        """Evict lowest-salience reconstructible spans until under target.

        Refuses to touch pinned spans. Fails closed if pins alone exceed budget.
        """
        pinned_tokens = sum(s.tokens for s in self.pinned)
        if pinned_tokens > self.budget:
            # Correct action: escalate/checkpoint, never relax a pin.
            raise EvictionInvariantViolation(
                f"pinned spans consume {pinned_tokens} > budget {self.budget}; "
                f"checkpoint and re-scope instead of evicting a pin"
            )

        current = pinned_tokens + sum(s.tokens for s in self.evictable)
        evicted: list[str] = []
        for span in sorted(self.evictable, key=lambda s: s.salience):
            if current <= target_tokens:
                break
            if span.pinned:  # defensive: pins must never reach this list
                raise EvictionInvariantViolation(
                    f"pinned span {span.span_id} found in evictable pool"
                )
            if span.provenance is not Provenance.RECONSTRUCTIBLE:
                raise EvictionInvariantViolation(
                    f"span {span.span_id} provenance={span.provenance.value} "
                    f"is not reconstructible; eviction would lose unrecoverable state"
                )
            current -= span.tokens
            evicted.append(span.span_id)

        if current > target_tokens:
            raise EvictionInvariantViolation(
                f"cannot reach target {target_tokens}: pinned floor is {current}"
            )
        self.evictable = [s for s in self.evictable if s.span_id not in evicted]
        return evicted


def demo() -> None:
    policy = ContextPolicy(budget=32_000)
    policy.ingest(Span("sys", 400, Provenance.RECONSTRUCTIBLE, salience=0.99))
    # The load-bearing low-salience observation:
    policy.ingest(Span("migration_0042", 1_900, Provenance.SIDE_EFFECTING, salience=0.11))
    policy.ingest(Span("chatter_12", 800, Provenance.RECONSTRUCTIBLE, salience=0.05))

    evicted = policy.rewrite(target_tokens=30_000)
    assert "migration_0042" not in evicted, "load-bearing span evicted"

    # Force the failure path: pins alone exceed budget.
    policy.ingest(Span("huge_mutation_log", 40_000, Provenance.SIDE_EFFECTING))
    try:
        policy.rewrite(target_tokens=30_000)
    except EvictionInvariantViolation as exc:
        print(f"correctly failed closed: {exc}")


if __name__ == "__main__":
    demo()
