Skip to main content

plugmem_host/
db.rs

1//! `Database`: the engine + its file + the maintenance policy behind
2//! one lock (§3).
3//!
4//! The orchestration model in one paragraph: a `Database` handle is
5//! `Clone + Send + Sync` (an `Arc` around an `RwLock`-guarded engine), so
6//! any number of threads or agents in one process share one file by
7//! cloning the handle — the read verbs (`recall`/`get`/`stats`/…) run
8//! concurrently under a shared guard, the write verbs serialize under an
9//! exclusive one; at microsecond engine calls neither is a bottleneck. A
10//! second *process* (or a second `Database` on the same path) is refused
11//! with [`HostError::Locked`] by the file lock. Different files are fully
12//! independent — open as many `Database`s as you have files.
13//!
14//! Everything expensive and external — computing embeddings over HTTP —
15//! happens **before** the lock is taken: while one agent waits for its
16//! embedding provider, others keep reading and writing.
17//!
18//! (Under the `counters` perf-gate feature the engine's instrumentation
19//! `Cell`s are not `Sync`, so the lock falls back to a `Mutex` and reads
20//! serialize — a single-threaded measurement build; the public API is
21//! unchanged. See `StateLock`.)
22//!
23//! ## Overlay write path
24//!
25//! Opening a database does **not** copy its snapshot into RAM. `open`
26//! memory-maps the snapshot file and the engine *borrows* the mapped pages
27//! (an overlay over the base), replaying the journal into a small owned
28//! overlay; a mutation lands its appends in an owned tail and copies only
29//! the pages it rewrites (per-page copy-on-write in `plugmem-arena`). So a
30//! multi-gigabyte database is opened and written to while resident only in
31//! the pages it actually touches — the SQLite model. A snapshot
32//! materializes the base + overlay into a fresh file and **re-maps** it, so
33//! the overlay collapses and a long write session stays bounded. A brand-new
34//! database has no file to map yet: it opens *owned* and empty, and switches
35//! to the mapped overlay at its first snapshot.
36
37use std::cell::RefCell;
38use std::collections::BTreeMap;
39use std::fs::File;
40use std::path::{Path, PathBuf};
41use std::sync::Arc;
42#[cfg(feature = "counters")]
43use std::sync::{Mutex, MutexGuard};
44#[cfg(not(feature = "counters"))]
45use std::sync::{RwLock, RwLockReadGuard, RwLockWriteGuard};
46
47use memmap2::Mmap;
48use plugmem_core::{
49    Config, Error, FactFault, FactRecord, LinkInput, MaintainReport, MaintenanceMode,
50    MaintenanceOptions, MemStorage, Memory, OpenReport, RecallQuery, RecallResult, RecallScratch,
51    RememberInput, RememberOutcome, Stats, Storage, UnlinkInput,
52};
53
54thread_local! {
55    /// Per-thread recall scratch. `recall` takes `&self` on the engine, so many
56    /// reader threads recall one [`Database`] at once; each reuses its own
57    /// scratch here (zero re-alloc after warm-up, no lock on the hot path).
58    static RECALL_SCRATCH: RefCell<RecallScratch> = RefCell::new(RecallScratch::new());
59}
60
61use crate::embedder::Embedder;
62use crate::error::HostError;
63use crate::readonly::ReadOnlyDatabase;
64use crate::storage::{FileScratch, FileStorage, FsyncPolicy};
65
66self_cell::self_cell!(
67    /// Owns the memory map and the overlay [`Memory`] that borrows it — the
68    /// read-write sibling of `readonly::MappedMemory`. `self_cell` keeps the
69    /// self-reference safe: the only `unsafe` on this path is the inherent
70    /// mmap call, not the borrow.
71    struct OverlayMap {
72        owner: Mmap,
73        #[covariant]
74        dependent: OverlayMemory,
75    }
76);
77
78/// The dependent type constructor `self_cell` reborrows per access.
79/// [`Memory`] is covariant in its lifetime (its byte pools are
80/// `Cow<'a, [u8]>`), so borrowing the map is sound.
81type OverlayMemory<'a> = Memory<'a>;
82
83/// The engine backing a live [`Database`]: either an owned in-RAM engine
84/// (a brand-new database with no snapshot file yet) or an overlay over a
85/// memory-mapped snapshot (the common case). Both are mutable; verbs reach
86/// the engine through [`Engine::with`] / [`Engine::read`], which unify the
87/// two lifetimes (`'static` vs the map's) behind one closure.
88enum Engine {
89    /// No snapshot file to map yet — owned and (initially) empty. Switches to
90    /// `Mapped` at the first snapshot, once the file exists. Boxed so the
91    /// common `Mapped` case does not carry the whole owned engine inline.
92    Owned(Box<Memory<'static>>),
93    /// Overlay over a memory-mapped snapshot: the base is borrowed, mutations
94    /// live in the overlay (owned tail + per-page copy-on-write).
95    Mapped(OverlayMap),
96}
97
98impl Engine {
99    /// Reads through an immutable borrow of the engine (owned or mapped).
100    fn read<R>(&self, f: impl for<'a> FnOnce(&Memory<'a>) -> R) -> R {
101        match self {
102            Engine::Owned(mem) => f(mem),
103            Engine::Mapped(map) => f(map.borrow_dependent()),
104        }
105    }
106
107    /// Mutates the engine and its store together (disjoint borrows). The
108    /// closure is higher-ranked over the engine's lifetime so one body serves
109    /// both the `'static` owned engine and the map-bound overlay.
110    fn with<R>(
111        &mut self,
112        store: &mut FileStorage,
113        f: impl for<'a> FnOnce(&mut Memory<'a>, &mut FileStorage) -> R,
114    ) -> R {
115        match self {
116            Engine::Owned(mem) => f(mem, store),
117            Engine::Mapped(map) => map.with_dependent_mut(|_owner, mem| f(mem, store)),
118        }
119    }
120}
121
122/// Opens the engine at `store`'s path: memory-maps the snapshot
123/// and borrows it as an overlay, replaying the journal. A missing snapshot
124/// file (a brand-new database) opens owned and empty — the file appears at the
125/// first snapshot. `store` must already hold the exclusive lock.
126fn open_engine(store: &mut FileStorage, cfg: &Config) -> Result<(Engine, OpenReport), HostError> {
127    let journal = store.read_journal()?;
128    let Some(genp) = store.current_snapshot_path()? else {
129        // No published generation yet. The database is owned until the first
130        // checkpoint publishes one — but a journal may already exist (mutations
131        // before any snapshot), so still replay it into the owned engine.
132        let (mem, report) = Memory::from_bytes(None, &journal, cfg.clone())?;
133        return Ok((Engine::Owned(Box::new(mem)), report));
134    };
135    let file = File::open(&genp).map_err(|e| HostError::io(&genp, e))?;
136    // SAFETY: mapping a file is inherently unsafe — a concurrent truncate or
137    // overwrite of the mapped file would fault the process (SIGBUS/exception)
138    // on the next page access. Our correctness argument: the
139    // generation file is **immutable** (a checkpoint publishes a new one and
140    // never rewrites this), and the `store` holds the exclusive writer lock, so
141    // nothing overwrites it under the map. A foreign `truncate`/`rm` under a
142    // live handle is out of contract — the same caveat as corrupting any
143    // database file under a running engine.
144    let map = unsafe { Mmap::map(&file) }.map_err(|e| HostError::io(&genp, e))?;
145    // The `File` handle is no longer needed: `Mmap` owns the mapping.
146    drop(file);
147    // Replay the journal into the overlay: no whole-arena clone, only the
148    // touched pages copy up. `self_cell` builds the engine borrowing the map;
149    // the replay report is captured out of the constructor closure.
150    let mut report = None;
151    let mapped = OverlayMap::try_new(map, |m| {
152        let (mem, rep) = Memory::from_bytes_overlay(&m[..], &journal, cfg.clone())?;
153        report = Some(rep);
154        Ok::<_, Error>(mem)
155    })?;
156    Ok((Engine::Mapped(mapped), report.unwrap_or_default()))
157}
158
159/// An owned view of one fact — [`Memory::get`] returns borrows that
160/// cannot cross the lock, so the database hands out copies.
161#[derive(Clone, Debug, PartialEq)]
162#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
163pub struct FactSnapshot {
164    /// The raw record (temporality, flags, references).
165    pub record: FactRecord,
166    /// The fact text.
167    pub text: String,
168    /// The fact's metadata as a sorted key→value map (empty when the fact
169    /// carries none). The engine stores it opaquely; this is the decoded view.
170    pub metadata: BTreeMap<String, String>,
171}
172
173/// One exported fact — the human-readable, id-free shape [`Database::export`]
174/// dumps and an importer re-`remember`s. Internal ids and
175/// `recorded_at` are the engine's bookkeeping and are *not* preserved across
176/// a round-trip; the knowledge itself (text, subject name, tags, validity
177/// start) is.
178#[derive(Clone, Debug, PartialEq)]
179#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
180pub struct ExportedFact {
181    /// The fact's id **in the database it came from**.
182    ///
183    /// Informational, and deliberately not restored on import: a fresh database
184    /// assigns its own. It is here because edges reference their provenance
185    /// fact by id, so a dump that carries edges needs something for them to
186    /// point at — an importer translates old id to new as it goes.
187    pub id: u32,
188    /// The fact text.
189    pub text: String,
190    /// Subject entity name, if the fact had one.
191    pub entity: Option<String>,
192    /// Tag strings.
193    pub tags: Vec<String>,
194    /// Metadata as a sorted key→value map (empty when none) — preserved on
195    /// import.
196    pub metadata: BTreeMap<String, String>,
197    /// When the memory learned it (informational; not restorable on import).
198    pub recorded_at: u64,
199    /// Validity start — preserved on import.
200    pub valid_from: u64,
201}
202
203/// One bounded page of currently-open facts.
204///
205/// `next_cursor` is the next fact id to inspect, not an offset into `facts`:
206/// closed, tombstoned, and purged ids are skipped without making the caller
207/// rescan them. `None` means the scan reached the database's current end.
208#[derive(Clone, Debug, PartialEq)]
209#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
210pub struct ExportPage {
211    /// The open facts found in this page, in fact-id order.
212    pub facts: Vec<ExportedFact>,
213    /// Pass this to the next [`Database::export_page`] call.
214    pub next_cursor: Option<u32>,
215}
216
217/// The outcome of a [`Database::recover`] salvage.
218#[derive(Clone, Copy, Debug, PartialEq, Eq)]
219#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
220pub struct RecoverReport {
221    /// Facts written to the destination (the survivors after the purge).
222    pub kept: usize,
223    /// Facts dropped because their stored text was not valid UTF-8.
224    pub dropped_text: usize,
225    /// Facts dropped because their vector slot was out of range or mismatched.
226    pub dropped_vector: usize,
227    /// Facts dropped because their metadata blob did not decode to a
228    /// well-formed key→value map.
229    pub dropped_metadata: usize,
230}
231
232/// Visits the currently-open facts (skipping closed revisions and tombstones),
233/// resolving each subject name and tag string, calling `f` once per fact. The
234/// streaming core of export: a caller that writes each fact out (CLI `export`)
235/// never materializes the whole dump, so a huge database exports without a RAM
236/// spike. Shared by the read-write and read-only handles.
237/// Decodes a fact's metadata into an owned, sorted key→value map (empty when
238/// the fact carries none). Shared by `get` (read-write and read-only) and
239/// `export`; the pairs come back from the engine in canonical order, so the
240/// resulting `BTreeMap` matches the raw core view key-for-key.
241pub(crate) fn metadata_map(mem: &Memory, id: plugmem_core::FactId) -> BTreeMap<String, String> {
242    let mut pairs = Vec::new();
243    mem.metadata_of(id, &mut pairs);
244    pairs
245        .into_iter()
246        .map(|(k, v)| (k.to_string(), v.to_string()))
247        .collect()
248}
249
250fn exported_fact(
251    mem: &Memory,
252    id: plugmem_core::FactId,
253    terms: &mut Vec<plugmem_core::TermId>,
254) -> Option<ExportedFact> {
255    use plugmem_core::{EntityId, VALID_TO_OPEN};
256    let view = mem.get(id)?;
257    if view.record.valid_to != VALID_TO_OPEN {
258        return None; // a closed revision — export the current state only
259    }
260    let entity = (view.record.entity != EntityId::NONE)
261        .then(|| mem.entity_name(view.record.entity))
262        .flatten()
263        .map(str::to_string);
264    terms.clear();
265    mem.tags_of(id, terms);
266    let tags = terms.iter().map(|t| mem.term(*t).to_string()).collect();
267    Some(ExportedFact {
268        id: id.0,
269        text: view.text.to_string(),
270        entity,
271        tags,
272        metadata: metadata_map(mem, id),
273        recorded_at: view.record.recorded_at,
274        valid_from: view.record.valid_from,
275    })
276}
277
278pub(crate) fn export_facts_each(mem: &Memory, mut f: impl FnMut(ExportedFact)) {
279    use plugmem_core::FactId;
280    let next = mem.stats().next_fact;
281    let mut terms = Vec::new();
282    for i in 0..next {
283        if let Some(fact) = exported_fact(mem, FactId(i), &mut terms) {
284            f(fact);
285        }
286    }
287}
288
289pub(crate) fn export_facts_page(mem: &Memory, cursor: u32, limit: usize) -> ExportPage {
290    use plugmem_core::FactId;
291    let end = mem.stats().next_fact;
292    let mut cursor = cursor.min(end);
293    let stop = cursor
294        .saturating_add(limit.min(u32::MAX as usize) as u32)
295        .min(end);
296    let mut terms = Vec::new();
297    let mut facts = Vec::with_capacity((stop - cursor) as usize);
298    while cursor < stop {
299        let id = FactId(cursor);
300        cursor += 1;
301        if let Some(fact) = exported_fact(mem, id, &mut terms) {
302            facts.push(fact);
303        }
304    }
305    ExportPage {
306        facts,
307        next_cursor: (cursor < end).then_some(cursor),
308    }
309}
310
311/// Collects the currently-open facts into a `Vec` (the owning form of
312/// [`export_facts_each`]). Used where the whole dump is wanted in memory.
313pub(crate) fn export_facts(mem: &Memory) -> Vec<ExportedFact> {
314    let mut out = Vec::new();
315    export_facts_each(mem, |e| out.push(e));
316    out
317}
318
319/// Tuning knobs of a [`Database`]. Construct through
320/// [`Database::builder`].
321pub struct DatabaseBuilder {
322    cfg: Config,
323    fsync: FsyncPolicy,
324    snapshot_every_ops: u64,
325    snapshot_journal_bytes: u64,
326    maintain_every_forgets: Option<u64>,
327    embedder: Option<Box<dyn Embedder>>,
328}
329
330impl DatabaseBuilder {
331    /// Journal fsync policy (default: every operation).
332    pub fn fsync(mut self, policy: FsyncPolicy) -> Self {
333        self.fsync = policy;
334        self
335    }
336
337    /// Auto-snapshot after this many mutations (default 1024; `0`
338    /// disables the count trigger).
339    pub fn snapshot_every_ops(mut self, ops: u64) -> Self {
340        self.snapshot_every_ops = ops;
341        self
342    }
343
344    /// Auto-snapshot when the journal outgrows this many bytes (default
345    /// 4 MiB; `0` disables the size trigger).
346    pub fn snapshot_journal_bytes(mut self, bytes: u64) -> Self {
347        self.snapshot_journal_bytes = bytes;
348        self
349    }
350
351    /// Optional auto-`maintain` after this many forgets (default off —
352    /// maintenance is O(database) and the first pass beyond the HNSW
353    /// threshold pays the graph build).
354    pub fn maintain_every_forgets(mut self, forgets: u64) -> Self {
355        self.maintain_every_forgets = Some(forgets);
356        self
357    }
358
359    /// The embedding provider. When set (and its `dim() > 0`),
360    /// `remember` without a vector embeds the fact text and `recall`
361    /// with a text but no vector embeds the query — both outside the
362    /// database lock. `Config::dim` must equal the embedder's dimension.
363    pub fn embedder(mut self, embedder: Box<dyn Embedder>) -> Self {
364        self.embedder = Some(embedder);
365        self
366    }
367
368    /// Opens (or creates) the database at `path`.
369    ///
370    /// # Errors
371    ///
372    /// [`HostError::Locked`] when the file is owned elsewhere;
373    /// [`HostError::Engine`] for config/snapshot/journal problems
374    /// (including an embedder dimension that disagrees with
375    /// `Config::dim`); [`HostError::Io`] for filesystem failures.
376    pub fn open(self, path: impl Into<PathBuf>) -> Result<(Database, OpenReport), HostError> {
377        if let Some(embedder) = &self.embedder {
378            let dim = embedder.dim();
379            if dim != 0 && dim != self.cfg.dim {
380                return Err(HostError::Engine(Error::ConfigMismatch(
381                    "embedder dimension must equal Config::dim",
382                )));
383            }
384        }
385        let mut store = FileStorage::open(path, self.fsync)?;
386        let (engine, report) = open_engine(&mut store, &self.cfg)?;
387        let db = Database {
388            inner: Arc::new(Inner {
389                state: StateLock::new(State {
390                    engine,
391                    store,
392                    ops: 0,
393                    forgets: 0,
394                }),
395                embedder: self.embedder,
396                cfg: self.cfg,
397                snapshot_every_ops: self.snapshot_every_ops,
398                snapshot_journal_bytes: self.snapshot_journal_bytes,
399                maintain_every_forgets: self.maintain_every_forgets,
400            }),
401        };
402        Ok((db, report))
403    }
404}
405
406/// The engine lock. Normally an `RwLock` so read-only verbs run concurrently
407/// (the whole point of Variant 1). Under `counters`, `State` embeds the arena's
408/// non-`Sync` instrumentation `Cell`s, and `RwLock<T>` needs `T: Sync` to hand
409/// out shared guards — so there we fall back to a `Mutex`. `counters` is a
410/// single-threaded perf-gate build, so serialized readers cost nothing there,
411/// and the `Mutex` keeps `Database: Send + Sync` so every test still builds.
412#[cfg(not(feature = "counters"))]
413type StateLock = RwLock<State>;
414#[cfg(feature = "counters")]
415type StateLock = Mutex<State>;
416
417struct Inner {
418    state: StateLock,
419    /// Unlocked: [`Embedder::embed`] takes `&self`, so several verbs may be
420    /// inside the provider at once. That is the point — the round trip is the
421    /// slow part of a write, and a lock here would queue every concurrent
422    /// caller behind one HTTP request.
423    embedder: Option<Box<dyn Embedder>>,
424    /// Kept to rebuild the overlay engine after a re-map on snapshot.
425    cfg: Config,
426    snapshot_every_ops: u64,
427    snapshot_journal_bytes: u64,
428    maintain_every_forgets: Option<u64>,
429}
430
431struct State {
432    engine: Engine,
433    store: FileStorage,
434    /// Mutations since the last snapshot.
435    ops: u64,
436    /// Forgets since the last maintain.
437    forgets: u64,
438}
439
440/// A clonable, thread-safe handle to one database file. See the module
441/// docs for the concurrency model.
442#[derive(Clone)]
443pub struct Database {
444    inner: Arc<Inner>,
445}
446
447impl Database {
448    /// Opens `path` with every knob at its default and no embedder.
449    pub fn open(path: impl Into<PathBuf>, cfg: Config) -> Result<(Self, OpenReport), HostError> {
450        Self::builder(cfg).open(path)
451    }
452
453    /// Opens `path` read-only over a memory-mapped snapshot:
454    /// the engine borrows the mapped pages instead of copying the file
455    /// into RAM, so a large read-mostly database residents only the pages
456    /// `recall`/`get` touch. Requires a checkpointed database (empty
457    /// journal) and takes a shared lock (N readers or one writer).
458    /// See [`ReadOnlyDatabase`].
459    ///
460    /// # Errors
461    ///
462    /// [`HostError::Locked`], [`HostError::NeedsCheckpoint`],
463    /// [`HostError::Io`], [`HostError::Engine`] — see
464    /// `ReadOnlyDatabase::open` semantics.
465    pub fn open_readonly(
466        path: impl Into<PathBuf>,
467        cfg: Config,
468    ) -> Result<ReadOnlyDatabase, HostError> {
469        ReadOnlyDatabase::open(path, cfg)
470    }
471
472    /// Starts a configured open (knobs).
473    pub fn builder(cfg: Config) -> DatabaseBuilder {
474        DatabaseBuilder {
475            cfg,
476            fsync: FsyncPolicy::default(),
477            snapshot_every_ops: 1024,
478            snapshot_journal_bytes: 4 * 1024 * 1024,
479            maintain_every_forgets: None,
480            embedder: None,
481        }
482    }
483
484    /// A shared (read) guard — for the read-only verbs (`recall`/`get`/
485    /// `stats`/`export`/`verify`). Many run at once; they exclude only writers.
486    /// (Under `counters` the lock is a `Mutex`, so reads serialize — see
487    /// [`StateLock`].) A panicked verb cannot leave the engine half-mutated
488    /// (check first, mutate last is the engine's own law), so a poisoned lock
489    /// is recoverable.
490    #[cfg(not(feature = "counters"))]
491    fn read(&self) -> RwLockReadGuard<'_, State> {
492        self.inner.state.read().unwrap_or_else(|e| e.into_inner())
493    }
494
495    /// An exclusive (write) guard — for the mutating verbs. Serializes writers
496    /// against each other and against every concurrent reader.
497    #[cfg(not(feature = "counters"))]
498    fn write(&self) -> RwLockWriteGuard<'_, State> {
499        self.inner.state.write().unwrap_or_else(|e| e.into_inner())
500    }
501
502    /// Under `counters` the engine lock is a `Mutex`: `read` and `write` both
503    /// take the one exclusive guard (readers serialize — acceptable for the
504    /// single-threaded perf-gate build). See [`StateLock`].
505    #[cfg(feature = "counters")]
506    fn read(&self) -> MutexGuard<'_, State> {
507        self.inner.state.lock().unwrap_or_else(|e| e.into_inner())
508    }
509
510    #[cfg(feature = "counters")]
511    fn write(&self) -> MutexGuard<'_, State> {
512        self.inner.state.lock().unwrap_or_else(|e| e.into_inner())
513    }
514
515    /// Embeds `text` outside the state lock, when an embedder is
516    /// configured. `None` = leave the input as it was.
517    fn embed_one(&self, text: &str) -> Result<Option<Vec<f32>>, HostError> {
518        let Some(embedder) = &self.inner.embedder else {
519            return Ok(None);
520        };
521        if embedder.dim() == 0 {
522            return Ok(None);
523        }
524        let mut vs = embedder.embed(&[text])?;
525        Ok(Some(vs.remove(0)))
526    }
527
528    /// Embeds a whole batch of texts in a **single** embedder call — outside the
529    /// lock, like [`embed_one`](Self::embed_one). `Ok(None)` when no embedder is
530    /// configured or `dim == 0`; otherwise a vector aligned one-to-one with
531    /// `texts` (the provider contract, checked by [`OpenAiCompatEmbedder`]). An
532    /// empty `texts` yields an empty vector without a round-trip. This is the one
533    /// HTTP that [`remember_many`](Self::remember_many) makes for a bulk write.
534    fn embed_many(&self, texts: &[&str]) -> Result<Option<Vec<Vec<f32>>>, HostError> {
535        let Some(embedder) = &self.inner.embedder else {
536            return Ok(None);
537        };
538        if embedder.dim() == 0 {
539            return Ok(None);
540        }
541        if texts.is_empty() {
542            return Ok(Some(Vec::new()));
543        }
544        Ok(Some(embedder.embed(texts)?))
545    }
546
547    /// Writes a full snapshot and re-maps the fresh file.
548    ///
549    /// Materializes the borrowed base + overlay into an owned buffer, drops
550    /// the current map, writes the buffer (tmp + fsync + rename) and clears
551    /// the journal, then maps the new file into a fresh overlay. The re-map
552    /// collapses the overlay so a long write session stays bounded, and
553    /// dropping the map **before** the rename keeps the write portable
554    /// (a mapped file cannot be renamed over on Windows).
555    fn resnapshot(&self, st: &mut State, now: u64) -> Result<(), HostError> {
556        // Stream the image straight to the tmp file — never a full-image Vec
557        // This reads through the live map, so it happens
558        // **before** the map is dropped.
559        {
560            let State { engine, store, .. } = &mut *st;
561            store.stage_snapshot(|sink| {
562                engine
563                    .read(|mem| mem.write_snapshot_to(now, &mut *sink))
564                    .map_err(HostError::from)
565            })?;
566        }
567        // Drop the current map before the rename: park a cheap empty engine.
568        // It is replaced by the fresh overlay below — or, if the commit fails,
569        // rebuilt from the intact on-disk snapshot + journal.
570        st.engine = Engine::Owned(Box::new(Memory::new(self.inner.cfg.clone())?));
571        let write = st
572            .store
573            .commit_snapshot()
574            .and_then(|()| st.store.clear_journal());
575        // Re-open regardless: on success the fresh file, on failure the
576        // untouched old file + journal (journal replay is idempotent, so a
577        // failed `clear_journal` does not corrupt state). Then surface the
578        // commit error, if any.
579        let (engine, _) = open_engine(&mut st.store, &self.inner.cfg)?;
580        st.engine = engine;
581        write
582    }
583
584    /// The post-mutation policy hook: counts the op, fires auto-maintain
585    /// and auto-snapshot inside the same critical section.
586    fn after_mutation(&self, st: &mut State, now: u64) -> Result<(), HostError> {
587        st.ops += 1;
588        if let Some(threshold) = self.inner.maintain_every_forgets
589            && st.forgets >= threshold
590        {
591            let State { engine, store, .. } = &mut *st;
592            engine.with(store, |mem, store| mem.maintain(store, now))?;
593            st.forgets = 0;
594        }
595        // A database that outgrows its shard layout re-shards itself. This is
596        // on by default, unlike `maintain_every_forgets`, because without it
597        // nothing would ever move a layout: a growing database would keep the
598        // one it was created with until somebody ran `maintain` by hand, and
599        // the cost of that is silent — memory, and a page directory that keeps
600        // lengthening.
601        //
602        // Affordable because both halves are bounded. The question is O(1)
603        // (stored record counts), so asking on every write is free; and the
604        // answer is self-limiting — the thresholds are a doubling up and a
605        // fourfold drop, so it says yes a handful of times over a database's
606        // whole life. `resharding_settles_instead_of_asking_forever` in the
607        // core suite is the test that keeps that true.
608        let State { engine, store, .. } = &mut *st;
609        if engine.with(store, |mem, _| mem.shard_layout_is_stale()) {
610            engine.with(store, |mem, store| mem.maintain(store, now))?;
611        }
612        let by_ops = self.inner.snapshot_every_ops > 0 && st.ops >= self.inner.snapshot_every_ops;
613        let by_bytes = self.inner.snapshot_journal_bytes > 0
614            && st.store.journal_bytes() >= self.inner.snapshot_journal_bytes;
615        if by_ops || by_bytes {
616            self.resnapshot(st, now)?;
617            st.ops = 0;
618        }
619        Ok(())
620    }
621
622    /// Remembers a fact. Without an explicit vector and with an embedder
623    /// configured, the text is embedded first — outside the lock.
624    pub fn remember(&self, input: RememberInput<'_>) -> Result<RememberOutcome, HostError> {
625        let embedded = match input.vector {
626            Some(_) => None,
627            None => self.embed_one(input.text)?,
628        };
629        let input = RememberInput {
630            vector: embedded.as_deref().or(input.vector),
631            ..input
632        };
633        let mut st = self.write();
634        let State { engine, store, .. } = &mut *st;
635        let out = engine.with(store, |mem, store| mem.remember(store, input))?;
636        self.after_mutation(&mut st, input.now)?;
637        Ok(out)
638    }
639
640    /// Remembers a **batch** of facts in one shot — the bulk-write path (CLI
641    /// `import`). Equivalent to [`remember`](Self::remember) on each input in
642    /// order, but far cheaper for a batch: the texts that need embedding are
643    /// embedded together in **one** embedder round-trip (outside the lock), and
644    /// all facts are written under **one** write-guard with **one** post-mutation
645    /// policy pass — instead of N HTTP calls and N critical sections.
646    ///
647    /// Inputs that already carry a `vector` are not re-embedded. **Chunking is
648    /// the caller's job**: this writes the whole slice it is given, so a caller
649    /// that needs bounded memory / a bounded HTTP body passes fixed-size batches
650    /// (CLI `import` streams the file in `--batch`-sized slices).
651    ///
652    /// **Fail-fast:** the first engine error returns `Err`; the facts written
653    /// before it stay written (exactly as separate `remember`s — the journal
654    /// replay is idempotent, so a retried bulk load is safe). Returns one
655    /// [`RememberOutcome`] per input, in order.
656    pub fn remember_many(
657        &self,
658        inputs: Vec<RememberInput<'_>>,
659    ) -> Result<Vec<RememberOutcome>, HostError> {
660        if inputs.is_empty() {
661            return Ok(Vec::new());
662        }
663        // One embedder round-trip for every vector-less input's text, outside the
664        // lock. `to_embed` is the vector-less inputs in order, so its result maps
665        // back onto them by a running cursor below.
666        let to_embed: Vec<&str> = inputs
667            .iter()
668            .filter(|i| i.vector.is_none())
669            .map(|i| i.text)
670            .collect();
671        let embedded = if to_embed.is_empty() {
672            None
673        } else {
674            self.embed_many(&to_embed)?
675        };
676
677        let mut st = self.write();
678        // Batch mode: journal appends skip their per-record fsync; one
679        // `sync_journal` at the end makes the whole batch durable at once.
680        st.store.set_batch(true);
681        let mut out = Vec::with_capacity(inputs.len());
682        let mut cursor = 0usize; // into `embedded`, over vector-less inputs in order
683        let mut latest = 0u64;
684        let mut failed = None;
685        for input in inputs {
686            latest = latest.max(input.now);
687            let vector = if input.vector.is_some() {
688                input.vector
689            } else if let Some(embedded) = &embedded {
690                let v = embedded[cursor].as_slice();
691                cursor += 1;
692                Some(v)
693            } else {
694                None // no embedder — lexical/structural only, as single remember
695            };
696            let input = RememberInput { vector, ..input };
697            let State { engine, store, .. } = &mut *st;
698            match engine.with(store, |mem, store| mem.remember(store, input)) {
699                Ok(o) => out.push(o),
700                Err(e) => {
701                    failed = Some(HostError::from(e));
702                    break;
703                }
704            }
705        }
706        // Always leave batch mode and fsync — this is the batch's durability
707        // point. On fail-fast it makes the facts written before the error durable
708        // (they stay, exactly like separate remembers).
709        st.store.set_batch(false);
710        st.store.sync_journal()?;
711        if let Some(e) = failed {
712            return Err(e);
713        }
714        // One policy pass for the whole batch. The op counter advances by one per
715        // batch; the journal-bytes threshold still fires on a large batch, so a
716        // snapshot is not starved.
717        self.after_mutation(&mut st, latest)?;
718        Ok(out)
719    }
720
721    /// Runs a recall. With a text, no vector and an embedder configured,
722    /// the query text is embedded first — outside the lock.
723    pub fn recall(&self, q: RecallQuery<'_>) -> Result<RecallResult, HostError> {
724        let embedded = match (q.vector, q.text) {
725            (None, Some(text)) => self.embed_one(text)?,
726            _ => None,
727        };
728        let q = RecallQuery {
729            vector: embedded.as_deref().or(q.vector),
730            ..q
731        };
732        // A shared guard: concurrent recalls run in parallel. `recall_into`
733        // takes `&self` on the engine and a per-thread scratch, so there is no
734        // writer path and no cross-reader contention on the hot path.
735        let st = self.read();
736        RECALL_SCRATCH.with(|scratch| {
737            let mut scratch = scratch.borrow_mut();
738            let mut out = RecallResult::default();
739            st.engine
740                .read(|mem| mem.recall_into(q, &mut scratch, &mut out))?;
741            Ok(out)
742        })
743    }
744
745    /// Revises `target` (same auto-embedding rule as `remember`).
746    pub fn revise(
747        &self,
748        target: plugmem_core::FactId,
749        input: RememberInput<'_>,
750    ) -> Result<RememberOutcome, HostError> {
751        let embedded = match input.vector {
752            Some(_) => None,
753            None => self.embed_one(input.text)?,
754        };
755        let input = RememberInput {
756            vector: embedded.as_deref().or(input.vector),
757            ..input
758        };
759        let mut st = self.write();
760        let State { engine, store, .. } = &mut *st;
761        let out = engine.with(store, |mem, store| mem.revise(store, target, input))?;
762        self.after_mutation(&mut st, input.now)?;
763        Ok(out)
764    }
765
766    /// Tombstones a fact.
767    pub fn forget(&self, now: u64, id: plugmem_core::FactId) -> Result<bool, HostError> {
768        let mut st = self.write();
769        let State { engine, store, .. } = &mut *st;
770        let fresh = engine.with(store, |mem, store| mem.forget(store, now, id))?;
771        st.forgets += 1;
772        self.after_mutation(&mut st, now)?;
773        Ok(fresh)
774    }
775
776    /// Upserts a typed edge.
777    pub fn link(&self, input: LinkInput<'_>) -> Result<(), HostError> {
778        let mut st = self.write();
779        let State { engine, store, .. } = &mut *st;
780        engine.with(store, |mem, store| mem.link(store, input))?;
781        self.after_mutation(&mut st, input.now)?;
782        Ok(())
783    }
784
785    /// Closes a typed edge. Returns `false` when the edge is already absent.
786    pub fn unlink(&self, input: UnlinkInput<'_>) -> Result<bool, HostError> {
787        let mut st = self.write();
788        let State { engine, store, .. } = &mut *st;
789        let fresh = engine.with(store, |mem, store| mem.unlink(store, input))?;
790        self.after_mutation(&mut st, input.now)?;
791        Ok(fresh)
792    }
793
794    /// An owned copy of one fact, or `None` for unknown/tombstoned ids.
795    pub fn get(&self, id: plugmem_core::FactId) -> Option<FactSnapshot> {
796        self.read().engine.read(|mem| {
797            mem.get(id).map(|v| FactSnapshot {
798                record: v.record,
799                text: v.text.to_string(),
800                metadata: metadata_map(mem, id),
801            })
802        })
803    }
804
805    /// One fact's tags, or an empty vector for an unknown or tombstoned id.
806    ///
807    /// [`FactSnapshot`] carries text and metadata but not tags, so without this
808    /// the only way to read one fact's tags is [`Database::export`] — a full
809    /// scan to answer a question about a single id.
810    pub fn tags_of(&self, id: plugmem_core::FactId) -> Vec<String> {
811        self.read().engine.read(|mem| {
812            let mut terms = Vec::new();
813            mem.tags_of(id, &mut terms);
814            terms.iter().map(|t| mem.term(*t).to_string()).collect()
815        })
816    }
817
818    /// Engine size counters.
819    pub fn stats(&self) -> Stats {
820        self.read().engine.read(|mem| mem.stats())
821    }
822
823    /// Dumps the currently-open facts for a human-readable backup
824    /// See [`ExportedFact`]. Collects the whole set; for a large
825    /// database prefer [`export_each`](Self::export_each), which streams.
826    pub fn export(&self) -> Vec<ExportedFact> {
827        self.read().engine.read(export_facts)
828    }
829
830    /// Streams the currently-open facts, calling `f` once per fact under the
831    /// read guard — the whole dump is never materialized, so a huge database
832    /// exports without a RAM spike (CLI `export` writes each line straight out).
833    /// See [`ExportedFact`].
834    pub fn export_each(&self, f: impl FnMut(ExportedFact)) {
835        self.read().engine.read(|mem| export_facts_each(mem, f));
836    }
837
838    /// Streams the currently-open **edges**, calling `f` with
839    /// `(source, relation, destination, provenance fact)` under the read guard.
840    ///
841    /// The companion to [`export_each`](Self::export_each): facts alone are not
842    /// the memory, and a dump without edges silently drops one of the four
843    /// recall sources. Names are borrowed, so a writer that formats them
844    /// directly allocates nothing per edge.
845    ///
846    /// `provenance` is the fact id **as this database numbers it**. Ids do not
847    /// survive a re-import, so a file format that wants to keep provenance has
848    /// to translate it — see the CLI's `export`/`import`, which rewrite it as a
849    /// position within the same file.
850    pub fn export_edges_each(&self, mut f: impl FnMut(&str, &str, &str, plugmem_core::FactId)) {
851        self.read().engine.read(|mem| {
852            mem.edges_each(|src, rel, dst, fact| {
853                f(src, rel, dst, fact);
854                true
855            });
856        });
857    }
858
859    /// Inspects at most `limit` fact ids starting at `cursor` and returns the
860    /// ones that are currently open. A sparse page may therefore contain fewer
861    /// facts, including zero, while still carrying a `next_cursor`.
862    ///
863    /// This is the pull-based counterpart to [`export_each`](Self::export_each):
864    /// it releases the database read guard before returning, so a boundary
865    /// caller can process the page, apply backpressure, or write to the database
866    /// without a callback running under this lock. Mutations between page calls
867    /// are visible to later pages; use a stable read-only checkpoint when
868    /// snapshot-consistent paging is required.
869    pub fn export_page(&self, cursor: u32, limit: std::num::NonZeroUsize) -> ExportPage {
870        self.read()
871            .engine
872            .read(|mem| export_facts_page(mem, cursor, limit.get()))
873    }
874
875    /// Runs a maintenance pass now (cheap no-op, purge/compaction, text
876    /// reindex, and/or bounded HNSW work — for the cost model).
877    ///
878    /// **Disk-first** (milestone H): the compacted image is written by streaming
879    /// the two big pools (vectors, text) through temp files and then re-mapped,
880    /// so peak RAM tracks the record count (metadata + graph), not the image
881    /// size — a database larger than RAM can be maintained. It writes a fresh
882    /// snapshot and clears the journal (like a checkpoint). The optional
883    /// auto-maintain policy (`maintain_every_forgets`) still runs in RAM inline
884    /// — it is for databases that fit.
885    ///
886    /// The report's byte counts are the on-disk image size before and after.
887    pub fn maintain(&self, now: u64) -> Result<MaintainReport, HostError> {
888        self.maintain_with_options(now, MaintenanceOptions::auto())
889    }
890
891    /// Runs a maintenance pass with explicit policy.
892    pub fn maintain_with_options(
893        &self,
894        now: u64,
895        options: MaintenanceOptions,
896    ) -> Result<MaintainReport, HostError> {
897        let mut st = self.write();
898        // The image size is the current snapshot generation's, not the tiny
899        // manifest at the base path.
900        let snap_len = |store: &FileStorage| -> usize {
901            store
902                .current_snapshot_path()
903                .ok()
904                .flatten()
905                .and_then(|p| std::fs::metadata(&p).ok())
906                .map(|m| m.len() as usize)
907                .unwrap_or(0)
908        };
909        let bytes_before = snap_len(&st.store);
910        if !st.engine.read(|mem| mem.maintenance_needed(options)) {
911            let mut report = st
912                .engine
913                .read(|mem| mem.maintenance_preview(options, bytes_before));
914            report.bytes_after = bytes_before;
915            return Ok(report);
916        }
917        let stats = st.engine.read(|mem| mem.stats());
918        let needs_disk_first =
919            stats.tombstones != 0 || matches!(options.mode, MaintenanceMode::Full);
920        if !needs_disk_first {
921            let mut report = {
922                let State { engine, store, .. } = &mut *st;
923                engine.with(store, |mem, store| {
924                    mem.maintain_with_options(store, now, options)
925                })?
926            };
927            self.resnapshot(&mut st, now)?;
928            st.forgets = 0;
929            st.ops = 0;
930            report.bytes_before = bytes_before;
931            report.bytes_after = snap_len(&st.store);
932            return Ok(report);
933        }
934        let text_tmp = tmp_sibling(st.store.path(), "mtext");
935        let vec_tmp = tmp_sibling(st.store.path(), "mvec");
936
937        // Stage a compacted snapshot, streaming the big pools through scratch;
938        // this reads through the live map, so it happens before the map is
939        // dropped (as in `resnapshot`).
940        let mut purged = 0usize;
941        let mut report = MaintainReport::default();
942        {
943            let State { engine, store, .. } = &mut *st;
944            store.stage_snapshot(|sink| {
945                engine.read(|mem| {
946                    let mut text_scratch = FileScratch::create(&text_tmp)?;
947                    let mut vec_scratch = FileScratch::create(&vec_tmp)?;
948                    report = mem
949                        .snapshot_disk_first_with_options(
950                            now,
951                            &mut text_scratch,
952                            &mut vec_scratch,
953                            &mut *sink,
954                            options,
955                        )
956                        .map_err(HostError::from)?;
957                    purged = report.purged;
958                    Ok(())
959                })
960            })?;
961        }
962        // Drop the current map before the rename (park a cheap empty engine),
963        // commit, clear the journal, then re-map the compacted file — exactly
964        // the `resnapshot` dance, so the map is never renamed over on Windows.
965        st.engine = Engine::Owned(Box::new(Memory::new(self.inner.cfg.clone())?));
966        st.store
967            .commit_snapshot()
968            .and_then(|()| st.store.clear_journal())?;
969        let (engine, _) = open_engine(&mut st.store, &self.inner.cfg)?;
970        st.engine = engine;
971        st.forgets = 0;
972        st.ops = 0;
973        let bytes_after = snap_len(&st.store);
974        report.purged = purged;
975        report.bytes_before = bytes_before;
976        report.bytes_after = bytes_after;
977        Ok(report)
978    }
979
980    /// Writes a full snapshot and clears the journal now (re-mapping the
981    /// fresh file — see `Database::resnapshot`).
982    pub fn checkpoint(&self, now: u64) -> Result<(), HostError> {
983        let mut st = self.write();
984        self.resnapshot(&mut st, now)?;
985        st.ops = 0;
986        Ok(())
987    }
988
989    /// Runs the on-demand integrity check — the equivalent of
990    /// SQLite's `integrity_check`. An open validates only the metadata, so the
991    /// large byte pools stay non-resident on an mmap'd base; this sweeps them
992    /// (text UTF-8, vector self-consistency and the fact↔slot bijection) and
993    /// reports any latent corruption. Skipping it is safe — the accessors never
994    /// panic on bad bytes; `verify` only turns corruption into an explicit
995    /// error.
996    ///
997    /// # Errors
998    ///
999    /// [`HostError::Engine`] wrapping [`Error::Corrupt`](plugmem_core::Error)
1000    /// for the first inconsistency found.
1001    pub fn verify(&self) -> Result<(), HostError> {
1002        Ok(self.read().engine.read(|mem| mem.verify())?)
1003    }
1004
1005    /// Salvages a content-corrupt database (Tier 2): opens `src`,
1006    /// drops the facts that fail the per-fact content checks (`verify`'s
1007    /// predicate), compacts the survivors and their indexes, and writes a clean
1008    /// image to `dst`. `src` on disk is left untouched — the evidence is
1009    /// preserved.
1010    ///
1011    /// It is **disk-first** (milestone H): `src` is opened as an mmap overlay
1012    /// (its pages are reclaimable) and the compacted image is written by
1013    /// streaming the two big pools (vectors, text) through temp files, so peak
1014    /// RAM tracks the record count (metadata + HNSW graph), not the image size.
1015    /// A database far larger than RAM can be recovered, as long as its graph
1016    /// fits.
1017    ///
1018    /// This handles *content* corruption (bad text bytes, a broken fact↔slot
1019    /// vector bijection). *Structural* damage — a snapshot that will not parse
1020    /// — is not salvageable here: `src` fails to open and recover returns the
1021    /// engine's typed error; restore from a backup instead (Tier 0).
1022    ///
1023    /// # Errors
1024    ///
1025    /// [`HostError::Locked`] if `src` or `dst` is owned elsewhere;
1026    /// [`HostError::Engine`] if `src` will not parse (structural corruption) or
1027    /// `dst` equals `src`; [`HostError::Io`] for filesystem failures.
1028    pub fn recover(
1029        src: impl AsRef<Path>,
1030        dst: impl AsRef<Path>,
1031        cfg: Config,
1032        now: u64,
1033    ) -> Result<RecoverReport, HostError> {
1034        let src = src.as_ref();
1035        let dst = dst.as_ref();
1036
1037        // Lock the source exclusively for the salvage's whole life. We never
1038        // write it — the lock only excludes a cooperating writer while we read.
1039        let mut src_store = FileStorage::open(src, FsyncPolicy::OnSnapshot)?;
1040        let src_base = src_store.path().to_path_buf();
1041
1042        // The destination must be a different file: recover preserves the source
1043        // as evidence and writes the clean image elsewhere.
1044        let same = dst == src_base
1045            || matches!(
1046                (std::fs::canonicalize(dst), std::fs::canonicalize(&src_base)),
1047                (Ok(a), Ok(b)) if a == b
1048            );
1049        if same {
1050            return Err(HostError::Engine(Error::Invalid(
1051                "recover destination must differ from the source",
1052            )));
1053        }
1054
1055        // Open the source as an overlay: borrow the mmap base (reclaimable
1056        // pages) and replay its journal into a small owned overlay — never an
1057        // owned copy of the image. A structurally corrupt image fails here —
1058        // that is Tier 0, not salvageable content corruption.
1059        let journal = src_store.read_journal()?;
1060        let Some(genp) = src_store.current_snapshot_path()? else {
1061            return Err(HostError::Engine(Error::Corrupt(
1062                "source database has no published snapshot to recover",
1063            )));
1064        };
1065        let file = File::open(&genp).map_err(|e| HostError::io(&genp, e))?;
1066        // SAFETY: as in `open_engine` — the generation file is immutable and
1067        // `src_store` holds the exclusive lock, so nothing touches it under us.
1068        let map = unsafe { Mmap::map(&file) }.map_err(|e| HostError::io(&genp, e))?;
1069        drop(file);
1070        let (mut mem, _report) = Memory::from_bytes_overlay(&map[..], &journal, cfg.clone())?;
1071
1072        // Drop each content-faulty fact into a throwaway store, so the source
1073        // file is never written. The disk-first rebuild below then physically
1074        // purges them and rebuilds clean indexes + HNSW from the survivors.
1075        let mut scratch = MemStorage::new();
1076        let mut dropped_text = 0usize;
1077        let mut dropped_vector = 0usize;
1078        let mut dropped_metadata = 0usize;
1079        for (id, fault) in mem.faulty_facts() {
1080            mem.forget(&mut scratch, now, id)?;
1081            match fault {
1082                FactFault::Text => dropped_text += 1,
1083                FactFault::Vector => dropped_vector += 1,
1084                FactFault::Metadata => dropped_metadata += 1,
1085            }
1086        }
1087
1088        // Write the compacted image to `dst`, streaming the big pools through
1089        // temp scratch files (metadata + graph are the only things resident).
1090        let mut dst_store = FileStorage::open(dst, FsyncPolicy::OnSnapshot)?;
1091        let text_tmp = tmp_sibling(dst_store.path(), "rectext");
1092        let vec_tmp = tmp_sibling(dst_store.path(), "recvec");
1093        let mut purged = 0usize;
1094        dst_store.stage_snapshot(|sink| {
1095            let mut text_scratch = FileScratch::create(&text_tmp)?;
1096            let mut vec_scratch = FileScratch::create(&vec_tmp)?;
1097            purged = mem
1098                .snapshot_disk_first(now, &mut text_scratch, &mut vec_scratch, &mut *sink)
1099                .map_err(HostError::from)?;
1100            Ok(())
1101        })?;
1102        dst_store.commit_snapshot()?;
1103
1104        let kept = mem.stats().facts.saturating_sub(purged);
1105        Ok(RecoverReport {
1106            kept,
1107            dropped_text,
1108            dropped_vector,
1109            dropped_metadata,
1110        })
1111    }
1112}
1113
1114/// A temp-file path beside `base` with the given tag (for disk-first scratch).
1115fn tmp_sibling(base: &Path, tag: &str) -> PathBuf {
1116    let mut p = base.as_os_str().to_os_string();
1117    p.push(".");
1118    p.push(tag);
1119    p.push(".tmp");
1120    PathBuf::from(p)
1121}
1122
1123impl std::fmt::Debug for Database {
1124    /// Summary only — the contents are the user's memory.
1125    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1126        let stats = self.stats();
1127        f.debug_struct("Database")
1128            .field("facts", &stats.facts)
1129            .field("entities", &stats.entities)
1130            .finish()
1131    }
1132}