# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-treat-a-forget-acknowledgement-as-a-deletion-warrant-rather-than-a-tombstone-hint-the-forget-ack-read-resurrection-boundary-in-m.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-treat-a-forget-acknowledgement-as-a-deletion-warrant-rather-than-a-tombstone-hint-the-forget-ack-read-resurrection-boundary-in-m.warrant.json
# Markdown SHA-256:   fbc5e71b927128f04729239599df7784855391ba8c48fe46d7a6ca09197e6233
# Code AST SHA-256:   758a337c092bb67d367ef836cf7b757d1cf4f52ab4c48633168ab0750f02584a
# Verified Classes:   ForgetContractViolation, MemoryState, ForgetAck, ReadResult, MemoryLedger
# Defensive Guards:   1 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from enum import Enum


class ForgetContractViolation(RuntimeError):
    """Raised when a read resurrects a key that a warrant-bearing forget removed."""


class MemoryState(Enum):
    KNOWN = "known"
    QUARANTINED = "quarantined"   # bare ack: value retained, untrusted
    FORGOTTEN = "forgotten"       # warrant ack: absence is actionable


@dataclass(frozen=True)
class ForgetAck:
    key: str
    status: str
    forget_epoch: int | None          # None => no warrant
    read_paths_invalidated: bool      # contract's explicit claim


@dataclass(frozen=True)
class ReadResult:
    key: str
    value: object
    epoch: int


def classify_ack(ack: ForgetAck) -> MemoryState:
    # A warrant requires BOTH an epoch stamp and an explicit read-path claim.
    if ack.status == "ok" and ack.forget_epoch is not None and ack.read_paths_invalidated:
        return MemoryState.FORGOTTEN
    return MemoryState.QUARANTINED


class MemoryLedger:
    def __init__(self) -> None:
        self._state: dict[str, MemoryState] = {}
        self._forget_epoch: dict[str, int] = {}

    def apply_forget(self, ack: ForgetAck) -> MemoryState:
        state = classify_ack(ack)
        self._state[ack.key] = state
        if ack.forget_epoch is not None:
            self._forget_epoch[ack.key] = ack.forget_epoch
        return state

    def admit_read(self, r: ReadResult) -> object:
        state = self._state.get(r.key, MemoryState.KNOWN)
        if state is MemoryState.FORGOTTEN:
            fe = self._forget_epoch.get(r.key)
            if fe is not None and r.epoch < fe:
                # Store returned a value the warrant said was unreachable.
                raise ForgetContractViolation(
                    f"resurrection of {r.key!r}: read epoch {r.epoch} < forget epoch {fe}"
                )
            # epoch >= forget_epoch => legitimate re-write
            self._state[r.key] = MemoryState.KNOWN
            return r.value
        if state is MemoryState.QUARANTINED:
            # Accept as contested evidence only; caller must reconcile.
            return {"contested": True, "value": r.value}
        return r.value


def handle_forget_then_read(ledger: MemoryLedger, ack: ForgetAck, r: ReadResult) -> object:
    state = ledger.apply_forget(ack)
    if state is MemoryState.QUARANTINED and r.key == ack.key:
        # Bare ack: we may NOT answer "unknown". We retain, flagged contested.
        return ledger.admit_read(r)
    return ledger.admit_read(r)
