# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-refuse-to-serve-a-tombstone-only-memory-scope.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-refuse-to-serve-a-tombstone-only-memory-scope.warrant.json
# Markdown SHA-256:   98e54e94aea74ec9c7f86dbda61946d276e27a762cc291c9cf6de13ad3b8f64c
# Code AST SHA-256:   fa0027424305605be17d0e0053afae0d5b6686d53c1f6b800b330d202cca9877
# Verified Classes:   TombstoneChainIncomplete, ScopeState
# Defensive Guards:   2 fail-closed invariants (zero external deps)

class TombstoneChainIncomplete(RuntimeError):
    """Raised when a tombstone-only scope cannot prove emptiness for the caller's epoch."""


class ScopeState:
    NEVER_POPULATED = "never_populated"
    TOMBSTONE_ONLY = "tombstone_only"
    LIVE = "live"


def read_scope(scope, expected_epoch=None):
    live = scope.live_records()
    tombstones = scope.tombstones()

    if live:
        return {"records": live, "scope_state": ScopeState.LIVE}

    if not tombstones:
        return {"records": [], "scope_state": ScopeState.NEVER_POPULATED}

    # Tombstone-only scope: emptiness is only provable if we can account for
    # every write the caller believes it made.
    if expected_epoch is None:
        return {
            "records": [],
            "scope_state": ScopeState.TOMBSTONE_ONLY,
            "tombstone_count": len(tombstones),
            "note": "caller supplied no epoch; emptiness unproven",
        }

    seqs = sorted(t.seq for t in tombstones)
    if seqs[0] != 0 or any(b - a != 1 for a, b in zip(seqs, seqs[1:])):
        raise TombstoneChainIncomplete(
            f"scope {scope.id!r}: tombstone sequence has gaps {seqs}; "
            f"cannot prove emptiness for epoch {expected_epoch!r}"
        )

    covering = [t for t in tombstones if t.epoch == expected_epoch]
    if not covering:
        raise TombstoneChainIncomplete(
            f"scope {scope.id!r}: no tombstone covers caller epoch "
            f"{expected_epoch!r}; refusing to serve [] as a negative answer"
        )

    return {
        "records": [],
        "scope_state": ScopeState.TOMBSTONE_ONLY,
        "deletion_receipt": [t.receipt_id for t in covering],
    }
