# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-deletes-a-memory-scope-while-a-concurrent-reader-holds-a-stale-cursor-the-tombstone-visibility-invariant-in-scoped-reten.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-deletes-a-memory-scope-while-a-concurrent-reader-holds-a-stale-cursor-the-tombstone-visibility-invariant-in-scoped-reten.warrant.json
# Markdown SHA-256:   c3dfcd73ff33f35b3ac76764105c2c5f883f5b55495cbbc0c8211b6f45ccae4f
# Code AST SHA-256:   d51c919900211d0ccb7288aaf900580a96860e6fa715ab3ee1d5411507219c8a
# Verified Classes:   TombstoneVisibilityError, Cursor, Tombstone
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Optional


class TombstoneVisibilityError(RuntimeError):
    """Raised when a read cursor would return a key whose tombstone postdates the cursor snapshot."""
    pass


@dataclass(frozen=True)
class Cursor:
    scope: str
    snapshot_seq: int


@dataclass(frozen=True)
class Tombstone:
    scope: str
    key: str
    scope_seq: int
    tombstone_id: str


def guarded_read(
    scope: str,
    cursor: Optional[Cursor],
    current_scope_seq: int,
    tombstones: dict[str, Tombstone],
    page_keys: list[str],
) -> list[str]:
    """
    Enforce the tombstone-visibility invariant before returning a page.

    If the cursor's snapshot predates the scope's current sequence, any key
    with a tombstone newer than the snapshot must not be emitted. We refuse
    the page outright rather than silently filtering, because a filtered page
    still advances the agent's reasoning over a partially-deleted view.
    """
    if cursor is None:
        return [k for k in page_keys if k not in tombstones]

    if cursor.scope != scope:
        raise TombstoneVisibilityError(
            f"cursor scope {cursor.scope!r} does not match read scope {scope!r}"
        )

    stale = cursor.snapshot_seq < current_scope_seq
    if not stale:
        return [k for k in page_keys if k not in tombstones]

    # Cursor spans a scope mutation. Check whether any emitted key is tombstoned
    # after the cursor snapshot; if so, the page is poisoned.
    poisoned = [
        k for k in page_keys
        if k in tombstones and tombstones[k].scope_seq > cursor.snapshot_seq
    ]
    if poisoned:
        raise TombstoneVisibilityError(
            f"cursor snapshot_seq={cursor.snapshot_seq} predates tombstones "
            f"{[(k, tombstones[k].tombstone_id) for k in poisoned]} "
            f"(current_scope_seq={current_scope_seq}); discard cursor and re-read from None"
        )

    return [k for k in page_keys if k not in tombstones]
