# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-treat-a-memory-tool-delete-as-a-tombstone-rather-than-a-guarantee-scoped-persistence-deletion-versus-ttl-eviction-race-in-agent.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-treat-a-memory-tool-delete-as-a-tombstone-rather-than-a-guarantee-scoped-persistence-deletion-versus-ttl-eviction-race-in-agent.warrant.json
# Markdown SHA-256:   5a7fbb81246d53776eda0c5fefc190d3a46846a153a672c50f271be920a65108
# Code AST SHA-256:   9c7906de60b08681e1d8b6ba515a73968ea629f927df2f9845c2f5fa408559c1
# Verified Classes:   DeletionGapViolation, MemoryTool, FencedForget
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from __future__ import annotations

import time
from dataclasses import dataclass, field
from typing import Any, Protocol


class DeletionGapViolation(RuntimeError):
    """Raised when a value believed deleted is still recallable within the deletion gap."""


class MemoryTool(Protocol):
    def write(self, scope: str, key: str, value: Any, ttl_s: int) -> None: ...
    def read(self, scope: str, key: str) -> Any | None: ...
    def forget(self, scope: str, key: str) -> bool: ...
    def recall(self, scope: str, query: str, k: int = 5) -> list[tuple[str, Any]]: ...


@dataclass
class FencedForget:
    """Wraps forget so that tombstoning is never mistaken for erasure."""

    tool: MemoryTool
    verification_attempts: int = 3
    backoff_s: float = 0.15
    _quarantine: set[tuple[str, str]] = field(default_factory=set)

    def forget_and_verify(
        self,
        scope: str,
        key: str,
        *,
        query: str,
        require_erasure: bool,
    ) -> None:
        acked = self.tool.forget(scope, key)
        if not acked:
            raise DeletionGapViolation(
                f"forget not acknowledged for scope={scope!r} key={key!r}"
            )

        # Quarantine: suppress semantic recall on this key for one turn.
        self._quarantine.add((scope, key))

        if not require_erasure:
            # Tombstoning is acceptable; overwrite will land next turn.
            return

        # Erasure path: prove the value is unreachable via semantic recall.
        for attempt in range(self.verification_attempts):
            hits = self.tool.recall(scope, query, k=5)
            leaked = [h for h in hits if h[0] == key]
            if not leaked:
                self._quarantine.discard((scope, key))
                return
            time.sleep(self.backoff_s * (2 ** attempt))

        # Still recallable after retries: the tombstone lost the race with a
        # late embedding. Do NOT proceed as if erased.
        raise DeletionGapViolation(
            f"value for key={key!r} in scope={scope!r} still recallable after "
            f"{self.verification_attempts} verification recalls; "
            f"tombstone likely applied before late embedding landed. "
            f"Escalate to hard-delete or keep scope quarantined."
        )

    def safe_read(self, scope: str, key: str) -> Any | None:
        if (scope, key) in self._quarantine:
            raise DeletionGapViolation(
                f"exact read on quarantined key={key!r} scope={scope!r}; "
                f"deletion not yet proven"
            )
        return self.tool.read(scope, key)
