# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-enforce-forget-scope-atomicity-when-a-memory-tool-s-write-and-delete-schemas-disagree-on-key-derivation.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-enforce-forget-scope-atomicity-when-a-memory-tool-s-write-and-delete-schemas-disagree-on-key-derivation.warrant.json
# Markdown SHA-256:   de575914906c92fcc8b84f070ab6faf127453418b0db6cf6df88f0a20d5e4b77
# Code AST SHA-256:   dd66d0aca8a9c994bba208091eec8f69c6284f4a4941cea3dfe81928256e05e6
# Verified Classes:   ForgetScopeViolation, MemoryRecord
# Defensive Guards:   4 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass, field


class ForgetScopeViolation(RuntimeError):
    """Raised when a forget predicate is not bound to the caller's write scope."""
    pass


@dataclass
class MemoryRecord:
    instance_token: str
    namespace: str
    key: str


def write_key(tenant: str, instance_token: str, namespace: str, key: str) -> str:
    # The authoritative key function. Forget MUST reuse this exact composition.
    return hashlib.sha256(
        f"{tenant}|{instance_token}|{namespace}|{key}".encode()
    ).hexdigest()


def forget_matches(
    records: list[MemoryRecord],
    tenant: str,
    caller_token: str,
    namespace: str,
    predicate_prefix: str,
    local_write_count: int,
) -> list[MemoryRecord]:
    """Resolve a forget predicate against the SAME key function used by write.

    Invariant: a wildcard forget is sound only if it is injective into the
    caller's own scope. If the predicate would match records whose
    instance_token differs from the caller, refuse before deleting.
    """
    if caller_token is None:
        raise ForgetScopeViolation(
            "forget called without a bound scope_token; wildcard delete is unsound"
        )

    candidates = [
        r for r in records
        if r.namespace == namespace and r.key.startswith(predicate_prefix)
    ]

    foreign = [r for r in candidates if r.instance_token != caller_token]
    if foreign:
        raise ForgetScopeViolation(
            f"predicate '{predicate_prefix}' in namespace '{namespace}' would "
            f"delete {len(foreign)} record(s) owned by other instances "
            f"({sorted({r.instance_token for r in foreign})}); "
            f"refusing cross-scope erasure"
        )

    if local_write_count is not None and len(candidates) != local_write_count:
        raise ForgetScopeViolation(
            f"matched={len(candidates)} but local ledger records "
            f"{local_write_count} writes; predicate over- or under-broad"
        )

    return candidates


def execute_forget(records, tenant, caller_token, namespace, prefix, ledger_count):
    matched = forget_matches(
        records, tenant, caller_token, namespace, prefix, ledger_count
    )
    deleted = len(matched)
    if matched and deleted != len(matched):
        raise ForgetScopeViolation("matched/deleted divergence: partial commit")
    return {"matched": len(matched), "deleted": deleted}
