# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-that-a-model-driven-pruning-policy-has-silently-invalidated-a-reversible-context-snapshot.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-that-a-model-driven-pruning-policy-has-silently-invalidated-a-reversible-context-snapshot.warrant.json
# Markdown SHA-256:   52255bc2879335b2afe6e43986e8817edf063dd07e4a0c689bf74cef97bf65f0
# Code AST SHA-256:   69de70063533f3d4253dcc34beca944b96f2dfdd7e415fe90827df15c3fd59cd
# Verified Classes:   StaleContextEpochError, SnapshotIntegrityError, ContextState, Snapshot, EpochGuardedContext
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Dict, List, Set


class StaleContextEpochError(RuntimeError):
    """Raised when an eviction proposal was computed against a context epoch
    that no longer matches the live context, meaning applying it would
    produce a snapshot that cannot be a valid rollback target."""
    pass


class SnapshotIntegrityError(RuntimeError):
    """Raised when a snapshot manifest is structurally valid but its epoch
    ordering relative to a later eviction is unprovable."""
    pass


@dataclass
class ContextState:
    epoch: int
    segments: Dict[str, str] = field(default_factory=dict)  # id -> content
    ephemeral: Set[str] = field(default_factory=set)


@dataclass
class Snapshot:
    epoch: int
    segment_ids: Set[str]
    manifest_hashes: Dict[str, str]


class EpochGuardedContext:
    def __init__(self) -> None:
        self.state = ContextState(epoch=0)
        self.snapshots: List[Snapshot] = []

    def _bump(self) -> None:
        self.state.epoch += 1

    def add_segment(self, seg_id: str, content: str, ephemeral: bool) -> None:
        self.state.segments[seg_id] = content
        if ephemeral:
            self.state.ephemeral.add(seg_id)
        self._bump()

    def capture(self) -> Snapshot:
        # Capture is atomic w.r.t. the current epoch by construction:
        # it reads a frozen view and records the epoch it read.
        snap = Snapshot(
            epoch=self.state.epoch,
            segment_ids=set(self.state.segments.keys()),
            manifest_hashes={k: str(hash(v)) for k, v in self.state.segments.items()},
        )
        self.snapshots.append(snap)
        return snap

    def propose_evictions(self, proposal_epoch: int, evict_ids: List[str]) -> None:
        # The model computed this proposal against proposal_epoch.
        # Refuse if the live context has advanced since.
        if proposal_epoch != self.state.epoch:
            raise StaleContextEpochError(
                f"proposal computed against epoch {proposal_epoch}, "
                f"live epoch is {self.state.epoch}; eviction is unsafe"
            )

    def apply_evictions(self, proposal_epoch: int, evict_ids: List[str]) -> None:
        self.propose_evictions(proposal_epoch, evict_ids)

        # Any ephemeral segment being evicted requires a snapshot whose
        # epoch is strictly earlier than the application epoch AND which
        # contains that segment. Otherwise the loss is irreversible.
        for seg_id in evict_ids:
            if seg_id in self.state.ephemeral:
                valid = [
                    s for s in self.snapshots
                    if s.epoch < self.state.epoch and seg_id in s.segment_ids
                ]
                if not valid:
                    raise SnapshotIntegrityError(
                        f"ephemeral segment {seg_id} has no valid pre-eviction "
                        f"snapshot at epoch < {self.state.epoch}; refusing eviction"
                    )
            self.state.segments.pop(seg_id, None)
            self.state.ephemeral.discard(seg_id)
        self._bump()

    def restore(self, snapshot: Snapshot, referenced_by_future: Set[str]) -> ContextState:
        # Structural check: manifest matches recorded IDs.
        restored = {sid: snapshot.manifest_hashes[sid] for sid in snapshot.segment_ids}
        if set(restored.keys()) != snapshot.segment_ids:
            raise SnapshotIntegrityError("manifest/ID set mismatch on restore")

        # Semantic check: every segment a future step might reference must
        # be present. If not, the snapshot is not a valid rollback target.
        missing = referenced_by_future - snapshot.segment_ids
        if missing:
            raise SnapshotIntegrityError(
                f"snapshot at epoch {snapshot.epoch} cannot serve as rollback "
                f"target: missing referenced segments {sorted(missing)}"
            )
        return ContextState(epoch=snapshot.epoch, segments=dict(restored))
