# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-s-retention-guarantee-silently-invert-when-a-forget-tombstone-lands-between-a-write-and-its-read-back-verification.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-s-retention-guarantee-silently-invert-when-a-forget-tombstone-lands-between-a-write-and-its-read-back-verification.warrant.json
# Markdown SHA-256:   e7515cedae692e7bb1288a941edb1933cbe963c47e101e08334691b57f48afb5
# Code AST SHA-256:   52581bca27470957e463f89ef6fc19d92c2b40ca9cf3b5b9eba2d9f773b1486e
# Verified Classes:   PendingTombstoneViolation, KeyState, MemoryClient
# 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, Optional


class PendingTombstoneViolation(RuntimeError):
    """Raised when a read is treated as durable while a tombstone is pending on its key."""


class KeyState(Enum):
    LIVE = "live"
    TOMBSTONED = "tombstoned"
    PENDING_TOMBSTONE = "pending_tombstone"


@dataclass
class MemoryClient:
    # service-observed state
    values: dict[str, Any] = field(default_factory=dict)
    write_version: dict[str, int] = field(default_factory=dict)
    tombstone_version: dict[str, int] = field(default_factory=dict)
    # client-side shadow: keys the agent itself has forgotten
    shadow: set[str] = field(default_factory=set)
    compaction_acked: set[str] = field(default_factory=set)

    def write(self, key: str, value: Any, resurrect: bool = False) -> int:
        if key in self.shadow and key not in self.compaction_acked and not resurrect:
            # write lands inside a pending-tombstone window; service would absorb it
            raise PendingTombstoneViolation(
                f"write to {key!r} while tombstone pending; "
                f"pass resurrect=True with a fresh epoch or wait for compact_ack"
            )
        v = self.write_version.get(key, 0) + 1
        self.write_version[key] = v
        self.values[key] = value
        return v

    def forget(self, key: str) -> int:
        t = self.tombstone_version.get(key, 0) + 1
        self.tombstone_version[key] = t
        self.shadow.add(key)
        self.compaction_acked.discard(key)
        return t

    def read(self, key: str, require_durable: bool = True) -> Optional[Any]:
        if require_durable and key in self.shadow and key not in self.compaction_acked:
            raise PendingTombstoneViolation(
                f"read of {key!r} is provisional: tombstone v{self.tombstone_version.get(key)} "
                f"pending compaction; value will vanish with no error at next tick"
            )
        return self.values.get(key)

    def compact(self, key: str) -> None:
        # the deferred application of the tombstone
        if key in self.shadow:
            self.values.pop(key, None)
            self.compaction_acked.add(key)


def depend_on_memory(client: MemoryClient, key: str) -> Any:
    """Irreversible downstream action gated on a memory read."""
    val = client.read(key, require_durable=True)
    if val is None:
        raise PendingTombstoneViolation(f"{key!r} unreadable at durable read; aborting action")
    return val
