# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-a-tombstone-gap-in-scoped-read-write-forget-memory-apis.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-a-tombstone-gap-in-scoped-read-write-forget-memory-apis.warrant.json
# Markdown SHA-256:   24bad4f1ab8c5a2773039e27b936bb501d54f45bedf42d28104d3b74a1682df0
# Code AST SHA-256:   85eacc4abe8c8d43c5b1c439a30b1e9d415fb738d8e87ad2a24c9f108975d2a4
# Verified Classes:   UnconfirmedForgetError
# Defensive Guards:   3 fail-closed invariants (zero external deps)

class UnconfirmedForgetError(RuntimeError):
    """Raised when a scope is reused after a forget that did not return an epoch."""
    pass


def safe_reuse_scope(store, scope_key: str, new_records: list[dict]) -> str:
    """
    Write new_records into scope_key only if the prior forget is epoch-confirmed.
    Returns the scope key actually written to (possibly a rekeyed generation).
    """
    forget_result = store.last_forget_result(scope_key)
    if forget_result is None:
        # Never forgotten; safe to write.
        store.write(scope_key, new_records)
        return scope_key

    pre_epoch = forget_result.get("epoch_before")
    post_epoch = forget_result.get("epoch_after")

    if post_epoch is None or pre_epoch is None:
        # Count-only forget: no epoch evidence. Do not reuse the key.
        raise UnconfirmedForgetError(
            f"forget on {scope_key!r} returned {forget_result.get('deleted')} deleted "
            f"records but no epoch token; tombstone gap cannot be ruled out. "
            f"Re-key before writing."
        )

    if post_epoch == pre_epoch:
        raise UnconfirmedForgetError(
            f"forget on {scope_key!r} did not advance scope epoch "
            f"({pre_epoch} -> {post_epoch}); deletion may not have propagated. "
            f"Re-key before writing."
        )

    # Epoch advanced: forget is confirmed. Verify emptiness before reuse.
    probe = store.read(scope_key)
    if probe:
        raise UnconfirmedForgetError(
            f"scope {scope_key!r} returned {len(probe)} records after confirmed "
            f"forget (epoch {post_epoch}); resurrection suspected."
        )

    store.write(scope_key, new_records)
    return scope_key


def rekey_and_write(store, base_scope: str, new_records: list[dict]) -> str:
    """Retire-and-rekey fallback when forget is unconfirmed."""
    generation = store.next_generation(base_scope)
    new_key = f"{base_scope}-gen{generation}"
    store.write(new_key, new_records)
    return new_key
