# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-a-memory-tool-forget-as-a-tombstone-rather-than-a-delete-and-why-a-naive-read-after-forget-across-session.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-a-memory-tool-forget-as-a-tombstone-rather-than-a-delete-and-why-a-naive-read-after-forget-across-session.warrant.json
# Markdown SHA-256:   66c6e717cb4b8192faa11ebae330614a8003cb282272c444bbcafbb8acd9211a
# Code AST SHA-256:   dcafc432aafa495516f672dae3b41f1e287ba451383425a99b80fb71483b7c8f
# Verified Classes:   TombstoneEpochViolation, ReadResult
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Optional


class TombstoneEpochViolation(RuntimeError):
    """Raised when a read is used to derive a write without a proven epoch."""
    pass


@dataclass(frozen=True)
class ReadResult:
    key: str
    value: str
    version: int
    tombstone_epoch: Optional[int]      # None means store did not report epoch
    applied_epoch: Optional[int]        # reader's replica epoch, if known


def derive_write(read: ReadResult, new_value: str) -> dict:
    """
    Gate any write derived from a read on the tombstone invariant.
    A read is only safe to derive from if we can prove the reader's
    applied epoch is at or beyond any tombstone that exists for the key.
    """
    if read.tombstone_epoch is None or read.applied_epoch is None:
        # Store did not expose epoch metadata: the value may be a stale
        # pre-tombstone snapshot. Derivation would be a resurrection vector.
        raise TombstoneEpochViolation(
            f"cannot derive write for {read.key!r}: read lacks epoch proof "
            f"(tombstone_epoch={read.tombstone_epoch!r}, "
            f"applied_epoch={read.applied_epoch!r})"
        )

    if read.applied_epoch < read.tombstone_epoch:
        raise TombstoneEpochViolation(
            f"cannot derive write for {read.key!r}: reader epoch "
            f"{read.applied_epoch} behind tombstone epoch "
            f"{read.tombstone_epoch}; value v{read.version} is stale"
        )

    # Safe: value is live at a version the tombstone filter has cleared.
    # Emit a compare-and-set write so a concurrent forget still wins.
    return {
        "key": read.key,
        "value": new_value,
        "expected_version": read.version,
        "min_tombstone_epoch": read.tombstone_epoch,
    }


def safe_forget_roundtrip(store, key: str, reader_epoch: int) -> ReadResult:
    """
    Demonstrates the failing path: forget returns an epoch, but a
    second session reads without that epoch applied.
    """
    forget_resp = store.forget(key)
    if "tombstone_epoch" not in forget_resp:
        raise TombstoneEpochViolation(
            f"forget({key!r}) returned no tombstone_epoch; contract unverifiable"
        )
    tombstone_epoch = forget_resp["tombstone_epoch"]

    # Session B's replica has not applied the tombstone yet.
    stale = store.read(key, replica_epoch=reader_epoch)
    result = ReadResult(
        key=key,
        value=stale["value"],
        version=stale["version"],
        tombstone_epoch=tombstone_epoch,
        applied_epoch=reader_epoch,
    )

    # This is the exact call that resurrected the poison in the trace:
    derive_write(result, new_value=result.value)  # -> raises here
    return result
