# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-a-tombstoned-memory-key-that-its-own-read-path-still-resolves-through-a-stale-vector-index-after-gdpr-erasure.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-a-tombstoned-memory-key-that-its-own-read-path-still-resolves-through-a-stale-vector-index-after-gdpr-erasure.warrant.json
# Markdown SHA-256:   e3c76f69500f6a8ced42a5ab37df5d55c86f9eda25ee437698676f825856d4cd
# Code AST SHA-256:   5d5dadd987fb462a8eaed4519827733b484beb67dc1aa8fa322fa45f143bcfea
# Verified Classes:   ErasureIntegrityError, CompactionState, ForgetReceipt, PostForgetQuarantine
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from __future__ import annotations

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


class ErasureIntegrityError(RuntimeError):
    """Raised when the read path does not honor a tombstone after forget()."""


class CompactionState(str, Enum):
    COMPLETE = "complete"
    QUEUED = "queued"
    PENDING = "pending"
    UNKNOWN = "unknown"


@dataclass(frozen=True)
class ForgetReceipt:
    scope: str
    keys_affected: int
    compaction: CompactionState
    request_id: str


@dataclass
class PostForgetQuarantine:
    """Instance-side guard: no key in scope reaches the context window
    until a canary read proves the read path honors the tombstone."""

    forgotten_scopes: list[str] = field(default_factory=list)
    quarantined_keys: set[str] = field(default_factory=set)
    _canary_passed: dict[str, bool] = field(default_factory=dict)

    def register_forget(self, receipt: ForgetReceipt) -> None:
        self.forgotten_scopes.append(receipt.scope)
        # If compaction is not proven complete, the whole scope is suspect.
        if receipt.compaction is not CompactionState.COMPLETE:
            self._canary_passed[receipt.scope] = False

    def is_quarantined(self, key: str) -> bool:
        if key in self.quarantined_keys:
            return True
        return any(_scope_matches(key, s) and not self._canary_passed.get(s, False)
                   for s in self.forgotten_scopes)

    def mark_canary_passed(self, scope: str) -> None:
        self._canary_passed[scope] = True


def _scope_matches(key: str, scope: str) -> bool:
    prefix = scope.rstrip("*")
    return key.startswith(prefix)


def safe_read(
    memory_tool: Any,
    quarantine: PostForgetQuarantine,
    query: str,
    scope: str,
    k: int = 8,
) -> list[dict]:
    """Read that refuses to surface quarantined keys into agent context."""
    raw = memory_tool.read(query=query, scope=scope, k=k)
    clean: list[dict] = []
    for hit in raw:
        key = hit.get("key", "")
        if quarantine.is_quarantined(key):
            # Erasure event, not a retrieval miss. Drop before context insertion.
            continue
        if hit.get("payload") is None:
            # C3: hydration miss must be terminal, not a silent k-1 drop.
            raise ErasureIntegrityError(
                f"index returned candidate {key!r} with no payload; "
                f"read path is not tombstone-guarded for scope {scope!r}"
            )
        clean.append(hit)
    return clean


def verify_erasure(
    memory_tool: Any,
    quarantine: PostForgetQuarantine,
    receipt: ForgetReceipt,
    canary_key: str,
) -> None:
    """Probe the read path after forget(). Raises if the tombstone is not honored."""
    if receipt.compaction is CompactionState.COMPLETE:
        quarantine.mark_canary_passed(receipt.scope)
        return

    result = memory_tool.read_by_key(canary_key)
    if result is None:
        # Payload gone, but did the read path consult the tombstone, or just miss?
        # A tombstone-honoring read must return a typed erasure signal.
        probe = memory_tool.read_by_key(canary_key, require_tombstone_signal=True)
        if probe is not None:
            raise ErasureIntegrityError(
                f"canary {canary_key!r} returned payload after forget "
                f"{receipt.request_id!r}; read path bypasses tombstone"
            )
        quarantine.mark_canary_passed(receipt.scope)
        return

    raise ErasureIntegrityError(
        f"canary {canary_key!r} still resolvable after forget "
        f"{receipt.request_id!r} (compaction={receipt.compaction.value}); "
        f"scope {receipt.scope!r} remains quarantined"
    )
