# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-rewrites-its-own-context-and-the-rewrite-evicts-the-evidence-that-justified-the-rewrite.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-rewrites-its-own-context-and-the-rewrite-evicts-the-evidence-that-justified-the-rewrite.warrant.json
# Markdown SHA-256:   a4f3aeac2639fd6138d3b95d7722f0fd3d3d7108ce5985ec11c68b93cca4d0a9
# Code AST SHA-256:   5e144940b3b9da7c7694094936d6ca707d7da41f299bb52201829e357bef960d
# Verified Classes:   UnsafeCompactionError, Span, EvictionRecord, ContextStore
# Defensive Guards:   6 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Iterable


class UnsafeCompactionError(RuntimeError):
    """Raised when a self-editing context operation would destroy evidence
    without leaving a resolvable, entity-complete, presence-marked record."""


@dataclass(frozen=True)
class Span:
    span_id: int
    text: str
    entities: frozenset[str]  # symbols, paths, IDs, constants observed in text


@dataclass(frozen=True)
class EvictionRecord:
    span_ids: tuple[int, ...]
    entities: frozenset[str]
    superseded_by: tuple[int, ...]
    resolvable: bool  # backing store still holds the spans


@dataclass
class ContextStore:
    live: dict[int, Span] = field(default_factory=dict)
    cold: dict[int, Span] = field(default_factory=dict)  # resolvable backing store
    records: list[EvictionRecord] = field(default_factory=list)
    pinned: set[int] = field(default_factory=set)  # eviction-record slots

    def validate_and_commit(self, span_ids: Iterable[int], record: EvictionRecord) -> None:
        span_ids = tuple(span_ids)

        # Clause 1: entity completeness. Every entity in the evicted spans must
        # appear in the record. A natural-language gloss will fail this.
        actual_entities: set[str] = set()
        for sid in span_ids:
            if sid not in self.live:
                raise UnsafeCompactionError(f"span {sid} not live; cannot evict")
            actual_entities |= set(self.live[sid].entities)
        missing = actual_entities - set(record.entities)
        if missing:
            raise UnsafeCompactionError(
                f"eviction record omits entities {sorted(missing)}; "
                f"record is a gloss, not an index"
            )

        # Clause 2: resolvability. The record must point at a store that still
        # holds the spans, or the record is a tombstone with no body.
        if not record.resolvable:
            raise UnsafeCompactionError(
                f"eviction of {span_ids} is unresolvable; spans would be lost"
            )

        # Recursive-compaction guard: never evict a pinned record slot.
        if self.pinned & set(span_ids):
            raise UnsafeCompactionError(
                f"attempt to compact pinned eviction records {sorted(self.pinned & set(span_ids))}"
            )

        # Record-first commit: move to cold store, then splice, then write record.
        for sid in span_ids:
            self.cold[sid] = self.live.pop(sid)
        self.records.append(record)

    def resolve(self, entity: str) -> Span | None:
        """Re-fetch the span containing an entity, for the presence-marker path."""
        for sid in self.cold:
            if entity in self.cold[sid].entities:
                return self.cold[sid]
        return None


def compact(store: ContextStore, span_ids: tuple[int, ...], record: EvictionRecord) -> None:
    if not span_ids:
        raise UnsafeCompactionError("empty compaction request")
    store.validate_and_commit(span_ids, record)


# --- Trace of the observed failure, replayed under the guardrail ---
store = ContextStore()
store.live[19] = Span(19, "grep: parse_legacy_header defined in legacy/header.py",
                      frozenset({"parse_legacy_header", "legacy/header.py"}))
store.live[20] = Span(20, "ls legacy/", frozenset({"legacy/"}))

# The step-61 rationale, encoded as a record, omits the symbol. This is the
# exact defect: the gloss names no entities, so it cannot reconstruct span 19.
bad_record = EvictionRecord(
    span_ids=(19, 20),
    entities=frozenset({"legacy/"}),  # missing parse_legacy_header
    superseded_by=(55, 56, 57, 58, 59, 60),
    resolvable=True,
)
try:
    compact(store, (19, 20), bad_record)
except UnsafeCompactionError as e:
    print(f"rejected at step 61: {e}")

# Corrected record: entity-complete, resolvable, presence-marked downstream.
good_record = EvictionRecord(
    span_ids=(19, 20),
    entities=frozenset({"parse_legacy_header", "legacy/header.py", "legacy/"}),
    superseded_by=(55, 56, 57, 58, 59, 60),
    resolvable=True,
)
compact(store, (19, 20), good_record)
assert store.resolve("parse_legacy_header") is not None  # step 88 succeeds
