Skip to main content

plugmem_host/
readonly.rs

1//! [`ReadOnlyDatabase`]: a zero-copy read-only open over an mmap'd
2//! snapshot.
3//!
4//! A normal [`Database`](crate::Database) open reads the whole snapshot
5//! into RAM (every byte pool is copied into an arena). For a large,
6//! read-mostly database that is wasteful: `open_readonly` maps the
7//! snapshot file instead and lets the engine's byte pools *borrow* the
8//! mapped pages, so the OS residents only the bytes `recall`/`get`
9//! actually touch. An 8 GiB database opens in milliseconds with a few
10//! pages resident, not 8 GiB.
11//!
12//! The handle is read-only by construction — it exposes `recall`/`get`/
13//! `stats` and nothing that mutates. It requires a **published snapshot
14//! generation**, and that is the only thing it requires: with none, the open
15//! is refused with [`HostError::NeedsCheckpoint`].
16//!
17//! A non-empty journal is **not** a refusal. The reader maps the published
18//! generation and never reads the journal at all — replaying one would copy
19//! whole arenas up (copy-on-write) and defeat the zero-copy intent, so the
20//! journal is simply not this handle's business: it describes the generation
21//! the writer has not published yet. What the reader offers is snapshot
22//! isolation, "as of the last checkpoint", not a demand to checkpoint first.
23//! (The core's `from_bytes_borrowed` *does* reject a journal, which is why
24//! this is worth stating: `open` never hands it one.)
25//!
26//! Locking is a **shared** advisory lock held for the handle's whole life
27//! many read-only handles — in this process or others — map
28//! the same file at once, so a read-mostly database serves concurrent
29//! readers. A shared lock still excludes every exclusive (read-write)
30//! owner, so no cooperating process writes or truncates the file while it
31//! is mapped — which is exactly the safety argument for the mmap (see the
32//! `unsafe` block in [`ReadOnlyDatabase::open`]).
33//!
34//! # When you actually need this — [`Database`] vs [`ReadOnlyDatabase`]
35//!
36//! Most callers do **not** need a read-only handle. The distinction is about
37//! **who else has the file open**, where "who else" means a **separate OS
38//! process** — a different running program (a different PID): a second copy of
39//! the CLI, an MCP server, another service — *not* another thread or another
40//! `Database` value inside your own program.
41//!
42//! - **One process reads and writes → just [`Database::open`](crate::Database::open).**
43//!   A read-write handle keeps an *overlay* (the mapped snapshot plus the journal
44//!   replayed in RAM), so `remember` is visible to the very next `recall` on that
45//!   same handle, with no checkpoint and no second open. This is **read-your-writes**:
46//!   an agent that stores a fact and immediately recalls it needs one handle and
47//!   sees its own write instantly. Opening the same database *twice* from one
48//!   process — once read-write, once read-only — is pointless and is **not** how
49//!   you get freshness; it only costs you a stale second view.
50//!
51//! - **Another process must read the same file while a writer is live →
52//!   [`Database::open_readonly`](crate::Database::open_readonly).** A separate
53//!   program cannot share the writer's in-RAM overlay (it is another address
54//!   space entirely), so it maps the last *published* generation instead. Such a
55//!   handle is a **point-in-time snapshot**: it observes the database "as of the
56//!   last checkpoint" and never moves on its own — the writer publishing a newer
57//!   generation does not disturb the snapshot you are already reading. To advance
58//!   to a freshly published generation, call [`ReadOnlyDatabase::refresh`], which
59//!   is a cheap 24-byte manifest read that re-maps only when the writer has
60//!   actually published something newer (see its docs).
61//!
62//! In short: `refresh`, `open_readonly`, and snapshot-isolation lag exist **only**
63//! for a reader looking at *another process's* writer. Within a single process,
64//! [`Database`] alone is always fresh.
65
66use std::cell::RefCell;
67use std::fs::File;
68use std::path::{Path, PathBuf};
69#[cfg(feature = "counters")]
70use std::sync::Mutex;
71
72use memmap2::Mmap;
73use plugmem_core::snapshot::{DEFAULT_SCRUB_BUDGET, ScrubCursor, ScrubProgress, Snapshot};
74use plugmem_core::{Config, FactId, Memory, RecallQuery, RecallResult, RecallScratch, Stats};
75
76thread_local! {
77    /// Per-thread recall scratch — the read-only analog of the one in
78    /// [`crate::db`]. `recall` borrows the mapped engine shared (`&Memory`), so
79    /// many threads recall one handle at once, each reusing its own scratch.
80    static RECALL_SCRATCH: RefCell<RecallScratch> = RefCell::new(RecallScratch::new());
81}
82
83use crate::db::FactSnapshot;
84use crate::error::HostError;
85use crate::storage::{pin_current_generation, read_manifest};
86
87self_cell::self_cell!(
88    /// Owns the memory map and the [`Memory`] that borrows it. `self_cell`
89    /// keeps the self-reference safe: the only `unsafe` on this path is
90    /// the inherent mmap call, not the borrow.
91    struct MappedMemory {
92        owner: Mmap,
93        #[covariant]
94        dependent: BorrowedMemory,
95    }
96);
97
98/// The dependent type constructor `self_cell` reborrows per access.
99/// [`Memory`] is covariant in its lifetime (its byte pools are
100/// `Cow<'a, [u8]>`), so borrowing the map is sound.
101type BorrowedMemory<'a> = Memory<'a>;
102
103/// A read-only database handle backed by a memory-mapped snapshot
104/// See the module docs. `Send + Sync` — share it across
105/// threads behind a reference or an `Arc`.
106pub struct ReadOnlyDatabase {
107    /// The map and the engine borrowing it. Normally no lock: every verb
108    /// borrows it shared (`&Memory`) — `recall` keeps its mutable scratch
109    /// per-thread — so many threads read one handle concurrently. Under
110    /// `counters` the engine embeds the arena's non-`Sync` counter `Cells`, so
111    /// it is wrapped in a `Mutex` to stay `Sync` (readers serialize — fine for
112    /// that single-threaded perf build). Purely internal: the public API is the
113    /// same under every feature.
114    #[cfg(not(feature = "counters"))]
115    mapped: MappedMemory,
116    #[cfg(feature = "counters")]
117    mapped: Mutex<MappedMemory>,
118    /// Holds a **shared** lock on the mapped generation file for this handle's
119    /// whole life — never read, but it *pins* the generation against the
120    /// writer's GC (the writer's exclusive try-lock fails while we hold this),
121    /// so the immutable snapshot we borrow can never be reclaimed under us.
122    _pin: File,
123    /// The database base (manifest) path.
124    path: PathBuf,
125    /// The generation number this handle is pinned to — the snapshot it maps.
126    /// Compared against the manifest by [`ReadOnlyDatabase::refresh`] to tell
127    /// whether the writer has published anything newer.
128    generation: u64,
129    /// Kept so [`ReadOnlyDatabase::refresh`] can rebuild the borrowed engine
130    /// over a freshly mapped generation with the same configuration.
131    cfg: Config,
132}
133
134impl ReadOnlyDatabase {
135    /// Opens the database at `path` read-only over an mmap.
136    ///
137    /// # Errors
138    ///
139    /// [`HostError::NeedsCheckpoint`] when the database has no published
140    /// snapshot generation yet (checkpoint it once, then retry); [`HostError::Io`]
141    /// when the generation file cannot be mapped; [`HostError::Engine`] for a
142    /// corrupt image or a config mismatch.
143    pub(crate) fn open(path: impl Into<PathBuf>, cfg: Config) -> Result<Self, HostError> {
144        let base: PathBuf = path.into();
145        // Pin the current generation with a shared lock (no writer lock — a
146        // reader coexists with the writer). The reader maps this immutable
147        // generation and ignores the journal, which belongs to the *next*
148        // generation the writer is building: this is the snapshot-isolation
149        // reader, "as of the last published checkpoint".
150        let Some((pin, genp, generation)) = pin_current_generation(&base)? else {
151            // No published generation yet — checkpoint the database first.
152            return Err(HostError::NeedsCheckpoint { path: base });
153        };
154
155        // SAFETY: mapping a file is inherently unsafe — a concurrent truncate or
156        // overwrite would fault the process on the next page access. Our
157        // argument: a generation file is **immutable** (a
158        // checkpoint publishes a *new* generation, never rewrites this one), and
159        // `pin` holds a shared lock on it for this handle's whole life, so the
160        // writer's GC cannot reclaim it under us. A foreign `truncate`/`rm` is
161        // out of contract — the same caveat as corrupting any live database file.
162        let map = unsafe { Mmap::map(&pin) }.map_err(|e| HostError::io(&genp, e))?;
163        let mapped = MappedMemory::try_new(map, |map| {
164            Memory::from_bytes_borrowed(&map[..], &[], cfg.clone())
165        })?;
166
167        Ok(Self {
168            #[cfg(not(feature = "counters"))]
169            mapped,
170            #[cfg(feature = "counters")]
171            mapped: Mutex::new(mapped),
172            _pin: pin,
173            path: base,
174            generation,
175            cfg,
176        })
177    }
178
179    /// Runs `f` over the mapped engine (`&Memory`). Normally a lock-free shared
180    /// borrow (concurrent readers); under `counters` it takes the `Mutex` first.
181    /// Private — the lock strategy never reaches the public API.
182    #[cfg(not(feature = "counters"))]
183    fn with_mem<R>(&self, f: impl FnOnce(&Memory<'_>) -> R) -> R {
184        f(self.mapped.borrow_dependent())
185    }
186
187    #[cfg(feature = "counters")]
188    fn with_mem<R>(&self, f: impl FnOnce(&Memory<'_>) -> R) -> R {
189        let guard = self.mapped.lock().unwrap_or_else(|e| e.into_inner());
190        f(guard.borrow_dependent())
191    }
192
193    /// Runs a recall. Same semantics as
194    /// [`Database::recall`](crate::Database::recall) minus the embedder:
195    /// a text-only query is not auto-embedded, so pass a vector for the
196    /// vector source.
197    pub fn recall(&self, q: RecallQuery<'_>) -> Result<RecallResult, HostError> {
198        self.with_mem(|mem| {
199            RECALL_SCRATCH.with(|scratch| {
200                let mut scratch = scratch.borrow_mut();
201                let mut out = RecallResult::default();
202                mem.recall_into(q, &mut scratch, &mut out)?;
203                Ok(out)
204            })
205        })
206    }
207
208    /// An owned copy of one fact, or `None` for unknown/tombstoned ids.
209    pub fn get(&self, id: FactId) -> Option<FactSnapshot> {
210        self.with_mem(|mem| {
211            mem.get(id).map(|v| FactSnapshot {
212                record: v.record,
213                text: v.text.to_string(),
214                metadata: crate::db::metadata_map(mem, id),
215            })
216        })
217    }
218
219    /// Engine size counters.
220    pub fn stats(&self) -> Stats {
221        self.with_mem(|mem| mem.stats())
222    }
223
224    /// One fact's tags, or an empty vector for an unknown or tombstoned id.
225    pub fn tags_of(&self, id: FactId) -> Vec<String> {
226        self.with_mem(|mem| {
227            let mut terms = Vec::new();
228            mem.tags_of(id, &mut terms);
229            terms
230                .iter()
231                .map(|term| mem.term(*term).to_string())
232                .collect()
233        })
234    }
235
236    /// Runs the on-demand integrity check — the equivalent of
237    /// SQLite's `integrity_check`. A read-only open validates only the metadata
238    /// (the mapped text and vector pools stay non-resident); this sweeps them
239    /// and reports any latent corruption. Reads the whole image, so it residents
240    /// the pools it checks.
241    ///
242    /// # Errors
243    ///
244    /// [`HostError::Engine`] for the first inconsistency found.
245    pub fn verify(&self) -> Result<(), HostError> {
246        Ok(self.with_mem(|mem| mem.verify())?)
247    }
248
249    /// A resumable byte-level container scrub of the snapshot file, with the
250    /// default slice budget (— the ZFS-scrub model). See
251    /// [`Scrub`] and [`ReadOnlyDatabase::scrub_with_budget`].
252    ///
253    /// # Errors
254    ///
255    /// [`HostError::Locked`]/[`HostError::Io`]/[`HostError::Engine`] if the
256    /// file cannot be locked, mapped, or structurally parsed for the scan.
257    pub fn scrub(&self) -> Result<Scrub, HostError> {
258        self.scrub_with_budget(DEFAULT_SCRUB_BUDGET)
259    }
260
261    /// A resumable container scrub hashing at most `budget` bytes per
262    /// [`Iterator::next`].
263    ///
264    /// The returned [`Scrub`] owns its own map and its own shared advisory
265    /// lock over the same file, so it holds a reader's lock for its whole
266    /// life (a writer is refused with [`HostError::Locked`] while any scrub
267    /// or read-only handle lives) and can be moved to its own thread — the
268    /// caller paces the scan (`next`, pause, resume, cancel) exactly like
269    /// the core [`ScrubCursor`]. Dropping it releases the lock.
270    ///
271    /// It is independent of `self`: the scrub keeps running after this handle
272    /// is dropped. A non-empty journal is not an obstacle — the scrub checks
273    /// the on-disk snapshot container as-is.
274    ///
275    /// # Errors
276    ///
277    /// As [`ReadOnlyDatabase::scrub`].
278    pub fn scrub_with_budget(&self, budget: usize) -> Result<Scrub, HostError> {
279        Scrub::open(&self.path, budget)
280    }
281
282    /// Dumps the currently-open facts for a human-readable backup
283    /// See [`ExportedFact`](crate::ExportedFact). Collects the whole
284    /// set; for a large database prefer [`export_each`](Self::export_each).
285    pub fn export(&self) -> Vec<crate::db::ExportedFact> {
286        self.with_mem(crate::db::export_facts)
287    }
288
289    /// Streams the currently-open facts, calling `f` once per fact under the map
290    /// — the whole dump is never materialized (the zero-copy analog of
291    /// [`Database::export_each`](crate::Database::export_each)).
292    pub fn export_each(&self, f: impl FnMut(crate::db::ExportedFact)) {
293        self.with_mem(|mem| crate::db::export_facts_each(mem, f));
294    }
295
296    /// Streams the currently-open edges — the zero-copy analog of
297    /// [`Database::export_edges_each`](crate::Database::export_edges_each), and
298    /// the path the CLI takes, since `export` runs read-only whenever it can.
299    pub fn export_edges_each(&self, mut f: impl FnMut(&str, &str, &str, plugmem_core::FactId)) {
300        self.with_mem(|mem| {
301            mem.edges_each(|src, rel, dst, fact| {
302                f(src, rel, dst, fact);
303                true
304            });
305        });
306    }
307
308    /// Returns at most `limit` open facts starting at the opaque fact-id
309    /// `cursor`. The mapped generation is immutable, so paging this handle is a
310    /// snapshot-consistent bounded export. Pass the returned `next_cursor` to
311    /// continue; `None` means the scan is complete.
312    pub fn export_page(&self, cursor: u32, limit: std::num::NonZeroUsize) -> crate::db::ExportPage {
313        self.with_mem(|mem| crate::db::export_facts_page(mem, cursor, limit.get()))
314    }
315
316    /// The database base path.
317    pub fn path(&self) -> &Path {
318        &self.path
319    }
320
321    /// The snapshot generation this handle is pinned to — the point in time it
322    /// reads "as of". Monotonic: a writer's checkpoint publishes a strictly
323    /// higher number. Compare it against a later call, or drive your own
324    /// freshness policy around [`refresh`](Self::refresh) with it.
325    pub fn generation(&self) -> u64 {
326        self.generation
327    }
328
329    /// Advances this handle to the writer's latest published generation, if
330    /// there is a newer one. Returns `true` when it re-mapped onto a newer
331    /// snapshot (subsequent reads now observe it), `false` when nothing changed.
332    ///
333    /// This is the **only** way a read-only handle moves forward in time: an
334    /// open handle is a point-in-time snapshot and never advances on its own
335    /// (see the module docs). It exists for a reader watching **another
336    /// process's** writer; a single process that reads and writes uses one
337    /// [`Database`](crate::Database) handle and sees its own writes instantly,
338    /// with no `refresh` at all.
339    ///
340    /// It is cheap to call speculatively — the freshness check is a read of the
341    /// tiny fixed-size manifest (a handful of bytes), and the `mmap` re-map
342    /// happens *only* when the writer has actually published a newer generation.
343    /// In steady state (no new checkpoint) it does no mapping and returns `false`
344    /// for the cost of that manifest read, so calling it before each read is a
345    /// reasonable "always fresh" policy; batching (refresh every N reads, or on a
346    /// timer) trades a bounded staleness for even fewer manifest reads. Re-mapping
347    /// borrows the new generation's pages lazily — no whole-file copy, no journal
348    /// replay, no index rebuild — and drops the old map, so RAM does not grow.
349    ///
350    /// The freshness policy is intentionally left to the caller: an autorefresh
351    /// baked into every read would forfeit snapshot isolation for callers who
352    /// need a *stable* view across a series of queries. Keep the reader stable by
353    /// not calling this; advance it by calling it.
354    ///
355    /// # Errors
356    ///
357    /// [`HostError::Io`] if the newer generation cannot be mapped;
358    /// [`HostError::Engine`] for a corrupt image. On any error the handle is
359    /// left untouched on its current generation (the re-map is built before it
360    /// replaces the live one).
361    pub fn refresh(&mut self) -> Result<bool, HostError> {
362        // Cheap detect: read the fixed-size manifest and bail unless the writer
363        // has published a strictly newer generation.
364        match read_manifest(&self.path)? {
365            Some(latest) if latest > self.generation => {}
366            _ => return Ok(false),
367        }
368        // Pin and map the current published generation. `pin_current_generation`
369        // re-reads the manifest and retries the GC race, so the pinned number is
370        // the freshest one on disk — which may even exceed the value we just
371        // read. If it is not actually newer than ours (a checkpoint raced back,
372        // impossible given monotonicity but cheap to guard), report no change.
373        let Some((pin, genp, generation)) = pin_current_generation(&self.path)? else {
374            return Ok(false);
375        };
376        if generation <= self.generation {
377            return Ok(false);
378        }
379        // SAFETY: identical to `open` — a generation file is immutable (a
380        // checkpoint publishes a *new* generation, never rewrites this one), and
381        // `pin` holds a shared lock on it for as long as we keep it, so the
382        // writer's GC cannot reclaim it under us. Built before we swap it in, so
383        // a failure leaves the live map intact.
384        let map = unsafe { Mmap::map(&pin) }.map_err(|e| HostError::io(&genp, e))?;
385        let cfg = self.cfg.clone();
386        let mapped =
387            MappedMemory::try_new(map, |map| Memory::from_bytes_borrowed(&map[..], &[], cfg))?;
388        // Commit: replace the map (dropping the old one and its pin) and record
389        // the new generation. The old `_pin`'s shared lock releases here, letting
390        // GC reclaim the generation we just left once nothing else pins it.
391        #[cfg(not(feature = "counters"))]
392        {
393            self.mapped = mapped;
394        }
395        #[cfg(feature = "counters")]
396        {
397            self.mapped = Mutex::new(mapped);
398        }
399        self._pin = pin;
400        self.generation = generation;
401        Ok(true)
402    }
403}
404
405impl std::fmt::Debug for ReadOnlyDatabase {
406    /// Summary only — the contents are the user's memory.
407    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
408        let stats = self.stats();
409        f.debug_struct("ReadOnlyDatabase")
410            .field("path", &self.path)
411            .field("facts", &stats.facts)
412            .field("entities", &stats.entities)
413            .finish()
414    }
415}
416
417self_cell::self_cell!(
418    /// Owns the memory map and the [`ScrubCursor`] that borrows it. As with
419    /// [`MappedMemory`], the only `unsafe` is the inherent mmap call, not the
420    /// self-reference.
421    struct MappedScrub {
422        owner: Mmap,
423        #[covariant]
424        dependent: BorrowedScrub,
425    }
426);
427
428/// The dependent type constructor. [`ScrubCursor`] is covariant in its
429/// lifetime (it borrows the mapped bytes as `&'a [u8]` and owns the rest),
430/// so borrowing the map is sound.
431type BorrowedScrub<'a> = ScrubCursor<'a>;
432
433/// A resumable, byte-level container scrub over a memory-mapped snapshot
434/// (— the ZFS-scrub model). Obtained from
435/// [`ReadOnlyDatabase::scrub`].
436///
437/// It implements [`Iterator`]: each [`Iterator::next`] hashes up to the slice
438/// budget and yields `Ok(ScrubProgress)`, verifying each section's stored
439/// xxh3 as its body completes and the whole-file hash at EOF; the first
440/// mismatch yields `Err(HostError::Engine(Error::Corrupt(..)))` and then
441/// `None` (fused). Because it only reads the mapped bytes linearly, the pages
442/// fault in, get hashed and stay reclaimable — a scrub never residents the
443/// whole file.
444///
445/// It pins its generation with a shared lock for its whole life (independent of
446/// the handle it came from), so the writer's GC cannot reclaim it while it runs.
447/// It is [`Send`] — pace it on its own thread. One-shot: obtain a new scrub to
448/// scan again.
449pub struct Scrub {
450    mapped: MappedScrub,
451    /// Holds the shared lock on the scrubbed generation for the scrub's whole
452    /// life (never read — the pin is the point), independent of the handle.
453    _pin: File,
454}
455
456impl Scrub {
457    /// Pins and maps the current generation at `base`, then builds the cursor.
458    /// See [`ReadOnlyDatabase::scrub_with_budget`].
459    ///
460    /// `pub(crate)` so [`crate::Database`] can reach it too: a scrub needs a
461    /// *published generation*, not a checkpointed database, so routing every
462    /// caller through a read-only handle would deny it to a writer with a
463    /// journal for no reason of its own.
464    pub(crate) fn open(base: &Path, budget: usize) -> Result<Self, HostError> {
465        // Pin the current generation with a shared lock (coexists with other
466        // readers and the writer; blocks only the writer's GC of this one).
467        let Some((pin, genp, _generation)) = pin_current_generation(base)? else {
468            return Err(HostError::NeedsCheckpoint {
469                path: base.to_path_buf(),
470            });
471        };
472
473        // SAFETY: identical to `ReadOnlyDatabase::open` — a generation file is
474        // immutable, and `pin` holds a shared lock on it for this scrub's whole
475        // life, so GC cannot reclaim it under the map.
476        let map = unsafe { Mmap::map(&pin) }.map_err(|e| HostError::io(&genp, e))?;
477
478        let mapped = MappedScrub::try_new(map, |map| {
479            Snapshot::parse(&map[..])
480                .map(|snap| snap.scrub_with_budget(budget))
481                .map_err(HostError::from)
482        })?;
483
484        Ok(Self { mapped, _pin: pin })
485    }
486}
487
488impl Iterator for Scrub {
489    type Item = Result<ScrubProgress, HostError>;
490
491    /// Hashes the next slice, mapping a core [`Error`](plugmem_core::Error)
492    /// mismatch into [`HostError::Engine`]. `None` once complete or fused.
493    fn next(&mut self) -> Option<Self::Item> {
494        self.mapped
495            .with_dependent_mut(|_map, cur| cur.next())
496            .map(|step| step.map_err(HostError::from))
497    }
498}
499
500impl std::fmt::Debug for Scrub {
501    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
502        f.debug_struct("Scrub").finish_non_exhaustive()
503    }
504}