# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-retention-decay-from-silently-resurrecting-forgotten-memories-through-vector-index-tombstones.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-retention-decay-from-silently-resurrecting-forgotten-memories-through-vector-index-tombstones.warrant.json
# Markdown SHA-256:   2f9b67f987553209251174fdd9a7da98aaf0a2a9beac4e3b0fefd566fe6a74dc
# Code AST SHA-256:   f8dce5f240271fff50c44d7a9a60d503bf3ef691b0e75f1ca753faf511c1beec
# Verified Classes:   ResurrectionError, MemoryRecord, MemoryTool
# Defensive Guards:   2 fail-closed invariants (zero external deps)

import time
from dataclasses import dataclass, field
from typing import Optional


class ResurrectionError(RuntimeError):
    """Raised when a forgotten key is returned by a read path."""


@dataclass
class MemoryRecord:
    key: str
    content: str
    written_at: float
    decay_rate: float
    forgotten: bool = False


class MemoryTool:
    """
    Reference implementation of the erasure barrier.

    Invariants enforced:
      1. forget() returns only after the tombstone is visible to all reads.
      2. Decay is never computed for forgotten records (score short-circuits).
      3. Correctness does not depend on compaction having run.
    """

    def __init__(self) -> None:
        self._records: dict[str, MemoryRecord] = {}
        self._tombstones: set[str] = set()  # authoritative, synchronous
        self._compactions_run: int = 0

    def write(self, key: str, content: str, decay_rate: float) -> None:
        self._records[key] = MemoryRecord(
            key=key, content=content, written_at=time.time(), decay_rate=decay_rate
        )
        self._tombstones.discard(key)

    def forget(self, key: str) -> None:
        # Tombstone FIRST, synchronously, before any ack.
        self._tombstones.add(key)
        rec = self._records.get(key)
        if rec is not None:
            rec.forgotten = True

    def _score(self, rec: MemoryRecord, now: float) -> float:
        # Invariant 2: never score a tombstoned record.
        if rec.key in self._tombstones or rec.forgotten:
            return float("-inf")
        age_hours = (now - rec.written_at) / 3600.0
        return pow(2.718281828, -rec.decay_rate * age_hours)

    def read(self, query: str, k: int = 10, min_score: float = 0.1) -> list[str]:
        now = time.time()
        candidates = []
        for rec in self._records.values():
            # Invariant 1: synchronous tombstone filter on EVERY read.
            if rec.key in self._tombstones:
                continue
            s = self._score(rec, now)
            if s >= min_score and query in rec.content:
                candidates.append((s, rec.key))
        candidates.sort(reverse=True)
        result = [key for _, key in candidates[:k]]
        # Invariant 3: assert barrier held even if compaction never ran.
        for key in result:
            if key in self._tombstones:
                raise ResurrectionError(
                    f"forgotten key {key!r} surfaced after "
                    f"{self._compactions_run} compactions; erasure barrier violated"
                )
        return result

    def compact(self) -> None:
        # Liveness only. Correctness must not depend on this.
        for key in list(self._tombstones):
            self._records.pop(key, None)
        self._compactions_run += 1


def resurrection_probe(tool: MemoryTool) -> None:
    """CI probe: forgotten record must not resurface on merit."""
    tool.write("deprecated_endpoint", "endpoint config v1", decay_rate=0.05)
    tool.forget("deprecated_endpoint")
    # Do NOT compact. Query would match on content and score on merit.
    hits = tool.read(query="endpoint config", k=10, min_score=0.0)
    if "deprecated_endpoint" in hits:
        raise ResurrectionError(
            "erasure barrier failed: forgotten record returned without compaction"
        )
