# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-tombstone-resurrection-in-scoped-memory-apis-with-read-write-forget-semantics.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-tombstone-resurrection-in-scoped-memory-apis-with-read-write-forget-semantics.warrant.json
# Markdown SHA-256:   5de7c4acbcc9ac27e52fc471df9c719b1287bd866df6c403d67c936d70511355
# Code AST SHA-256:   bbb282f838523d33b031c1f14cc76a675a8dddb425a734be1faf1045fc0234a2
# Verified Classes:   TombstoneResurrectionError, Record, ScopedMemory
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Optional


class TombstoneResurrectionError(RuntimeError):
    """Raised when a write would re-create a record that was forgotten after the writer's read."""

    def __init__(self, scope: str, key: str, observed_gen: int, tombstone_gen: int):
        super().__init__(
            f"write to ({scope!r}, {key!r}) observed generation {observed_gen} "
            f"but tombstone at generation {tombstone_gen}; refusing to resurrect"
        )
        self.scope = scope
        self.key = key
        self.observed_gen = observed_gen
        self.tombstone_gen = tombstone_gen


@dataclass
class Record:
    value: str
    generation: int


class ScopedMemory:
    def __init__(self, tombstone_ttl_seconds: int = 3600):
        self._live: dict[tuple[str, str], Record] = {}
        self._tombstones: dict[tuple[str, str], int] = {}
        self._gen: dict[tuple[str, str], int] = {}
        self.tombstone_ttl_seconds = tombstone_ttl_seconds

    def _next_gen(self, scope: str, key: str) -> int:
        g = self._gen.get((scope, key), 0) + 1
        self._gen[(scope, key)] = g
        return g

    def read(self, scope: str, key: str) -> Optional[Record]:
        return self._live.get((scope, key))

    def forget(self, scope: str, key: str) -> bool:
        existed = (scope, key) in self._live
        self._live.pop((scope, key), None)
        self._tombstones[(scope, key)] = self._next_gen(scope, key)
        return existed

    def write(self, scope: str, key: str, value: str, observed_gen: Optional[int]) -> Record:
        tomb = self._tombstones.get((scope, key))
        if tomb is not None:
            if observed_gen is None:
                raise TombstoneResurrectionError(scope, key, -1, tomb)
            if observed_gen < tomb:
                raise TombstoneResurrectionError(scope, key, observed_gen, tomb)
        rec = Record(value=value, generation=self._next_gen(scope, key))
        self._live[(scope, key)] = rec
        return rec
