# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-refuse-a-scoped-memory-deletion-when-the-retention-warrant-and-the-tombstone-digest-disagree.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-refuse-a-scoped-memory-deletion-when-the-retention-warrant-and-the-tombstone-digest-disagree.warrant.json
# Markdown SHA-256:   d702844073f75076ce09ce724d27bfc18706bbadebde5b509fec167cb89aaec8
# Code AST SHA-256:   47f1d91073fb4316dc853472e2aec5282cf5d2953b6f78a20befdd01dd6b8a64
# Verified Classes:   WarrantDriftError, Warrant
# Defensive Guards:   4 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass


class WarrantDriftError(RuntimeError):
    """Raised when a deletion warrant no longer matches live content."""
    pass


@dataclass(frozen=True)
class Warrant:
    tenant: str
    key: str
    retention_class: str
    bound_version: int
    bound_digest: str
    allow_drift: bool
    signature: str  # opaque; validated by retention engine


def digest(content: bytes) -> str:
    return hashlib.sha256(content).hexdigest()


def commit_forget(
    warrant: Warrant,
    store: dict,
    versions: dict,
    tenant: str,
) -> str:
    """Commit a scoped deletion; return tombstone digest or raise."""
    if warrant.tenant != tenant:
        raise WarrantDriftError(
            f"tenant scope mismatch: warrant={warrant.tenant} caller={tenant}"
        )
    if warrant.key not in store:
        raise WarrantDriftError(f"key {warrant.key!r} absent; nothing to erase")

    current = store[warrant.key]
    current_version = versions[warrant.key]
    current_digest = digest(current)

    # Version pin: a bump means content changed since mint.
    if current_version != warrant.bound_version and not warrant.allow_drift:
        raise WarrantDriftError(
            f"stale warrant: bound_version={warrant.bound_version} "
            f"current_version={current_version} for key {warrant.key!r}"
        )

    # Digest pin: content-scoped warrants must match byte-for-byte.
    if current_digest != warrant.bound_digest and not warrant.allow_drift:
        raise WarrantDriftError(
            f"digest drift on key {warrant.key!r}: "
            f"warrant={warrant.bound_digest[:12]} current={current_digest[:12]}"
        )

    # Atomic tombstone + erase.
    tombstone = current_digest
    del store[warrant.key]
    versions[warrant.key] = current_version + 1
    return tombstone
