# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-refuse-a-tombstoned-memory-read-rather-than-return-a-redacted-stub-resolving-the-tombstone-visibility-race-in-agent-memory-tool.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-refuse-a-tombstoned-memory-read-rather-than-return-a-redacted-stub-resolving-the-tombstone-visibility-race-in-agent-memory-tool.warrant.json
# Markdown SHA-256:   b60988c4f62f62bdd11c870e678322ecf58012a427330891c6423c3dc652d79c
# Code AST SHA-256:   3d4165b13d9acdc18fc0da39dd8b89d0aaf866a6dcc0e9b078ffc94eb1d23b71
# Verified Classes:   MemoryState, ReadResult, ResurrectionAttempt, MemoryClient
# Defensive Guards:   2 fail-closed invariants (zero external deps)

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


class MemoryState(Enum):
    LIVE = "live"
    TOMBSTONED = "tombstoned"
    TOMBSTONE_PENDING = "tombstone_pending"


@dataclass
class ReadResult:
    handle: str
    state: MemoryState
    content: Optional[str]
    tombstone_id: Optional[str]


class ResurrectionAttempt(RuntimeError):
    """Raised when an instance tries to re-write or re-forget a handle it must treat as forgotten."""
    pass


class MemoryClient:
    def __init__(self):
        self._forgotten: dict[str, str] = {}  # handle -> tombstone_id, append-only

    def forget(self, handle: str) -> str:
        if handle in self._forgotten:
            # Idempotent: do not re-issue, do not reset retention clock.
            return self._forgotten[handle]
        tombstone_id = f"ts_{len(self._forgotten):04d}"
        self._forgotten[handle] = tombstone_id
        return tombstone_id

    def read(self, handle: str, backend: ReadResult) -> ReadResult:
        """backend is what the (possibly stale) read replica returned."""
        if handle in self._forgotten:
            if backend.state is MemoryState.LIVE:
                # Replica is behind an acknowledged tombstone: consistency violation.
                raise ResurrectionAttempt(
                    f"handle {handle} acknowledged forgotten as {self._forgotten[handle]} "
                    f"but replica returned LIVE content; refusing to reason on stale data"
                )
            if backend.state is MemoryState.TOMBSTONE_PENDING:
                # Visibility window: quarantine content, do not surface, do not re-forget.
                return ReadResult(handle, MemoryState.TOMBSTONE_PENDING, None, self._forgotten[handle])
            return ReadResult(handle, MemoryState.TOMBSTONED, None, backend.tombstone_id)

        if backend.state is MemoryState.TOMBSTONED:
            # Forgotten by another actor: binding. Adopt into local set, forbid re-write.
            self._forgotten[handle] = backend.tombstone_id or "external"
            return ReadResult(handle, MemoryState.TOMBSTONED, None, backend.tombstone_id)

        return backend

    def write(self, handle: str, content: str) -> None:
        if handle in self._forgotten:
            raise ResurrectionAttempt(
                f"refusing to write {handle}: tombstoned as {self._forgotten[handle]}; "
                f"re-derivation must target a new handle"
            )
        # ... persist ...
