# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-issues-a-scoped-forget-that-races-an-in-flight-consolidation-pass.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-issues-a-scoped-forget-that-races-an-in-flight-consolidation-pass.warrant.json
# Markdown SHA-256:   fbce72256b4092eb7d856a901af09d2cb2c89cf54eb5862f9f4214afb5e86a1b
# Code AST SHA-256:   82774544841b33809f12b6a3d26ab488c7d462a578e0316d2d6e9c2492179294
# Verified Classes:   ScopedForgetRaceError, MemoryStore
# Defensive Guards:   2 fail-closed invariants (zero external deps)

class ScopedForgetRaceError(RuntimeError):
    """Raised when a scoped forget returns before in-flight derivations
    touching that scope have drained, leaving an untargeted derivative."""
    pass


class MemoryStore:
    def __init__(self):
        self.episodic = {}          # scope -> list of records
        self.semantic = []          # derived records, each with source_scope
        self.tombstones = set()
        self.inflight_derivations = {}  # scope -> count of in-flight consolidations

    def begin_consolidation(self, scope):
        self.inflight_derivations[scope] = self.inflight_derivations.get(scope, 0) + 1

    def end_consolidation(self, scope):
        self.inflight_derivations[scope] = max(0, self.inflight_derivations.get(scope, 0) - 1)

    def forget(self, scope, require_drain=True):
        # Phase 1: tombstone so no NEW derivation reads this scope.
        self.tombstones.add(scope)

        # Phase 2: drain barrier. If derivations are still in flight, we
        # cannot honestly promise the scope is gone.
        if require_drain and self.inflight_derivations.get(scope, 0) > 0:
            raise ScopedForgetRaceError(
                f"forget({scope!r}) issued while "
                f"{self.inflight_derivations[scope]} derivation(s) still hold the scope; "
                "a derivative may be written after this call and survive the delete"
            )

        # Phase 3: purge source AND any already-written derivatives.
        deleted = len(self.episodic.pop(scope, []))
        before = len(self.semantic)
        self.semantic = [r for r in self.semantic if r.get("source_scope") != scope]
        purged_derivatives = before - len(self.semantic)

        return {"deleted": deleted, "derivatives_purged": purged_derivatives, "drained": True}


def safe_forget(store, scope):
    try:
        return store.forget(scope, require_drain=True)
    except ScopedForgetRaceError as e:
        # Do NOT swallow: a partial acknowledgement is worse than a hard failure,
        # because the caller will believe the poison is gone.
        raise ScopedForgetRaceError(
            f"refusing to acknowledge forget for {scope!r}: {e}. "
            "Retry after derivations drain, or quarantine the query namespace."
        ) from e
