# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-silent-resurrection-of-forgotten-memory-records-under-retention-policy-compaction.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-silent-resurrection-of-forgotten-memory-records-under-retention-policy-compaction.warrant.json
# Markdown SHA-256:   06986204ed2585690dcc9a2dbda980d701ae3d9ca2a3c363785d959820cad6d7
# Code AST SHA-256:   b439e1c1745dff2aac503282c0ab3145c25a7ee538e4963f76f2f30e6144b33d
# Verified Classes:   ResurrectionAfterForgetError
# Defensive Guards:   3 fail-closed invariants (zero external deps)

class ResurrectionAfterForgetError(RuntimeError):
    """Raised when a record readable after forget indicates a resurrection."""
    pass


def verify_forget_is_effective(memory_api, content_identity: str, tombstone_seq: int) -> None:
    """
    Verify that a forget is effective, not merely recorded.

    The audit log records intent. This function checks state: a read-back
    must return no record whose content identity matches, and no record
    whose sequence number is <= the tombstone sequence number.
    """
    audit = memory_api.audit_log()
    forgets = [e for e in audit if e.get("content_identity") == content_identity and e.get("op") == "forget"]
    if not forgets:
        raise ResurrectionAfterForgetError(
            f"no forget event for content_identity={content_identity!r}; cannot verify"
        )

    max_tombstone_seq = max(e["seq"] for e in forgets)
    if max_tombstone_seq != tombstone_seq:
        raise ResurrectionAfterForgetError(
            f"tombstone_seq mismatch: caller={tombstone_seq} audit={max_tombstone_seq}"
        )

    survivors = memory_api.read(content_identity=content_identity)
    resurrected = [
        r for r in survivors
        if r.get("seq", 0) <= max_tombstone_seq
        or r.get("content_identity") == content_identity
    ]
    if resurrected:
        raise ResurrectionAfterForgetError(
            f"content_identity={content_identity!r} still readable after forget "
            f"at seq {max_tombstone_seq}: {len(resurrected)} record(s) survived. "
            f"Likely cause: compaction replay/reorder or ungated re-ingest. "
            f"Check read-time tombstone filtering and content-identity in tombstone."
        )


def safe_forget(memory_api, content_identity: str) -> int:
    """
    Forget and verify. Returns the tombstone sequence number on success.
    Raises ResurrectionAfterForgetError if the forget is not effective.
    """
    tombstone_seq = memory_api.forget(content_identity=content_identity)
    verify_forget_is_effective(memory_api, content_identity, tombstone_seq)
    return tombstone_seq
