# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-a-deletion-acknowledgement-as-a-tombstone-rather-than-a-proof-of-erasure.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-a-deletion-acknowledgement-as-a-tombstone-rather-than-a-proof-of-erasure.warrant.json
# Markdown SHA-256:   b9cd7614f117a5f727d1e3df2bca117cf87d591f4c512a61ca649acee06d2dec
# Code AST SHA-256:   564f079a99f7f55cedb8b6eb70f7e551f8ec395edea30af6a78934cfef95ec77
# Verified Classes:   TombstoneViolation, AckKind, ForgetAck, ScopedMemory
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass, field
from enum import Enum


class TombstoneViolation(RuntimeError):
    """Raised when a write or handoff would re-materialize a tombstoned key."""


class AckKind(Enum):
    ERASURE = "erasure"        # reclaimed + checkpointed + no leases
    TOMBSTONE = "tombstone"    # logical delete only; must be re-asserted


@dataclass
class ForgetAck:
    ok: bool
    reclaimed: bool
    checkpoint_advanced: bool
    outstanding_leases: int
    compaction_due: bool

    def classify(self) -> AckKind:
        if (
            self.ok
            and self.reclaimed
            and self.checkpoint_advanced
            and self.outstanding_leases == 0
            and not self.compaction_due
        ):
            return AckKind.ERASURE
        return AckKind.TOMBSTONE


@dataclass
class ScopedMemory:
    scope: str
    records: dict = field(default_factory=dict)
    # Tombstones live OUTSIDE the data scope and survive cold start.
    tombstones: set = field(default_factory=set)
    pending_reassert: dict = field(default_factory=dict)  # key -> last ack

    def write(self, key: str, value: str) -> None:
        if key in self.tombstones:
            raise TombstoneViolation(
                f"write to tombstoned key {key!r} in scope {self.scope!r}; "
                "tombstone must be reclaimed before re-materialization"
            )
        self.records[key] = value

    def forget(self, key: str, ack: ForgetAck) -> AckKind:
        self.records.pop(key, None)
        kind = ack.classify()
        if kind is AckKind.TOMBSTONE:
            self.tombstones.add(key)
            self.pending_reassert[key] = ack
        else:
            self.tombstones.discard(key)
            self.pending_reassert.pop(key, None)
        return kind

    def ingest_handoff(self, key: str, value: str, origin_key: str) -> None:
        # A peer summary quoting a tombstoned origin is a laundering channel.
        if origin_key in self.tombstones or key in self.tombstones:
            raise TombstoneViolation(
                f"handoff re-materializes tombstoned origin {origin_key!r} "
                f"as {key!r}; route to quarantine, do not ingest"
            )
        self.write(key, value)

    def on_cold_start(self) -> list:
        # Re-assert every pending tombstone before serving any read.
        return list(self.pending_reassert.keys())


def recover_after_restart(mem: ScopedMemory, replay_wal: list) -> None:
    # Replay may re-apply writes that were logically deleted.
    for op in replay_wal:
        if op["op"] == "write":
            if op["key"] in mem.tombstones:
                raise TombstoneViolation(
                    f"WAL replay would resurrect tombstoned key {op['key']!r} "
                    "in scope {mem.scope!r}; delete marker not checkpointed"
                )
            mem.records[op["key"]] = op["value"]
    for key in mem.on_cold_start():
        # Caller must re-issue forget(key) until reclaimed == True.
        pass
