# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-forget-the-tombstones-before-it-forgets-the-payloads-deletion-ordering-inversion-in-forget-capable-memory-tool-contracts.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-forget-the-tombstones-before-it-forgets-the-payloads-deletion-ordering-inversion-in-forget-capable-memory-tool-contracts.warrant.json
# Markdown SHA-256:   46e096d95df00b8cf3ce2ddfd78ecf2d139f9c322ba76f99ac00f606151d59c2
# Code AST SHA-256:   d522c5b9e6eb5ac3813c906907c444d85ad31e1f2bc80ca7ff1c8a97856142ed
# Verified Classes:   ForgetContractViolation, MemoryTool, ForgetReceipt
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from __future__ import annotations

import time
from dataclasses import dataclass
from typing import Any, Optional, Protocol


class ForgetContractViolation(RuntimeError):
    """Raised when a forget-capable tool cannot support read-after-forget verification."""


class MemoryTool(Protocol):
    def write(self, key: str, value: Any) -> dict: ...
    def read(self, key: str, min_epoch: Optional[int] = None) -> Optional[Any]: ...
    def forget(self, key: str) -> dict: ...


@dataclass(frozen=True)
class ForgetReceipt:
    key: str
    status: str
    epoch: Optional[int]          # None means the tool did not expose an epoch
    compaction_pending: bool      # tool's own admission that payload outlives tombstone


def forget_and_verify(
    tool: MemoryTool,
    key: str,
    *,
    max_wait_s: float = 5.0,
    poll_s: float = 0.05,
) -> ForgetReceipt:
    """
    Forget `key` and verify deletion without falling into the resurrection window.

    Precondition: the tool MUST either (a) guarantee synchronous read-after-forget,
    or (b) return an epoch that read() honors as min_epoch. An unversioned read
    against an eventually-consistent tool is treated as a contract violation,
    because it cannot distinguish 'not yet compacted' from 'still present'.
    """
    raw = tool.forget(key)
    epoch = raw.get("epoch")
    pending = bool(raw.get("compaction_pending", False))

    if raw.get("status") != "deleted":
        raise ForgetContractViolation(
            f"forget({key!r}) did not report deletion: {raw!r}"
        )

    # Case (a): synchronous guarantee, or tool gave us an epoch to pin the read.
    if epoch is not None:
        observed = tool.read(key, min_epoch=epoch)
        if observed is not None:
            raise ForgetContractViolation(
                f"resurrection: read({key!r}, min_epoch={epoch}) returned payload "
                f"after forget reported success; tool tombstone is not authoritative"
            )
        return ForgetReceipt(key, "deleted", epoch, pending)

    # Case (b): tool gave no epoch. If it also admits async compaction, an
    # unversioned read-back is unsafe and must not be used as verification.
    if pending:
        deadline = time.monotonic() + max_wait_s
        while time.monotonic() < deadline:
            # Poll a *compaction-completion* signal, never a naive read.
            if tool.read(key, min_epoch=None) is None and not _compaction_pending(tool, key):
                return ForgetReceipt(key, "deleted", None, False)
            time.sleep(poll_s)
        raise ForgetContractViolation(
            f"forget({key!r}) returned success but compaction did not complete "
            f"within {max_wait_s}s and no epoch was exposed; cannot verify deletion "
            f"without risking resurrection-window contamination"
        )

    # No epoch, no pending compaction: tool claims synchronous. One read is safe.
    if tool.read(key) is not None:
        raise ForgetContractViolation(
            f"forget({key!r}) reported synchronous success but read returned payload"
        )
    return ForgetReceipt(key, "deleted", None, False)


def _compaction_pending(tool: MemoryTool, key: str) -> bool:
    probe = getattr(tool, "compaction_status", None)
    if probe is None:
        return True  # cannot prove completion; treat as pending
    return bool(probe(key).get("pending", True))
