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    pub fn remember(&mut self, memory: Memory) -> Result<Ulid> {
253        if self.read_only {
254            return Err(MnemoError::ReadOnly);
255        }
256        self.put(memory)
257    }
258
259    /// Fetch a memory by ID.
260    pub fn get(&mut self, id: &Ulid) -> Result<Memory> {
261        let idx = self
262            .index
263            .get(id.0, &self.catalog)
264            .ok_or_else(|| MnemoError::NotFound(id.to_string()))?;
265        let entry = self.catalog[idx].clone();
266        if entry.deleted {
267            return Err(MnemoError::NotFound(id.to_string()));
268        }
269        self.read_memory(&entry)
270    }
271
272    /// Soft-delete a memory (tombstoned; space reclaimed by `compact`).
273    pub fn delete(&mut self, id: &Ulid) -> Result<()> {
274        if self.read_only {
275            return Err(MnemoError::ReadOnly);
276        }
277        let idx = self
278            .index
279            .get(id.0, &self.catalog)
280            .ok_or_else(|| MnemoError::NotFound(id.to_string()))?;
281        // R-004.2 / 12.1: with the handle caches built, read the record
282        // being deleted (one decrypt) so the key slot, superseded set and
283        // thread layers drop exactly what it contributed.
284        let entry = self.catalog[idx].clone();
285        if self.layers.is_some() && !entry.deleted {
286            let old = self.read_memory(&entry)?;
287            self.note_removed(&old)?;
288        }
289        if !self.catalog[idx].deleted {
290            self.catalog[idx].deleted = true;
291            self.dirty_catalog = true;
292            self.touch(idx);
293            // FMT-9f: drop its document from the stats in place.
294            if let (Some(stats), Some(r)) = (self.bm25.stats.as_mut(), entry.v9) {
295                if r.doc != 0 {
296                    stats.remove(r.doc);
297                }
298            }
299            if self.is_v9() {
300                self.kill_record(idx, &entry);
301                self.kill_vector(idx, &entry);
302            } else {
303                self.release_pages(entry.start_page, entry.page_count as u64);
304            }
305        }
306        if let Some(ann) = &mut self.ann {
307            if ann.contains(id.0) {
308                ann.remove(id.0);
309                self.dirty_index = true;
310                self.index_persist.changes += 1;
311            }
312        }
313        // FIX-1 R-001.8 part 2: we can't tell whether this delete
314        // removed the last memory of its agent without a decrypt
315        // (the catalog entry doesn't carry `agent_id` in format v8),
316        // so just invalidate the lazy set. The next `stats()` call
317        // rebuilds from live memories.
318        self.agent_set = None;
319        // Phase 12.1: delete of a keyed record removes it from the slot,
320        // and delete of a superseded record frees a `history` entry. When
321        // the caches are built, `note_removed` above did that exactly;
322        // otherwise they're built from scratch on first use anyway.
323        Ok(())
324    }
325
326    /// Keep the handle caches (12.1 key slots, superseded set, R-004.2
327    /// layers) current after `put` writes `m`. No-op until they're built.
328    /// FMT-9e: a cold thread is warmed first, so its layer entry is whole.
329    pub(super) fn note_added(&mut self, m: &Memory) -> Result<()> {
330        if let Some(thread) = meta_str(m, MNEMO_META_THREAD) {
331            self.warm_thread(thread)?;
332        }
333        let id = m.id.0;
334        if let (Some(keys), Some(sup)) = (self.key_index.as_mut(), self.superseded.as_mut()) {
335            if m.metadata.contains_key(MNEMO_META_SUPERSEDED_BY) {
336                sup.insert(id);
337            } else if let Some(Value::String(k)) = m.metadata.get(MNEMO_META_KEY) {
338                keys.insert(Self::key_slot_for(m, k), id);
339            }
340        }
341        if let Some(layers) = self.layers.as_mut() {
342            layers.add(m);
343        }
344        Ok(())
345    }
346
347    /// Undo [`Mnemo::note_added`] for the stored version of a record that's
348    /// about to be overwritten or deleted.
349    pub(super) fn note_removed(&mut self, m: &Memory) -> Result<()> {
350        if let Some(thread) = meta_str(m, MNEMO_META_THREAD) {
351            self.warm_thread(thread)?;
352        }
353        let id = m.id.0;
354        if let (Some(keys), Some(sup)) = (self.key_index.as_mut(), self.superseded.as_mut()) {
355            sup.remove(&id);
356            if let Some(Value::String(k)) = m.metadata.get(MNEMO_META_KEY) {
357                let slot = Self::key_slot_for(m, k);
358                if keys.get(&slot) == Some(&id) {
359                    keys.remove(&slot);
360                }
361            }
362        }
363        if let Some(layers) = self.layers.as_mut() {
364            layers.remove(m);
365        }
366        Ok(())
367    }
368
369    /// FMT-9e: decode `thread`'s cold turn records (see
370    /// [`LayerCache::cold_turns`]) into the layer cache. Every record in
371    /// the thread's hash bucket is decoded and filed under its own thread,
372    /// so a hash collision just warms both threads. A no-op when the
373    /// caches aren't built or the bucket is already warm.
374    pub(super) fn warm_thread(&mut self, thread: &str) -> Result<()> {
375        self.warm_thread_decoded(thread).map(|_| ())
376    }
377
378    /// [`Mnemo::warm_thread`], returning the records it decoded (without
379    /// vectors), so a caller about to read the thread decodes each once.
380    pub(super) fn warm_thread_decoded(
381        &mut self,
382        thread: &str,
383    ) -> Result<std::collections::HashMap<u128, Memory>> {
384        let mut decoded = std::collections::HashMap::new();
385        let h = fnv1a32(&[thread.as_bytes()]);
386        let Some(ids) = self.layers.as_mut().and_then(|l| l.cold_turns.remove(&h)) else {
387            return Ok(decoded);
388        };
389        for e in self.live_entries(ids) {
390            let m = self.read_memory_meta(&e)?;
391            if let Some(layers) = self.layers.as_mut() {
392                layers.add(&m);
393            }
394            decoded.insert(e.id, m);
395        }
396        Ok(decoded)
397    }
398
399    /// Decode a record's memory without its vector or live access stats:
400    /// what the handle caches need (metadata, scope, agent), without the
401    /// v9 vector-column read [`Mnemo::read_memory`] adds.
402    pub(super) fn read_memory_meta(&mut self, e: &CatalogEntry) -> Result<Memory> {
403        let bytes = self.read_record(e)?;
404        self.decode_memory(&bytes)
405    }
406
407    /// The live catalog entries for `ids` (ids that are gone are skipped).
408    pub(super) fn live_entries(&self, ids: impl IntoIterator<Item = u128>) -> Vec<CatalogEntry> {
409        ids.into_iter()
410            .filter_map(|id| {
411                self.index
412                    .get(id, &self.catalog)
413                    .map(|i| self.catalog[i].clone())
414            })
415            .filter(|e| !e.deleted)
416            .collect()
417    }
418
419    /// Catalog entries of the essence items, from the handle caches.
420    pub(super) fn essence_entries(&mut self) -> Result<Vec<CatalogEntry>> {
421        self.ensure_key_caches()?;
422        let ids: Vec<u128> = self
423            .layers
424            .as_ref()
425            .map(|l| l.essence.iter().copied().collect())
426            .unwrap_or_default();
427        Ok(self.live_entries(ids))
428    }
429
430    /// Catalog entries of every record filed under `thread`, from the
431    /// handle caches.
432    pub(super) fn thread_entries(&mut self, thread: &str) -> Result<Vec<CatalogEntry>> {
433        Ok(self.thread_entries_decoded(thread)?.0)
434    }
435
436    /// [`Mnemo::thread_entries`], plus the records that warming a cold
437    /// thread just decoded (see [`Mnemo::warm_thread_decoded`]).
438    pub(super) fn thread_entries_decoded(
439        &mut self,
440        thread: &str,
441    ) -> Result<(Vec<CatalogEntry>, std::collections::HashMap<u128, Memory>)> {
442        self.ensure_key_caches()?;
443        let decoded = self.warm_thread_decoded(thread)?;
444        let ids: Vec<u128> = self
445            .layers
446            .as_ref()
447            .and_then(|l| l.threads.get(thread))
448            .map(|tc| tc.records.iter().copied().collect())
449            .unwrap_or_default();
450        Ok((self.live_entries(ids), decoded))
451    }
452
453    // --- Phase 12.1: edit in place + keyed supersession -----------------
454
455    /// Scope-aware key-slot identifier for `memory` and a caller key.
456    ///
457    /// * [`Scope::Private`] → owned by the memory's `agent_id`.
458    /// * [`Scope::Shared`]  → one slot across the whole file.
459    pub(super) fn key_slot_for(memory: &Memory, key: &str) -> crate::store::KeySlot {
460        let scope_owner = match memory.scope {
461            Scope::Private => Some(memory.agent_id.clone()),
462            Scope::Shared => None,
463        };
464        crate::store::KeySlot {
465            scope_owner,
466            key: key.to_string(),
467        }
468    }
469
470    /// The handle's one lazy scan: builds the 12.1 `key_index` +
471    /// `superseded` caches and the R-004.2 layer cache (essence ids,
472    /// onboarding ids, threads, links) from live records, and prunes
473    /// non-fact ids from a loaded ANN index (files written before v0.10.0
474    /// indexed every kind). Decrypts every live record once per handle;
475    /// `put` and `delete` keep the result current after that.
476    pub(super) fn ensure_key_caches(&mut self) -> Result<()> {
477        if self.key_index.is_some() && self.superseded.is_some() && self.layers.is_some() {
478            return Ok(());
479        }
480        let entries: Vec<CatalogEntry> = self
481            .catalog
482            .iter()
483            .filter(|e| !e.deleted)
484            .cloned()
485            .collect();
486        let mut keys: std::collections::HashMap<crate::store::KeySlot, u128> =
487            std::collections::HashMap::new();
488        let mut superseded: std::collections::HashSet<u128> = std::collections::HashSet::new();
489        let mut layers = LayerCache::default();
490        let mut non_facts: Vec<u128> = Vec::new();
491        for e in &entries {
492            // FMT-9e: a v9 turn row with no key slot and no supersession
493            // contributes only to its thread's layer entry, so it's left
494            // undecoded in the thread's cold bucket (most of a
495            // thread-heavy file). Its row says it isn't a fact.
496            if let Some(r) = e.v9 {
497                if r.kind == ROW_KIND_TURN
498                    && r.thread_hash != 0
499                    && r.key_hash == 0
500                    && r.flags & ROW_SUPERSEDED == 0
501                {
502                    layers
503                        .cold_turns
504                        .entry(r.thread_hash)
505                        .or_default()
506                        .push(e.id);
507                    non_facts.push(e.id);
508                    continue;
509                }
510            }
511            let m = self.read_memory_meta(e)?;
512            layers.add(&m);
513            if !is_ann_kind(&m) {
514                non_facts.push(e.id);
515            }
516            if m.metadata.get(MNEMO_META_SUPERSEDED_BY).is_some() {
517                superseded.insert(e.id);
518                continue;
519            }
520            if let Some(Value::String(k)) = m.metadata.get(MNEMO_META_KEY) {
521                let slot = Self::key_slot_for(&m, k);
522                // Catalog order is insertion order; a later live record
523                // with the same slot would only exist if a prior build
524                // of this code allowed it. Keep the later id (newer
525                // ULID), in case of a tie.
526                keys.entry(slot)
527                    .and_modify(|cur| {
528                        if *cur < e.id {
529                            *cur = e.id;
530                        }
531                    })
532                    .or_insert(e.id);
533            }
534        }
535        self.key_index = Some(keys);
536        self.superseded = Some(superseded);
537        self.layers = Some(layers);
538        if let Some(ann) = &mut self.ann {
539            let mut pruned = 0usize;
540            for id in non_facts {
541                if ann.contains(id) {
542                    ann.remove(id);
543                    pruned += 1;
544                }
545            }
546            if pruned > 0 {
547                self.dirty_index = true;
548                self.index_persist.changes += pruned;
549            }
550        }
551        Ok(())
552    }
553}