# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-the-boundary-of-a-forget-that-silently-leaves-semantic-residue-in-its-own-retrieval-path.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-the-boundary-of-a-forget-that-silently-leaves-semantic-residue-in-its-own-retrieval-path.warrant.json
# Markdown SHA-256:   1509e043a77ebc3bb876702c37a990162709a492d76f2f0f8e87a5bb1612b121
# Code AST SHA-256:   b3205ea1471641b96cd99dba1ea9d3246824c976c6d79850917b233c5f6aea63
# Verified Classes:   ErasureResidueError
# Defensive Guards:   2 fail-closed invariants (zero external deps)

class ErasureResidueError(RuntimeError):
    """Raised when a retrievable artifact derives from an erased source."""
    pass


def resolve_provenance(artifact, store, seen=None):
    """Walk derivation edges from artifact back to live sources.

    Returns the set of live source ids. Raises if any edge terminates
    in a tombstone, because that means erasure did not propagate.
    """
    if seen is None:
        seen = set()
    if artifact.id in seen:
        return set()
    seen.add(artifact.id)

    live_sources = set()
    for edge in store.provenance_edges(artifact.id):
        source = store.get(edge.source_id)
        if source is None or source.tombstoned:
            raise ErasureResidueError(
                f"artifact {artifact.id} derives from erased source "
                f"{edge.source_id}; erasure did not traverse derivation closure"
            )
        if source.is_derived:
            live_sources |= resolve_provenance(source, store, seen)
        else:
            live_sources.add(source.id)
    return live_sources


def assert_retrievable(artifact, store):
    """Precondition for serving any semantic artifact to the context window."""
    if not artifact.is_derived:
        return True
    try:
        resolve_provenance(artifact, store)
    except ErasureResidueError:
        store.quarantine(artifact.id)
        raise
    return True


def erase_subject(subject_id, store):
    """Erasure must operate over the derivation closure, not the row table."""
    matched = store.records_matching_subject(subject_id)
    closure = store.derivation_closure(record.id for record in matched)
    for artifact_id in closure:
        artifact = store.get(artifact_id)
        if artifact is not None and not artifact.tombstoned:
            store.tombstone(artifact_id)
    store.await_consolidation_settled(subject_id)
    for artifact in store.retrievable_artifacts():
        assert_retrievable(artifact, store)
    return store.issue_receipt(subject_id, closure)
