# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-deletes-a-memory-namespace-while-a-peer-agent-still-holds-a-live-read-cursor-into-it.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-deletes-a-memory-namespace-while-a-peer-agent-still-holds-a-live-read-cursor-into-it.warrant.json
# Markdown SHA-256:   d0e3dc6800f12ab88f18078219fd9c00146b26fa0e4a9489c3c67a4aebbf8266
# Code AST SHA-256:   75ff7001ee1c06d68ef3643fe1465df1a5218976bbe491842c031b3eda2a9ef6
# Verified Classes:   NamespaceTombstonedError
# Defensive Guards:   3 fail-closed invariants (zero external deps)

class NamespaceTombstonedError(RuntimeError):
    """Raised when a read cursor or derived write references a namespace
    epoch that has been tombstoned. Fail-closed: never return empty,
    never return pre-deletion records."""
    def __init__(self, ns: str, minted_epoch: int, deleted_epoch: int):
        self.ns = ns
        self.minted_epoch = minted_epoch
        self.deleted_epoch = deleted_epoch
        super().__init__(
            f"namespace {ns!r} tombstoned at epoch {deleted_epoch}; "
            f"cursor minted at epoch {minted_epoch} is invalid"
        )


def read_with_cursor(store, ns: str, cursor_epoch: int, offset: int):
    meta = store.namespace_meta(ns)          # linearized with delete
    if meta.tombstone is not None:
        # deletion is logical-immediate, physical-eventual:
        # do NOT fall through to reading reclaimed-but-present records
        raise NamespaceTombstonedError(ns, cursor_epoch, meta.tombstone.epoch)
    if cursor_epoch != meta.current_epoch:
        raise NamespaceTombstonedError(ns, cursor_epoch, meta.current_epoch)
    return store.read_page(ns, epoch=cursor_epoch, offset=offset)


def write_derived(store, target_ns: str, content, provenance: list[tuple[str, int]]):
    for src_ns, src_epoch in provenance:
        meta = store.namespace_meta(src_ns)
        if meta.tombstone is not None or meta.current_epoch != src_epoch:
            # derived write would resurrect a tombstoned epoch
            raise NamespaceTombstonedError(src_ns, src_epoch,
                                           meta.tombstone.epoch if meta.tombstone
                                           else meta.current_epoch)
    return store.put(target_ns, content, provenance=provenance)
