Skip to main content

mnemo_engine/store/
crud.rs

1//! Public CRUD (remember, get, delete, embedder), and the handle caches (key slots, superseded set, thread layers).
2
3use super::*;
4
5/// R-004.2: where the thread layers and the onboarding briefing live,
6/// built by the handle's one lazy scan (`ensure_key_caches`, together with
7/// the 12.1 key caches) and then kept current by `put` and `delete`. It
8/// lets `about`, `essence`, `ingest_thread`, `thread_export` and
9/// thread-pinned recall read just their own records instead of decrypting
10/// the whole file each time.
11#[derive(Debug, Default)]
12pub(super) struct LayerCache {
13    /// Live essence item ids.
14    pub(super) essence: std::collections::HashSet<u128>,
15    /// Live ids tagged `metadata.area = "onboarding"` (superseded versions
16    /// included; `about` drops those when it reads them).
17    pub(super) onboarding: std::collections::HashSet<u128>,
18    /// Per `_mnemo.thread`: its records and archive state.
19    pub(super) threads: std::collections::HashMap<String, ThreadCache>,
20    /// Thread → (the thread it continues, the link record's id).
21    pub(super) links: std::collections::HashMap<String, (String, u128)>,
22    /// FMT-9e: on v9, thread-turn records the lazy scan didn't decode,
23    /// by their row's `thread_hash`. A thread's bucket is decoded into
24    /// `threads` the first time that thread is used
25    /// ([`Mnemo::warm_thread`]), so a cold handle never decodes (or
26    /// decompresses) the turns of threads it doesn't touch.
27    pub(super) cold_turns: std::collections::HashMap<u32, Vec<u128>>,
28}
29
30/// One thread's records (turns, essence items, link), the turn ids already
31/// archived (with how many records each has: long turns are chunked), and
32/// the highest `_mnemo.seq` seen.
33#[derive(Debug, Default)]
34pub(super) struct ThreadCache {
35    pub(super) records: std::collections::HashSet<u128>,
36    pub(super) turns: std::collections::HashMap<String, u32>,
37    pub(super) max_seq: Option<u64>,
38}
39
40pub(super) fn meta_str<'a>(m: &'a Memory, key: &str) -> Option<&'a str> {
41    m.metadata.get(key).and_then(|v| v.as_str())
42}
43
44pub(super) fn is_onboarding(m: &Memory) -> bool {
45    meta_str(m, "area").is_some_and(|s| s.eq_ignore_ascii_case("onboarding"))
46}
47
48impl LayerCache {
49    pub(super) fn add(&mut self, m: &Memory) {
50        let id = m.id.0;
51        let kind = meta_str(m, MNEMO_META_KIND);
52        if kind == Some(MNEMO_META_KIND_ESSENCE) {
53            self.essence.insert(id);
54        }
55        if is_onboarding(m) {
56            self.onboarding.insert(id);
57        }
58        let Some(thread) = meta_str(m, MNEMO_META_THREAD) else {
59            return;
60        };
61        let tc = self.threads.entry(thread.to_string()).or_default();
62        tc.records.insert(id);
63        if kind == Some(MNEMO_META_KIND_TURN) {
64            if let Some(turn_id) = meta_str(m, MNEMO_META_TURN_ID) {
65                *tc.turns.entry(turn_id.to_string()).or_insert(0) += 1;
66            }
67            if let Some(seq) = m.metadata.get(MNEMO_META_SEQ).and_then(|v| v.as_u64()) {
68                tc.max_seq = Some(tc.max_seq.map_or(seq, |s| s.max(seq)));
69            }
70        }
71        if kind == Some(MNEMO_META_KIND_THREAD_LINK) {
72            if let Some(from) = meta_str(m, MNEMO_META_CONTINUES) {
73                self.links
74                    .entry(thread.to_string())
75                    .or_insert_with(|| (from.to_string(), id));
76            }
77        }
78    }
79
80    /// Undo [`LayerCache::add`] for the stored version of a record that is
81    /// being overwritten or deleted. A thread with no records left is
82    /// dropped, so a forgotten thread's `_mnemo.seq` restarts at 0. Partial
83    /// deletes keep the old maximum (sequence gaps are harmless).
84    pub(super) fn remove(&mut self, m: &Memory) {
85        let id = m.id.0;
86        self.essence.remove(&id);
87        self.onboarding.remove(&id);
88        let Some(thread) = meta_str(m, MNEMO_META_THREAD) else {
89            return;
90        };
91        if self.links.get(thread).is_some_and(|(_, link)| *link == id) {
92            self.links.remove(thread);
93        }
94        let Some(tc) = self.threads.get_mut(thread) else {
95            return;
96        };
97        tc.records.remove(&id);
98        if meta_str(m, MNEMO_META_KIND) == Some(MNEMO_META_KIND_TURN) {
99            if let Some(turn_id) = meta_str(m, MNEMO_META_TURN_ID) {
100                if let Some(n) = tc.turns.get_mut(turn_id) {
101                    *n -= 1;
102                    if *n == 0 {
103                        tc.turns.remove(turn_id);
104                    }
105                }
106            }
107        }
108        if tc.records.is_empty() {
109            self.threads.remove(thread);
110        }
111    }
112}
113
114impl Mnemo {
115    /// Register a text embedder for this handle. Enables
116    /// [`Mnemo::remember_text`] and the text-side `RecallRequest`
117    /// convenience path. Does two checks before storing the embedder:
118    ///
119    /// 1. **Dimension check.** The embedder's `identity().dimensions`
120    ///    must equal [`Mnemo::dimensions`] (the width this database
121    ///    was created with). Mismatch returns
122    ///    [`MnemoError::DimensionMismatch`].
123    /// 2. **Manifest identity check.** If the scaffold / onboarding
124    ///    manifest already records an embedder — the canonical shape
125    ///    is `metadata.embedder = { name, dimensions, normalize }`,
126    ///    with the legacy flat `embedder_name` / `embedder_dimensions`
127    ///    / `embedder_normalize` keys accepted as an alias — the new
128    ///    embedder's identity must match exactly. A different name —
129    ///    even at the same dimensions — returns
130    ///    [`MnemoError::Invalid`] with
131    ///    [`EmbedderIdentity::MISMATCH_MSG`] in the message. If the
132    ///    manifest has no embedder metadata yet, this call upserts
133    ///    the nested object into the first onboarding/manifest memory
134    ///    (write + flush so a subsequent reopen sees the identity).
135    ///
136    /// **Read-only handles.** `set_embedder` on an `open_read_only`
137    /// handle performs both checks and adopts the embedder in memory;
138    /// it never writes. Readers (CLI `--text`, agent-side `recall_text`)
139    /// can therefore use the text path next to a writer that holds
140    /// the exclusive lock.
141    ///
142    /// On both failure paths the handle's embedder slot is left
143    /// unchanged. On success the embedder is wrapped in an `Arc<dyn
144    /// Embedder>` and consulted by every text-side call made through
145    /// this handle. The slot is per-handle and not persisted — a
146    /// fresh open must re-register (same identity, so the manifest
147    /// check round-trips cleanly).
148    pub fn set_embedder<E: Embedder + 'static>(&mut self, embedder: E) -> Result<()> {
149        let identity = embedder.identity();
150        if identity.dimensions != self.dimensions {
151            return Err(MnemoError::DimensionMismatch {
152                expected: self.dimensions,
153                got: identity.dimensions,
154            });
155        }
156
157        // Find a scaffold/onboarding manifest to inspect (or upsert
158        // into). `about()` already filters + sorts the onboarding set.
159        let onboarding = self.about()?;
160        let mut upsert_target: Option<usize> = None;
161        for (i, m) in onboarding.iter().enumerate() {
162            if let Some(saw) = embed::read_identity_from_metadata(&m.metadata) {
163                if saw != identity {
164                    return Err(embed::identity_mismatch_err(&saw, &identity));
165                }
166                // Match — nothing to persist; adopt + done. Works the
167                // same on read-only and read-write handles.
168                self.embedder = Some(std::sync::Arc::new(embedder));
169                return Ok(());
170            }
171            if upsert_target.is_none() {
172                upsert_target = Some(i);
173            }
174        }
175
176        // No existing identity on the manifest. On a read-write handle
177        // upsert into the first onboarding memory so later opens see
178        // it; on a read-only handle skip the write (readers must not
179        // mutate the file), but still adopt the embedder in memory.
180        if !self.read_only {
181            if let Some(idx) = upsert_target {
182                let mut m = onboarding[idx].clone();
183                embed::write_identity_into_metadata(&mut m.metadata, &identity);
184                // Reuse the memory's existing id so this is an in-place
185                // update of the scaffold manifest, not a new entry.
186                self.put(m)?;
187                self.flush()?;
188            }
189        }
190
191        self.embedder = Some(std::sync::Arc::new(embedder));
192        Ok(())
193    }
194
195    /// Borrow the currently-registered embedder, if any. Returns
196    /// `None` when no embedder has been set via
197    /// [`Mnemo::set_embedder`]. Bindings use this to drive their own
198    /// text-side convenience methods without duplicating the identity
199    /// check.
200    pub fn embedder(&self) -> Option<&dyn Embedder> {
201        self.embedder.as_deref()
202    }
203
204    /// Shared handle to the registered embedder, cloned so the caller
205    /// can drop the borrow on this `Mnemo` before invoking `embed()`.
206    /// FIX-1 / PY-1 (R-001.11): the Python binding needs this so an
207    /// embedder callback that re-enters `Mnemo` (e.g. a Python
208    /// embedder that calls `db.dimensions()` or `db.cache_get(...)`)
209    /// doesn't hit PyO3's "Already borrowed" — we clone the Arc under
210    /// a short `&self` borrow, release that borrow, then invoke
211    /// `embed()` with no `&mut Mnemo` held.
212    pub fn embedder_arc(&self) -> Option<std::sync::Arc<dyn Embedder>> {
213        self.embedder.clone()
214    }
215
216    /// Embed `content` with the registered embedder and `remember` the
217    /// result. Returns the new memory's ULID. Convenience path for
218    /// callers who have a string, want it stored, and don't need any
219    /// of the per-memory options [`Memory`] exposes (agent, importance,
220    /// metadata, ttl, scope) — build a [`Memory`] by hand and call
221    /// [`Mnemo::remember`] for those.
222    ///
223    /// Fails with [`MnemoError::Invalid`] if no embedder has been
224    /// registered on this handle (call [`Mnemo::set_embedder`] first);
225    /// with [`MnemoError::DimensionMismatch`] if the embedder returned
226    /// the wrong width for this database.
227    pub fn remember_text(&mut self, content: &str, memory_type: MemoryType) -> Result<Ulid> {
228        if self.read_only {
229            return Err(MnemoError::ReadOnly);
230        }
231        let embedder = self.embedder.as_ref().ok_or_else(|| {
232            MnemoError::Invalid(
233                "no embedder registered on this handle; call set_embedder first".into(),
234            )
235        })?;
236        let mut vectors = embedder.embed(&[content])?;
237        let vector = vectors.pop().ok_or_else(|| {
238            MnemoError::Invalid("embedder returned no vector for the input text".into())
239        })?;
240        if vector.len() != self.dimensions {
241            return Err(MnemoError::DimensionMismatch {
242                expected: self.dimensions,
243                got: vector.len(),
244            });
245        }
246        let memory = Memory::new(content.to_string(), memory_type, vector);
247        self.remember(memory)
248    }
249
250    /// Store a memory. Returns its ULID. If the memory's ID is nil a fresh
251    /// one is assigned; an existing ID overwrites in place.
252    ///
253    /// Metadata keys starting with `_mnemo.` are the engine's (supersession,
254    /// keys, threads, kinds): a new memory carrying one is refused with
255    /// [`MnemoError::Invalid`]. An in-place overwrite may carry the stored
256    /// record's own `_mnemo.*` keys through unchanged (the usual `get`,
257    /// change a field, `remember`), but can't add, change or drop one.
258    pub fn remember(&mut self, memory: Memory) -> Result<Ulid> {
259        if self.read_only {
260            return Err(MnemoError::ReadOnly);
261        }
262        self.check_caller_metadata(&memory)?;
263        self.put(memory)
264    }
265
266    /// RB-001.24: the caller's metadata may not set engine state. For a
267    /// memory with a nil or unknown id, any `_mnemo.*` key is refused; for
268    /// an overwrite in place, the `_mnemo.*` keys must equal the stored
269    /// record's.
270    pub(super) fn check_caller_metadata(&mut self, memory: &Memory) -> Result<()> {
271        let reserved: Vec<(&String, &Value)> = memory
272            .metadata
273            .iter()
274            .filter(|(k, _)| k.starts_with(crate::memory::MNEMO_META_NS))
275            .collect();
276        if reserved.is_empty() {
277            return Ok(());
278        }
279        let stored = if memory.id.is_nil() {
280            None
281        } else {
282            match self.index.get(memory.id.0, &self.catalog) {
283                Some(idx) if !self.catalog[idx].deleted => {
284                    let entry = self.catalog[idx].clone();
285                    Some(self.read_memory(&entry)?)
286                }
287                _ => None,
288            }
289        };
290        if let Some(old) = stored {
291            let old_reserved: Vec<(&String, &Value)> = old
292                .metadata
293                .iter()
294                .filter(|(k, _)| k.starts_with(crate::memory::MNEMO_META_NS))
295                .collect();
296            if old_reserved == reserved {
297                return Ok(());
298            }
299        }
300        Err(reserved_key_error(reserved[0].0))
301    }
302
303    /// Fetch a memory by ID.
304    pub fn get(&mut self, id: &Ulid) -> Result<Memory> {
305        let idx = self
306            .index
307            .get(id.0, &self.catalog)
308            .ok_or_else(|| MnemoError::NotFound(id.to_string()))?;
309        let entry = self.catalog[idx].clone();
310        if entry.deleted {
311            return Err(MnemoError::NotFound(id.to_string()));
312        }
313        self.read_memory(&entry)
314    }
315
316    /// Soft-delete a memory (tombstoned; space reclaimed by `compact`).
317    pub fn delete(&mut self, id: &Ulid) -> Result<()> {
318        if self.read_only {
319            return Err(MnemoError::ReadOnly);
320        }
321        let idx = self
322            .index
323            .get(id.0, &self.catalog)
324            .ok_or_else(|| MnemoError::NotFound(id.to_string()))?;
325        // R-004.2 / 12.1: with the handle caches built, read the record
326        // being deleted (one decrypt) so the key slot, superseded set and
327        // thread layers drop exactly what it contributed.
328        let entry = self.catalog[idx].clone();
329        if self.layers.is_some() && !entry.deleted {
330            let old = self.read_memory(&entry)?;
331            self.note_removed(&old)?;
332        }
333        if !self.catalog[idx].deleted {
334            self.catalog[idx].deleted = true;
335            self.dirty_catalog = true;
336            self.touch(idx);
337            // FMT-9f: drop its document from the stats in place.
338            if let (Some(stats), Some(r)) = (self.bm25.stats.as_mut(), entry.v9) {
339                if r.doc != 0 {
340                    stats.remove(r.doc);
341                }
342            }
343            if self.is_v9() {
344                self.kill_record(idx, &entry);
345                self.kill_vector(idx, &entry);
346            } else {
347                self.release_pages(entry.start_page, entry.page_count as u64);
348            }
349        }
350        if let Some(ann) = &mut self.ann {
351            if ann.contains(id.0) {
352                ann.remove(id.0);
353                self.dirty_index = true;
354                self.index_persist.changes += 1;
355            }
356        }
357        // FIX-1 R-001.8 part 2: we can't tell whether this delete
358        // removed the last memory of its agent without a decrypt
359        // (the catalog entry doesn't carry `agent_id` in format v8),
360        // so just invalidate the lazy set. The next `stats()` call
361        // rebuilds from live memories.
362        self.agent_set = None;
363        // Phase 12.1: delete of a keyed record removes it from the slot,
364        // and delete of a superseded record frees a `history` entry. When
365        // the caches are built, `note_removed` above did that exactly;
366        // otherwise they're built from scratch on first use anyway.
367        Ok(())
368    }
369
370    /// Keep the handle caches (12.1 key slots, superseded set, R-004.2
371    /// layers) current after `put` writes `m`. No-op until they're built.
372    /// FMT-9e: a cold thread is warmed first, so its layer entry is whole.
373    pub(super) fn note_added(&mut self, m: &Memory) -> Result<()> {
374        if let Some(thread) = meta_str(m, MNEMO_META_THREAD) {
375            self.warm_thread(thread)?;
376        }
377        let id = m.id.0;
378        if let (Some(keys), Some(sup)) = (self.key_index.as_mut(), self.superseded.as_mut()) {
379            if m.metadata.contains_key(MNEMO_META_SUPERSEDED_BY) {
380                sup.insert(id);
381            } else if let Some(Value::String(k)) = m.metadata.get(MNEMO_META_KEY) {
382                keys.insert(Self::key_slot_for(m, k), id);
383            }
384        }
385        if let Some(layers) = self.layers.as_mut() {
386            layers.add(m);
387        }
388        Ok(())
389    }
390
391    /// Undo [`Mnemo::note_added`] for the stored version of a record that's
392    /// about to be overwritten or deleted.
393    pub(super) fn note_removed(&mut self, m: &Memory) -> Result<()> {
394        if let Some(thread) = meta_str(m, MNEMO_META_THREAD) {
395            self.warm_thread(thread)?;
396        }
397        let id = m.id.0;
398        if let (Some(keys), Some(sup)) = (self.key_index.as_mut(), self.superseded.as_mut()) {
399            sup.remove(&id);
400            if let Some(Value::String(k)) = m.metadata.get(MNEMO_META_KEY) {
401                let slot = Self::key_slot_for(m, k);
402                if keys.get(&slot) == Some(&id) {
403                    keys.remove(&slot);
404                }
405            }
406        }
407        if let Some(layers) = self.layers.as_mut() {
408            layers.remove(m);
409        }
410        Ok(())
411    }
412
413    /// FMT-9e: decode `thread`'s cold turn records (see
414    /// [`LayerCache::cold_turns`]) into the layer cache. Every record in
415    /// the thread's hash bucket is decoded and filed under its own thread,
416    /// so a hash collision just warms both threads. A no-op when the
417    /// caches aren't built or the bucket is already warm.
418    pub(super) fn warm_thread(&mut self, thread: &str) -> Result<()> {
419        self.warm_thread_decoded(thread).map(|_| ())
420    }
421
422    /// [`Mnemo::warm_thread`], returning the records it decoded (without
423    /// vectors), so a caller about to read the thread decodes each once.
424    pub(super) fn warm_thread_decoded(
425        &mut self,
426        thread: &str,
427    ) -> Result<std::collections::HashMap<u128, Memory>> {
428        let mut decoded = std::collections::HashMap::new();
429        let h = fnv1a32(&[thread.as_bytes()]);
430        let Some(ids) = self.layers.as_mut().and_then(|l| l.cold_turns.remove(&h)) else {
431            return Ok(decoded);
432        };
433        for e in self.live_entries(ids) {
434            let m = self.read_memory_meta(&e)?;
435            if let Some(layers) = self.layers.as_mut() {
436                layers.add(&m);
437            }
438            decoded.insert(e.id, m);
439        }
440        Ok(decoded)
441    }
442
443    /// Decode a record's memory without its vector or live access stats:
444    /// what the handle caches need (metadata, scope, agent), without the
445    /// v9 vector-column read [`Mnemo::read_memory`] adds.
446    pub(super) fn read_memory_meta(&mut self, e: &CatalogEntry) -> Result<Memory> {
447        let bytes = self.read_record(e)?;
448        self.decode_memory(&bytes)
449    }
450
451    /// The live catalog entries for `ids` (ids that are gone are skipped).
452    pub(super) fn live_entries(&self, ids: impl IntoIterator<Item = u128>) -> Vec<CatalogEntry> {
453        ids.into_iter()
454            .filter_map(|id| {
455                self.index
456                    .get(id, &self.catalog)
457                    .map(|i| self.catalog[i].clone())
458            })
459            .filter(|e| !e.deleted)
460            .collect()
461    }
462
463    /// Catalog entries of the essence items, from the handle caches.
464    pub(super) fn essence_entries(&mut self) -> Result<Vec<CatalogEntry>> {
465        self.ensure_key_caches()?;
466        let ids: Vec<u128> = self
467            .layers
468            .as_ref()
469            .map(|l| l.essence.iter().copied().collect())
470            .unwrap_or_default();
471        Ok(self.live_entries(ids))
472    }
473
474    /// Catalog entries of every record filed under `thread`, from the
475    /// handle caches.
476    pub(super) fn thread_entries(&mut self, thread: &str) -> Result<Vec<CatalogEntry>> {
477        Ok(self.thread_entries_decoded(thread)?.0)
478    }
479
480    /// [`Mnemo::thread_entries`], plus the records that warming a cold
481    /// thread just decoded (see [`Mnemo::warm_thread_decoded`]).
482    pub(super) fn thread_entries_decoded(
483        &mut self,
484        thread: &str,
485    ) -> Result<(Vec<CatalogEntry>, std::collections::HashMap<u128, Memory>)> {
486        self.ensure_key_caches()?;
487        let decoded = self.warm_thread_decoded(thread)?;
488        let ids: Vec<u128> = self
489            .layers
490            .as_ref()
491            .and_then(|l| l.threads.get(thread))
492            .map(|tc| tc.records.iter().copied().collect())
493            .unwrap_or_default();
494        Ok((self.live_entries(ids), decoded))
495    }
496
497    // --- Phase 12.1: edit in place + keyed supersession -----------------
498
499    /// Scope-aware key-slot identifier for `memory` and a caller key.
500    ///
501    /// * [`Scope::Private`] → owned by the memory's `agent_id`.
502    /// * [`Scope::Shared`]  → one slot across the whole file.
503    pub(super) fn key_slot_for(memory: &Memory, key: &str) -> crate::store::KeySlot {
504        let scope_owner = match memory.scope {
505            Scope::Private => Some(memory.agent_id.clone()),
506            Scope::Shared => None,
507        };
508        crate::store::KeySlot {
509            scope_owner,
510            key: key.to_string(),
511        }
512    }
513
514    /// The handle's one lazy scan: builds the 12.1 `key_index` +
515    /// `superseded` caches and the R-004.2 layer cache (essence ids,
516    /// onboarding ids, threads, links) from live records, and prunes
517    /// non-fact ids from a loaded ANN index (files written before v0.10.0
518    /// indexed every kind). Decrypts every live record once per handle;
519    /// `put` and `delete` keep the result current after that.
520    pub(super) fn ensure_key_caches(&mut self) -> Result<()> {
521        if self.key_index.is_some() && self.superseded.is_some() && self.layers.is_some() {
522            return Ok(());
523        }
524        let entries: Vec<CatalogEntry> = self
525            .catalog
526            .iter()
527            .filter(|e| !e.deleted)
528            .cloned()
529            .collect();
530        let mut keys: std::collections::HashMap<crate::store::KeySlot, u128> =
531            std::collections::HashMap::new();
532        let mut superseded: std::collections::HashSet<u128> = std::collections::HashSet::new();
533        let mut layers = LayerCache::default();
534        let mut non_facts: Vec<u128> = Vec::new();
535        for e in &entries {
536            // FMT-9e: a v9 turn row with no key slot and no supersession
537            // contributes only to its thread's layer entry, so it's left
538            // undecoded in the thread's cold bucket (most of a
539            // thread-heavy file). Its row says it isn't a fact.
540            if let Some(r) = e.v9 {
541                if r.kind == ROW_KIND_TURN
542                    && r.thread_hash != 0
543                    && r.key_hash == 0
544                    && r.flags & ROW_SUPERSEDED == 0
545                {
546                    layers
547                        .cold_turns
548                        .entry(r.thread_hash)
549                        .or_default()
550                        .push(e.id);
551                    non_facts.push(e.id);
552                    continue;
553                }
554            }
555            let m = self.read_memory_meta(e)?;
556            layers.add(&m);
557            if !is_ann_kind(&m) {
558                non_facts.push(e.id);
559            }
560            if m.metadata.get(MNEMO_META_SUPERSEDED_BY).is_some() {
561                superseded.insert(e.id);
562                continue;
563            }
564            if let Some(Value::String(k)) = m.metadata.get(MNEMO_META_KEY) {
565                let slot = Self::key_slot_for(&m, k);
566                // Catalog order is insertion order; a later live record
567                // with the same slot would only exist if a prior build
568                // of this code allowed it. Keep the later id (newer
569                // ULID), in case of a tie.
570                keys.entry(slot)
571                    .and_modify(|cur| {
572                        if *cur < e.id {
573                            *cur = e.id;
574                        }
575                    })
576                    .or_insert(e.id);
577            }
578        }
579        self.key_index = Some(keys);
580        self.superseded = Some(superseded);
581        self.layers = Some(layers);
582        if let Some(ann) = &mut self.ann {
583            let mut pruned = 0usize;
584            for id in non_facts {
585                if ann.contains(id) {
586                    ann.remove(id);
587                    pruned += 1;
588                }
589            }
590            if pruned > 0 {
591                self.dirty_index = true;
592                self.index_persist.changes += pruned;
593            }
594        }
595        Ok(())
596    }
597}
598
599/// RB-001.24: the error for caller metadata that sets an engine key.
600pub(super) fn reserved_key_error(key: &str) -> MnemoError {
601    MnemoError::Invalid(format!(
602        "metadata key \"{key}\" is reserved: keys starting with \"{}\" are set by the engine",
603        crate::memory::MNEMO_META_NS
604    ))
605}