# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-enforce-a-forget-guarantee-when-a-redaction-tombstone-races-an-in-flight-episodic-write.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-enforce-a-forget-guarantee-when-a-redaction-tombstone-races-an-in-flight-episodic-write.warrant.json
# Markdown SHA-256:   16e371093b25b920982bcc1e01427251bf3fe312f67fb15f295b192df899ce67
# Code AST SHA-256:   d957d5a9bddc644d64e2ddbaf45a3c7576a15333e9d350d7fbc248c94a41045e
# Verified Classes:   ForgetGuaranteeViolation, ForgetNotQuiesced
# Defensive Guards:   3 fail-closed invariants (zero external deps)

class ForgetGuaranteeViolation(RuntimeError):
    """Raised when a post-forget read surfaces content that should be unrecoverable."""


class ForgetNotQuiesced(RuntimeError):
    """Raised when a barriered forget cannot confirm the ingest watermark passed the tombstone."""


def barriered_forget(memory, mem_id, *, cascade="derived", max_polls=8):
    """Issue a hard forget and confirm quiescence before declaring erasure.

    Returns the tombstone id only after the ingest watermark has advanced past
    the tombstone sequence AND the derivation graph walk has completed.
    """
    tomb = memory.forget(mem_id=mem_id, mode="hard", cascade=cascade)
    if tomb.get("status") != "ok":
        raise ForgetGuaranteeViolation(
            f"forget({mem_id}) did not return ok: {tomb!r}"
        )
    tomb_seq = tomb["seq"]

    for _ in range(max_polls):
        status = memory.forget_status(tombstone=tomb["tombstone"])
        if status.get("ingest_watermark", -1) >= tomb_seq and status.get("derivation_walk") == "complete":
            break
        memory.flush()
    else:
        raise ForgetNotQuiesced(
            f"tombstone {tomb['tombstone']} for {mem_id} never quiesced; "
            "erasure is unconfirmed and must not be reported as done"
        )

    # Verification: the only empirical proof the guarantee held.
    probe = memory.read(mem_id=mem_id, include_derived=True)
    if probe.get("content"):
        raise ForgetGuaranteeViolation(
            f"post-forget read of {mem_id} returned content; "
            f"tombstone {tomb['tombstone']} was insert-blind or non-transitive"
        )
    return tomb["tombstone"]
