# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-tombstone-resurrection-when-a-ttl-expired-memory-key-is-re-materialized-from-a-stale-episodic-cache.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-tombstone-resurrection-when-a-ttl-expired-memory-key-is-re-materialized-from-a-stale-episodic-cache.warrant.json
# Markdown SHA-256:   9340ff19208fff084f600a0095573959a89256ecba26c8af4726e1ffff68cd42
# Code AST SHA-256:   4deb09d8014a6f97fc49c97688ef42738660a41d4585317521aa1cea87cbaade
# Verified Classes:   MemoryError_, TombstoneViolation, ResurrectionSignal, Source, ReadResult
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from enum import Enum
from typing import Optional


class MemoryError_(RuntimeError):
    pass


class TombstoneViolation(MemoryError_):
    """Raised when a write targets a key with a live RTBF tombstone."""


class ResurrectionSignal(MemoryError_):
    """Raised when a cache read returns a value the store reports as erased/expired."""


class Source(Enum):
    STORE = "store"
    CACHE = "cache"


@dataclass(frozen=True)
class ReadResult:
    key: str
    value: Optional[str]
    source: Source
    write_epoch: int
    tombstone_epoch: int


def guarded_write(store, key: str, value: str, scope: str) -> int:
    """Write only if no live tombstone shadows the key. Fails closed."""
    ts = store.live_tombstone(key)
    if ts is not None:
        raise TombstoneViolation(
            f"write to {scope}:{key} blocked by tombstone {ts.tombstone_id} "
            f"(epoch {ts.epoch}); call lift_tombstone with authorization"
        )
    return store.put(key, value, scope)


def guarded_read(store, cache, key: str, scope: str, rtbf: bool) -> ReadResult:
    """Reconcile store vs cache; treat divergence as resurrection, not a miss."""
    s = store.get(key)
    c = cache.get(key)
    if rtbf and c is not None and (s is None or s.tombstone_epoch > c.write_epoch):
        raise ResurrectionSignal(
            f"cache re-materialized {scope}:{key} (cache_epoch={c.write_epoch}, "
            f"store_tombstone_epoch={getattr(s, 'tombstone_epoch', 'n/a')}); "
            f"invalidating cache and emitting audit event"
        )
    if c is not None and s is None:
        # non-RTBF scope: legal post-TTL resurrection only if store says expired
        if store.state(key) != "expired":
            raise ResurrectionSignal(f"unexplained cache hit for {scope}:{key}")
        return ReadResult(key, c.value, Source.CACHE, c.write_epoch, 0)
    return ReadResult(key, s.value if s else None, Source.STORE,
                      getattr(s, "write_epoch", 0), getattr(s, "tombstone_epoch", 0))
