# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-refuse-to-honor-a-scoped-memory-delete-when-the-namespace-tombstone-and-the-decay-clock-disagree.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-refuse-to-honor-a-scoped-memory-delete-when-the-namespace-tombstone-and-the-decay-clock-disagree.warrant.json
# Markdown SHA-256:   33a497cd83e04d8d128a9b8a888800fdb7e6ecbdee5122cb76e9a32cecff475a
# Code AST SHA-256:   4b0d86c33b2c001c48d7d7b05b1a2f7a4ee5d075c55adfef84f60c83443dc89c
# Verified Classes:   TombstoneResurrection, MemoryRead, ForgetAck
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Optional


class TombstoneResurrection(RuntimeError):
    """Raised when a read returns a value the agent has acknowledged as deleted."""


@dataclass(frozen=True)
class MemoryRead:
    key: str
    namespace: str
    value: Optional[str]
    write_epoch: int
    decay_score: float


@dataclass(frozen=True)
class ForgetAck:
    key: str
    namespace: str
    tombstone_epoch: int


def guarded_read(
    read: MemoryRead,
    ack: Optional[ForgetAck],
    *,
    sentinel: str = "__DELETED__",
) -> Optional[str]:
    """Enforce deleted(K,N) => not readable(K,N) for all post-ack reads.

    Invariant: a value is trustworthy only if its write_epoch is strictly
    greater than the tombstone epoch for the same (namespace, key). Decay
    score is ignored for existence; it is a liveness signal only.
    """
    if ack is not None:
        if (ack.namespace, ack.key) != (read.namespace, read.key):
            raise TombstoneResurrection(
                f"ack/read namespace-key mismatch: "
                f"ack=({ack.namespace},{ack.key}) read=({read.namespace},{read.key})"
            )
        if read.write_epoch <= ack.tombstone_epoch:
            # Store returned a value the agent has tombstoned. Do not act on it.
            raise TombstoneResurrection(
                f"resurrected {read.namespace}/{read.key}: "
                f"write_epoch={read.write_epoch} <= tombstone_epoch={ack.tombstone_epoch}, "
                f"decay_score={read.decay_score}"
            )
    if read.value == sentinel:
        return None
    return read.value


def safe_forget_or_overwrite(
    ack: Optional[ForgetAck],
    read: MemoryRead,
    *,
    sentinel: str = "__DELETED__",
) -> str:
    """Fallback when the store exposes no epochs: convert delete to overwrite.

    Returns the sentinel to write. Caller must write it before any read whose
    correctness depends on absence.
    """
    if ack is None:
        return sentinel
    if read.write_epoch <= ack.tombstone_epoch:
        raise TombstoneResurrection(
            f"cannot trust absence of {read.namespace}/{read.key}; "
            "store did not honor tombstone on read path"
        )
    return sentinel
