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