# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-a-provenance-orphaned-memory-write-when-ttl-expiry-erases-the-tombstone-before-the-dependent-semantic-record-is-re-derived.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-a-provenance-orphaned-memory-write-when-ttl-expiry-erases-the-tombstone-before-the-dependent-semantic-record-is-re-derived.warrant.json
# Markdown SHA-256:   31029520f826609676eaa575685f17dfe06179ddaa370e4ee296b334f41f427c
# Code AST SHA-256:   94ab6592aceeb8bbdb527b958cbc1aa2307fb4bacaeaa05137b201284cb52f83
# Verified Classes:   ProvenanceOrphanErasureError
# Defensive Guards:   1 fail-closed invariants (zero external deps)

class ProvenanceOrphanErasureError(RuntimeError):
    """Raised when RTBF erasure cannot be certified because a dependent
    record's provenance resolves to an expired-and-GC'd source with no tombstone."""


# Provenance store states for a resolved record id.
ABSENT_NEVER_EXISTED = "absent_never_existed"
ABSENT_ERASED = "absent_erased"                    # tombstone present, cascade done
ABSENT_EXPIRED_NO_TOMBSTONE = "absent_expired_no_tombstone"  # dangerous


def forget_session(store, session_id):
    """Enforce the cascade invariant before acknowledging erasure."""
    targets = store.resolve_session(session_id)  # ids written under this session
    dangling = []
    for rec_id in targets:
        state = store.provenance_state(rec_id)
        if state == ABSENT_EXPIRED_NO_TOMBSTONE:
            # Source expired without a tombstone; find live dependents.
            for dep in store.live_dependents_of(rec_id):
                dangling.append((rec_id, dep.id, dep.provenance))
        # Tombstone the target so future forgets see ABSENT_ERASED.
        store.tombstone(rec_id, retain_out_edges=True)

    if dangling:
        # Fail closed: do NOT report success. The erasure guarantee is unmet.
        raise ProvenanceOrphanErasureError(
            f"RTBF incomplete for session {session_id}: "
            f"{len(dangling)} dependent record(s) have provenance on "
            f"expired sources with no tombstone: {dangling}"
        )

    # Safe: no live dependent transitively references an un-tombstoned source.
    store.erase_tombstones(targets)
    return {"status": "erased", "session": session_id, "targets": len(targets)}


def ttl_sweep(store, now):
    """Expiry must demote to tombstone, never hard-delete, when out_degree > 0."""
    for rec in store.expired(now):
        if store.out_degree(rec.id) > 0:
            store.tombstone(rec.id, retain_out_edges=True)
            store.schedule_rederivation(rec.id)  # close the orphan window
        else:
            store.hard_delete(rec.id)
