# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-reconcile-a-gdpr-erasure-tombstone-against-an-in-flight-episodic-write-whose-retention-scope-was-already-destroyed.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-reconcile-a-gdpr-erasure-tombstone-against-an-in-flight-episodic-write-whose-retention-scope-was-already-destroyed.warrant.json
# Markdown SHA-256:   e26de042d1ed713219558d954eb485303c22106a0503d5fa00fc7947e3ecd624
# Code AST SHA-256:   a2c5a8eb31450834100dc1b8628236a60b34b3382408d6414fd41e59469788a0
# Verified Classes:   TombstonedScopeError, ErasureBreachDetected, ScopeState, MemoryTool
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional


class TombstonedScopeError(RuntimeError):
    """Raised when a write or read targets a scope whose tombstone epoch has advanced."""


class ErasureBreachDetected(RuntimeError):
    """Raised when a post-erasure verification read returns records for an erased scope."""


@dataclass
class ScopeState:
    name: str
    tombstone_epoch: int = 0
    tombstoned: bool = False
    records: list = field(default_factory=list)


class MemoryTool:
    def __init__(self) -> None:
        self._scopes: dict[str, ScopeState] = {}
        self._pending: dict[str, tuple[str, int]] = {}  # write_id -> (scope, admitted_epoch)
        self._write_seq = 0

    def _get(self, name: str) -> Optional[ScopeState]:
        return self._scopes.get(name)

    def write(self, scope: str, record: dict, expected_tombstone_epoch: int) -> str:
        state = self._get(scope)
        current_epoch = state.tombstone_epoch if state else 0
        if current_epoch != expected_tombstone_epoch:
            raise TombstonedScopeError(
                f"scope {scope!r} epoch is {current_epoch}, writer expected {expected_tombstone_epoch}"
            )
        if state is None:
            # Lazy creation is allowed ONLY because epoch 0 matched; a tombstoned
            # scope would have epoch >= 1 and would have raised above.
            state = ScopeState(name=scope)
            self._scopes[scope] = state
        self._write_seq += 1
        write_id = f"w_{self._write_seq}"
        self._pending[write_id] = (scope, current_epoch)
        return write_id

    def flush(self, write_id: str, record: dict) -> None:
        scope, admitted_epoch = self._pending.pop(write_id)
        state = self._get(scope)
        current_epoch = state.tombstone_epoch if state else admitted_epoch
        if current_epoch != admitted_epoch:
            # Tombstone advanced between admission and commit: fail closed.
            raise TombstonedScopeError(
                f"flush of {write_id} rejected: scope {scope!r} epoch moved "
                f"{admitted_epoch} -> {current_epoch}"
            )
        state.records.append(record)

    def forget(self, scope: str, reason: str) -> int:
        state = self._get(scope)
        if state is None:
            # Tombstone a never-created scope by materializing a tombstoned state
            # so a later lazy write cannot resurrect it at epoch 0.
            state = ScopeState(name=scope, tombstone_epoch=1, tombstoned=True)
            self._scopes[scope] = state
            return 0
        erased = len(state.records)
        state.records.clear()
        state.tombstoned = True
        state.tombstone_epoch += 1
        return erased

    def verify_erasure(self, scope: str) -> None:
        state = self._get(scope)
        if state is not None and state.tombstoned and state.records:
            raise ErasureBreachDetected(
                f"scope {scope!r} tombstoned at epoch {state.tombstone_epoch} "
                f"but still holds {len(state.records)} records"
            )


def run_erasure_race() -> None:
    tool = MemoryTool()
    wid = tool.write("user:42", {"fact": "dietary: vegan"}, expected_tombstone_epoch=0)
    tool.forget("user:42", reason="gdpr_art17")  # epoch 0 -> 1
    try:
        tool.flush(wid, {"fact": "dietary: vegan"})
    except TombstonedScopeError:
        pass
    # A new writer that did not observe the tombstone must be rejected.
    try:
        tool.write("user:42", {"fact": "home: Berlin"}, expected_tombstone_epoch=0)
    except TombstonedScopeError as exc:
        raise ErasureBreachDetected(
            "post-erasure write admitted under stale epoch"
        ) from exc
