# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-treat-a-memory-forget-acknowledgement-as-unverified-until-the-retention-epoch-advances.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-treat-a-memory-forget-acknowledgement-as-unverified-until-the-retention-epoch-advances.warrant.json
# Markdown SHA-256:   8a25c3817ba7c8d0f431dbbf1c95a338b9da41823c4aa8761ce196709c679efc
# Code AST SHA-256:   c901b30493c41e0a8ad31b2925bfd9b1acd612b642bb2946f8481f9ee0a00b84
# Verified Classes:   UnconfirmedForgetError, ForgetReceipt
# Defensive Guards:   2 fail-closed invariants (zero external deps)

import time
from dataclasses import dataclass


class UnconfirmedForgetError(RuntimeError):
    """Raised when a forget acknowledgement is not backed by an epoch advance."""
    pass


@dataclass
class ForgetReceipt:
    scope: str
    key: str
    issued_epoch: int


def forget_and_confirm(memory, scope: str, key: str, timeout_s: float = 5.0) -> ForgetReceipt:
    """
    Issue a forget and block until the scope's retention epoch advances past
    the epoch at which the forget was issued. Only then is the forget
    considered observable as complete.
    """
    ack = memory.forget(scope=scope, key=key)
    receipt = ForgetReceipt(scope=scope, key=key, issued_epoch=ack["epoch"])

    # Invalidate any local retrieval memoization keyed to this scope.
    memory.invalidate_local_cache(scope=scope, key=key)

    deadline = time.monotonic() + timeout_s
    while time.monotonic() < deadline:
        status = memory.scope_status(scope=scope)
        if status["epoch"] > receipt.issued_epoch:
            return receipt
        time.sleep(0.05)

    # The forget was acknowledged but never confirmed by an epoch advance.
    # We must NOT proceed as if the record is unreachable.
    raise UnconfirmedForgetError(
        f"forget of {key!r} in scope {scope!r} acknowledged at epoch "
        f"{receipt.issued_epoch} but scope epoch did not advance within "
        f"{timeout_s}s; record may still be readable on lagging replicas"
    )


def handoff_scope(memory, scope: str, sub_agent) -> None:
    """
    Propagate a scope handle to a sub-agent only after confirming the scope's
    current epoch. The sub-agent must reject reads stamped at or before this
    epoch for any key that was recently forgotten.
    """
    status = memory.scope_status(scope=scope)
    if status.get("pending_tombstones", 0) > 0:
        raise UnconfirmedForgetError(
            f"scope {scope!r} has {status['pending_tombstones']} unapplied "
            f"tombstones; refusing handoff until retention epoch is clean"
        )
    sub_agent.inherit_scope(scope=scope, confirmed_epoch=status["epoch"])
