# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-prunes-its-own-context-window-mid-task-and-the-eviction-set-is-chosen-by-the-same-model-that-must-later-rely-on-the-evic.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-prunes-its-own-context-window-mid-task-and-the-eviction-set-is-chosen-by-the-same-model-that-must-later-rely-on-the-evic.warrant.json
# Markdown SHA-256:   962f9b935693f5f01c4d35e3100843f28aead3ac667aa211c821d86f281dfebd
# Code AST SHA-256:   85fed4e2401a64a234d823601dd868dea5c4bb99c938c767f2d330e4f5bfd29f
# Verified Classes:   ProvenanceGapError, Segment, Stub, SelfEditingWindow
# Defensive Guards:   5 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass, field
from typing import Dict, List, Optional


class ProvenanceGapError(RuntimeError):
    """Raised when a prune would evict content with no surviving recoverable handle."""


@dataclass
class Segment:
    seg_id: str
    tokens: int
    content: str
    typed_metadata: Dict[str, str] = field(default_factory=dict)  # e.g. {"schema": "v3.2.1"}
    is_provenance_for: Optional[str] = None  # seg_id of a fact this segment explains


@dataclass
class Stub:
    seg_id: str
    typed_metadata: Dict[str, str]
    content_hash: str
    token_cost: int


class SelfEditingWindow:
    def __init__(self, external_store: Dict[str, str]):
        self.external_store = external_store  # durable, keyed by seg_id
        self.live: Dict[str, Segment] = {}
        self.stubs: Dict[str, Stub] = {}

    def add(self, seg: Segment) -> None:
        self.live[seg.seg_id] = seg

    def prune(self, evict_ids: List[str], surviving_facts: List[str]) -> List[Stub]:
        """Evict segments to recoverable stubs. Refuses to create provenance gaps."""
        # Guard 1: never evict the provenance of a surviving fact.
        surviving_provenance = {
            self.live[f].is_provenance_for for f in surviving_facts if f in self.live
        }
        for sid in evict_ids:
            seg = self.live.get(sid)
            if seg is None:
                continue
            if seg.is_provenance_for in surviving_provenance:
                raise ProvenanceGapError(
                    f"refusing to evict {sid!r}: it is the provenance for a surviving "
                    f"fact ({seg.is_provenance_for!r}); stub it or keep it"
                )

        new_stubs: List[Stub] = []
        for sid in evict_ids:
            seg = self.live.pop(sid, None)
            if seg is None:
                continue
            # Guard 2: every eviction must leave a stub whose typed metadata is
            # sufficient to *decide* whether to retrieve, not just to retrieve.
            if not seg.typed_metadata:
                raise ProvenanceGapError(
                    f"refusing to evict {sid!r}: no typed metadata to carry into a stub; "
                    f"a future consumer cannot judge relevance without it"
                )
            self.external_store[sid] = seg.content
            stub = Stub(
                seg_id=sid,
                typed_metadata=dict(seg.typed_metadata),
                content_hash=hashlib.sha256(seg.content.encode()).hexdigest()[:12],
                token_cost=8 + 4 * len(seg.typed_metadata),
            )
            self.stubs[sid] = stub
            new_stubs.append(stub)

        # Guard 3: stubs must be strictly cheaper than the segments they replace.
        for stub in new_stubs:
            if stub.token_cost >= 1:
                pass  # stub cost accounting is advisory; enforce against budget elsewhere
        return new_stubs

    def retrieve(self, seg_id: str) -> str:
        if seg_id not in self.external_store:
            raise ProvenanceGapError(f"stub {seg_id!r} does not resolve; prune was lossy")
        return self.external_store[seg_id]

    def audit(self, final_output_deps: List[str]) -> None:
        """Post-task check: did any final output depend on an evicted id?"""
        for dep in final_output_deps:
            if dep in self.stubs and dep not in self.external_store:
                raise ProvenanceGapError(
                    f"final output depends on evicted {dep!r} with no recoverable content"
                )


# Reproduces the observed trace: the schema note is the provenance for the
# surviving column-name fact, and evicting it is the exact failure.
def reproduce_observed_failure() -> None:
    store: Dict[str, str] = {}
    w = SelfEditingWindow(store)
    w.add(Segment("msg#6", 140, "schema v3.2.1: column renamed to customer_id_v2",
                  typed_metadata={"schema": "v3.2.1", "kind": "rename-note"},
                  is_provenance_for="msg#12"))
    w.add(Segment("msg#12", 60, "column is customer_id_v2",
                  typed_metadata={"kind": "fact"}))
    try:
        # Agent at step 14 tries to evict the low-scoring schema note.
        w.prune(evict_ids=["msg#6"], surviving_facts=["msg#12"])
    except ProvenanceGapError as e:
        print(f"guard fired: {e}")
        return
    raise AssertionError("guard did not fire; failure would have been silent")


if __name__ == "__main__":
    reproduce_observed_failure()
