# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-scoped-forget-memory-tools-from-leaking-tombstoned-facts-back-through-retrieval-rehydration.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-scoped-forget-memory-tools-from-leaking-tombstoned-facts-back-through-retrieval-rehydration.warrant.json
# Markdown SHA-256:   2dfdf2b89e123af80745ebe82a96eed8a610b8632de5aa27eee6b60c873080e5
# Code AST SHA-256:   a6c333aced7504db5724ffdb3dc0a84beb0e6393780d67f12c092c3c1260f590
# Verified Classes:   StaleDerivationError, ScopedMemory
# Defensive Guards:   1 fail-closed invariants (zero external deps)

class StaleDerivationError(RuntimeError):
    """Raised when a derived memory write would launder a tombstoned source."""


class ScopedMemory:
    def __init__(self):
        self.records = {}          # (scope, key) -> value
        self.generation = {}       # scope -> monotonic forget counter
        self.tombstones = set()    # (scope, key)

    def _gen(self, scope):
        return self.generation.get(scope, 0)

    def write(self, scope, key, value, source_gen=None, source_scopes=None):
        # source_gen is the snapshot taken when derivation was enqueued.
        if source_scopes is not None:
            for src in source_scopes:
                if self._gen(src) != source_gen.get(src, 0):
                    raise StaleDerivationError(
                        f"derived write {scope}/{key} rejected: source scope "
                        f"{src} advanced from gen {source_gen.get(src, 0)} "
                        f"to {self._gen(src)} (tombstone landed mid-derivation)"
                    )
        self.records[(scope, key)] = value

    def forget(self, scope, key):
        self.tombstones.add((scope, key))
        self.records.pop((scope, key), None)
        self.generation[scope] = self._gen(scope) + 1
        return self._gen(scope)  # caller must thread this forward

    def read(self, scope, query):
        return {
            k: v for (s, k), v in self.records.items()
            if s == scope and (s, k) not in self.tombstones
        }


def distill(mem, src_scope, dst_scope, dst_key, extract):
    # Snapshot generations at enqueue time.
    snap = {src_scope: mem._gen(src_scope)}
    src_records = mem.read(src_scope, query="*")
    derived = extract(src_records)
    # Commit with the snapshot; guardrail fires if forget landed in between.
    mem.write(dst_scope, dst_key, derived,
              source_gen=snap, source_scopes=[src_scope])


# Reproduction of the observed leak, now blocked:
m = ScopedMemory()
m.write("profile", "preferred_units", "imperial")
m.write("research/A", "measurement_notes", "values in imperial units")

snap = {"profile": m._gen("profile")}
src = m.read("profile", "*")
m.forget("profile", "preferred_units")   # generation bumps to 1

try:
    m.write("research/A", "units_convention", "imperial",
            source_gen=snap, source_scopes=["profile"])
except StaleDerivationError as e:
    print("blocked:", e)   # laundered fact never lands
