# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-retention-eviction-inversion-in-read-write-forget-memory-tool-interfaces.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-retention-eviction-inversion-in-read-write-forget-memory-tool-interfaces.warrant.json
# Markdown SHA-256:   f1d17067e41720648c6b44d5c37d4babfc456d9d06f5f3fd2f8c858d8976f42d
# Code AST SHA-256:   b9cb565db56643ae533fd4c614a1d9cf166c9a261588af083833d26d2d0badfe
# Verified Classes:   RetentionEvictionInversionError, MemoryRecord, RetentionProbe
# Defensive Guards:   5 fail-closed invariants (zero external deps)

import time
from dataclasses import dataclass


class RetentionEvictionInversionError(RuntimeError):
    """Raised when observed retention state contradicts an acknowledged mutation."""
    pass


@dataclass
class MemoryRecord:
    key: str
    value: object
    version: int
    written_at_ms: float
    slot_id: int


class RetentionProbe:
    """Probes a read/write/forget memory tool for retention-eviction inversion.

    Assumes the tool exposes:
      read(key)    -> MemoryRecord | None  (with written_at_ms and slot_id)
      write(key,v) -> int                  (new version)
      forget(key)  -> bool                 (acknowledged)
    """

    def __init__(self, tool, capacity: int, clock=time.monotonic):
        self._tool = tool
        self._capacity = capacity
        self._clock = clock
        self._forget_log: dict[str, float] = {}
        self._slot_eviction_log: set[int] = set()

    def forget_and_verify(self, key: str) -> None:
        ack = self._tool.forget(key)
        if not ack:
            return
        forget_ts = self._clock() * 1000.0
        self._forget_log[key] = forget_ts

        # Probe: a value read after forget whose age predates the forget
        # proves the value survived the tombstone eviction.
        rec = self._tool.read(key)
        if rec is not None and rec.written_at_ms < forget_ts:
            raise RetentionEvictionInversionError(
                f"forget({key!r}) acknowledged at {forget_ts:.1f}ms but "
                f"read returned value written at {rec.written_at_ms:.1f}ms "
                f"(slot_id={rec.slot_id}); tombstone was evicted before sweep"
            )

    def write_and_verify(self, key: str, value: object) -> int:
        version = self._tool.write(key, value)
        rec = self._tool.read(key)
        if rec is None:
            raise RetentionEvictionInversionError(
                f"write({key!r}) returned version {version} but read returned "
                f"None; value was evicted by a sweep using stale recency"
            )
        if rec.version != version:
            raise RetentionEvictionInversionError(
                f"write({key!r}) returned version {version} but read returned "
                f"version {rec.version}; recency update landed on shadow index"
            )
        if rec.slot_id in self._slot_eviction_log:
            raise RetentionEvictionInversionError(
                f"write({key!r}) landed in slot_id={rec.slot_id} previously "
                f"observed evicted; slot reuse across forget boundary"
            )
        return version

    def check_capacity_invariant(self, live_keys: set[str]) -> None:
        forgotten = set(self._forget_log)
        transient = len(live_keys) + len(forgotten & live_keys)
        if transient > self._capacity:
            raise RetentionEvictionInversionError(
                f"live({len(live_keys)}) + forgotten-still-live("
                f"{len(forgotten & live_keys)}) = {transient} exceeds capacity "
                f"{self._capacity}; snapshot-window double-count detected"
            )
