# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-forget-a-fact-it-can-still-retrieve-scoped-deletion-tombstones-leaking-through-the-retrieval-index-in-memory-tool-apis.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-forget-a-fact-it-can-still-retrieve-scoped-deletion-tombstones-leaking-through-the-retrieval-index-in-memory-tool-apis.warrant.json
# Markdown SHA-256:   05fbf2036d55300e4c59959ed3b61dbf85445102e26116e20f2f946af8da18a8
# Code AST SHA-256:   1acbdef7b57bb5de0d401145d74e4265400344dc2771320a04cc881161844736
# Verified Classes:   Liveness, ScopedDeletionViolation, Record, MemoryStore, RetrievalIndex
# Defensive Guards:   5 fail-closed invariants (zero external deps)

from __future__ import annotations

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


class Liveness(str, Enum):
    LIVE = "live"
    TOMBSTONED = "tombstoned"
    UNKNOWN = "unknown"


class ScopedDeletionViolation(RuntimeError):
    """Raised when a retrieval result violates the read-your-forgets invariant."""


@dataclass
class Record:
    memory_id: str
    payload: str
    deletion_epoch: int = 0  # 0 == never deleted


@dataclass
class MemoryStore:
    records: dict[str, Record] = field(default_factory=dict)
    epoch: int = 0

    def write(self, memory_id: str, payload: str) -> None:
        self.records[memory_id] = Record(memory_id, payload)

    def forget(self, memory_ids: Iterable[str]) -> int:
        self.epoch += 1
        for mid in memory_ids:
            if mid in self.records:
                self.records[mid].deletion_epoch = self.epoch
        return self.epoch


@dataclass
class RetrievalIndex:
    # Intentionally lagging: maps memory_id -> similarity, may contain tombstones.
    entries: dict[str, float] = field(default_factory=dict)
    applied_epoch: int = 0

    def index(self, memory_id: str, similarity: float) -> None:
        self.entries[memory_id] = similarity

    def query(self, k: int) -> list[tuple[str, float]]:
        return sorted(self.entries.items(), key=lambda kv: -kv[1])[:k]


def read_with_liveness(
    store: MemoryStore,
    index: RetrievalIndex,
    min_epoch: int,
    k: int,
) -> list[dict]:
    """Read that honors the read-your-forgets invariant.

    Any index hit whose record deletion_epoch exceeds min_epoch is filtered.
    Any index hit whose record is missing from the store is reported UNKNOWN
    and must not be acted upon.
    """
    results: list[dict] = []
    for memory_id, similarity in index.query(k):
        record = store.records.get(memory_id)
        if record is None:
            results.append({
                "id": memory_id,
                "payload": None,
                "liveness": Liveness.UNKNOWN.value,
                "similarity": similarity,
            })
            continue
        if record.deletion_epoch > min_epoch:
            # Forgotten after the caller's fence: must not surface as live.
            results.append({
                "id": memory_id,
                "payload": None,
                "liveness": Liveness.TOMBSTONED.value,
                "similarity": similarity,
            })
            continue
        results.append({
            "id": memory_id,
            "payload": record.payload,
            "liveness": Liveness.LIVE.value,
            "similarity": similarity,
        })
    return results


def act_on_memory(result: dict, irreversible: bool) -> str:
    """Gate irreversible actions on liveness, never on payload presence."""
    if result["liveness"] == Liveness.LIVE.value:
        return result["payload"]
    if result["liveness"] == Liveness.TOMBSTONED.value:
        # Forgotten fact resurfaced from the index: correct behavior is to
        # ignore it, but the invariant was at risk, so surface it.
        raise ScopedDeletionViolation(
            f"retrieval surfaced tombstoned memory {result['id']!r} "
            f"as a candidate; refusing to use it"
        )
    if irreversible:
        raise ScopedDeletionViolation(
            f"cannot act irreversibly on memory {result['id']!r} "
            f"with liveness={result['liveness']!r}; require explicit status check"
        )
    return ""


# --- Reproduction of the observed failure ---
store = MemoryStore()
store.write("m_8841", "acme prefers eu-west-1, never us-east-1")
store.write("m_8843", "acme uses terraform 1.7")

index = RetrievalIndex()
index.index("m_8841", 0.91)
index.index("m_8843", 0.42)

# Caller captures a fence before forgetting.
fence = store.epoch
store.forget(["m_8841"])  # record-store commit; index NOT updated (the bug)

# Naive read that trusts the index returns the forgotten payload as live:
naive = index.query(5)
assert naive[0][0] == "m_8841"  # the forgotten fact is still rank-1

# Fenced read correctly reports TOMBSTONED and refuses to leak the payload:
results = read_with_liveness(store, index, min_epoch=fence, k=5)
top = results[0]
assert top["liveness"] == Liveness.TOMBSTONED.value
assert top["payload"] is None

try:
    act_on_memory(top, irreversible=True)
except ScopedDeletionViolation as exc:
    print(f"invariant held: {exc}")
