# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-resurrect-a-forgotten-fact-when-a-retention-scope-outlives-the-ttl-of-the-record-it-scoped.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-resurrect-a-forgotten-fact-when-a-retention-scope-outlives-the-ttl-of-the-record-it-scoped.warrant.json
# Markdown SHA-256:   2c690990d90ff3dbdd4d4c56574ee8bee94288bd8b05d2f7d27b62efbb0a7a66
# Code AST SHA-256:   610cd505e7b5461d542bb969b1d9d3e2671ae9fbb11714aac64eb3ace757a991
# Verified Classes:   ResurrectionAfterErasure
# Defensive Guards:   4 fail-closed invariants (zero external deps)

class ResurrectionAfterErasure(RuntimeError):
    """Raised when a fact is retrievable after its erasure was reported successful."""
    pass


def verify_erasure(memory, subject_id: str, probe_queries: list[str]) -> None:
    """
    Post-erasure invariant check. Must be run from a cold-started context:
    a warm session-local cache would mask the resurrection.
    """
    scope = memory.resolve_scope(f"subject:{subject_id}")
    # Invariant 1: the scope must be unresolvable, not merely empty.
    if scope is not None and scope.is_live():
        raise ResurrectionAfterErasure(
            f"scope subject:{subject_id} still live after forget "
            f"(expires_at={scope.expires_at}); a live empty scope is a "
            f"resurrection key for cross-scope projections"
        )

    # Invariant 2: derivation closure — no projection may survive.
    survivors = memory.walk_derivations(subject_id, direction="up")
    if survivors:
        raise ResurrectionAfterErasure(
            f"derived artifacts survived erasure of subject:{subject_id}: "
            f"{[s.key for s in survivors]}"
        )

    # Invariant 3: fact-level tombstone must gate every read path.
    for q in probe_queries:
        hits = memory.read(q, scope=f"subject:{subject_id}")
        if hits:
            raise ResurrectionAfterErasure(
                f"probe {q!r} returned {len(hits)} hit(s) post-erasure; "
                f"tombstone not consulted before scope filter"
            )


def forget(memory, subject_id: str, reason: str) -> dict:
    memory.tombstone_fact(subject_id, reason=reason)      # gate reads first
    memory.walk_derivations(subject_id, direction="up",
                            action="tombstone")            # close derivations
    memory.delete_rows_in_scope(f"subject:{subject_id}")   # container cleanup
    memory.expire_scope(f"subject:{subject_id}")           # kill the key
    try:
        verify_erasure(memory, subject_id, probe_queries=memory.recent_probes)
    except ResurrectionAfterErasure as exc:
        raise ResurrectionAfterErasure(
            f"forget() reported success but erasure invariant failed: {exc}"
        ) from exc
    return {"subject": subject_id, "status": "forgotten", "reason": reason}
