# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-a-memory-tool-forget-acknowledgment-as-non-durable-until-a-tombstone-barrier-is-observed.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-a-memory-tool-forget-acknowledgment-as-non-durable-until-a-tombstone-barrier-is-observed.warrant.json
# Markdown SHA-256:   e3d1e3baa2a97a841ce2c9ad6171c6098f0955eebb639900664cca4596ea91e2
# Code AST SHA-256:   4dba94488bc09e6f885e1bd7692432cc222b8de7a418018dad1cdb91a0b38303
# Verified Classes:   ForgetBarrierViolation, Tombstone, MemoryClient, Quarantine
# Defensive Guards:   1 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Protocol


class ForgetBarrierViolation(RuntimeError):
    """Raised when an agent retrieves a forgotten key before its tombstone
    has propagated to every read channel the agent will use."""


@dataclass
class Tombstone:
    key: str
    tombstone_id: str
    tombstone_epoch: int


@dataclass
class MemoryClient(Protocol):
    def forget(self, key: str) -> Tombstone: ...
    def index_epoch(self, channel: str) -> int: ...
    def search(self, query: str, k: int) -> list[tuple[str, str]]: ...


@dataclass
class Quarantine:
    """Per-task set of keys forgotten but not yet barrier-confirmed."""
    _pending: dict[str, Tombstone] = field(default_factory=dict)
    _channels: tuple[str, ...] = ("primary", "replica", "vector_index")

    def record(self, tomb: Tombstone) -> None:
        self._pending[tomb.key] = tomb

    def barrier_cleared(self, client: MemoryClient, key: str) -> bool:
        tomb = self._pending.get(key)
        if tomb is None:
            return True
        return all(
            client.index_epoch(ch) >= tomb.tombstone_epoch
            for ch in self._channels
        )

    def safe_search(
        self, client: MemoryClient, query: str, k: int
    ) -> list[tuple[str, str]]:
        # Refuse to search while any quarantine entry is unconfirmed on any
        # channel the search path may consult; otherwise the search can
        # re-import a forgotten value and resurrect it on the next write.
        for key, tomb in self._pending.items():
            if not self.barrier_cleared(client, key):
                raise ForgetBarrierViolation(
                    f"search blocked: tombstone {tomb.tombstone_id} for "
                    f"key={key!r} not yet propagated to all channels; "
                    f"index_epoch < tombstone_epoch={tomb.tombstone_epoch}"
                )
        results = client.search(query, k)
        # Post-filter by key identity as defense in depth: never trust the
        # index to have purged a quarantined key.
        return [(key, text) for key, text in results if key not in self._pending]

    def confirm(self, client: MemoryClient) -> None:
        for key in list(self._pending):
            if self.barrier_cleared(client, key):
                del self._pending[key]
