Skip to main content

mnemo_engine/store/
recall.rs

1//! Retrieval: memories(), about(), exact search, recall (scoring, filters, budgets, the ANN and BM25 candidate paths).
2
3use super::*;
4
5/// The thread a recall filter pins with `_mnemo.thread` equality, if any.
6fn filter_thread_pin(f: &Filter) -> Option<&str> {
7    f.terms.iter().find_map(|t| match t {
8        FilterTerm::Eq(k, Value::String(s)) if k == MNEMO_META_THREAD => Some(s.as_str()),
9        _ => None,
10    })
11}
12
13/// Whether a recall filter can only match records that aren't in the ANN
14/// (R-004.2): it pins `_mnemo.thread`, or restricts `_mnemo.kind` to turns,
15/// essence items or thread links. Such recalls scan exactly instead.
16fn filter_bypasses_ann(f: &Filter) -> bool {
17    let non_ann = |v: &Value| {
18        matches!(
19            v.as_str(),
20            Some(MNEMO_META_KIND_TURN)
21                | Some(MNEMO_META_KIND_ESSENCE)
22                | Some(MNEMO_META_KIND_THREAD_LINK)
23        )
24    };
25    filter_thread_pin(f).is_some()
26        || f.terms.iter().any(|t| match t {
27            FilterTerm::Eq(k, v) => k == MNEMO_META_KIND && non_ann(v),
28            FilterTerm::In(k, vs) => {
29                k == MNEMO_META_KIND && !vs.is_empty() && vs.iter().all(non_ann)
30            }
31            _ => false,
32        })
33}
34
35impl Mnemo {
36    /// Return every live memory (used by tooling and compaction).
37    pub fn memories(&mut self) -> Result<Vec<Memory>> {
38        // FMT-9b: one pass over the vector pages instead of one per record.
39        self.ensure_column()?;
40        let entries: Vec<CatalogEntry> = self
41            .catalog
42            .iter()
43            .filter(|e| !e.deleted)
44            .cloned()
45            .collect();
46        let mut out = Vec::with_capacity(entries.len());
47        for e in &entries {
48            out.push(self.read_memory(e)?);
49        }
50        Ok(out)
51    }
52
53    /// Return the database's **self-describing onboarding memories** — the
54    /// ones tagged `metadata.area = "onboarding"`. This is the engine-level
55    /// surface for the *single-file philosophy*: an agent who receives a
56    /// `.mnemo` file (and its passphrase) can call this to learn what the
57    /// file is, which embedder it expects, the recommended agent id, and any
58    /// other conventions the file's author chose to record — all without
59    /// needing any external documentation.
60    ///
61    /// Ordering: the canonical manifest (tag `metadata.topic = "manifest"`)
62    /// always comes first; everything else follows in `importance` descending,
63    /// then `created_at` ascending for deterministic results.
64    pub fn about(&mut self) -> Result<Vec<Memory>> {
65        // Phase 12.1: drop records that have been superseded by a newer
66        // keyed write. They still live in snapshot history and
67        // `history(key)` — just not here.
68        // R-004.2: read only the onboarding records, from the handle caches.
69        self.ensure_key_caches()?;
70        let ids: Vec<u128> = self
71            .layers
72            .as_ref()
73            .map(|l| l.onboarding.iter().copied().collect())
74            .unwrap_or_default();
75        let mut out: Vec<Memory> = Vec::new();
76        for e in self.live_entries(ids) {
77            let m = self.read_memory(&e)?;
78            if !m.metadata.contains_key(MNEMO_META_SUPERSEDED_BY) && is_onboarding(&m) {
79                out.push(m);
80            }
81        }
82        out.sort_by(|a, b| {
83            let a_manifest = is_manifest(a);
84            let b_manifest = is_manifest(b);
85            // Manifest topic wins first; then importance desc; then created_at asc.
86            b_manifest
87                .cmp(&a_manifest)
88                .then_with(|| b.importance.total_cmp(&a.importance))
89                .then_with(|| a.created_at.cmp(&b.created_at))
90        });
91        Ok(out)
92    }
93
94    /// The project essence for the `about` briefing (Phase 12.7d): the
95    /// [`EssenceScope::Project`] render at the default budget
96    /// ([`ESSENCE_DEFAULT_RENDER_BYTES`]), or `None` when the file has no
97    /// open project-scope item or timeline entry. The CLI and MCP `about`
98    /// append it after the manifest and onboarding memories; [`Mnemo::about`]
99    /// itself keeps returning records.
100    pub fn about_essence(&mut self) -> Result<Option<String>> {
101        let entries = self.essence_entries()?;
102        let mut any = false;
103        for e in &entries {
104            let m = self.read_memory(e)?;
105            let is_project_essence = m.metadata.get(MNEMO_META_KIND).and_then(|v| v.as_str())
106                == Some(MNEMO_META_KIND_ESSENCE)
107                && !m.metadata.contains_key(MNEMO_META_THREAD);
108            if is_project_essence && status_of(&m) != Some(essence_status::RESOLVED) {
109                any = true;
110                break;
111            }
112        }
113        if !any {
114            return Ok(None);
115        }
116        self.essence(EssenceScope::Project, ESSENCE_DEFAULT_RENDER_BYTES)
117            .map(Some)
118    }
119
120    // --- retrieval --------------------------------------------------------
121
122    /// Phase-1 brute-force search: rank live memories by raw similarity only.
123    /// Read-only — does not update access statistics.
124    pub fn search(
125        &mut self,
126        query: &[f32],
127        top_k: usize,
128        metric: Metric,
129    ) -> Result<Vec<(Memory, f32)>> {
130        if query.len() != self.dimensions {
131            return Err(MnemoError::DimensionMismatch {
132                expected: self.dimensions,
133                got: query.len(),
134            });
135        }
136        let now = memory::now_secs();
137        let entries: Vec<CatalogEntry> = self
138            .catalog
139            .iter()
140            .filter(|e| !e.deleted)
141            .cloned()
142            .collect();
143
144        let mut scored: Vec<(Memory, f32)> = Vec::new();
145        for e in &entries {
146            let m = self.read_memory(e)?;
147            if m.is_expired(now) {
148                continue;
149            }
150            let sim = memory::similarity(metric, query, &m.vector);
151            scored.push((m, sim));
152        }
153        scored.sort_by(|a, b| b.1.total_cmp(&a.1));
154        scored.truncate(top_k);
155        Ok(scored)
156    }
157
158    /// Phase-5 multi-signal recall: rank by
159    /// `α·similarity + β·recency + γ·importance + δ·ln(freq)`, with type and
160    /// agent filtering. Updates `accessed_at` / `access_count` on the
161    /// returned memories (persisted on the next `flush`).
162    ///
163    /// When an ANN index has been built ([`Mnemo::build_index`]), recall runs
164    /// the tiered IVF→PQ→rerank pipeline: it scores only the similarity-nearest
165    /// `n_rerank` candidates rather than every memory. Without an index it
166    /// scores every live memory exactly.
167    /// One pass of filter + score for [`Mnemo::recall`]. Factored out of
168    /// `recall` so the outer path can retry with a wider shortlist when
169    /// the type/agent/supersession/TTL filters starve the ANN-narrowed
170    /// result below `top_k` (Phase 12.1 short-results-on-indexed-path
171    /// fix).
172    ///
173    /// * `force_exact = false` → use the ANN index when one exists; fall
174    ///   back to a full scan only if none is built.
175    /// * `force_exact = true` → skip the ANN index and scan every live
176    ///   non-superseded record. Used by the outer path as the last-resort
177    ///   attempt when widening the shortlist would already touch half or
178    ///   more of the live non-superseded set.
179    ///
180    /// Returns an unsorted, un-truncated `Vec<RecallResult>`; the outer
181    /// `recall` sorts and truncates once.
182    pub(super) fn score_once(
183        &mut self,
184        req: &RecallRequest,
185        now: i64,
186        force_exact: bool,
187    ) -> Result<Vec<RecallResult>> {
188        // Candidate set: ANN-narrowed when an index exists and the
189        // caller hasn't forced an exact scan, else everything live.
190        // R-004.2: a filter pinning `_mnemo.thread` scans just that
191        // thread's records (from the handle caches); one that can only
192        // match non-fact kinds skips the ANN, which doesn't hold them.
193        // FMT-9d: keyword matches, normalised by the best one.
194        self.kw = None;
195        // 12.3 step 4: a recall by text uses its text when no keywords
196        // were given (hybrid by default); empty keywords opt out.
197        if let Some(text) = req.keywords_for(self.is_v9()).map(str::to_string) {
198            let scores = self.bm25_scores(&text, req.bm25_k1, req.bm25_b)?;
199            let max = scores.values().copied().fold(0.0f32, f32::max);
200            if max > 0.0 {
201                self.kw = Some(
202                    scores
203                        .into_iter()
204                        .map(|(row, s)| (self.catalog[row].id, s / max))
205                        .collect(),
206                );
207            } else {
208                self.kw = Some(std::collections::HashMap::new());
209            }
210        }
211        if let Some(thread) = filter_thread_pin(&req.filter) {
212            let thread = thread.to_string();
213            let entries = self.thread_entries(&thread)?;
214            return self.score_entries(req, now, &entries);
215        }
216        // Keyword-only: the candidates are the matches.
217        if req.query.is_empty() {
218            let ids: Vec<u128> = self
219                .kw
220                .as_ref()
221                .map_or(Vec::new(), |k| k.keys().copied().collect());
222            let entries: Vec<CatalogEntry> = ids
223                .into_iter()
224                .filter_map(|id| self.index.get(id, &self.catalog))
225                .map(|i| self.catalog[i].clone())
226                .filter(|e| !e.deleted)
227                .collect();
228            return self.score_entries(req, now, &entries);
229        }
230        let force_exact = force_exact || filter_bypasses_ann(&req.filter);
231        let mut entries: Vec<CatalogEntry> = match (&self.ann, force_exact) {
232            (Some(ann), false) => {
233                let n_rerank = self.rerank_for(ann, req);
234                let ids = ann.query(&req.query, req.n_probe, n_rerank);
235                ids.iter()
236                    .filter_map(|&id| self.index.get(id, &self.catalog))
237                    .map(|i| self.catalog[i].clone())
238                    .filter(|e| !e.deleted)
239                    .collect()
240            }
241            _ => self
242                .catalog
243                .iter()
244                .filter(|e| !e.deleted)
245                .cloned()
246                .collect(),
247        };
248        // FMT-9d: an ANN shortlist plus the keyword matches it missed.
249        if let Some(kw) = &self.kw {
250            if entries.len() < self.catalog.len() {
251                let have: std::collections::HashSet<u128> = entries.iter().map(|e| e.id).collect();
252                let extra: Vec<u128> = kw.keys().copied().filter(|id| !have.contains(id)).collect();
253                for id in extra {
254                    if let Some(i) = self.index.get(id, &self.catalog) {
255                        if !self.catalog[i].deleted {
256                            entries.push(self.catalog[i].clone());
257                        }
258                    }
259                }
260            }
261        }
262
263        self.score_entries(req, now, &entries)
264    }
265
266    /// FMT-9d: a candidate's relevance: its vector similarity plus ε times
267    /// its normalised keyword score (keyword-only requests: just the
268    /// keyword score). Returns `(relevance, reported similarity)`.
269    pub(super) fn relevance(&self, req: &RecallRequest, id: u128, sim: f32) -> (f32, f32) {
270        let kw = self
271            .kw
272            .as_ref()
273            .and_then(|k| k.get(&id).copied())
274            .unwrap_or(0.0);
275        if req.query.is_empty() {
276            (kw, kw)
277        } else {
278            (sim + req.effective_keyword_weight() * kw, sim)
279        }
280    }
281
282    /// Score one candidate set for [`Mnemo::score_once`].
283    pub(super) fn score_entries(
284        &mut self,
285        req: &RecallRequest,
286        now: i64,
287        entries: &[CatalogEntry],
288    ) -> Result<Vec<RecallResult>> {
289        // FMT-9b: score v9 candidates from their rows and the fp16 column,
290        // decrypting only what makes `top_k`. A metadata filter needs the
291        // record body, so it takes the general path below.
292        if self.is_v9() && req.filter.is_empty() {
293            return self.score_rows(req, now, entries);
294        }
295        let mut scored: Vec<RecallResult> = Vec::with_capacity(entries.len());
296        for e in entries {
297            // Phase 12.1: drop superseded records.
298            //
299            // Fast path: if the lazy `superseded` set has already been
300            // built by a prior keyed op on this handle, check it before
301            // decrypt — O(1), no AES work. On a fresh read-only handle
302            // it is typically `None`, so we fall through to the slow
303            // path (one `_mnemo.superseded_by` lookup per surviving
304            // record, O(k) over user metadata), and never trigger the
305            // full-file scan that `ensure_key_caches()` would do.
306            if self.superseded.as_ref().is_some_and(|s| s.contains(&e.id)) {
307                continue;
308            }
309            let m = self.read_memory(e)?;
310            if m.metadata.contains_key(MNEMO_META_SUPERSEDED_BY) {
311                continue;
312            }
313            if m.is_expired(now) {
314                continue;
315            }
316            if let Some(types) = &req.memory_types {
317                if !types.contains(&m.memory_type) {
318                    continue;
319                }
320            }
321            if let Some(agent) = &req.agent_id {
322                let visible = m.agent_id == *agent || m.scope == Scope::Shared;
323                if !visible {
324                    continue;
325                }
326            }
327            // Phase 12.6: pre-scoring filter (session_id + metadata
328            // conditions). Cheap when `req.filter.is_empty()`; the
329            // filter struct's `matches` is a short-circuit AND.
330            if !req.filter.is_empty() && !req.filter.matches(&m) {
331                continue;
332            }
333            // Phase 12.7: default-exclude the thread layers from fact
334            // recall: archive turns (12.7a), essence items (12.7b; read
335            // by scope through the render, not by similarity) and
336            // thread-link markers (12.7c; they carry an all-equal
337            // sentinel vector and would surface as junk hits). A caller
338            // that wants them opts in by placing any `_mnemo.*` term in
339            // the filter (equality, `$in`, `$exists`, or a range on
340            // `_mnemo.thread` / `_mnemo.kind` / `_mnemo.seq`).
341            if !req.filter.mentions_mnemo_meta()
342                && matches!(
343                    m.metadata.get(MNEMO_META_KIND).and_then(|v| v.as_str()),
344                    Some(MNEMO_META_KIND_TURN)
345                        | Some(MNEMO_META_KIND_ESSENCE)
346                        | Some(MNEMO_META_KIND_THREAD_LINK)
347                )
348            {
349                continue;
350            }
351            let sim = if req.query.is_empty() {
352                0.0
353            } else {
354                memory::similarity(req.metric, &req.query, &m.vector)
355            };
356            let (rel, sim) = self.relevance(req, e.id, sim);
357            let age_secs = (now - m.created_at) as f32;
358            let score = req
359                .weights
360                .score(rel, age_secs, m.importance, m.access_count);
361            scored.push(RecallResult {
362                memory: m,
363                score,
364                similarity: sim,
365            });
366        }
367        Ok(scored)
368    }
369
370    /// FMT-9b: [`Mnemo::score_entries`] for a v9 file with no metadata
371    /// filter. Every check the general path makes on the decrypted record
372    /// is made on the row instead (supersession, TTL, type, agent
373    /// visibility, the thread-layer kinds), the similarity comes from the
374    /// fp16 column, and the score from the row's `created_at` and
375    /// `importance`. Candidates are then decrypted best-first until `top_k`
376    /// survive; the agent check is repeated on the record, since the row
377    /// only has a hash of the agent id.
378    pub(super) fn score_rows(
379        &mut self,
380        req: &RecallRequest,
381        now: i64,
382        entries: &[CatalogEntry],
383    ) -> Result<Vec<RecallResult>> {
384        self.ensure_column()?;
385        let d = self.dimensions;
386        let q = &req.query;
387        let q_norm = q.iter().map(|x| x * x).sum::<f32>().sqrt();
388        let agent_h = req.agent_id.as_deref().map(|a| fnv1a32(&[a.as_bytes()]));
389        let types: Option<Vec<u8>> = req
390            .memory_types
391            .as_ref()
392            .map(|ts| ts.iter().map(|&t| memory_type_code(t)).collect());
393        let mut cand: Vec<(f32, f32, usize)> = Vec::with_capacity(entries.len());
394        for (pos, e) in entries.iter().enumerate() {
395            let Some(r) = e.v9 else { continue };
396            if r.flags & ROW_SUPERSEDED != 0 {
397                continue;
398            }
399            if self.superseded.as_ref().is_some_and(|s| s.contains(&e.id)) {
400                continue;
401            }
402            if r.flags & ROW_HAS_TTL != 0 && now >= r.expires_at {
403                continue;
404            }
405            if let Some(ts) = &types {
406                if !ts.contains(&r.memory_type) {
407                    continue;
408                }
409            }
410            if let Some(ah) = agent_h {
411                if r.flags & ROW_SHARED == 0 && r.agent_hash != ah {
412                    continue;
413                }
414            }
415            if matches!(
416                r.kind,
417                ROW_KIND_TURN | ROW_KIND_ESSENCE | ROW_KIND_THREAD_LINK
418            ) {
419                continue;
420            }
421            let Some(idx) = self.index.get(e.id, &self.catalog) else {
422                continue;
423            };
424            if !req.query.is_empty()
425                && self.col.resident
426                && idx < self.col.have.len()
427                && !self.col.have[idx]
428                && !self.col.hot.contains_key(&idx)
429            {
430                self.fill_column_page(idx)?;
431            }
432            let sim = if req.query.is_empty() {
433                0.0
434            } else if let Some((h, n)) = self.col.hot.get(&idx) {
435                veccol::similarity_f16(req.metric, q, q_norm, h, *n)
436            } else if self.col.resident && self.col.have.get(idx).copied().unwrap_or(false) {
437                veccol::similarity_f16(
438                    req.metric,
439                    q,
440                    q_norm,
441                    &self.col.data[idx * d..(idx + 1) * d],
442                    self.col.norms[idx],
443                )
444            } else {
445                let (h, n) = self.column_entry(e)?;
446                veccol::similarity_f16(req.metric, q, q_norm, &h, n)
447            };
448            let (rel, sim) = self.relevance(req, e.id, sim);
449            let score = req.weights.score(
450                rel,
451                (now - r.created_at) as f32,
452                r.importance,
453                e.access_count,
454            );
455            cand.push((score, sim, pos));
456        }
457        cand.sort_by(|a, b| b.0.total_cmp(&a.0));
458        let mut out: Vec<RecallResult> = Vec::with_capacity(req.top_k.min(cand.len()));
459        for (score, sim, pos) in cand {
460            if out.len() >= req.top_k {
461                break;
462            }
463            let m = self.read_memory(&entries[pos])?;
464            if let Some(agent) = &req.agent_id {
465                if !(m.agent_id == *agent || m.scope == Scope::Shared) {
466                    continue;
467                }
468            }
469            out.push(RecallResult {
470                memory: m,
471                score,
472                similarity: sim,
473            });
474        }
475        Ok(out)
476    }
477
478    /// 12.3 step 5: the keywords the registered embedder chooses for this
479    /// request ([`crate::Embedder::query_keywords`]): asked only for a recall
480    /// by text with no keywords given, on a v9 file (a v8 file has no
481    /// keyword index and ignores the text).
482    fn embedder_keywords(&self, req: &RecallRequest) -> Option<String> {
483        if req.keywords.is_some() || !self.is_v9() {
484            return None;
485        }
486        let text = req.text.as_deref().filter(|t| !t.trim().is_empty())?;
487        self.embedder.as_ref()?.query_keywords(text)
488    }
489
490    /// Phase-5 multi-signal recall under the v0.7.0 scoring-v2 formula
491    /// (see [`crate::ScoreWeights`]). Thin wrapper over
492    /// [`Mnemo::recall_budgeted`] that drops the `truncated` flag;
493    /// use the budgeted form if you need to know whether
494    /// [`RecallRequest::max_bytes`] cut anything.
495    pub fn recall(&mut self, req: &RecallRequest) -> Result<Vec<RecallResult>> {
496        Ok(self.recall_budgeted(req)?.hits)
497    }
498
499    /// Phase 12.8 budgeted recall: scoring v2 (see [`crate::ScoreWeights`])
500    /// with an optional UTF-8-content byte cap. Ranks by
501    /// `sim + max(sim, 0) · (β·recency + γ·(importance − 0.5) + δ·tanh(uses/5))`,
502    /// with type / agent / supersession / TTL filters and the 12.6
503    /// `Filter` applied before the scorer. Updates `accessed_at` /
504    /// `access_count` on the returned memories (persisted on the next
505    /// `flush`).
506    ///
507    /// When an ANN index has been built ([`Mnemo::build_index`]),
508    /// recall runs the tiered IVF→PQ→rerank pipeline. If the filters
509    /// (type / agent / supersession / TTL / 12.6) reduce the ANN
510    /// shortlist below `top_k`, Phase 12.1's short-results-on-indexed-
511    /// path fix kicks in: the query is retried with `n_probe` and
512    /// `n_rerank` doubled, and if that would already touch half or
513    /// more of the live non-superseded records, the ANN pass is
514    /// skipped for an exact scan. Without an index, recall scores
515    /// every live non-superseded memory.
516    ///
517    /// Phase 12.8: after `top_k` is applied, if
518    /// [`RecallRequest::max_bytes`] is set, hits are dropped in rank
519    /// order once the running sum of `content` UTF-8 bytes would
520    /// exceed the budget. The top-1 hit is always kept even if it
521    /// alone exceeds the budget. [`RecallResponse::truncated`] is
522    /// `true` iff at least one hit was dropped by the budget.
523    pub fn recall_budgeted(&mut self, req: &RecallRequest) -> Result<RecallResponse> {
524        // 12.3 step 5 (v0.15): the registered embedder may name the keywords
525        // for a recall by text (the built-in's identifier-aware recall).
526        let chosen;
527        let req = match self.embedder_keywords(req) {
528            Some(k) => {
529                chosen = req.clone().keywords(k);
530                &chosen
531            }
532            None => req,
533        };
534        // FMT-9d: keyword recall needs a v9 file's BM25 index; a
535        // keyword-only request has no vector.
536        if req
537            .keywords
538            .as_deref()
539            .is_some_and(|k| !k.trim().is_empty())
540            && !self.is_v9()
541        {
542            return Err(MnemoError::Invalid(
543                "keyword recall (keywords) needs a v9 file; run `mnemo compact` to upgrade".into(),
544            ));
545        }
546        let keyword_only = req.query.is_empty() && req.keywords.is_some();
547        if !keyword_only && req.query.len() != self.dimensions {
548            return Err(MnemoError::DimensionMismatch {
549                expected: self.dimensions,
550                got: req.query.len(),
551            });
552        }
553        // PERF-1 step 3: the ANN index loads on the first recall.
554        self.ensure_ann()?;
555        // Access-tracking bumps `accessed_at` / `access_count` in the
556        // catalog, which is a mutation. On a read-only handle the caller
557        // must pass `track_access(false)` (via CLI `--no-track`).
558        // 12.4: a shared read (read-only for the call, with a delta) keeps
559        // the bumps for the handle's next commit instead.
560        if self.read_only && req.track_access && self.access_delta.is_none() {
561            return Err(MnemoError::ReadOnly);
562        }
563        // Phase 12.1 **fix** (lane A v0.8.0 REVIEW): do NOT call
564        // `ensure_key_caches()` here. A fresh read-only handle that
565        // only ever recalls would otherwise pay a full-file decrypt
566        // on its first query to build the lazy superseded set. Instead
567        // `score_once` checks `_mnemo.superseded_by` per-record after
568        // decrypt (slow path) and consults the set only when it has
569        // already been built by a prior keyed op on this handle (fast
570        // path). `live_non_superseded` is not knowable without a
571        // decrypt pass either, so we approximate by `live_count`; the
572        // exact-scan gate uses this as a conservative upper bound,
573        // which errs toward widening (cheaper) rather than skipping
574        // straight to a full scan.
575        let live_count = self.catalog.iter().filter(|e| !e.deleted).count();
576        let live_non_superseded = live_count;
577        let now = memory::now_secs();
578
579        // Scoring v2 (shipped v0.7.0). Single-pass filter + score:
580        //   * `age_secs = now - m.created_at`, so a recall doesn't bump
581        //     its own results' recency on later queries.
582        //   * `ScoreWeights::score` applies the similarity-gated,
583        //     importance-centered, saturating-usage formula documented
584        //     on `ScoreWeights`.
585        //
586        // Phase 12.1 + 12.6 short-results-on-indexed-path fix: when the
587        // ANN shortlist is narrower than the live count, the filters
588        // (type / agent / supersession / TTL / 12.6) can reduce the
589        // result below `top_k`. If that happens, re-query the index
590        // with `n_probe` / `n_rerank` doubled from their *effective*
591        // base; if that would already cover ≥50% of the live set,
592        // skip the index and do an exact scan.
593        //
594        // Lane A v0.8.0 REVIEW fix: widen from
595        // `IvfPqIndex::effective_defaults()` when the caller didn't
596        // pin the knobs. The pre-fix code only doubled when `req.n_*`
597        // was already `Some(_)`, which skipped the widen step for the
598        // default (unpinned) recall path and jumped straight to an
599        // exact scan on moderately selective filters.
600        let mut scored = self.score_once(req, now, false)?;
601        let mut used_exact_scan = self.ann.is_none() || filter_bypasses_ann(&req.filter);
602        if !used_exact_scan && scored.len() < req.top_k && live_non_superseded > req.top_k {
603            if let Some(ann) = &self.ann {
604                let (default_probe, default_rerank) = ann.effective_defaults();
605                let base_probe = req.n_probe.unwrap_or(default_probe);
606                let base_rerank = self.rerank_for(ann, req).unwrap_or(default_rerank);
607                let widen_probe = base_probe.saturating_mul(2);
608                let widen_rerank = base_rerank.saturating_mul(2);
609                // Attempt 2: widen once, 2× from the effective base.
610                // Only worth another ANN pass if either knob actually
611                // grew (saturating_mul on usize::MAX would cap).
612                if widen_probe > base_probe || widen_rerank > base_rerank {
613                    let widened = RecallRequest {
614                        n_probe: Some(widen_probe),
615                        n_rerank: Some(widen_rerank),
616                        ..req.clone()
617                    };
618                    scored = self.score_once(&widened, now, false)?;
619                }
620                // Attempt 3: if still short after widening, pay the
621                // exact scan — it's the only path that guarantees
622                // `top_k` correct hits when the filter is more
623                // selective than `widen_rerank / live_count`. Before
624                // the fix this was gated on `widened_rerank * 2 >=
625                // live_non_superseded`, which silently returned fewer
626                // than `top_k` hits on selective filters that fell in
627                // the gap. Exact scan is bounded (one decrypt per
628                // live record); the previous widen is an optimization.
629                if scored.len() < req.top_k {
630                    scored = self.score_once(req, now, true)?;
631                    used_exact_scan = true;
632                }
633            }
634        }
635        scored.sort_by(|a, b| b.score.total_cmp(&a.score));
636        scored.truncate(req.top_k);
637
638        // Update access statistics for everything we surfaced — but only
639        // mutate the catalog entry, not the full record on disk. Pre-v5
640        // this loop called `self.put(r.memory.clone())`, which serialized
641        // and rewrote every result (vector included) to fresh pages,
642        // turning a top-K recall into K full record rewrites. Now the
643        // catalog is the source of truth for these two fields and the
644        // record body stays untouched until the next real edit.
645        if req.track_access && self.read_only {
646            if let Some(delta) = self.access_delta.as_mut() {
647                for r in &scored {
648                    delta.memory_hit(r.memory.id.0, now);
649                }
650            }
651        } else if req.track_access {
652            for r in &mut scored {
653                if let Some(idx) = self.index.get(r.memory.id.0, &self.catalog) {
654                    self.touch(idx);
655                    let entry = &mut self.catalog[idx];
656                    entry.accessed_at = now;
657                    entry.access_count = entry.access_count.saturating_add(1);
658                    // Propagate the just-updated values onto the returned
659                    // Memory so the caller sees the post-recall state.
660                    r.memory.accessed_at = entry.accessed_at;
661                    r.memory.access_count = entry.access_count;
662                }
663            }
664            // Mark the catalog dirty so the next flush persists these
665            // bumps. The records themselves are not dirty.
666            if !scored.is_empty() {
667                self.dirty_catalog = true;
668            }
669        }
670
671        // Phase 12.8: apply the `max_bytes` budget *after* tracking has
672        // seen the full top-k list. Access stats record what the scorer
673        // chose; the byte budget shouldn't suppress the signal.
674        let truncated = if let Some(budget) = req.max_bytes {
675            let orig_len = scored.len();
676            let mut running = 0usize;
677            let mut cut_at: Option<usize> = None;
678            for (i, r) in scored.iter().enumerate() {
679                let w = r.memory.content.len();
680                if i == 0 {
681                    // Always keep the top hit, even if it's over budget
682                    // on its own. Avoid "I asked for top_k results and
683                    // got zero" when a single memory exceeds the cap.
684                    running += w;
685                    continue;
686                }
687                if running.saturating_add(w) > budget {
688                    cut_at = Some(i);
689                    break;
690                }
691                running += w;
692            }
693            if let Some(idx) = cut_at {
694                scored.truncate(idx);
695                scored.len() < orig_len
696            } else {
697                false
698            }
699        } else {
700            false
701        };
702
703        self.kw = None;
704        Ok(RecallResponse {
705            hits: scored,
706            truncated,
707            used_exact_scan,
708        })
709    }
710
711    // --- approximate index ------------------------------------------------
712}