# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-of-a-forget-operation-succeed-while-the-underlying-bytes-remain-recoverable-the-tombstone-before-erasure-invariant-in-scoped-memo.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-of-a-forget-operation-succeed-while-the-underlying-bytes-remain-recoverable-the-tombstone-before-erasure-invariant-in-scoped-memo.warrant.json
# Markdown SHA-256:   d3cb92846374adb77a36c508f1633e5f9ff3590c24af35793804209d657b9889
# Code AST SHA-256:   ff644f245b89d170a6697833f3774ced6b2d4527b7571cc71e4c566fedd24f95
# Verified Classes:   ErasureNotConfirmedError, ForgetReceipt
# Defensive Guards:   2 fail-closed invariants (zero external deps)

import time
from dataclasses import dataclass
from typing import Optional


class ErasureNotConfirmedError(RuntimeError):
    """Raised when a caller requires byte erasure but only visibility removal is confirmed."""


@dataclass
class ForgetReceipt:
    key: str
    scope: str
    tombstone_committed: bool
    compaction_barrier: Optional[str]  # None until compaction acknowledges erasure


def forget_and_require_erasure(
    api,
    scope: str,
    key: str,
    *,
    require_byte_erasure: bool,
    barrier_timeout_s: float = 300.0,
    poll_interval_s: float = 1.0,
) -> ForgetReceipt:
    """
    Issue a forget and, if byte erasure is required, block until the compaction
    barrier acknowledges it. The forget call itself only guarantees visibility
    removal; treating its return as erasure completion is the boundary failure.
    """
    resp = api.forget(scope=scope, key=key, reason="redaction")
    receipt = ForgetReceipt(
        key=key,
        scope=scope,
        tombstone_committed=bool(resp.get("status") == "forgotten"),
        compaction_barrier=None,
    )

    if not receipt.tombstone_committed:
        raise ErasureNotConfirmedError(
            f"forget did not commit a tombstone for {scope}/{key}: {resp!r}"
        )

    if not require_byte_erasure:
        # Visibility removal is the contract; return without waiting.
        return receipt

    deadline = time.monotonic() + barrier_timeout_s
    while time.monotonic() < deadline:
        barrier = api.await_compaction_barrier(scope=scope, key=key)
        if barrier is not None:
            receipt.compaction_barrier = barrier
            return receipt
        time.sleep(poll_interval_s)

    # Tombstone is durable, but bytes may still be recoverable from segments,
    # replicas, or backups. Do not report success to an erasure-requiring caller.
    raise ErasureNotConfirmedError(
        f"tombstone committed for {scope}/{key} but compaction barrier not "
        f"acknowledged within {barrier_timeout_s}s; payload may remain "
        f"recoverable from segments/replicas/backups. Do not treat as erased."
    )
