# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-a-successful-memory-delete-as-a-tombstone-rather-than-an-erasure-and-why-forgetting-then-relearning-silently.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-a-successful-memory-delete-as-a-tombstone-rather-than-an-erasure-and-why-forgetting-then-relearning-silently.warrant.json
# Markdown SHA-256:   6ae2a89e4bde72c7610f03422fbb3f7f49b86493454bf8db87fb8be5a1513935
# Code AST SHA-256:   ef730a22142ee927fbe610853606af0a84059c355004cd145f09da9a3bf31610
# Verified Classes:   ResurrectionError, Tombstone, MemoryStore
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional


class ResurrectionError(RuntimeError):
    """Raised when a write attempts to reintroduce a suppressed memory key
    without an explicit override, indicating a stale-fact resurrection."""


@dataclass
class Tombstone:
    key: str
    suppressed_at: float
    reason: str
    prior_value_hash: str


@dataclass
class MemoryStore:
    live: dict = field(default_factory=dict)
    tombstones: dict = field(default_factory=dict)

    def write(self, key: str, value: str, now: float,
              override_suppression: bool = False,
              override_reason: Optional[str] = None) -> None:
        tomb = self.tombstones.get(key)
        if tomb is not None and not override_suppression:
            raise ResurrectionError(
                f"write to '{key}' blocked: key suppressed at {tomb.suppressed_at} "
                f"(reason={tomb.reason!r}). A stale source is attempting to "
                f"resurrect a forgotten fact. Pass override_suppression=True "
                f"with a stated reason to re-assert deliberately."
            )
        if tomb is not None and override_suppression:
            if not override_reason:
                raise ResurrectionError(
                    f"override for '{key}' requires a stated reason; "
                    f"cannot distinguish user correction from resurrection."
                )
            del self.tombstones[key]
        self.live[key] = {"value": value, "created_at": now, "salience": 1.0}

    def forget(self, key: str, now: float, reason: str) -> None:
        rec = self.live.pop(key, None)
        if rec is None:
            return
        self.tombstones[key] = Tombstone(
            key=key,
            suppressed_at=now,
            reason=reason,
            prior_value_hash=str(hash(rec["value"])),
        )

    def expire(self, key: str) -> None:
        # TTL-driven: erasure is correct, relearning is expected.
        self.live.pop(key, None)

    def read(self, key: str) -> Optional[str]:
        rec = self.live.get(key)
        return rec["value"] if rec else None


def reconcile_stale_summarizer(store: MemoryStore, key: str,
                               stale_value: str, now: float) -> str:
    """Called by a summarizer sub-task that found an old fact in a document.
    Must not silently overwrite a suppressed key."""
    try:
        store.write(key, stale_value, now)
    except ResurrectionError as e:
        return f"DISCARDED stale fact for '{key}': {e}"
    return f"wrote '{key}'"


if __name__ == "__main__":
    s = MemoryStore()
    s.write("user_pref_timezone", "UTC-8", now=0.0)
    s.forget("user_pref_timezone", now=40.0, reason="user moved to UTC+1")
    s.write("user_pref_timezone", "UTC+1", now=40.0)

    # Day 70: a stale document mentions UTC-8; summarizer tries to write it.
    result = reconcile_stale_summarizer(s, "user_pref_timezone", "UTC-8", now=70.0)
    print(result)
    assert s.read("user_pref_timezone") == "UTC+1"
