# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-halt-in-place-context-rewriting-when-the-eviction-predicate-is-non-monotonic-across-the-rewrite-pass.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-halt-in-place-context-rewriting-when-the-eviction-predicate-is-non-monotonic-across-the-rewrite-pass.warrant.json
# Markdown SHA-256:   16cd7bcaaa79e57be7571429fdfbfea0158076de91ac7289e371d883ffe6889f
# Code AST SHA-256:   2e931067fa61434685f78d0d34f3be9d5bb128beed598e84c5c0b957cad68bd9
# Verified Classes:   NonMonotonicEvictionError, Span
# Defensive Guards:   1 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Callable


class NonMonotonicEvictionError(RuntimeError):
    """Raised when an in-place context rewrite evicts a span whose liveness
    depended on another span evicted earlier in the same pass."""


@dataclass
class Span:
    id: str
    text: str
    anchors: set[str] = field(default_factory=set)  # ids this span supports


def snapshot_evict(
    buffer: list[Span],
    is_stale: Callable[[Span, list[Span]], bool],
) -> list[Span]:
    """Sound compaction: score against a frozen snapshot, apply as set-difference."""
    snapshot = list(buffer)
    evict_ids = {s.id for s in snapshot if is_stale(s, snapshot)}
    rewritten = [s for s in snapshot if s.id not in evict_ids]

    # Fixpoint check: no span may become newly stale after the apply.
    newly_orphaned = [
        s.id for s in rewritten
        if is_stale(s, rewritten) and not is_stale(s, snapshot)
    ]
    if newly_orphaned:
        raise NonMonotonicEvictionError(
            f"eviction predicate non-monotonic: spans {newly_orphaned} "
            f"became stale only after eviction; rewrite unsound, "
            f"escalate to full re-summarization"
        )
    return rewritten


def in_place_evict(
    buffer: list[Span],
    is_stale: Callable[[Span, list[Span]], bool],
) -> list[Span]:
    """Unsound: re-scores against the mutating buffer. Kept to demonstrate the bug."""
    working = list(buffer)
    for span in reversed(working):  # reverse traversal: the S11-before-S7 hazard
        if is_stale(span, working):
            working.remove(span)
            # NOTE: 'working' is now mutated; the next is_stale call sees a
            # buffer missing the span we just removed. If span supported a
            # later-scanned span's liveness, that span is now orphaned.
    # No fixpoint check: orphaned live spans silently survive or silently drop.
    return working
