# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-tombstone-a-memory-key-that-its-own-retrieval-layer-still-returns.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-tombstone-a-memory-key-that-its-own-retrieval-layer-still-returns.warrant.json
# Markdown SHA-256:   5bd24a582e54344e9b818ca5e5bf7d4a25ee0fe03f3105b704e8dd7e11b7a640
# Code AST SHA-256:   4f8597e21201b04f7ea6fe6c2141183bef3de6acadfc234b7b51f53b3ea360d0
# Verified Classes:   TombstoneProjectionDivergence
# Defensive Guards:   2 fail-closed invariants (zero external deps)

class TombstoneProjectionDivergence(RuntimeError):
    """Raised when a read returns a key that is tombstoned in the authoritative
    store but still present in the retrieval projection."""
    pass


def read_with_tombstone_guard(
    query: str,
    scope: str,
    projection_epoch: int,
    forget_watermark: int,
    tombstone_set: set[str],
    ann_index,
) -> list[dict]:
    """
    Read from the ANN projection, but refuse to return anything that is
    tombstoned in the authoritative store, and refuse to serve a projection
    that has not caught up to the forget watermark.
    """
    if projection_epoch < forget_watermark:
        raise TombstoneProjectionDivergence(
            f"projection epoch {projection_epoch} < forget watermark "
            f"{forget_watermark} for scope {scope}; read is untrusted"
        )

    hits = ann_index.query(query, scope=scope)
    clean = []
    for hit in hits:
        if hit["key"] in tombstone_set:
            # projection still serves a tombstoned key: divergence, not a
            # normal miss. Surface it rather than silently dropping.
            raise TombstoneProjectionDivergence(
                f"key {hit['key']} tombstoned in store but returned by "
                f"projection at epoch {projection_epoch}"
            )
        clean.append(hit)
    return clean
