# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-a-scoped-retention-memory-tool-has-silently-degraded-from-verifiable-deletion-to-tombstone-only-deletion.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-a-scoped-retention-memory-tool-has-silently-degraded-from-verifiable-deletion-to-tombstone-only-deletion.warrant.json
# Markdown SHA-256:   b15cd02543a1dfe151daf1e14433b6ec3d8065062dffbd959b35d2a95a868884
# Code AST SHA-256:   5ae294768f3f3b1dc37ec17812819ccb86d8813269325e4f06d603fcf3ff6dad
# Verified Classes:   DeletionNotVerifiableError
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import hashlib

class DeletionNotVerifiableError(RuntimeError):
    """Raised when a memory tool reports forget() success but structural
    probes indicate tombstone-only (suppression) rather than true deletion."""
    pass

def verify_deletion(memory_tool, scope: str, key: str, content: bytes,
                    forgotten_count: int) -> None:
    """
    memory_tool must expose:
      write(scope, key, content) -> None
      read(scope, key) -> bytes | None
      forget(scope, key) -> str          # returns 'ok' on reported success
      scope_cardinality(scope) -> int
      storage_bytes(scope) -> int        # tool-level accounting
    """
    before_card = memory_tool.scope_cardinality(scope)
    before_bytes = memory_tool.storage_bytes(scope)

    result = memory_tool.forget(scope, key)
    if result != "ok":
        # Explicit failure is fine; we only guard the silent case.
        return

    if memory_tool.read(scope, key) is not None:
        raise DeletionNotVerifiableError(
            f"forget({scope!r},{key!r}) returned ok but read still yields data"
        )

    after_card = memory_tool.scope_cardinality(scope)
    if before_card - after_card != forgotten_count:
        raise DeletionNotVerifiableError(
            f"cardinality delta {before_card - after_card} != forgotten "
            f"{forgotten_count}; record suppressed, not reclaimed"
        )

    # Re-write identical content: a true deletion cannot deduplicate against
    # a record that no longer exists.
    before_rewrite = memory_tool.storage_bytes(scope)
    memory_tool.write(scope, key, content)
    after_rewrite = memory_tool.storage_bytes(scope)
    grew = after_rewrite - before_rewrite
    if grew <= 0:
        raise DeletionNotVerifiableError(
            f"re-write of identical content grew storage by {grew} bytes; "
            f"content hash survived forget() -> tombstone-only deletion"
        )

    # Cleanup probe write so the caller's state is unchanged.
    memory_tool.forget(scope, key)
