# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-deletes-a-memory-scope-it-is-still-reading-from.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-deletes-a-memory-scope-it-is-still-reading-from.warrant.json
# Markdown SHA-256:   c09a9381db07384421e79f1a9028c4405ed1c34e61eef0b0f8228724b56152f2
# Code AST SHA-256:   a917d6136e8a10a774a8c43ac5f49ac683eda0d966bd265577c0f7ead23b5f87
# Verified Classes:   RetentionViolation, MemoryStore
# Defensive Guards:   5 fail-closed invariants (zero external deps)

class RetentionViolation(RuntimeError):
    pass


class MemoryStore:
    def __init__(self):
        self.scopes = {}          # scope -> {key: value}
        self.provenance = {}      # scope -> set of source scopes
        self.tombstones = set()   # acknowledged-forgotten scopes

    def write(self, scope, key, value, derived_from=None):
        if scope in self.tombstones:
            raise RetentionViolation(f"write to forgotten scope {scope!r}")
        if derived_from is not None:
            if derived_from in self.tombstones:
                raise RetentionViolation(
                    f"cannot derive {scope!r} from forgotten scope {derived_from!r}"
                )
            self.provenance.setdefault(scope, set()).add(derived_from)
        self.scopes.setdefault(scope, {})[key] = value

    def read(self, scope, converged=True):
        if scope in self.tombstones and converged:
            raise RetentionViolation(f"read of forgotten scope {scope!r}")
        return dict(self.scopes.get(scope, {}))

    def forget(self, scope):
        # cascade: refuse if any live scope derives from this one
        for child, sources in self.provenance.items():
            if scope in sources and child not in self.tombstones:
                raise RetentionViolation(
                    f"cannot forget {scope!r}: live derived scope {child!r} "
                    f"still depends on it; forget children first"
                )
        self.tombstones.add(scope)
        self.scopes.pop(scope, None)


def finalize_session(store, session_scope, derived_scope):
    # Derived scope must be forgotten before its source, or the
    # source forget will (correctly) refuse.
    if derived_scope in store.scopes:
        store.forget(derived_scope)
    store.forget(session_scope)
    # Verify only after convergence; an immediate read is not an oracle.
    try:
        store.read(session_scope, converged=True)
    except RetentionViolation:
        return True
    raise RetentionViolation(
        f"scope {session_scope!r} still readable after forget; "
        f"retention guarantee not observable"
    )
