# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-refuse-to-prune-before-the-salience-weighted-retention-policy-has-committed-its-eviction-ledger.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-refuse-to-prune-before-the-salience-weighted-retention-policy-has-committed-its-eviction-ledger.warrant.json
# Markdown SHA-256:   26d096d5e19d85a9fa6261ce3d1176d97941ada5f08cda72727129bf753a7cc8
# Code AST SHA-256:   9ad316ab57ef6092e8266948d08e0a3451e366ae790cddad669b81141a74a2a7
# Verified Classes:   EvictionOrderError, AbsenceKind, Tombstone, ContextWindow
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from enum import Enum
from typing import Optional


class EvictionOrderError(RuntimeError):
    """Raised when a prune is attempted without a committed tombstone."""
    pass


class AbsenceKind(Enum):
    PRESENT = "present"
    EVICTED = "evicted"
    NEVER_PRESENT = "never_present"


@dataclass
class Tombstone:
    span_id: str
    reason: str
    step: int
    salience: float


@dataclass
class ContextWindow:
    spans: dict[str, str] = field(default_factory=dict)
    ledger: dict[str, Tombstone] = field(default_factory=dict)
    ledger_committed: bool = True

    def prune(self, span_id: str, reason: str, step: int, salience: float) -> None:
        # Invariant: eviction is atomic with its ledger entry.
        # If the ledger cannot be committed in this same step, refuse.
        if not self.ledger_committed:
            raise EvictionOrderError(
                f"refusing to prune {span_id!r}: prior eviction ledger not committed; "
                "checkpoint full context instead of prune-and-hope"
            )
        if span_id not in self.spans:
            raise EvictionOrderError(f"span {span_id!r} not present; cannot prune")

        # Begin transaction: mark ledger uncommitted, then write tombstone, then drop span.
        self.ledger_committed = False
        self.ledger[span_id] = Tombstone(span_id, reason, step, salience)
        del self.spans[span_id]
        # Commit: only now is the eviction durable and the window consistent.
        self.ledger_committed = True

    def lookup(self, span_id: str) -> tuple[AbsenceKind, Optional[str]]:
        # Typed absence: never collapse EVICTED into NEVER_PRESENT.
        if span_id in self.spans:
            return AbsenceKind.PRESENT, self.spans[span_id]
        if span_id in self.ledger:
            return AbsenceKind.EVICTED, None
        return AbsenceKind.NEVER_PRESENT, None


def safe_rollback(window: ContextWindow, conn_span_id: str) -> str:
    kind, value = window.lookup(conn_span_id)
    if kind is AbsenceKind.EVICTED:
        tomb = window.ledger[conn_span_id]
        raise EvictionOrderError(
            f"connection string was EVICTED at step {tomb.step} "
            f"(salience={tomb.salience}); do NOT re-derive from stale sources — "
            "restore from checkpoint"
        )
    if kind is AbsenceKind.NEVER_PRESENT:
        raise EvictionOrderError(
            "connection string never present in context; refuse rollback"
        )
    return value  # PRESENT
