# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-reconcile-a-tombstoned-memory-that-a-downstream-tool-call-still-holds-a-live-handle-to.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-reconcile-a-tombstoned-memory-that-a-downstream-tool-call-still-holds-a-live-handle-to.warrant.json
# Markdown SHA-256:   1dc42e9590977f468e4d52e95b5c527f0b6fe487181e19397a0c0b0b1ad8d842
# Code AST SHA-256:   cd3db45938a2dc350a3e91f00d9d2f39bc4ecb6780d7302841fc29c16ed50ab1
# Verified Classes:   UnreconciledTombstoneError, MemoryHandle
# Defensive Guards:   4 fail-closed invariants (zero external deps)

class UnreconciledTombstoneError(RuntimeError):
    """Raised when an effect would be derived from a forgotten record
    whose handle could not be proven live at dispatch time."""
    pass


class MemoryHandle:
    __slots__ = ("record_id", "version", "tombstone_epoch", "grant")

    def __init__(self, record_id, version, tombstone_epoch, grant):
        self.record_id = record_id
        self.version = version
        self.tombstone_epoch = tombstone_epoch
        self.grant = grant


def validate_handle_before_effect(handle, store, current_epoch, timeout_s=0.25):
    # Fail-closed: an unreachable authority is never a license to emit.
    try:
        state = store.lookup(handle.record_id, timeout_s=timeout_s)
    except TimeoutError:
        raise UnreconciledTombstoneError(
            f"authority unreachable for {handle.record_id}; refusing effect"
        )

    if state is None or state.tombstone_epoch > handle.tombstone_epoch:
        raise UnreconciledTombstoneError(
            f"{handle.record_id} tombstoned after handle issued "
            f"(handle_epoch={handle.tombstone_epoch}, store_epoch={current_epoch})"
        )
    if state.version != handle.version:
        raise UnreconciledTombstoneError(
            f"{handle.record_id} version drift: {handle.version} -> {state.version}"
        )
    if handle.grant not in state.active_grants:
        raise UnreconciledTombstoneError(
            f"grant {handle.grant} revoked for {handle.record_id}; effect forbidden"
        )
    return True


def forget_with_dag_walk(record_id, store, max_depth=4):
    # Deletion must traverse provenance back-edges, not just the record.
    pending, depth, unreachable = [record_id], 0, set()
    while pending:
        if depth > max_depth:
            unreachable.update(pending)  # escalate, do not assume independence
            break
        for rid in pending:
            store.tombstone(rid)
            pending = store.dependents(rid)  # derived_from back-edges
        depth += 1
    return {"deleted": True, "unreachable_handles": sorted(unreachable)}
