# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-distinguish-a-forgotten-memory-key-from-a-never-written-one-tombstone-semantics-at-the-read-write-forget-boundary.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-distinguish-a-forgotten-memory-key-from-a-never-written-one-tombstone-semantics-at-the-read-write-forget-boundary.warrant.json
# Markdown SHA-256:   77309021330c84b2e5f189616ef3f15efde9a550c91e6abb732a71c481e061f5
# Code AST SHA-256:   76225cd83f9872620d6e7c5773f42ef61baa9cd7b24e5b227fa2da3910cfb611
# Verified Classes:   MemoryLifecycleError, ReadResult, TombstoneStore
# Defensive Guards:   2 fail-closed invariants (zero external deps)

import time
from dataclasses import dataclass
from typing import Optional


class MemoryLifecycleError(RuntimeError):
    """Raised when a memory operation violates tombstone/lifecycle invariants."""
    pass


@dataclass(frozen=True)
class ReadResult:
    state: str                      # "present" | "forgotten" | "absent"
    value: Optional[str] = None
    forgotten_at: Optional[float] = None


class TombstoneStore:
    """Keyed store where forget() inserts a tombstone rather than deleting."""

    def __init__(self, max_reader_staleness_s: float):
        self._values: dict[str, str] = {}
        self._tombstones: dict[str, float] = {}
        self._max_staleness = max_reader_staleness_s

    def write(self, key: str, value: str, *, resurrect: bool = False) -> None:
        if key in self._tombstones and not resurrect:
            raise MemoryLifecycleError(
                f"write to forgotten key {key!r} is a resurrection; "
                f"pass resurrect=True to override the negative assertion"
            )
        self._tombstones.pop(key, None)
        self._values[key] = value

    def forget(self, key: str) -> None:
        if key not in self._values and key not in self._tombstones:
            # Forgetting an absent key is a no-op, not an error, but it must
            # NOT create a tombstone -- absent and forgotten stay distinct.
            return
        self._values.pop(key, None)
        self._tombstones[key] = time.monotonic()

    def read(self, key: str) -> ReadResult:
        if key in self._values:
            return ReadResult(state="present", value=self._values[key])
        if key in self._tombstones:
            return ReadResult(state="forgotten", forgotten_at=self._tombstones[key])
        return ReadResult(state="absent")

    def sweep_tombstones(self, now: Optional[float] = None) -> int:
        now = time.monotonic() if now is None else now
        expired = [
            k for k, ts in self._tombstones.items()
            if now - ts > self._max_staleness
        ]
        for k in expired:
            del self._tombstones[k]
        return len(expired)


def derive_from_context(store: TombstoneStore, key: str, ctx_value: str) -> None:
    """A planner loop that re-derives a missing key from context.

    This is the exact operation that caused resurrection under hard-delete
    semantics. It must refuse to act on a forgotten key.
    """
    result = store.read(key)
    if result.state == "forgotten":
        raise MemoryLifecycleError(
            f"refusing to re-derive {key!r}: it was explicitly forgotten at "
            f"monotonic {result.forgotten_at:.3f}; re-derivation would "
            f"resurrect a negative assertion"
        )
    if result.state == "present":
        return
    store.write(key, ctx_value)
