# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-tombstones-from-resurrecting-delete-then-rewrite-races-in-scoped-memory-tool-apis.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-tombstones-from-resurrecting-delete-then-rewrite-races-in-scoped-memory-tool-apis.warrant.json
# Markdown SHA-256:   1fe5e2659f36db5d1d3f0ba3b85ed18b036763a1ece655d5e6ba5c845435b4d1
# Code AST SHA-256:   089b791ed2cf5f3ecc7249269d7a3e93d49e8986b0824820d3474126e9675eef
# Verified Classes:   TombstoneResurrectionError
# Defensive Guards:   3 fail-closed invariants (zero external deps)

class TombstoneResurrectionError(RuntimeError):
    """Raised when a write after forget reuses the deleted record's identity/epoch."""
    pass


def write_after_forget(store, scope: str, key: str, value, client_seq: int) -> dict:
    tomb = store.get_tombstone(scope, key)
    if tomb is None:
        return store.apply_fresh(scope, key, value, epoch=0, client_seq=client_seq)

    # Tombstone exists: only a strictly newer client_seq may create a new epoch.
    if client_seq <= tomb["forget_seq"]:
        raise TombstoneResurrectionError(
            f"stale write for ({scope!r},{key!r}): client_seq={client_seq} "
            f"<= forget_seq={tomb['forget_seq']}; refusing to resurrect epoch "
            f"{tomb['epoch']} (provenance={tomb.get('provenance')!r})"
        )

    new_epoch = tomb["epoch"] + 1
    result = store.apply_fresh(scope, key, value, epoch=new_epoch, client_seq=client_seq)

    # Invariant check: the applied record must carry fresh metadata, not the tombstone's.
    applied = store.read(scope, key, include_meta=True)
    if applied["epoch"] != new_epoch:
        raise TombstoneResurrectionError(
            f"epoch did not advance for ({scope!r},{key!r}): "
            f"expected {new_epoch}, got {applied['epoch']}"
        )
    if applied["created_at"] <= tomb["forget_at"]:
        raise TombstoneResurrectionError(
            f"resurrected metadata for ({scope!r},{key!r}): "
            f"created_at={applied['created_at']} <= forget_at={tomb['forget_at']}"
        )
    return result


def forget(store, scope: str, key: str, client_seq: int) -> dict:
    current = store.read(scope, key, include_meta=True)
    if current is None:
        # Idempotent forget still advances the forget_seq so late writes are rejected.
        store.record_tombstone(scope, key, epoch=store.current_epoch(scope, key),
                               forget_seq=client_seq, forget_at=store.now(),
                               provenance=None)
        return {"deleted": True, "epoch": store.current_epoch(scope, key)}

    store.record_tombstone(scope, key, epoch=current["epoch"],
                           forget_seq=client_seq, forget_at=store.now(),
                           provenance=current.get("provenance"))
    store.mark_deleted(scope, key, epoch=current["epoch"])
    return {"deleted": True, "epoch": current["epoch"]}
