mnemo_engine/store/mod.rs
1//! The Mnemo database — ties the storage engine and the memory model together.
2//!
3//! Layout of a populated file:
4//!
5//! ```text
6//! page 0 : Header (unencrypted)
7//! pages 1..W : write-ahead log region
8//! pages W.. : encrypted record runs + catalog runs + index +
9//! snapshot manifest (append-only)
10//! ```
11//!
12//! Durability is provided by a **write-ahead log** ([`crate::wal`]). A `flush`
13//! is one transaction: record data pages are written copy-on-write to fresh
14//! pages, then the new catalog, ANN index, and header are logged to the WAL
15//! and committed with a single fsync. A checkpoint then folds the WAL into the
16//! home pages. A crash before the commit leaves the previous state intact; a
17//! crash after it is repaired by replaying the WAL on open.
18//!
19//! Because pages are only ever appended, every past transaction's runs survive
20//! on disk. Each flush also appends an entry to a **snapshot manifest**, so
21//! [`Mnemo::restore_to`] can reinstate any past state. Stale pages — and the
22//! history along with them — are reclaimed by [`Mnemo::compact_file`].
23
24use std::fs::{File, OpenOptions};
25use std::io::{Read, Seek, SeekFrom, Write};
26use std::path::{Path, PathBuf};
27
28use fs4::fs_std::FileExt;
29use serde::{Deserialize, Serialize};
30use serde_json::{Map, Value};
31use ulid::Ulid;
32
33use crate::crypto::{self, KdfParams, SecretKind};
34use crate::embed::{self, Embedder};
35use crate::error::{MnemoError, Result};
36use crate::format::{
37 Header, RunPtr, FLAG_ENCRYPTED, PAGE_SIZE, PAYLOAD, VERSION, VERSION_V9, WRAPPED_DEK_LEN,
38};
39use crate::freelist::FreeList;
40use crate::index::{IndexConfig, IndexInfo, IndexOp, IvfPqIndex};
41#[cfg(feature = "dev-hooks")]
42use crate::keyslot::KeySlot as KeySlotEntry;
43use crate::keyslot::KeySlotRun;
44use crate::memory::{
45 self, status as essence_status, CommitBatch, CommitReport, EssenceOp, EssenceOpKind,
46 EssenceScope, EssenceSection, ExportedTurn, Filter, FilterTerm, IngestReport, KeyScope, Memory,
47 MemoryPatch, MemoryType, Metric, Scope, ScoreWeights, ThreadTurn, TurnPolicy, WriteOutcome,
48 CONTINUATION_TIMELINE_ENTRIES, ESSENCE_DEFAULT_RENDER_BYTES, ESSENCE_TRANSITIONS,
49 MNEMO_META_CONTINUES, MNEMO_META_INVALID_AT, MNEMO_META_KEY, MNEMO_META_KIND,
50 MNEMO_META_KIND_ESSENCE, MNEMO_META_KIND_THREAD_LINK, MNEMO_META_KIND_TURN, MNEMO_META_LENGTH,
51 MNEMO_META_MARKERS_ONLY, MNEMO_META_PART, MNEMO_META_REFS, MNEMO_META_ROLE, MNEMO_META_SECTION,
52 MNEMO_META_SEQ, MNEMO_META_SHA256, MNEMO_META_STATUS, MNEMO_META_STATUS_HISTORY,
53 MNEMO_META_SUPERSEDED_BY, MNEMO_META_SUPERSEDES, MNEMO_META_THREAD, MNEMO_META_TURN_ID,
54 MNEMO_META_UPDATED_AT, THREAD_TOOL_RESULT_TRUNCATE_BYTES, THREAD_TURN_CHUNK_BYTES,
55};
56use crate::pager::{LockedFile, Pager};
57use crate::result_cache::{
58 self, BatchState, CacheBudget, CacheDirectoryEntry, CacheEntry, CacheFlushPolicy, CachePutOpts,
59 CacheStats, CachedValue, CounterState, DirectoryIndex, SemanticCachePutOpts,
60};
61use crate::text;
62use crate::veccol;
63use crate::wal;
64
65mod ann;
66mod cache_api;
67mod continuation;
68mod crud;
69mod essence;
70pub(crate) use essence::format_unix_date;
71mod flush;
72#[cfg(test)]
73mod header_graft_tests;
74// HOOKS-1: the hidden test hooks exist only in test, bench and example
75// builds (the `dev-hooks` feature), never in a release build.
76#[cfg(feature = "dev-hooks")]
77mod hooks;
78mod keyed;
79mod load;
80mod maintenance;
81mod open;
82mod recall;
83mod records;
84mod shared;
85mod snapshots;
86mod threads;
87use crud::*;
88use essence::*;
89use load::*;
90pub(crate) use load::{is_file_at, is_lock_conflict};
91pub(crate) use maintenance::{create_temp, remove_dead_temps};
92pub(crate) use open::wal_header_salts;
93pub(crate) use records::plain_record;
94use records::*;
95pub use shared::SharedMnemo;
96
97/// Default initial size of the write-ahead log region, in pages (64 KiB).
98/// The region grows automatically when a transaction's control plane outgrows
99/// it, so this is a *floor* on the fresh-file footprint, not a cap on
100/// transaction size. Was 64 pages (512 KiB) in v0.1.0 — lowered because that
101/// reservation dominated small-file size (~62% of a 31-memory dogfood file).
102const DEFAULT_WAL_PAGES: u64 = 8;
103
104/// Hard floor on the WAL reservation. A single header-page flush already
105/// needs one full DATA frame plus a COMMIT frame; two pages are the bare
106/// minimum that lets the first transaction commit without immediate growth.
107const MIN_WAL_PAGES: u64 = 2;
108
109/// Default cap on retained snapshot manifest entries. Each `flush` appends
110/// one entry; without a cap, long-running processes accumulate entries
111/// forever, growing per-flush manifest-serialize cost as O(total flushes)
112/// and the manifest run size on disk in lockstep. 256 keeps roughly a
113/// week of hourly snapshots while staying tiny (256 × ~82 bytes ≈ 21 KiB
114/// of manifest). Set `MnemoConfig::max_snapshots = 0` to disable the cap.
115pub const DEFAULT_MAX_SNAPSHOTS: usize = 256;
116
117/// PERF-1: the ANN index is derived data, so `flush` persists it only every
118/// this many commits that changed it (or see
119/// [`INDEX_PERSIST_EVERY_CHANGES`], [`Mnemo::flush_index`], [`Mnemo::close`]).
120/// Between persists, only the catalog is rewritten.
121pub const INDEX_PERSIST_EVERY_COMMITS: u32 = 64;
122
123/// PERF-1: …or once this many vectors were added, changed or removed since
124/// the last persist. Records written after the persisted index are
125/// re-assigned when the index is next loaded, so this bounds that work.
126pub const INDEX_PERSIST_EVERY_CHANGES: usize = 1_000;
127
128/// FMT-9d: default weight ε of the normalised BM25 score in hybrid recall
129/// (`relevance = similarity + ε · bm25 / max bm25`).
130pub const DEFAULT_KEYWORD_WEIGHT: f32 = 0.5;
131
132/// 12.3 step 4 (v0.15): default weight of the BM25 score when it comes from
133/// a recall's own text (hybrid by default, no keywords given). Lower than
134/// [`DEFAULT_KEYWORD_WEIGHT`] because a question's common words ("how",
135/// "the") match unrelated memories: on this project's brain at 0.5 a memory
136/// with similarity 0.18 came second on "how releases are approved"; at 0.25
137/// the right fact led all three DOGFOOD-0 questions with no such intruder
138/// (`docs/design/12.3-retrieval.md`, section 5).
139pub const DEFAULT_TEXT_KEYWORD_WEIGHT: f32 = 0.25;
140
141/// FMT-9b: default [`Mnemo::set_vector_cache_budget`]: the fp16 vector
142/// column stays resident while it fits (100K × 384 dims is about 77 MB) and
143/// is read through the page cache above it. PLANNER-A, 2026-11-07.
144pub const DEFAULT_VECTOR_CACHE_BUDGET: usize = 96 * 1024 * 1024;
145
146/// FMT-9b: below this many facts a v9 file has no ANN index: an exact
147/// fp16 scan of 20K × 384 dims is about a millisecond, and the IVF+PQ
148/// codebook alone would cost more disk than it saves time.
149pub const V9_ANN_MIN_FACTS: usize = 20_000;
150
151/// FMT-9f (PLANNER-A, 2026-11-08): on v9 an unpinned recall reranks at
152/// least this many candidates per requested hit (500 for `top_k` 10), or
153/// the index's own auto depth when that's deeper (above 100K). The v9
154/// index is trained on fp16-rounded vectors, and at 20K–50K the auto
155/// depth (×10–×25) lost up to 0.03 recall@10 against v8; ×50 is within
156/// 0.005 at every measured tier. v8 is unchanged.
157pub const V9_RERANK_PER_HIT: usize = 50;
158
159/// FMT-9c: page runs longer than this are written copy-on-write straight
160/// to their home pages (and fsynced) before the commit, instead of through
161/// the WAL, on v9. The WAL then carries only the header and small runs, so
162/// it stays at its 64 KiB default instead of growing to the largest
163/// catalog or index (26 MB at 100K on v8). Safe for the same reason data
164/// pages are: the pages come from the tail or from quarantined free runs,
165/// so nothing committed references them until the header flips.
166const V9_WAL_RUN_MAX_PAGES: u64 = 2;
167
168/// FMT-9c: snapshot retention on v9: the newest 16 snapshots, plus any
169/// from the last 24 hours, with retained snapshots never pinning more than
170/// a quarter of the file (past that, the oldest go first, whatever their
171/// age). `set_max_snapshots` changes the count.
172pub const V9_DEFAULT_MAX_SNAPSHOTS: usize = 16;
173const V9_SNAPSHOT_KEEP_SECS: i64 = 24 * 3600;
174/// FMT-9c: the pin cap never drops below 128 pages (1 MiB).
175const V9_PIN_FLOOR_PAGES: u64 = 128;
176
177/// FMT-9d: the layout byte at the start of a v9 ANN index run (1: the
178/// whole IVF+PQ index, followed by delta runs). A reader treats an unknown
179/// layout as no index, so a later layout (partition-major, PERF-2) ships
180/// without a format bump.
181const V9_INDEX_LAYOUT: u8 = 1;
182
183/// FMT-9b: how many sparse vector pages one commit folds into its new
184/// pages (the vacuum). Bounded so a commit's cost stays bounded.
185const VACUUM_PAGES_PER_COMMIT: usize = 4;
186
187/// FMT-9c.2: and at most this many rows moved by the vacuum per commit (a
188/// moved row is a changed catalog row, so it lands in the commit's delta).
189/// Pages with more live rows than this stay as they are until deletes thin
190/// them out.
191const VACUUM_MAX_ROWS: usize = 64;
192
193/// FMT-9b: header flag: the file also keeps each record's float vector
194/// (`MnemoConfig::store_float_vectors`).
195const FLAG_FLOAT_VECTORS: u32 = 2;
196
197/// PERF-1: when the in-memory ANN index was last persisted, and whether the
198/// next flush must persist it.
199#[derive(Debug, Default, Clone, Copy)]
200struct IndexPersist {
201 /// Persist on the next flush (build, rebuild, drop, `flush_index`,
202 /// `close`, snapshot restore).
203 forced: bool,
204 /// Commits since the last persist that left the index dirty.
205 commits: u32,
206 /// Vectors added, re-assigned or removed since the last persist.
207 changes: usize,
208}
209
210/// Configuration for creating a new database.
211#[derive(Clone, Copy, Debug)]
212pub struct MnemoConfig {
213 /// Embedding dimensionality. Every stored vector must match this.
214 pub dimensions: usize,
215 /// Key-derivation parameters.
216 pub kdf: KdfParams,
217 /// Initial size of the WAL region in 8 KiB pages. Default is
218 /// [`DEFAULT_WAL_PAGES`] (8 pages = 64 KiB), which keeps fresh files
219 /// small; the region auto-grows when a transaction's control plane needs
220 /// more space, so raising this is only a hint for the expected steady-state
221 /// transaction size. Write-heavy databases that routinely flush large
222 /// catalogs or ANN indexes can set this higher (e.g. 64 = 512 KiB) to
223 /// avoid early grow events; tiny embedded uses can leave it at the
224 /// default. Clamped to a minimum of [`MIN_WAL_PAGES`] (2 pages).
225 pub wal_pages_initial: u64,
226 /// Maximum number of snapshot manifest entries to retain. Each `flush`
227 /// appends one entry; once the cap is hit, the *oldest* entry is dropped
228 /// from the in-memory manifest before the new one is added, so the
229 /// retained set is always the most-recent N. Defaults to
230 /// [`DEFAULT_MAX_SNAPSHOTS`] (256). Set to `0` to disable the cap and
231 /// retain every snapshot forever (the pre-v0.3 behavior).
232 ///
233 /// Pages referenced *only* by pruned snapshots stay on disk until the
234 /// next [`Mnemo::compact_file`], which reclaims them. Point-in-time
235 /// recovery via [`Mnemo::restore_to`] into a pruned `txn_id` returns
236 /// [`MnemoError::NotFound`].
237 ///
238 /// Apply to an already-open database with [`Mnemo::set_max_snapshots`].
239 pub max_snapshots: usize,
240 /// The on-disk format a new file is created in. `0` (the default)
241 /// means v9, the current format. `8` creates a v8 file, for tools that
242 /// still need to read it with v0.10 or earlier; it's kept for one
243 /// release (v0.12 makes v8 read-only). **Not a stable API.**
244 #[doc(hidden)]
245 pub format_version: u16,
246 /// FMT-9b (v9 files only; ignored for v8): also keep each memory's
247 /// full-precision vector in its record, so `get()` and `recall()`
248 /// return it exactly. Off by default: a v9 file stores vectors as
249 /// fp16 (about 1e-3 relative error) in the vector column, which recall
250 /// scores from either way. Costs `4 × dimensions` bytes per memory.
251 pub store_float_vectors: bool,
252}
253
254impl Default for MnemoConfig {
255 fn default() -> Self {
256 Self {
257 dimensions: 768,
258 kdf: KdfParams::secure(),
259 wal_pages_initial: DEFAULT_WAL_PAGES,
260 max_snapshots: DEFAULT_MAX_SNAPSHOTS,
261 format_version: 0,
262 store_float_vectors: false,
263 }
264 }
265}
266
267/// FMT-9: resolve [`MnemoConfig::format_version`] for a new file.
268fn resolve_format_version(requested: u16) -> Result<u16> {
269 match requested {
270 // FMT-9f: new files are v9; the `MNEMO_DEV_FORMAT` switch is gone.
271 0 => Ok(crate::format::DEFAULT_NEW_VERSION),
272 VERSION_V9 => Ok(requested),
273 // The v8 sunset (v0.13): v8 files open read-only and compact to v9;
274 // no new one is created.
275 v => Err(MnemoError::Invalid(format!(
276 "format_version {v} is not supported for new files: new files are v9 (pass 0 or 9)"
277 ))),
278 }
279}
280
281/// Catalog entry: maps a memory ID to its page run on disk.
282///
283/// **Schema (v5+):** carries `accessed_at` and `access_count` so `recall`
284/// can update access stats by mutating the catalog entry rather than
285/// rewriting the entire record (Phase 2.1 of the improvement plan). The
286/// values in a memory's serialized record body become a stale snapshot
287/// after the first recall; [`Mnemo::read_memory`] re-populates them from
288/// the catalog so consumers always see the live values.
289#[derive(Serialize, Deserialize, Clone, Debug)]
290struct CatalogEntry {
291 /// ULID as a raw `u128`.
292 id: u128,
293 start_page: u64,
294 page_count: u32,
295 /// Exact serialized byte length of the record.
296 len: u32,
297 deleted: bool,
298 /// Unix seconds of the most recent recall hit (or write, for fresh entries).
299 accessed_at: i64,
300 /// How many times `recall` has surfaced this memory.
301 access_count: u32,
302 /// FMT-9: the generation the record's pages were sealed under (v9 page
303 /// AAD). `0`, and left out of the encoding, on v8 files, so a v8
304 /// catalog is byte-for-byte what v0.10 writes.
305 #[serde(default, skip_serializing_if = "crate::format::is_zero_u64")]
306 gen: u64,
307 /// FMT-9b: the v9 row's tags, scoring inputs and vector location
308 /// (`None`, and left out of the encoding, on v8 files).
309 #[serde(default, skip_serializing_if = "Option::is_none")]
310 v9: Option<RowV9>,
311}
312
313/// FMT-9b: what a v9 catalog row carries beyond the v8 fields, so recall
314/// can filter and score a candidate without decrypting its record, and a
315/// cold handle can select records by kind or thread.
316#[derive(Serialize, Deserialize, Clone, Copy, Debug, Default)]
317struct RowV9 {
318 /// The vector column entry: page (`0` while it's waiting for the next
319 /// flush), slot, and the page's generation.
320 vec_page: u64,
321 vec_slot: u16,
322 vec_gen: u64,
323 /// FMT-9b.2: the record's slot on its packed page (`start_page`), or
324 /// [`REC_SPAN`] when the record owns a run of whole pages.
325 rec_slot: u16,
326 /// `ROW_KIND_*`.
327 kind: u8,
328 /// `ROW_SUPERSEDED | ROW_HAS_TTL | ROW_SHARED`.
329 flags: u8,
330 /// [`memory_type_code`].
331 memory_type: u8,
332 /// FNV-1a of `_mnemo.thread`, of the 12.1 key slot, and of `agent_id`
333 /// (`0` = none). A collision only lets a non-match through to the
334 /// decrypted check.
335 thread_hash: u32,
336 key_hash: u32,
337 agent_hash: u32,
338 created_at: i64,
339 importance: f32,
340 /// `created_at + ttl_secs` when `ROW_HAS_TTL` is set.
341 expires_at: i64,
342 /// FMT-9d: the row's BM25 document id (`0`: not keyword-indexed) and
343 /// its token count. Live rows define which documents are live, and
344 /// N and avgdl, so segments never hold lengths or tombstones.
345 doc: u32,
346 doc_len: u16,
347}
348
349/// FMT-9e: by default a thread turn is written plain and compressed once
350/// it's a week old (by its `created_at`), so a live session's recent turns
351/// read at full speed and archived history is small.
352pub const DEFAULT_TURN_COMPRESS_AFTER_SECS: i64 = 7 * 24 * 3600;
353/// Frozen v4 catalog entry shape, used only by the v4→v5 migration path in
354/// [`Mnemo::open`]. Its layout matches the catalog encoding written by
355/// pre-v5 builds (5 positional fields). Do not change this struct.
356#[derive(Serialize, Deserialize, Clone, Debug)]
357struct CatalogEntryV4 {
358 id: u128,
359 start_page: u64,
360 page_count: u32,
361 len: u32,
362 deleted: bool,
363}
364
365/// Returned by [`Mnemo::prepare_for_flush`] and consumed by [`Mnemo::flush`].
366/// Carries the already-serialized control-plane bytes through the prelude
367/// so we don't re-serialize after the lease has been persisted.
368struct FlushPrelude {
369 cat_bytes: Option<Vec<u8>>,
370 /// FMT-9c.2: `cat_bytes` is a delta run, not a base catalog.
371 cat_delta: bool,
372 /// FMT-9c.3: `idx_bytes` is an index delta run, not a whole index.
373 idx_delta: bool,
374 /// FMT-9d: this commit's BM25 segment, and the segments it replaces.
375 bm25_seg: Option<(Vec<u8>, Option<usize>)>,
376 idx_bytes: Option<Vec<u8>>,
377 /// Serialized result-cache directory bytes when `dirty_cache` is
378 /// set (Phase 10.1). `None` if the cache didn't change since the
379 /// last flush — in that case the header keeps its current
380 /// `cache_start` / `cache_pages` / `cache_len` and no fresh cache
381 /// run is written.
382 cache_bytes: Option<Vec<u8>>,
383}
384
385/// One entry in the append-only snapshot manifest. Because record, catalog,
386/// and index pages are only ever *appended*, the runs a past flush wrote are
387/// still on disk; a `Snapshot` is the set of pointers needed to reconstruct
388/// the database exactly as that flush left it.
389#[derive(Serialize, Deserialize, Clone, Debug)]
390struct Snapshot {
391 txn_id: u64,
392 created_at: i64,
393 catalog_start: u64,
394 catalog_pages: u64,
395 catalog_len: u64,
396 index_start: u64,
397 index_pages: u64,
398 index_len: u64,
399 memory_count: u64,
400 /// FMT-9: generations of the catalog and index runs (v9 only; `None`,
401 /// and left out of the encoding, on v8 files).
402 #[serde(default, skip_serializing_if = "Option::is_none")]
403 gens: Option<SnapshotGens>,
404}
405
406/// FMT-9: the generations a v9 snapshot's runs were sealed under.
407#[derive(Serialize, Deserialize, Clone, Copy, Debug, Default)]
408struct SnapshotGens {
409 catalog: u64,
410 index: u64,
411 /// FMT-9c.2: the catalog's delta-chain head at this snapshot.
412 #[serde(default)]
413 delta: (u64, u64, u64, u64),
414 /// FMT-9c.3: the index's delta-chain head at this snapshot.
415 #[serde(default)]
416 index_delta: (u64, u64, u64, u64),
417 /// FMT-9d: the BM25 manifest at this snapshot.
418 #[serde(default)]
419 bm25: (u64, u64, u64, u64),
420}
421
422impl Snapshot {
423 fn catalog_gen(&self) -> u64 {
424 self.gens.map_or(0, |g| g.catalog)
425 }
426 fn index_gen(&self) -> u64 {
427 self.gens.map_or(0, |g| g.index)
428 }
429 fn delta_head(&self) -> RunPtr {
430 self.gens.map_or(RunPtr::default(), |g| tuple_ptr(g.delta))
431 }
432 fn index_delta_head(&self) -> RunPtr {
433 self.gens
434 .map_or(RunPtr::default(), |g| tuple_ptr(g.index_delta))
435 }
436}
437
438/// A restorable point in a database's history — see [`Mnemo::snapshots`].
439#[derive(Clone, Copy, Debug)]
440pub struct SnapshotInfo {
441 /// Id of the transaction that produced this snapshot (monotonic from 1).
442 pub txn_id: u64,
443 /// When the snapshot was committed (unix seconds).
444 pub created_at: i64,
445 /// Live memory count captured in the snapshot.
446 pub memory_count: u64,
447}
448
449/// What [`Mnemo::stats`] and [`Mnemo::stats_summary`] report about restore
450/// points (INSP-1, RB-001.25).
451pub(super) struct RestorePoints {
452 pub(super) retained: usize,
453 pub(super) oldest_at: Option<i64>,
454 pub(super) pinned_bytes: u64,
455}
456
457/// A retrieval request for [`Mnemo::recall`].
458#[derive(Clone, Debug)]
459pub struct RecallRequest {
460 /// Query embedding.
461 pub query: Vec<f32>,
462 /// Maximum results to return.
463 pub top_k: usize,
464 /// Restrict to these memory types (`None` = all types).
465 pub memory_types: Option<Vec<MemoryType>>,
466 /// Restrict to a single agent's view: its own memories plus shared ones.
467 pub agent_id: Option<String>,
468 /// Similarity metric.
469 pub metric: Metric,
470 /// Multi-signal score weights.
471 pub weights: ScoreWeights,
472 /// Index override: partitions to probe (`None` = index default). Ignored
473 /// when no ANN index is present.
474 pub n_probe: Option<usize>,
475 /// Index override: candidates to rerank (`None` = index default). Ignored
476 /// when no ANN index is present.
477 pub n_rerank: Option<usize>,
478 /// Whether to update each result's `accessed_at` and `access_count` in
479 /// the catalog. Defaults to `true`, matching pre-v5 behavior.
480 ///
481 /// Set to `false` for **fully read-only recall** — useful for batch
482 /// scoring, dry-run scoring, or recalls run by introspection tooling
483 /// (e.g. `mnemo about` consumers) where you don't want the score's own
484 /// observation to perturb the database. With `false`, recall does not
485 /// dirty the catalog and the next `flush` is a no-op.
486 pub track_access: bool,
487 /// Phase 12.6 pre-scoring filter: `session_id` + AND-ed metadata
488 /// conditions applied before the candidate is scored. Default is
489 /// [`Filter::default`] (no constraints). When the ANN index is on
490 /// and this filter is selective enough to starve the shortlist
491 /// below `top_k`, Phase 12.1's widen-then-exact-scan logic kicks
492 /// in so the result still carries up to `top_k` correct hits.
493 pub filter: Filter,
494 /// Phase 12.8 post-scoring budget: stop adding hits once the UTF-8
495 /// bytes of their `content` fields (not the serialized record
496 /// body) would exceed this many bytes. `None` (default) means no
497 /// budget and every hit through `top_k` is returned. If the top-1
498 /// hit is already over budget it is still returned — callers that
499 /// need an absolute cap should also pre-size `top_k`.
500 ///
501 /// Counts only the UTF-8 `content` bytes so the number is stable
502 /// across the Rust / Python / CLI / MCP surfaces; the JSON or
503 /// MessagePack envelope is excluded. Roughly 4 bytes per BPE
504 /// token for English text — a 4 KB budget comfortably holds ~1K
505 /// tokens.
506 ///
507 /// Observable through [`RecallResponse::truncated`]
508 /// ([`Mnemo::recall_budgeted`]): `true` iff at least one scored
509 /// hit was dropped by this budget, `false` otherwise.
510 pub max_bytes: Option<usize>,
511 /// FMT-9d (Phase 2, v9 files): **identifiers or exact terms to match**
512 /// (a version, a PR number, a function name) for hybrid recall. BM25
513 /// scores, divided by this query's best, are added to each candidate's
514 /// similarity with weight [`RecallRequest::keyword_weight`] before the
515 /// usual scoring. With an empty `query` vector
516 /// ([`RecallRequest::keywords_only`]), recall is keyword-only.
517 ///
518 /// **Since v0.15 (12.3 step 4), a recall by text is hybrid by default:**
519 /// with `keywords` `None`, the request's [`RecallRequest::text`] is
520 /// used for BM25, so give keywords only for identifiers the question
521 /// doesn't contain. Keywords given replace the text. **Empty keywords
522 /// (`.keywords("")`) opt out:** vector-only recall. `None` on a request
523 /// with no text is plain vector recall.
524 pub keywords: Option<String>,
525 /// 12.3 step 4 (v0.15): the query text a recall by text was built from
526 /// ([`RecallRequest::from_text`] sets it). With `keywords` `None` it's
527 /// also scored with BM25 on a v9 file (hybrid by default); a v8 file,
528 /// which has no keyword index, ignores it.
529 pub text: Option<String>,
530 /// FMT-9d: weight ε of the normalised BM25 score in hybrid recall
531 /// (default [`DEFAULT_KEYWORD_WEIGHT`]), for keywords given.
532 pub keyword_weight: f32,
533 /// 12.3 step 4 (v0.15): the weight when BM25 scores the request's
534 /// [`RecallRequest::text`] (no keywords given); default
535 /// [`DEFAULT_TEXT_KEYWORD_WEIGHT`].
536 pub text_keyword_weight: f32,
537 /// FMT-9d: BM25 term-frequency saturation `k1` (default 1.2).
538 pub bm25_k1: f32,
539 /// FMT-9d: BM25 length normalisation `b` (default 0.75).
540 pub bm25_b: f32,
541}
542
543impl RecallRequest {
544 /// A request with sensible defaults for a query embedding.
545 pub fn new(query: Vec<f32>) -> Self {
546 Self {
547 query,
548 top_k: 10,
549 memory_types: None,
550 agent_id: None,
551 metric: Metric::Cosine,
552 weights: ScoreWeights::default(),
553 n_probe: None,
554 n_rerank: None,
555 track_access: true,
556 filter: Filter::default(),
557 max_bytes: None,
558 keywords: None,
559 text: None,
560 keyword_weight: DEFAULT_KEYWORD_WEIGHT,
561 text_keyword_weight: DEFAULT_TEXT_KEYWORD_WEIGHT,
562 bm25_k1: 1.2,
563 bm25_b: 0.75,
564 }
565 }
566
567 /// FMT-9d (v9 files): a keyword-only request: BM25 over `keywords`
568 /// (identifiers or exact terms), no query vector, so it works without
569 /// an embedder.
570 pub fn keywords_only(keywords: impl Into<String>) -> Self {
571 Self::new(Vec::new()).keywords(keywords)
572 }
573
574 /// FMT-9d (v9 files): add identifiers or exact terms to match (hybrid
575 /// recall). They replace the request's text for BM25; `""` opts out of
576 /// keyword scoring. See the `keywords` field.
577 pub fn keywords(mut self, text: impl Into<String>) -> Self {
578 self.keywords = Some(text.into());
579 self
580 }
581
582 /// 12.3 step 4: the weight of the text's keyword score when no keywords
583 /// are given (see [`RecallRequest::text_keyword_weight`]).
584 pub fn text_keyword_weight(mut self, w: f32) -> Self {
585 self.text_keyword_weight = w;
586 self
587 }
588
589 /// 12.3 step 4: the weight of this request's keyword score: the text's
590 /// when it's the text that's scored, the keywords' otherwise.
591 pub(crate) fn effective_keyword_weight(&self) -> f32 {
592 if self.keywords.is_none() {
593 self.text_keyword_weight
594 } else {
595 self.keyword_weight
596 }
597 }
598
599 /// 12.3 step 4: the text BM25 scores for this request: the keywords
600 /// given (none if they're empty), or else the query text on a v9 file.
601 pub(crate) fn keywords_for(&self, v9: bool) -> Option<&str> {
602 match self.keywords.as_deref() {
603 Some(k) if k.trim().is_empty() => None,
604 Some(k) => Some(k),
605 None if v9 => self.text.as_deref().filter(|t| !t.trim().is_empty()),
606 None => None,
607 }
608 }
609
610 /// FMT-9d: the weight ε of the keyword score in hybrid recall.
611 pub fn keyword_weight(mut self, w: f32) -> Self {
612 self.keyword_weight = w;
613 self
614 }
615
616 /// Phase 12.6: attach a pre-scoring filter. See [`Filter`] and
617 /// [`FilterTerm`] for term shapes.
618 pub fn filter(mut self, filter: Filter) -> Self {
619 self.filter = filter;
620 self
621 }
622
623 /// Phase 12.8: cap the total UTF-8 bytes of returned `content`
624 /// fields. See [`RecallRequest::max_bytes`].
625 pub fn max_bytes(mut self, n: usize) -> Self {
626 self.max_bytes = Some(n);
627 self
628 }
629
630 /// Build a request by embedding `query_text` with the supplied
631 /// embedder (Phase 3). Since v0.15 it embeds with
632 /// [`Embedder::embed_query`] and keeps the text in
633 /// [`RecallRequest::text`], so the recall is hybrid by default (see
634 /// [`RecallRequest::keywords`]; `.keywords("")` opts out). Otherwise the
635 /// same defaults as `new`. Fails if the embedder returns an empty vector
636 /// list or an embedding failure.
637 pub fn from_text(embedder: &dyn Embedder, query_text: &str) -> Result<Self> {
638 let mut vectors = embedder.embed_query(&[query_text])?;
639 let v = vectors.pop().ok_or_else(|| {
640 MnemoError::Invalid("embedder returned no vector for the query text".into())
641 })?;
642 Ok(Self::new(v).text(query_text))
643 }
644
645 /// 12.3 step 4: set the query text (see [`RecallRequest::text`]), for
646 /// a caller that embedded it itself.
647 pub fn text(mut self, text: impl Into<String>) -> Self {
648 self.text = Some(text.into());
649 self
650 }
651 /// Set the result cap.
652 pub fn top_k(mut self, k: usize) -> Self {
653 self.top_k = k;
654 self
655 }
656 /// Restrict to specific memory types.
657 pub fn types(mut self, t: Vec<MemoryType>) -> Self {
658 self.memory_types = Some(t);
659 self
660 }
661 /// Restrict to one agent's view.
662 pub fn agent(mut self, agent_id: impl Into<String>) -> Self {
663 self.agent_id = Some(agent_id.into());
664 self
665 }
666 /// Set the similarity metric (default: cosine).
667 pub fn metric(mut self, metric: Metric) -> Self {
668 self.metric = metric;
669 self
670 }
671 /// Replace the multi-signal score weights.
672 pub fn weights(mut self, weights: ScoreWeights) -> Self {
673 self.weights = weights;
674 self
675 }
676 /// Override the number of IVF partitions probed (accuracy/speed dial).
677 pub fn n_probe(mut self, n: usize) -> Self {
678 self.n_probe = Some(n);
679 self
680 }
681 /// Override the number of candidates reranked exactly (accuracy dial).
682 pub fn n_rerank(mut self, n: usize) -> Self {
683 self.n_rerank = Some(n);
684 self
685 }
686 /// Toggle whether recall updates `accessed_at` / `access_count` on
687 /// the returned memories' catalog entries (default `true`). Pass
688 /// `false` for a fully read-only recall — see the field doc.
689 pub fn track_access(mut self, track: bool) -> Self {
690 self.track_access = track;
691 self
692 }
693}
694
695/// One scored result from [`Mnemo::recall`].
696#[derive(Clone, Debug)]
697pub struct RecallResult {
698 /// The retrieved memory.
699 pub memory: Memory,
700 /// Combined multi-signal score.
701 pub score: f32,
702 /// The bare similarity component (before other signals).
703 pub similarity: f32,
704}
705
706/// Phase 12.8 budgeted-recall envelope returned by
707/// [`Mnemo::recall_budgeted`]. Wraps the `Vec<RecallResult>` the
708/// legacy [`Mnemo::recall`] returns so callers can tell whether
709/// [`RecallRequest::max_bytes`] cut anything.
710#[derive(Clone, Debug)]
711pub struct RecallResponse {
712 /// Scored hits, best first, truncated to at most `top_k` and then
713 /// to fit the `max_bytes` budget if set.
714 pub hits: Vec<RecallResult>,
715 /// `true` iff the `max_bytes` budget dropped at least one hit
716 /// that would otherwise have been returned (i.e. the result is
717 /// shorter than what `top_k` alone would produce).
718 pub truncated: bool,
719 /// Phase 12.1 + 12.6 observability: `true` iff recall fell
720 /// through to an exact scan (ANN shortlist too narrow after
721 /// filtering, and the widen pass also came up short, so the
722 /// index was skipped for one full-corpus pass). Monitoring on
723 /// this flag is how callers detect selective-filter regressions
724 /// or supersession chains outgrowing the ANN shortlist.
725 pub used_exact_scan: bool,
726}
727
728/// Where a file's bytes and an open handle's heap go (P-0 device budget,
729/// `examples/device_budget.rs`). **Unstable diagnostic**: fields may
730/// change in any release. File figures come from the header and the
731/// catalog. RAM figures are buffer capacities, with hash maps estimated
732/// from their capacity; they cover the engine's main structures, not
733/// every allocation, and not allocator overhead.
734#[doc(hidden)]
735#[derive(Clone, Debug, Default, serde::Serialize)]
736#[cfg(feature = "dev-hooks")]
737pub struct BudgetReport {
738 pub file_bytes: u64,
739 pub page_size: u64,
740 /// Page 0.
741 pub header_bytes: u64,
742 /// Whole pages holding live records (superseded versions included).
743 pub record_page_bytes: u64,
744 /// Serialized bytes of those records; the rest of their pages is
745 /// slack.
746 pub record_payload_bytes: u64,
747 /// Pages still holding soft-deleted records (reclaimed by compact).
748 pub deleted_record_page_bytes: u64,
749 pub catalog_run_bytes: u64,
750 pub catalog_payload_bytes: u64,
751 pub index_run_bytes: u64,
752 pub index_payload_bytes: u64,
753 /// First page of the persisted index run (0 = none).
754 pub index_start_page: u64,
755 pub wal_bytes: u64,
756 pub snapshot_manifest_bytes: u64,
757 pub cache_dir_run_bytes: u64,
758 /// Everything else: superseded catalog, index and directory runs from
759 /// earlier flushes, and freed pages, until the next compact.
760 pub unreferenced_bytes: u64,
761 pub live_records: u64,
762 pub ram_catalog: u64,
763 pub ram_id_map: u64,
764 pub ram_ann_centroids: u64,
765 pub ram_ann_codebook: u64,
766 pub ram_ann_posting_ids: u64,
767 pub ram_ann_posting_codes: u64,
768 pub ram_ann_assignment: u64,
769 pub ram_cache_dir: u64,
770 pub ram_key_caches: u64,
771 /// FMT-9b: the resident fp16 vector column as allocated (rows not yet
772 /// touched by recall cost no physical memory).
773 pub ram_vector_column: u64,
774 /// Sum of the `ram_*` fields.
775 pub ram_total: u64,
776}
777
778/// Summary statistics for a database.
779#[derive(Clone, Debug)]
780pub struct Stats {
781 /// Live (non-deleted) memory count.
782 pub memories: usize,
783 /// Tombstoned entries awaiting compaction.
784 pub deleted: usize,
785 /// Embedding dimensionality.
786 pub dimensions: usize,
787 /// File size in bytes.
788 pub file_bytes: u64,
789 /// Distinct agent IDs present.
790 pub agents: Vec<String>,
791 /// Whether pages are encrypted (always true in v1).
792 pub encrypted: bool,
793 /// Creation time (unix seconds).
794 pub created_at: i64,
795 /// ANN index shape, if an index has been built.
796 pub index: Option<IndexInfo>,
797 /// Current size of the write-ahead log region, in 8 KiB pages.
798 pub wal_pages: u64,
799 /// Fsyncs issued by the most recent successful [`Mnemo::flush`] on
800 /// this handle. `0` on a fresh handle before any flush, or when
801 /// `flush()` short-circuited (nothing dirty). Phase 6 instrumentation
802 /// for the Phase 11.1 write-latency work — the planner wants this
803 /// before deciding whether cutting fsync count is a viable
804 /// durability-preserving fix.
805 pub fsyncs_last_flush: u32,
806 /// FMT-9f: the file's on-disk format (`8` or `9`). Since v0.13 a v8 file
807 /// opens read-only; `mnemo compact` converts it to v9.
808 pub format_version: u16,
809 /// MOBILE-2d: how recall scores vectors on this handle right now.
810 pub recall_mode: RecallMode,
811 /// INSP-1 (RB-001.25): the snapshots retained right now, each a
812 /// restore point for [`Mnemo::restore_to`]. Under churn the pin cap can
813 /// keep fewer than the policy's 16-and-24-hours, so this, not the
814 /// policy, is what can be restored.
815 pub snapshots_retained: usize,
816 /// When the oldest retained snapshot was committed (unix seconds):
817 /// the furthest back a restore reaches. `None` with no snapshot.
818 pub oldest_restorable_at: Option<i64>,
819 /// The bytes the retained snapshots keep from reuse (pages freed after
820 /// the oldest one). `0` on v8, which never reuses pages.
821 pub snapshot_pinned_bytes: u64,
822 /// TOK-1 (v0.15): the keyword index's tokenizer: `V2` for a file v0.15
823 /// created or rebuilt, `V1` for an older file until a compaction or
824 /// `reembed` rebuilds it, `Mixed` after a build before v0.15 wrote to
825 /// a tokenizer 2 index. `None` on v8, which has no keyword index.
826 pub keyword_tokenizer: Option<crate::KeywordTokenizer>,
827}
828
829/// [`Mnemo::stats_summary`]: the cheap statistics, read from the catalog and
830/// the header (v0.12.2, RB-002.3).
831#[derive(Clone, Debug, PartialEq, Eq)]
832pub struct StatsSummary {
833 /// Live (non-deleted) memory count.
834 pub memories: usize,
835 /// Tombstoned entries awaiting compaction.
836 pub deleted: usize,
837 /// Embedding dimensionality.
838 pub dimensions: usize,
839 /// File size in bytes.
840 pub file_bytes: u64,
841 /// The on-disk format, `8` or `9`.
842 pub format_version: u16,
843 /// Current size of the write-ahead log region, in 8 KiB pages.
844 pub wal_pages: u64,
845 /// Whether an IVF+PQ index exists (loaded, or persisted in the file).
846 pub has_index: bool,
847 /// How recall scores vectors right now.
848 pub recall_mode: RecallMode,
849 /// The bytes the v9 vector column needs to stay in memory: the live
850 /// facts × (`2 × dimensions + 4`). Recall is `ExactResident` while the
851 /// vector cache budget is at least this; `0` on v8, which has no column.
852 pub vector_column_bytes: u64,
853 /// INSP-1 (RB-001.25): the snapshots retained right now, each a
854 /// restore point for [`Mnemo::restore_to`]. Under churn the pin cap can
855 /// keep fewer than the policy's 16-and-24-hours, so this, not the
856 /// policy, is what can be restored.
857 pub snapshots_retained: usize,
858 /// When the oldest retained snapshot was committed (unix seconds):
859 /// the furthest back a restore reaches. `None` with no snapshot.
860 pub oldest_restorable_at: Option<i64>,
861 /// The bytes the retained snapshots keep from reuse (pages freed after
862 /// the oldest one). `0` on v8, which never reuses pages.
863 pub snapshot_pinned_bytes: u64,
864}
865
866/// MOBILE-2d: how recall scores vectors, from [`Mnemo::stats`].
867#[derive(Clone, Copy, Debug, PartialEq, Eq)]
868pub enum RecallMode {
869 /// An exact scan over the fp16 vector column held in memory: a v9 file
870 /// whose live facts fit [`Mnemo::set_vector_cache_budget`]. The fast
871 /// path.
872 ExactResident,
873 /// An exact scan that reads vectors through the page cache: a v9 file
874 /// whose live facts are over the budget, or a v8 file. Slower, and
875 /// slower still as the file grows; raise the budget or build an index.
876 ExactPaged,
877 /// An IVF+PQ index shortlists the candidates
878 /// ([`Mnemo::build_index`]).
879 Indexed,
880}
881
882impl RecallMode {
883 /// `exact_resident`, `exact_paged` or `indexed`.
884 pub fn as_str(&self) -> &'static str {
885 match self {
886 RecallMode::ExactResident => "exact_resident",
887 RecallMode::ExactPaged => "exact_paged",
888 RecallMode::Indexed => "indexed",
889 }
890 }
891}
892
893/// The error from [`Mnemo::try_close`]: the final flush failed, and the
894/// handle comes back with it, still open and still holding every write that
895/// wasn't flushed.
896pub struct CloseError {
897 pub(super) handle: Box<Mnemo>,
898 pub(super) error: MnemoError,
899}
900
901impl CloseError {
902 /// Why the flush failed.
903 pub fn error(&self) -> &MnemoError {
904 &self.error
905 }
906
907 /// The handle, to retry [`Mnemo::flush`] or [`Mnemo::try_close`].
908 pub fn into_inner(self) -> Mnemo {
909 *self.handle
910 }
911
912 /// The handle and the error.
913 pub fn into_parts(self) -> (Mnemo, MnemoError) {
914 (*self.handle, self.error)
915 }
916}
917
918impl std::fmt::Debug for CloseError {
919 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
920 f.debug_struct("CloseError")
921 .field("error", &self.error)
922 .finish_non_exhaustive()
923 }
924}
925
926impl std::fmt::Display for CloseError {
927 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
928 write!(f, "close failed (the handle is kept): {}", self.error)
929 }
930}
931
932impl std::error::Error for CloseError {
933 fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
934 Some(&self.error)
935 }
936}
937
938/// Result of a [`Mnemo::compact_file`] run.
939#[derive(Clone, Copy, Debug, Default)]
940pub struct CompactReport {
941 /// Live memories before compaction.
942 pub before: usize,
943 /// Live memories after compaction (expired ones dropped).
944 pub after: usize,
945 /// Live, non-expired cache entries before compaction. FIX-1
946 /// R-001.1: compaction now preserves the result cache instead of
947 /// silently dropping it.
948 pub cache_before: usize,
949 /// Live, non-expired cache entries after compaction (tombstoned
950 /// and TTL-expired ones dropped).
951 pub cache_after: usize,
952 /// Legacy onboarding or manifest memories that held an all-zero vector
953 /// (from before the zero-vector rule) and were given the sentinel unit
954 /// vector a current manifest has.
955 pub zero_vector_manifests: usize,
956 /// Other memories with an all-zero vector, carried unchanged: their
957 /// content and recall behaviour are the same as before.
958 pub zero_vector_memories: usize,
959}
960
961/// What [`Mnemo::reembed_file`] did (12.3 step 4, v0.15).
962#[derive(Clone, Debug, PartialEq, Eq)]
963pub struct ReembedReport {
964 /// Live memories embedded again: facts, superseded versions, essence
965 /// items and thread turns (expired ones are dropped, as by compaction).
966 pub memories: usize,
967 /// Manifests kept on the sentinel vector (resized to the new width).
968 pub manifests: usize,
969 /// Thread links (`_mnemo.kind = "thread_link"`) kept on the sentinel
970 /// vector (resized to the new width), R-008.3.
971 pub thread_links: usize,
972 /// Result-cache entries copied (the engine's own aren't counted).
973 pub cache_entries: usize,
974 /// Semantic cache entries dropped because their vector has the old
975 /// width (only when the width changed).
976 pub cache_dropped: usize,
977 /// The identity the file recorded before, if any.
978 pub from: Option<crate::EmbedderIdentity>,
979 /// The identity it records now.
980 pub to: crate::EmbedderIdentity,
981}
982
983/// What [`Mnemo::verify_report`] checked.
984#[derive(Clone, Debug, PartialEq, Eq)]
985pub struct VerifyReport {
986 /// Records decrypted and decoded: live memories and cache entries (the
987 /// engine's own entries aren't counted).
988 pub records: usize,
989 /// Live memories whose vector is all zeros (from before the zero-vector
990 /// rule). They score 0.0 on every vector query.
991 pub zero_vector_memories: usize,
992 /// TOK-1: the keyword index's tokenizer (see
993 /// [`Stats::keyword_tokenizer`]). `Mixed` is worth a compaction.
994 pub keyword_tokenizer: Option<crate::KeywordTokenizer>,
995}
996
997/// An encrypted, single-file agent memory database.
998pub struct Mnemo {
999 /// 12.4: the lock layer's note for a handle opened through it for a
1000 /// long operation ([`Mnemo::open_exclusive`], compaction): its
1001 /// `lock-info` line, removed when the handle drops. Declared first so
1002 /// it drops before `pager`, whose file's unlock comes after it.
1003 lock_note: Option<crate::shared::Held>,
1004 /// 12.3: what this handle has to tell its owner once, such as a
1005 /// passphrase on raw-key KDF parameters ([`Mnemo::notices`]).
1006 notices: Vec<String>,
1007 pager: Pager,
1008 header: Header,
1009 catalog: Vec<CatalogEntry>,
1010 index: IdIndex,
1011 /// The path this handle opened, made absolute at open (so a later
1012 /// change of the process's directory doesn't change what it names).
1013 /// `ensure_not_replaced` checks that it still names the open file.
1014 path: PathBuf,
1015 dimensions: usize,
1016 kdf: KdfParams,
1017 /// Set whenever the catalog changes; drives whether `flush` rewrites it.
1018 dirty_catalog: bool,
1019 /// Optional IVF+PQ approximate-nearest-neighbour index.
1020 ann: Option<IvfPqIndex>,
1021 /// Set whenever the in-memory ANN index differs from the persisted one.
1022 /// PERF-1: `flush` persists it only per [`IndexPersist`]'s policy.
1023 dirty_index: bool,
1024 /// PERF-1: index persistence policy state.
1025 index_persist: IndexPersist,
1026 /// PERF-1 step 3: the header points at a persisted ANN index that
1027 /// hasn't been loaded yet. It loads on first use (`ensure_ann`).
1028 ann_unloaded: bool,
1029 /// Append-only manifest of committed snapshots, oldest first. Capped
1030 /// at [`Mnemo::max_snapshots`] entries on every flush — the oldest
1031 /// entries are pruned first.
1032 manifest: Vec<Snapshot>,
1033 /// Maximum manifest entries to retain across flushes. `0` disables
1034 /// the cap (retain forever). Defaults to [`DEFAULT_MAX_SNAPSHOTS`].
1035 max_snapshots: usize,
1036 /// If `true`, this handle was opened via [`Mnemo::open_read_only`] and
1037 /// every mutating API returns [`MnemoError::ReadOnly`]. The underlying
1038 /// file was opened without write permission and holds an OS shared
1039 /// lock; the OS would reject a write() anyway, but gating in Rust
1040 /// gives callers a clean, typed error.
1041 read_only: bool,
1042 /// Result-cache directory (Phase 10.1). See [`crate::result_cache`].
1043 /// Loaded from `header.cache_start` on open; persisted on `flush`
1044 /// via the same seal_run pipeline as catalog/index/manifest.
1045 cache_dir: Vec<CacheDirectoryEntry>,
1046 /// In-memory index over `cache_dir` for O(1) `(namespace, key_hash)`
1047 /// lookups. Rebuilt on open + kept in sync on `cache_put`/`delete`.
1048 cache_idx: DirectoryIndex,
1049 /// Set whenever `cache_dir` changes; drives whether `flush` rewrites
1050 /// the cache directory run.
1051 dirty_cache: bool,
1052 /// Per-namespace eviction budgets. Missing entries fall back to
1053 /// [`CacheBudget::default`]. Not persisted (per-handle policy).
1054 cache_budgets: std::collections::HashMap<String, CacheBudget>,
1055 /// Flush policy for cache mutations. Memory writes ignore this and
1056 /// always behave as `Strict`.
1057 cache_flush_policy: CacheFlushPolicy,
1058 /// Bookkeeping for `CacheFlushPolicy::Batched` — pending mutation
1059 /// count and first-dirty timestamp.
1060 cache_batch: BatchState,
1061 /// In-memory hit/miss/eviction counters (reset on reopen).
1062 cache_counters: CounterState,
1063 /// Optional handle-scoped embedder (Phase 3, PR 10a). Registered
1064 /// via [`Mnemo::set_embedder`]; consulted by [`Mnemo::remember_text`]
1065 /// and [`RecallRequest::from_text`]. `None` means text-side APIs
1066 /// return [`MnemoError::Invalid`] with a "no embedder" message.
1067 /// Not persisted — the handle is re-registered after every open.
1068 embedder: Option<std::sync::Arc<dyn Embedder>>,
1069 /// Fsyncs issued by the most recent `flush()` call. Snapshotted
1070 /// from the thread-local fsync counter in `lib.rs::fsync_counter`:
1071 /// `flush()` reads it on entry, does its work (each `sync_all` the
1072 /// pager / wal / recovery path makes bumps the counter), and
1073 /// stores the delta here. `0` on a fresh handle before any flush,
1074 /// or on a read-only handle where `flush()` short-circuits.
1075 /// Exposed through [`Stats::fsyncs_last_flush`] for diagnostics —
1076 /// the Phase 6 planner wants this before deciding whether cutting
1077 /// fsync count is a viable write-latency win.
1078 fsyncs_last_flush: u32,
1079 /// FIX-1 R-001.8 part 2: lazy cache of the distinct agent IDs
1080 /// across every live memory, built once on first `stats()` call
1081 /// per handle. `remember()` adds to it in O(1); `delete()` can't
1082 /// cheaply tell whether the removed memory was the last of its
1083 /// agent (the agent lives in the encrypted body, not the catalog
1084 /// — pre-v9 format), so it just invalidates the set and the next
1085 /// `stats()` call rebuilds. Pre-FIX-1 every `stats()` call
1086 /// decrypted every live memory to collect agents, turning an
1087 /// otherwise-cheap diagnostic into an O(N) decrypt.
1088 agent_set: Option<std::collections::BTreeSet<String>>,
1089 /// Phase 12.1 lazy caches, built together on the first keyed op this
1090 /// handle sees (`remember_keyed`, `update` that touches `_mnemo.key`,
1091 /// or any `history(...)` call). Both are maintained incrementally
1092 /// after that. `None` → not built yet; `Some(…)` → authoritative.
1093 ///
1094 /// * `key_index`: `(scope_owner, key) → ULID bytes` of the **live**
1095 /// record for each keyed slot. `scope_owner` is `Some(agent_id)`
1096 /// for a `Private` scope slot and `None` for a `Shared` one, so a
1097 /// private write never collides with a shared one.
1098 /// * `superseded`: the ULID bytes of every record that has been
1099 /// superseded (`_mnemo.superseded_by` set on it). `recall` and
1100 /// `about` skip these before any decrypt.
1101 ///
1102 /// Building both costs one scan over live records (~1s at 100K with
1103 /// hardware AES) and happens at most once per handle. A format bump
1104 /// to v9 moves the key into the catalog row so the scan goes away.
1105 key_index: Option<std::collections::HashMap<KeySlot, u128>>,
1106 superseded: Option<std::collections::HashSet<u128>>,
1107 /// R-004.2: thread layers + onboarding ids, built by the same lazy scan.
1108 layers: Option<LayerCache>,
1109 /// REKEY-1 (RB-004.2): what the last successful rekey couldn't scrub
1110 /// once the new secret was in force (see [`Mnemo::rekey_cleanup_error`]).
1111 rekey_cleanup: Option<String>,
1112 /// 12.4 shared mode: access statistics from reads made under the
1113 /// shared lock (recall hits, cache hits), applied with this handle's
1114 /// next commit. `None` on every other handle.
1115 access_delta: Option<shared::AccessDelta>,
1116 /// 12.4 shared mode: the transaction id of the commit `flush` had
1117 /// reached the WAL with, when it fails after that point. A shared write
1118 /// uses it to tell a lost write from one that may be in the file.
1119 commit_point: Option<u64>,
1120 /// 12.4 shared mode (RB-007.5): a `flush` since the window started
1121 /// committed. Set by every committing flush; a shared write window
1122 /// clears it first, and then knows that part of the window is in the
1123 /// file when a later step fails.
1124 window_committed: bool,
1125 /// 12.4 shared mode: this handle is a shared handle's state, so a
1126 /// `rekey` inside a window is refused (`SharedMnemo::rekey` does it and
1127 /// updates the kept secret).
1128 shared: bool,
1129 /// FMT-9e: thread turns are compressed once older than this many
1130 /// seconds (`0`: at write). Per handle, not persisted.
1131 turn_compress_after: i64,
1132 /// FMT-9 (a): the committed free list (v9; always empty on v8). Pages
1133 /// allocated from it since the last commit are already removed.
1134 free: FreeList,
1135 /// FMT-9 (a): runs this transaction stopped referencing (overwritten
1136 /// or deleted records, tombstoned cache entries, a relocated WAL
1137 /// region). The next commit adds them to the free list, freed at its
1138 /// own transaction id.
1139 pending_free: Vec<(u64, u64)>,
1140 /// FMT-9 (a): the free list changed (an allocation took pages from it)
1141 /// and must be rewritten by the next commit.
1142 free_dirty: bool,
1143 /// FMT-9 (b): the key-slot run (v9; empty until Phase 13.2 adds slots).
1144 key_slots: KeySlotRun,
1145 /// FMT-9 (b): `key_slots` changed since the last commit.
1146 dirty_keys: bool,
1147 /// FMT-9: this writable session has burned a transaction id with a
1148 /// durable header-only commit (`ensure_gen_lease`), so the generations
1149 /// its pages carry can't repeat ones a crashed earlier session used.
1150 gen_leased: bool,
1151 /// FMT-9b: the fp16 vector column (v9; unused on v8).
1152 col: VecColumn,
1153 /// FMT-9b.2: packed record pages (v9; unused on v8).
1154 recs: RecPages,
1155 /// FMT-9d: the BM25 keyword index (v9; unused on v8).
1156 bm25: Bm25State,
1157 /// FMT-9d: test hook: write this layout byte instead of the current
1158 /// one (to exercise the unknown-layout path).
1159 index_layout_override: Option<u8>,
1160 /// FMT-9d: during one recall, each keyword match's normalised BM25
1161 /// score, by id.
1162 kw: Option<std::collections::HashMap<u128, f32>>,
1163 /// FMT-9c.2: catalog rows changed since the last commit (v9 writes
1164 /// them as a delta run instead of the whole catalog).
1165 dirty_rows: std::collections::BTreeSet<usize>,
1166 /// FMT-9c.2: the delta runs on top of the base catalog, oldest first,
1167 /// and how many rows they hold in all.
1168 delta_chain: Vec<RunPtr>,
1169 delta_rows: usize,
1170 /// FMT-9c.3: the ANN index's delta runs on top of its base run, oldest
1171 /// first, and how many changes they hold in all.
1172 index_chain: Vec<RunPtr>,
1173 index_chain_ops: usize,
1174 /// FMT-9c.3: the next commit writes the whole index (after a build,
1175 /// rebuild or restore).
1176 index_rebase: bool,
1177 /// FMT-9c.3: this flush's index changes, when it writes them as a
1178 /// delta run.
1179 index_delta_ops: Option<Vec<IndexOp>>,
1180 /// FMT-9c.2: the next commit writes a whole base catalog (after a
1181 /// restore, or when the chain has grown too long).
1182 catalog_rewrite: bool,
1183 /// FMT-9c: the snapshot count was set explicitly (config or
1184 /// `set_max_snapshots`), which replaces v9's default retention policy.
1185 snapshot_cap_explicit: bool,
1186 /// FMT-9c: this flush wrote big runs straight to their home pages,
1187 /// which must be fsynced before the commit.
1188 direct_writes: bool,
1189 /// FMT-9b: keep the column resident while it fits this many bytes.
1190 vector_cache_budget: usize,
1191}
1192
1193/// Composite key for the lazy `key_index` on `Mnemo`. A slot is identified
1194/// by `(scope_owner, key)`:
1195/// * `Scope::Private` writes carry the owning agent → `Some(agent_id)`.
1196/// * `Scope::Shared` writes are per-file → `None`.
1197///
1198/// A private write never supersedes a shared one, and the reverse is also
1199/// true. Scope lives on `Memory.scope`, agent on `Memory.agent_id`.
1200#[derive(Debug, Clone, PartialEq, Eq, Hash)]
1201pub(crate) struct KeySlot {
1202 /// `Some(agent_id)` for `Scope::Private`, `None` for `Scope::Shared`.
1203 pub(crate) scope_owner: Option<String>,
1204 /// The caller-supplied key string, exactly as given (no case-fold).
1205 pub(crate) key: String,
1206}
1207
1208/// True if a memory's metadata marks it as the canonical onboarding manifest
1209/// (`metadata.topic == "manifest"`). Used by [`Mnemo::about`] to hoist the
1210/// manifest to the top of the briefing regardless of importance ordering.
1211fn is_manifest(m: &Memory) -> bool {
1212 m.metadata
1213 .get("topic")
1214 .and_then(|v| v.as_str())
1215 .map(|s| s.eq_ignore_ascii_case("manifest"))
1216 .unwrap_or(false)
1217}
1218
1219/// PERF-1 step 4: ULID → catalog row, as an open-addressing table of `u32`
1220/// row numbers: 4 bytes a slot, about 5 bytes an entry, against about 43
1221/// for the `HashMap<u128, usize>` it replaces. A probe compares against the
1222/// catalog's own id at that row, so the ids aren't stored twice. Rows are
1223/// never removed (a delete only tombstones the catalog entry), so there's
1224/// no delete path.
1225#[derive(Debug, Clone, Default)]
1226struct IdIndex {
1227 slots: Vec<u32>,
1228 len: usize,
1229}
1230
1231const NO_ROW: u32 = u32::MAX;
1232
1233impl IdIndex {
1234 fn build(catalog: &[CatalogEntry]) -> IdIndex {
1235 let mut t = IdIndex {
1236 slots: vec![NO_ROW; crate::index::table_capacity_for(catalog.len())],
1237 len: 0,
1238 };
1239 for (row, e) in catalog.iter().enumerate() {
1240 t.insert(e.id, row, catalog);
1241 }
1242 t
1243 }
1244
1245 /// The catalog row holding `id`, if any.
1246 fn get(&self, id: u128, catalog: &[CatalogEntry]) -> Option<usize> {
1247 if self.slots.is_empty() {
1248 return None;
1249 }
1250 let cap = self.slots.len();
1251 let mut i = crate::index::slot_home(id, cap);
1252 loop {
1253 let row = self.slots[i];
1254 if row == NO_ROW {
1255 return None;
1256 }
1257 if catalog[row as usize].id == id {
1258 return Some(row as usize);
1259 }
1260 i = crate::index::next_slot(i, cap);
1261 }
1262 }
1263
1264 /// Map `id` to `row`. `catalog` must hold every row already in the
1265 /// table (the new row may not be pushed yet).
1266 fn insert(&mut self, id: u128, row: usize, catalog: &[CatalogEntry]) {
1267 if (self.len + 1) * 4 > self.slots.len() * 3 {
1268 let cap = (self.slots.len() * 2).max(crate::index::table_capacity_for(self.len + 1));
1269 let old = std::mem::replace(&mut self.slots, vec![NO_ROW; cap]);
1270 self.len = 0;
1271 for r in old.into_iter().filter(|&r| r != NO_ROW) {
1272 self.insert(catalog[r as usize].id, r as usize, catalog);
1273 }
1274 }
1275 let cap = self.slots.len();
1276 let mut i = crate::index::slot_home(id, cap);
1277 loop {
1278 let r = self.slots[i];
1279 if r == NO_ROW {
1280 self.slots[i] = row as u32;
1281 self.len += 1;
1282 return;
1283 }
1284 if catalog[r as usize].id == id {
1285 self.slots[i] = row as u32;
1286 return;
1287 }
1288 i = crate::index::next_slot(i, cap);
1289 }
1290 }
1291
1292 #[cfg(feature = "dev-hooks")]
1293 fn heap_bytes(&self) -> usize {
1294 self.slots.capacity() * std::mem::size_of::<u32>()
1295 }
1296}
1297
1298/// Build the ULID → catalog-row lookup.
1299fn build_id_index(catalog: &[CatalogEntry]) -> IdIndex {
1300 IdIndex::build(catalog)
1301}
1302
1303// ---------------------------------------------------------------------------
1304// Phase 12.7a helpers used by `ingest_thread`.
1305// ---------------------------------------------------------------------------
1306
1307/// PERF-1 / FMT-9: was this catalog row written after the persisted index
1308/// run? v8 allocates pages monotonically, so a record past the run's first
1309/// page is newer. v9 reuses pages, so it compares generations instead.
1310fn written_after_index(e: &CatalogEntry, v9: bool, index_start: u64, index_gen: u64) -> bool {
1311 if v9 {
1312 // `start_page` 0: packed at the next flush, so certainly newer.
1313 e.start_page == 0 || e.gen > index_gen
1314 } else {
1315 e.start_page > index_start
1316 }
1317}
1318
1319/// Whether a record belongs in the ANN index: facts only. Thread-archive
1320/// turns, essence items and thread links are read by kind and scope, never
1321/// by similarity, so they stay out (R-004.2).
1322/// v0.16.1: a thread turn whose content is only transcript markers
1323/// ([`MNEMO_META_MARKERS_ONLY`]), by its flag or, for one saved before the
1324/// flag, by its content.
1325pub(super) fn is_markers_only_turn(m: &Memory) -> bool {
1326 meta_str(m, MNEMO_META_KIND) == Some(MNEMO_META_KIND_TURN)
1327 && (m.metadata.get(MNEMO_META_MARKERS_ONLY) == Some(&Value::Bool(true))
1328 || crate::transcript::is_marker_only(&m.content))
1329}
1330
1331#[cfg(test)]
1332#[test]
1333fn a_marker_only_turn_saved_before_the_flag_is_recognised_by_its_content() {
1334 let turn = |content: &str| {
1335 let mut m = Memory::new(content, MemoryType::Episodic, vec![1.0]);
1336 m.metadata.insert(
1337 MNEMO_META_KIND.into(),
1338 Value::String(MNEMO_META_KIND_TURN.into()),
1339 );
1340 m
1341 };
1342 assert!(is_markers_only_turn(&turn("[thinking]")));
1343 assert!(is_markers_only_turn(&turn(
1344 "[tool_use name=mcp__mnemo__remember]"
1345 )));
1346 assert!(!is_markers_only_turn(&turn(
1347 "staging-7\n[tool_use name=Bash]"
1348 )));
1349 // Only turns: a fact that reads like a marker is a fact.
1350 assert!(!is_markers_only_turn(&Memory::new(
1351 "[thinking]",
1352 MemoryType::Semantic,
1353 vec![1.0]
1354 )));
1355}
1356
1357fn is_ann_kind(m: &Memory) -> bool {
1358 !matches!(
1359 m.metadata.get(MNEMO_META_KIND).and_then(|v| v.as_str()),
1360 Some(MNEMO_META_KIND_TURN)
1361 | Some(MNEMO_META_KIND_ESSENCE)
1362 | Some(MNEMO_META_KIND_THREAD_LINK)
1363 )
1364}