# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-refuse-a-forget-that-is-not-yet-durable-the-retention-tombstone-write-resurrection-race-in-agent-memory-tool-apis.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-refuse-a-forget-that-is-not-yet-durable-the-retention-tombstone-write-resurrection-race-in-agent-memory-tool-apis.warrant.json
# Markdown SHA-256:   94c7d01034c1046e433a11ca70031354a34ebaf279ad8edefe4f2cfd18895bd6
# Code AST SHA-256:   9cc6d898fd43fb7bc7be446ca2523b7db7f086c780cfb2732844a0b350392341
# Verified Classes:   ForgetNotDurableError, ForgetReceipt, MemoryView
# Defensive Guards:   5 fail-closed invariants (zero external deps)

from __future__ import annotations

from dataclasses import dataclass, field
from typing import Optional


class ForgetNotDurableError(RuntimeError):
    """Raised when a forget receipt cannot be treated as an erasure.

    Triggered when the store's read path still serves the key, when a
    subsequent write would reuse a version at or below the receipt's
    version_floor, or when the receipt omits the version floor entirely.
    """


@dataclass(frozen=True)
class ForgetReceipt:
    key: str
    tombstone_id: str
    retention_until: float
    version_floor: Optional[int]  # None == store did not expose a floor


@dataclass
class MemoryView:
    """Minimal client-side model of the store's observable state."""
    live: dict[str, tuple[str, int]] = field(default_factory=dict)  # key -> (value, version)
    tombstones: dict[str, list[ForgetReceipt]] = field(default_factory=dict)
    global_version: int = 0


def verify_forget(
    view: MemoryView,
    receipt: ForgetReceipt,
    *,
    agent_wrote_since: bool,
) -> None:
    """Enforce the durability invariant for a single forget receipt.

    Raises ForgetNotDurableError if the receipt cannot be trusted as an
    erasure. Returns None only when the invariant holds.
    """
    if receipt.version_floor is None:
        raise ForgetNotDurableError(
            f"forget({receipt.key!r}) returned no version_floor; "
            f"receipt {receipt.tombstone_id} is an intent, not an effect"
        )

    prior = view.tombstones.get(receipt.key, [])
    if prior:
        # Idempotency collapse: a second tombstone for the same key must
        # not shorten the retention window relative to the first.
        earliest = min(p.retention_until for p in prior)
        if receipt.retention_until < earliest:
            raise ForgetNotDurableError(
                f"duplicate tombstone {receipt.tombstone_id} for {receipt.key!r} "
                f"shortens retention from {earliest} to {receipt.retention_until}; "
                f"retry must reuse original tombstone_id"
            )

    if receipt.key in view.live:
        value, version = view.live[receipt.key]
        if version <= receipt.version_floor:
            raise ForgetNotDurableError(
                f"read path still serves {receipt.key!r} at version {version} "
                f"<= version_floor {receipt.version_floor} after tombstone "
                f"{receipt.tombstone_id}; read path is not fenced"
            )
        if not agent_wrote_since:
            raise ForgetNotDurableError(
                f"read path serves {receipt.key!r} at version {version} > floor "
                f"{receipt.version_floor} but this agent issued no write; "
                f"a peer or the store resurrected the key — quarantine, do not retry"
            )
        # agent_wrote_since and version > floor: legitimate re-creation.
        return

    # Read path empty for the key: the forget is provisionally durable.
    return


def safe_forget(
    view: MemoryView,
    receipt: ForgetReceipt,
    *,
    agent_wrote_since: bool,
) -> None:
    try:
        verify_forget(view, receipt, agent_wrote_since=agent_wrote_since)
    except ForgetNotDurableError:
        # Do NOT retry forget() here: a blind retry produces a second
        # tombstone. Escalate to quarantine with the original tombstone_id.
        raise
    view.tombstones.setdefault(receipt.key, []).append(receipt)
