# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-scoped-forget-apis-from-silently-resurrecting-deleted-memory-through-derived-indexes.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-scoped-forget-apis-from-silently-resurrecting-deleted-memory-through-derived-indexes.warrant.json
# Markdown SHA-256:   332befae817f9882d64c67cd4394f88e0ec4d5525530cb41d64bdcea81f0c40d
# Code AST SHA-256:   1dd31ac211198b2bef67300aca2be994c04af8bda2de9dc9be3c3f2345cee8f0
# Verified Classes:   ScopedForgetViolation, MemoryRecord, DerivedIndex
# Defensive Guards:   3 fail-closed invariants (zero external deps)

class ScopedForgetViolation(RuntimeError):
    """Raised when a read path can reconstruct content outside the live scope."""
    pass


class MemoryRecord:
    def __init__(self, record_id, scope, text, tombstoned=False):
        self.record_id = record_id
        self.scope = scope
        self.text = text
        self.tombstoned = tombstoned


class DerivedIndex:
    """Vector/keyword index that must consult tombstones at derivative-use time."""

    def __init__(self, store):
        self.store = store
        self.vectors = {}      # record_id -> embedding
        self.summary_cache = {}  # content_hash -> summary fragment

    def _live(self, record_id):
        rec = self.store.get(record_id)
        return rec is not None and not rec.tombstoned

    def count_matches(self, term):
        # Aggregate must be computed post-tombstone, not pre-filtered.
        total = 0
        for rid, payload in self.vectors.items():
            if term in payload and self._live(rid):
                total += 1
        return total

    def neighbours(self, query_vec, k):
        scored = []
        for rid, vec in self.vectors.items():
            if not self._live(rid):
                continue  # tombstone consulted before neighbour expansion
            scored.append((self._similarity(query_vec, vec), rid))
        scored.sort(reverse=True)
        out = []
        for _, rid in scored[:k]:
            rec = self.store[rid]
            if not self._live(rid):
                raise ScopedForgetViolation(
                    f"neighbour {rid} resurrected after forget"
                )
            out.append(rec.text)
        return out

    def summary_for(self, content_hash, scope):
        # Cache is keyed on content and must be scope-checked on hit.
        cached = self.summary_cache.get(content_hash)
        if cached is not None:
            owner = cached["scope"]
            owner_rec = self.store.get(cached["record_id"])
            if owner_rec is None or owner_rec.tombstoned or owner != scope:
                raise ScopedForgetViolation(
                    f"summary cache hit for {content_hash} crosses scope {scope}"
                )
            return cached["summary"]
        return None

    @staticmethod
    def _similarity(a, b):
        return sum(x * y for x, y in zip(a, b))


def forget(store, index, predicate):
    deleted = 0
    for rid, rec in list(store.items()):
        if predicate(rec):
            rec.tombstoned = True
            deleted += 1
    # Derived structures are not mutated here; reads must honour tombstones.
    return deleted


def guarded_read(index, query_vec, term, scope):
    # A count computed over an untombstoned index is a reconstruction channel.
    if index.count_matches(term) > 0 and not any(
        index._live(rid) for rid in index.vectors
    ):
        raise ScopedForgetViolation(
            "aggregate count leaks forgotten records outside scope"
        )
    return index.neighbours(query_vec, k=5)
