# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-prunes-a-memory-it-is-still-reasoning-over-the-self-eviction-read-after-free-in-model-driven-context-rewriting.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-prunes-a-memory-it-is-still-reasoning-over-the-self-eviction-read-after-free-in-model-driven-context-rewriting.warrant.json
# Markdown SHA-256:   d30a2047abd4b381d64e0ed50b5a1c8f2735b4602bad53bc5ed1a6a4c67283a5
# Code AST SHA-256:   ff9c1c19fa551e5082464416395232016f43b222538ef2d93949600438f0b4a8
# Verified Classes:   ReadAfterFreeEviction, Span
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field


class ReadAfterFreeEviction(RuntimeError):
    """Raised when an eviction removes a span that surviving spans depend on."""
    pass


@dataclass
class Span:
    span_id: str
    text: str
    salience: float
    introduces: set = field(default_factory=set)   # symbols/constraints this span defines
    depends_on: set = field(default_factory=set)   # symbols this span relies on


CONSTRAINT_MARKERS = ("must", "never", "not ", "Decimal", "unit:", "type:")


def is_constraint_bearing(span: Span) -> bool:
    low = span.text.lower()
    return any(m.lower() in low for m in CONSTRAINT_MARKERS)


def commit_eviction(spans, evict_ids, *, intra_generation: bool) -> list:
    """Apply an eviction only if dependency closure holds on the post-eviction window.

    Mirrors the article's guardrail: closure is checked on the *materialized*
    post-eviction set, and constraint spans are pinned when pruning mid-generation.
    """
    if intra_generation and any(
        is_constraint_bearing(s) for s in spans if s.span_id in evict_ids
    ):
        # Pinned-span guardrail: refuse to evict load-bearing constraints mid-decode.
        raise ReadAfterFreeEviction(
            "intra-generation eviction of constraint-bearing span; "
            "defer to generation boundary or summarize-in-place"
        )

    survivors = [s for s in spans if s.span_id not in evict_ids]
    available = set().union(*(s.introduces for s in survivors)) if survivors else set()

    for s in survivors:
        missing = s.depends_on - available
        if missing:
            raise ReadAfterFreeEviction(
                f"span {s.span_id!r} depends on evicted symbols {sorted(missing)}; "
                "dependency closure violated on post-eviction window"
            )
    return survivors


def compact(spans, evict_ids, *, intra_generation: bool):
    try:
        return commit_eviction(spans, evict_ids, intra_generation=intra_generation)
    except ReadAfterFreeEviction:
        # Fallback: summarize rather than delete, preserving constraints.
        raise
