# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-forget-a-deletion-that-its-own-audit-log-proves-it-performed.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-forget-a-deletion-that-its-own-audit-log-proves-it-performed.warrant.json
# Markdown SHA-256:   94934488aa2f59fa87b7bb8a3ac491bb7d1ac97538042df63506af89a94a5aa8
# Code AST SHA-256:   26c2812b44f029b31505eb5a62d355dcd7056594320f00384717f8ac864f103a
# Verified Classes:   ErasureContinuityViolation, Tombstone, MemoryStore
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional


class ErasureContinuityViolation(RuntimeError):
    """Raised when a write resurrects a tombstoned key without authorization."""


@dataclass
class Tombstone:
    key: str
    audit_id: str
    seq: int
    max_retention_days: int


@dataclass
class MemoryStore:
    rows: dict = field(default_factory=dict)
    tombstones: dict = field(default_factory=dict)  # key -> Tombstone, monotonic
    audit: list = field(default_factory=list)
    _seq: int = 0

    def _next_seq(self) -> int:
        self._seq += 1
        return self._seq

    def forget(self, key: str, reason: str, actor: str, retention_days: int = 0) -> str:
        seq = self._next_seq()
        audit_id = f"a-{seq}"
        prior = self.tombstones.get(key)
        max_ret = max(retention_days, prior.max_retention_days if prior else 0)
        self.rows.pop(key, None)
        self.tombstones[key] = Tombstone(key, audit_id, seq, max_ret)
        self.audit.append({"seq": seq, "op": "forget", "key": key,
                           "audit_id": audit_id, "reason": reason, "actor": actor})
        return audit_id

    def write(self, key: str, value, source: str,
              resurrect_token: Optional[str] = None) -> str:
        tomb = self.tombstones.get(key)
        if tomb is not None:
            if resurrect_token is None:
                # Absence is not prohibition: reject re-derivation of a
                # tombstoned key unless an authorized resurrection is shown.
                raise ErasureContinuityViolation(
                    f"write to tombstoned key {key!r} (tombstone {tomb.audit_id}, "
                    f"source={source!r}) without resurrection token"
                )
            if resurrect_token != tomb.audit_id:
                raise ErasureContinuityViolation(
                    f"resurrection token for {key!r} does not match tombstone "
                    f"{tomb.audit_id}"
                )
            # Authorized resurrection: tombstone is superseded, not deleted,
            # so the audit chain still links back to the original erasure.
        seq = self._next_seq()
        audit_id = f"a-{seq}"
        self.rows[key] = value
        self.audit.append({"seq": seq, "op": "write", "key": key,
                           "audit_id": audit_id, "source": source,
                           "resurrect_of": tomb.audit_id if tomb else None})
        return audit_id

    def verify_erasure_continuity(self) -> None:
        """End-of-task check: any same-key write after a tombstone with no
        resurrection link is a continuity violation, even if the store
        currently looks clean."""
        last_tombstone_seq: dict = {}
        for entry in self.audit:
            if entry["op"] == "forget":
                last_tombstone_seq[entry["key"]] = entry["seq"]
            elif entry["op"] == "write":
                t = last_tombstone_seq.get(entry["key"])
                if t is not None and entry.get("resurrect_of") is None:
                    raise ErasureContinuityViolation(
                        f"key {entry['key']!r} re-written at seq {entry['seq']} "
                        f"after tombstone at seq {t} with no resurrection link"
                    )


# Reproduction of the observed trace:
store = MemoryStore()
store.write("user/pref/api_region", "eu-west-1", source="user_stated")
store.forget("user/pref/api_region", reason="erasure_request", actor="user")

# Turn 2: agent re-derives the value from residual context and tries to persist.
try:
    store.write("user/pref/api_region", "eu-west-1", source="inferred")
except ErasureContinuityViolation as exc:
    print("blocked at write boundary:", exc)

# If the write path had been absence-only, the violation would surface here:
store.verify_erasure_continuity()
