Skip to main content

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