# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-forget-as-a-tombstone-rather-than-a-deletion-the-read-after-forget-resurrection-invariant.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-forget-as-a-tombstone-rather-than-a-deletion-the-read-after-forget-resurrection-invariant.warrant.json
# Markdown SHA-256:   aa359657820eb4d876fe9f0b921742637699b66221915d2f28baf1c8c4c41391
# Code AST SHA-256:   b1f7af3be5f4d997038200f27740cd51b30a1b31192b09b883ec7baf2c49e42e
# Verified Classes:   ResurrectionInvariantError, ScopedMemory
# Defensive Guards:   4 fail-closed invariants (zero external deps)

class ResurrectionInvariantError(RuntimeError):
    """Raised when a read observes a generation that a prior forget claimed to remove,
    or when a post-forget write is suppressed by a stale tombstone."""
    pass


class ScopedMemory:
    def __init__(self):
        # key -> (generation, value)
        self._live = {}
        # key -> highest generation tombstoned
        self._tombstone_gen = {}
        self._gen_counter = 0

    def write(self, key: str, value) -> int:
        self._gen_counter += 1
        gen = self._gen_counter
        tomb = self._tombstone_gen.get(key, -1)
        if gen <= tomb:
            # A post-forget write must always be a newer generation than the tombstone.
            raise ResurrectionInvariantError(
                f"write generation {gen} not newer than tombstone {tomb} for key {key!r}"
            )
        self._live[key] = (gen, value)
        return gen

    def read(self, key: str, expected_gen: int | None = None):
        entry = self._live.get(key)
        if entry is None:
            return None
        gen, value = entry
        tomb = self._tombstone_gen.get(key, -1)
        if gen <= tomb:
            # Resurrection: a live generation at or below the tombstone survived.
            raise ResurrectionInvariantError(
                f"read of key {key!r} gen {gen} violates tombstone gen {tomb}"
            )
        if expected_gen is not None and gen != expected_gen:
            raise ResurrectionInvariantError(
                f"read of key {key!r} returned gen {gen}, expected {expected_gen}"
            )
        return value

    def forget(self, key: str) -> int:
        entry = self._live.pop(key, None)
        if entry is None:
            # Idempotent: forgetting an absent key is a no-op, not an error.
            return self._tombstone_gen.get(key, -1)
        gen, _ = entry
        self._tombstone_gen[key] = max(self._tombstone_gen.get(key, -1), gen)
        return self._tombstone_gen[key]

    def apply_delayed_tombstone(self, key: str, tomb_gen: int) -> None:
        """Simulates an asynchronous compaction applying a stale tombstone."""
        entry = self._live.get(key)
        if entry is not None:
            gen, _ = entry
            if gen <= tomb_gen:
                raise ResurrectionInvariantError(
                    f"delayed tombstone gen {tomb_gen} would delete live gen {gen} for {key!r}"
                )
        self._tombstone_gen[key] = max(self._tombstone_gen.get(key, -1), tomb_gen)
