# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-a-forget-success-as-a-tombstone-rather-than-a-delete-and-why-a-subsequent-read-that-misses-proves-nothing.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-a-forget-success-as-a-tombstone-rather-than-a-delete-and-why-a-subsequent-read-that-misses-proves-nothing.warrant.json
# Markdown SHA-256:   36b15b9f11cd0e86b18a670c31140cc54b22504d115772de3f770020cf2b80ba
# Code AST SHA-256:   88c8dc32d56b778c10e80c195df8e1b4c4c9e54c970fa8b586df97781cb5b404
# Verified Classes:   TombstoneIntegrityError, ForgetReceipt, ReadResult
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Optional


class TombstoneIntegrityError(RuntimeError):
    """Raised when a forget/read/write sequence cannot be proven consistent."""


@dataclass
class ForgetReceipt:
    key: str
    ok: bool
    matched: int
    epoch: Optional[int]  # None means the store did not disclose propagation epoch


@dataclass
class ReadResult:
    key: str
    found: bool
    value: Optional[str]
    epoch: Optional[int]


def safe_forget_then_rewrite(store, key: str, new_value: str) -> str:
    """
    Forget `key` and write `new_value` without risking tombstone resurrection.
    Returns the key actually written (may be generation-bumped).
    """
    receipt: ForgetReceipt = store.forget(key)
    if not receipt.ok:
        raise TombstoneIntegrityError(f"forget({key!r}) did not confirm")

    if receipt.epoch is None:
        # Store hides propagation epoch: we cannot prove the tombstone has
        # reached the write target. Generation-bump to make resurrection
        # structurally impossible instead of racing anti-entropy.
        bumped = f"{key}@orphan-{store.new_nonce()}"
        store.write(bumped, new_value)
        return bumped

    # Verify the tombstone is visible on the read path we will use for writes.
    probe: ReadResult = store.read(key)
    if probe.found:
        raise TombstoneIntegrityError(
            f"read({key!r}) still returns a value after forget epoch "
            f"{receipt.epoch}; replica skew — refusing to write under {key!r}"
        )
    if probe.epoch is None or probe.epoch < receipt.epoch:
        raise TombstoneIntegrityError(
            f"read({key!r}) epoch {probe.epoch!r} does not dominate tombstone "
            f"epoch {receipt.epoch}; empty result is UNKNOWN, not ABSENT"
        )

    # Epoch dominates: the key is genuinely free in this consistency domain.
    store.write(key, new_value)
    return key
