# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-s-forget-tool-silently-fail-to-guarantee-erasure-when-the-memory-store-deduplicates-on-content-hash-before-tombstoning.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-s-forget-tool-silently-fail-to-guarantee-erasure-when-the-memory-store-deduplicates-on-content-hash-before-tombstoning.warrant.json
# Markdown SHA-256:   dbc39b55bcde7ec939aad08a8f9b91414ff1286bfbf4b00ed29489f6d8271bae
# Code AST SHA-256:   a0c3efb8f47cb8fce8255b2d6b1c9e44b265e475e7f709309e41338bb94eeabc
# Verified Classes:   ErasureGuaranteeViolation, MemoryStore
# Defensive Guards:   2 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass, field


class ErasureGuaranteeViolation(RuntimeError):
    """Raised when a forget operation cannot satisfy the content-erasure
    guarantee the caller is about to attest. Pointer-layer success is not
    sufficient evidence of content-layer erasure."""


@dataclass
class MemoryStore:
    # logical key -> content hash
    index: dict = field(default_factory=dict)
    # content hash -> (bytes, refcount)
    blobs: dict = field(default_factory=dict)
    # content hash -> set of keys still referencing it
    refs: dict = field(default_factory=dict)

    @staticmethod
    def _hash(content: str) -> str:
        return hashlib.sha256(content.encode()).hexdigest()

    def write(self, key: str, content: str) -> None:
        h = self._hash(content)
        if h not in self.blobs:
            self.blobs[h] = [content, 0]
        self.blobs[h][1] += 1
        self.index[key] = h
        self.refs.setdefault(h, set()).add(key)

    def forget(self, key: str) -> dict:
        h = self.index.pop(key, None)
        if h is None:
            return {"status": "not_found"}
        self.refs[h].discard(key)
        self.blobs[h][1] -= 1
        return {"status": "ok", "deleted": 1, "surviving_refs": sorted(self.refs[h])}

    def search(self, needle: str):
        return [h for h, (content, _rc) in self.blobs.items() if needle in content]


def forget_with_attestation(store: MemoryStore, key: str, sensitive_substring: str) -> dict:
    """Forget `key` and only attest erasure if no surviving blob still contains
    the sensitive content. This is the verify-by-content protocol."""
    result = store.forget(key)

    # Pointer-layer check alone is the trap: it would pass here and lie.
    if result["status"] != "ok":
        return {"attested": False, "reason": "key_not_present", "detail": result}

    survivors = store.search(sensitive_substring)
    if survivors:
        raise ErasureGuaranteeViolation(
            f"forget({key!r}) removed the pointer but content still reachable "
            f"via hashes {survivors}; surviving refs {result['surviving_refs']}. "
            f"Cannot attest content erasure."
        )

    return {"attested": True, "key": key, "surviving_refs": result["surviving_refs"]}


# --- reproduction of the observed failure ---
store = MemoryStore()
store.write("project.notes.bootstrap", "bootstrap: api key sk-live-ABC123 for staging")
store.write("session.creds", "sk-live-ABC123")

try:
    forget_with_attestation(store, "session.creds", "sk-live-ABC123")
except ErasureGuaranteeViolation as e:
    print("BLOCKED false attestation:", e)
    # Correct remediation: rewrite the containing record with the substring
    # redacted, forget the old record, then re-verify.
    store.write("project.notes.bootstrap", "bootstrap: api key [REDACTED] for staging")
    store.forget("project.notes.bootstrap")
    store.forget("session.creds")
    assert store.search("sk-live-ABC123") == [], "still reachable"
    print("erasure verified by content after redaction sweep")
