# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-a-forget-acknowledgment-as-provisional-until-the-deletion-is-re-verified-against-the-backing-store-rather.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-a-forget-acknowledgment-as-provisional-until-the-deletion-is-re-verified-against-the-backing-store-rather.warrant.json
# Markdown SHA-256:   f19a660ddd5468d52c142381a1714863462bd8b60bf1c57566d10f939851fd37
# Code AST SHA-256:   ab1504871b65ad5df34f7e7400ebc1dc84e1b7b65b1b8a9ffef73b628930dbe6
# Verified Classes:   DeletionNotVerifiedError, ReadResult
# Defensive Guards:   2 fail-closed invariants (zero external deps)

import time
from dataclasses import dataclass


class DeletionNotVerifiedError(RuntimeError):
    """Raised when a forget acknowledgment cannot be confirmed against a read
    whose revision is at or beyond the delete revision. Signals that the agent
    must NOT proceed to derive or hand off content from this scope."""
    pass


@dataclass
class ReadResult:
    revision: int
    record: dict | None
    tombstone: bool


def forget_and_verify(memory, scope: str, key: str, max_attempts: int = 5,
                       backoff_s: float = 0.4) -> int:
    """Issue a scoped forget, then fence all subsequent reads on the delete
    revision. Returns the verified delete revision. Raises if verification
    cannot be established within the attempt budget."""
    ack = memory.forget(scope=scope, key=key)
    delete_rev = ack["revision"]

    for attempt in range(max_attempts):
        read: ReadResult = memory.read(scope=scope, key=key)

        if read.revision < delete_rev:
            # Stale replica: pre-deletion state. MUST discard, never ingest.
            time.sleep(backoff_s * (2 ** attempt))
            continue

        if read.revision >= delete_rev and read.record is None and read.tombstone:
            return delete_rev  # deletion verified; ack is now terminal

        if read.revision >= delete_rev and read.record is not None:
            # Deletion did not take: wrong scope/key, tombstone rejected, etc.
            raise DeletionNotVerifiedError(
                f"forget ack rev={delete_rev} but read at rev={read.revision} "
                f"still returns record for scope={scope} key={key}; "
                f"do not derive or hand off from this scope"
            )

    raise DeletionNotVerifiedError(
        f"could not observe a read at revision >= {delete_rev} for "
        f"scope={scope} key={key} within {max_attempts} attempts; "
        f"treating deletion as unverified and blocking downstream use"
    )
