second-brain-core 0.9.0

Core library for second-brain: KuzuDB graph storage, BGE embeddings, and weighted query engine
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
pub mod blend;
mod onnx_rerank;
pub mod rerank;
pub mod rrf;

pub use rerank::{RerankScorer, RerankTimeoutError, Reranker};

use std::collections::HashMap;

use anyhow::Result;
use uuid::Uuid;

use crate::index::Indexes;
use crate::query::{QueryRequest, QueryResult};
use crate::schema::Memory;
use crate::sqlite_store::SqliteStore;
use crate::store::Store;
use blend::BlendWeights;

/// Ceiling on the widened BM25 fetch a scoped query may ask for.
const SCOPED_LEXICAL_MAX_K: usize = 5000;

/// Dense and lexical candidate lists, each best-first as (memory id, score).
#[derive(Debug, Clone, Default)]
pub struct Candidates {
    pub dense: Vec<(Uuid, f32)>,
    pub lexical: Vec<(Uuid, f32)>,
    /// Set when generation scanned the caller's entire scope, so this pool is
    /// every memory the filter admits rather than a relevance-ranked slice of
    /// the store.
    pub scope_exhausted: bool,
}

impl Candidates {
    pub fn new(dense: Vec<(Uuid, f32)>, lexical: Vec<(Uuid, f32)>) -> Self {
        Self {
            dense,
            lexical,
            scope_exhausted: false,
        }
    }
}

#[derive(Debug, Clone, Copy)]
pub struct RetrievalTunables {
    pub dense_k: usize,
    pub lexical_k: usize,
    pub fuse_top: usize,
    pub rerank_gate: f32,
    pub cosine_gate: f32,
    /// Membership floor, in cosine, for a scope generation scanned whole. It
    /// sits under `cosine_gate` because naming a scope is the caller
    /// asserting the haystack, so a weak real match must still come back.
    /// Calibrated on the gold set (`sb-recall-eval floor-sweep`,
    /// evals/exhausted-floor.md) as the highest floor that keeps 99% of gold
    /// memories answerable from their own project. With the BGE query
    /// instruction applied, the best match in an unrelated project has a
    /// median cosine of 0.65, so this floor rarely empties an unrelated
    /// scope; it only drops noise.
    pub exhausted_cosine_gate: f32,
    pub weights: BlendWeights,
}

impl Default for RetrievalTunables {
    fn default() -> Self {
        Self {
            dense_k: 150,
            lexical_k: 150,
            fuse_top: 100,
            rerank_gate: 0.30,
            cosine_gate: blend::MIN_SIMILARITY,
            exhausted_cosine_gate: blend::EXHAUSTED_MIN_SIMILARITY,
            weights: BlendWeights::default(),
        }
    }
}

#[derive(Default)]
pub struct Retriever {
    pub tunables: RetrievalTunables,
}

pub fn cosine(a: &[f32], b: &[f32]) -> f32 {
    if a.len() != b.len() || a.is_empty() {
        return 0.0;
    }
    let dot: f32 = a.iter().zip(b).map(|(x, y)| x * y).sum();
    let na: f32 = a.iter().map(|x| x * x).sum::<f32>().sqrt();
    let nb: f32 = b.iter().map(|x| x * x).sum::<f32>().sqrt();
    if na == 0.0 || nb == 0.0 {
        return 0.0;
    }
    dot / (na * nb)
}

impl Retriever {
    /// Index-side candidate generation: dense and lexical top-k, both
    /// best-first. Separated from rank() so the eval harness can feed rank()
    /// through its CachingStore while candidates come from real indexes.
    pub fn candidates(
        &self,
        indexes: &Indexes,
        store: &SqliteStore,
        request: &QueryRequest,
    ) -> Result<Candidates> {
        let source = request.filters.source.as_deref();
        let memory_type = request.filters.memory_type;
        let project_path = request.filters.project_path.as_deref();
        if source.is_some() || memory_type.is_some() || project_path.is_some() {
            return self.scoped_candidates(
                indexes,
                store,
                request,
                source,
                memory_type,
                project_path,
            );
        }
        let dense = indexes.vector_search(store, &request.embedding, self.tunables.dense_k)?;
        let lexical = indexes.bm25_search(&request.text, self.tunables.lexical_k)?;
        Ok(Candidates::new(dense, lexical))
    }

    /// Candidate generation for a query scoped by source, type, and/or
    /// project.
    ///
    /// The unfiltered path picks its shortlist before the filter is known, so
    /// a memory outside the global top-k cannot be reached however narrow the
    /// scope is; the scope must therefore constrain generation rather than
    /// trim its output. Dense becomes an exhaustive cosine scan of the
    /// matching subset, which is affordable because the store already
    /// brute-forces `vector_search` over the whole table, making a subset scan
    /// strictly cheaper. Lexical over-fetches and intersects instead, because
    /// the tantivy schema carries only body text and cannot filter on source
    /// or project.
    #[allow(clippy::too_many_arguments)]
    fn scoped_candidates(
        &self,
        indexes: &Indexes,
        store: &SqliteStore,
        request: &QueryRequest,
        source: Option<&str>,
        memory_type: Option<crate::schema::MemoryType>,
        project_path: Option<&str>,
    ) -> Result<Candidates> {
        let dense: Vec<(Uuid, f32)> = store
            .filtered_vector_search(
                &request.embedding,
                source,
                memory_type,
                project_path,
                self.tunables.dense_k,
            )?
            .into_iter()
            .map(|(memory, similarity)| (memory.id, similarity))
            .collect();

        // A short list means the scan ran out of scope rather than out of room,
        // so dense already holds every memory the filter admits and no lexical
        // sweep can add one. This is the common case for a narrow scope, and it
        // keeps the scope-wide id read below off that path entirely.
        if dense.len() < self.tunables.dense_k {
            return Ok(Candidates {
                dense,
                lexical: Vec::new(),
                scope_exhausted: true,
            });
        }

        // Widen the sweep by the scope's inverse selectivity: a scope holding
        // one row in a thousand needs a proportionally deeper BM25 list before
        // any in-scope document appears at all. The cap bounds the worst case,
        // and a scope too narrow to survive it loses nothing, because the dense
        // side of this pair already scanned it exhaustively.
        let scoped = store
            .scoped_count(source, memory_type, project_path)?
            .max(1);
        let total = <SqliteStore as Store>::memory_count(store)?.max(scoped);
        let widen = total.div_ceil(scoped);
        let k = self
            .tunables
            .lexical_k
            .saturating_mul(widen)
            .min(SCOPED_LEXICAL_MAX_K);

        // Membership is resolved against the fetched hits, never by reading the
        // scope out, so this stays bounded by k however large the scope is.
        let hits = indexes.bm25_search(&request.text, k)?;
        let hit_ids: Vec<Uuid> = hits.iter().map(|(id, _)| *id).collect();
        let in_scope = store.retain_in_scope(&hit_ids, source, memory_type, project_path)?;
        let lexical = hits
            .into_iter()
            .filter(|(id, _)| in_scope.contains(id))
            .take(self.tunables.lexical_k)
            .collect();
        Ok(Candidates::new(dense, lexical))
    }

    /// Fuse, gate, and blend pre-computed candidates. With a scorer the
    /// primary term is its 0..1 cross-encoder score gated at rerank_gate;
    /// without one it is cosine similarity gated at the legacy cosine_gate,
    /// recomputed from stored embeddings for candidates that arrived through
    /// the lexical list only.
    pub fn rank<S: Store + ?Sized>(
        &self,
        store: &S,
        request: &QueryRequest,
        pool: &Candidates,
        reranker: Option<&dyn RerankScorer>,
    ) -> Result<Vec<QueryResult>> {
        let dense_ids: Vec<Uuid> = pool.dense.iter().map(|(id, _)| *id).collect();
        let lexical_ids: Vec<Uuid> = pool.lexical.iter().map(|(id, _)| *id).collect();
        let fused = rrf::fuse(
            &[&dense_ids, &lexical_ids],
            rrf::RRF_K,
            self.tunables.fuse_top,
        );
        let dense_sim: HashMap<Uuid, f32> = pool.dense.iter().copied().collect();

        let mut candidates: Vec<Memory> = Vec::new();
        for (id, _) in &fused {
            let Some(memory) = store.get_memory_with_embedding(*id)? else {
                continue;
            };
            // The indexes lag the store by an outbox drain, so a candidate
            // can be a row recall must no longer show.
            if memory.tier != crate::schema::Tier::Hot || memory.superseded_by.is_some() {
                continue;
            }
            if let Some(min_conf) = request.filters.min_confidence
                && memory.confidence < min_conf
            {
                continue;
            }
            if let Some(ref source) = request.filters.source
                && !store.source_admits(&memory, source)?
            {
                continue;
            }
            if let Some(ref mt) = request.filters.memory_type
                && &memory.memory_type != mt
            {
                continue;
            }
            candidates.push(memory);
        }

        let cosine_primaries = |cands: &[Memory]| -> Vec<f32> {
            cands
                .iter()
                .map(|m| {
                    dense_sim
                        .get(&m.id)
                        .copied()
                        .unwrap_or_else(|| cosine(&request.embedding, &m.embedding))
                })
                .collect()
        };

        // A saturated rerank pool, or an overloaded remote scorer, must
        // degrade this query, not fail it: the caller gets the non-reranked
        // hybrid answer (still RRF-fused, still graph/recency blended)
        // instead of an error, the same way the recall route already
        // degrades to the legacy engine on other hybrid-path failures.
        let (primaries, reranked) = match reranker {
            Some(r) => {
                let docs: Vec<&str> = candidates.iter().map(|m| m.content.as_str()).collect();
                match r.rerank(&request.text, &docs) {
                    // Zipping a short score list would silently drop the
                    // unscored tail of the candidates.
                    Ok(scores) if scores.len() != docs.len() => anyhow::bail!(
                        "rerank scorer returned {} scores for {} documents",
                        scores.len(),
                        docs.len()
                    ),
                    Ok(scores) => (scores, true),
                    Err(e) if e.downcast_ref::<RerankTimeoutError>().is_some() => {
                        tracing::warn!(
                            "rerank unavailable ({e}); falling back to the \
                             non-reranked hybrid path for this query"
                        );
                        (cosine_primaries(&candidates), false)
                    }
                    Err(e) => return Err(e),
                }
            }
            None => (cosine_primaries(&candidates), false),
        };
        // An exhausted scope is every memory the caller's filter admits, so a
        // gate calibrated for slicing a whole-store ranking would blank the
        // answer to a question that named its own haystack; a cross-encoder
        // is no help there either, because it scores a weak real match
        // ("job title" against a memory stating the job) below outright
        // nonsense. Membership therefore falls back to a relaxed cosine floor
        // on that path, while the reranked primary still orders the answer.
        let cosines = cosine_primaries(&candidates);
        let admitted = |i: usize, primary: f32| -> bool {
            if pool.scope_exhausted {
                cosines[i] >= self.tunables.exhausted_cosine_gate
            } else if reranked {
                primary >= self.tunables.rerank_gate
            } else {
                primary >= self.tunables.cosine_gate
            }
        };

        let query_entity_ids = blend::resolve_query_entities(store, &request.filters.entity_names);

        // Blend over at most limit*3 candidates ranked by the primary term,
        // mirroring the legacy engine's vector_search(limit*3) pool. Graph and
        // recency carry enough weight that blending a wider fused pool lets
        // recent, well-connected memories displace strong matches wholesale.
        let mut shortlist: Vec<(usize, Memory, f32)> = candidates
            .into_iter()
            .zip(primaries)
            .enumerate()
            .map(|(i, (memory, primary))| (i, memory, primary))
            .collect();
        shortlist.sort_by(|a, b| b.2.partial_cmp(&a.2).unwrap_or(std::cmp::Ordering::Equal));
        shortlist.truncate(request.limit * 3);

        let mut scored: Vec<QueryResult> = Vec::new();
        for (i, memory, primary) in shortlist {
            // Membership is gated on the primary term alone, exactly like the
            // legacy path: graph and recency only re-rank.
            if !admitted(i, primary) {
                continue;
            }
            let recency = blend::compute_recency(&memory);
            let graph =
                blend::compute_graph_relevance(store, &memory, &query_entity_ids).unwrap_or(0.0);
            let score = blend::blend(primary, graph, recency, self.tunables.weights);
            let score = blend::apply_project_affinity(
                score,
                &memory,
                request.filters.project_path.as_deref(),
            );
            scored.push(QueryResult {
                memory,
                score,
                path: Vec::new(),
            });
        }

        scored.sort_by(|a, b| {
            b.score
                .partial_cmp(&a.score)
                .unwrap_or(std::cmp::Ordering::Equal)
        });
        scored.truncate(request.limit);
        Ok(scored)
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::query::QueryFilters;
    use crate::schema::{Conversation, Entity, MemoryType, Relation};
    use crate::store::Store;
    use chrono::Utc;

    struct StubStore {
        memories: Vec<Memory>,
    }

    impl Store for StubStore {
        fn store_memory(&self, _: &Memory) -> Result<()> {
            unimplemented!()
        }
        fn get_memory(&self, id: Uuid) -> Result<Option<Memory>> {
            Ok(self.memories.iter().find(|m| m.id == id).cloned())
        }
        fn get_memory_with_embedding(&self, id: Uuid) -> Result<Option<Memory>> {
            self.get_memory(id)
        }
        fn delete_memory(&self, _: Uuid) -> Result<()> {
            unimplemented!()
        }
        fn store_entity(&self, _: &Entity) -> Result<()> {
            unimplemented!()
        }
        fn get_entity(&self, _: Uuid) -> Result<Option<Entity>> {
            Ok(None)
        }
        fn find_entity_by_name(&self, _: &str) -> Result<Option<Entity>> {
            Ok(None)
        }
        fn store_conversation(&self, _: &Conversation) -> Result<()> {
            unimplemented!()
        }
        fn store_relation(&self, _: &Relation) -> Result<()> {
            unimplemented!()
        }
        fn get_relations(
            &self,
            _: Uuid,
            _: Option<crate::schema::RelationType>,
        ) -> Result<Vec<Relation>> {
            Ok(Vec::new())
        }
        fn vector_search(&self, _: &[f32], _: usize) -> Result<Vec<(Memory, f32)>> {
            unimplemented!()
        }
        fn filtered_vector_search(
            &self,
            embedding: &[f32],
            source: Option<&str>,
            memory_type: Option<MemoryType>,
            project_path: Option<&str>,
            limit: usize,
        ) -> Result<Vec<(Memory, f32)>> {
            let mut scored: Vec<(Memory, f32)> = self
                .memories
                .iter()
                .filter(|m| source.is_none_or(|s| m.source == s))
                .filter(|m| memory_type.is_none_or(|t| m.memory_type == t))
                .filter(|m| project_path.is_none_or(|p| m.project_path.as_deref() == Some(p)))
                .map(|m| (m.clone(), cosine(embedding, &m.embedding)))
                .collect();
            scored.sort_by(|a, b| b.1.partial_cmp(&a.1).unwrap_or(std::cmp::Ordering::Equal));
            scored.truncate(limit);
            Ok(scored)
        }
        fn traverse(&self, _: Uuid, _: u32) -> Result<Vec<(Memory, Vec<Relation>)>> {
            unimplemented!()
        }
        fn memories_by_source(&self, _: &str) -> Result<Vec<Memory>> {
            unimplemented!()
        }
        fn memories_by_type(&self, _: MemoryType) -> Result<Vec<Memory>> {
            unimplemented!()
        }
        fn update_memory(&self, _: &Memory) -> Result<()> {
            unimplemented!()
        }
        fn record_access(&self, _: &Memory) -> Result<()> {
            unimplemented!()
        }
        fn bm25_search(&self, _: &str, _: usize) -> Result<Vec<Memory>> {
            unimplemented!()
        }
        fn memory_count(&self) -> Result<usize> {
            unimplemented!()
        }
        fn all_memory_ids(&self) -> Result<Vec<Uuid>> {
            unimplemented!()
        }
        fn all_relations(&self) -> Result<Vec<Relation>> {
            unimplemented!()
        }
    }

    fn memory(content: &str, embedding: Vec<f32>) -> Memory {
        let mut m = Memory::new(
            content.to_string(),
            MemoryType::Semantic,
            "test".to_string(),
            String::new(),
        );
        m.embedding = embedding;
        m
    }

    fn request(embedding: Vec<f32>) -> QueryRequest {
        QueryRequest {
            text: "query".to_string(),
            embedding,
            limit: 10,
            filters: QueryFilters::default(),
        }
    }

    #[test]
    fn candidate_on_both_lists_outranks_dense_only_at_equal_similarity() {
        let both = memory("on both lists", vec![1.0, 0.0]);
        let dense_only = memory("dense only", vec![1.0, 0.0]);
        let store = StubStore {
            memories: vec![both.clone(), dense_only.clone()],
        };
        let retriever = Retriever::default();

        let dense = vec![(dense_only.id, 0.9), (both.id, 0.9)];
        let lexical = vec![(both.id, 5.0)];
        let results = store_rank(
            &retriever,
            &store,
            &request(vec![1.0, 0.0]),
            &dense,
            &lexical,
        );

        assert_eq!(results[0].memory.id, both.id);
    }

    #[test]
    fn low_cosine_candidate_is_gated_out_on_the_no_rerank_path() {
        let strong = memory("strong match", vec![1.0, 0.0]);
        let weak = memory("weak match", vec![1.0, 0.0]);
        let store = StubStore {
            memories: vec![strong.clone(), weak.clone()],
        };
        let retriever = Retriever::default();

        let dense = vec![(strong.id, 0.92), (weak.id, 0.45)];
        let results = store_rank(&retriever, &store, &request(vec![1.0, 0.0]), &dense, &[]);

        assert_eq!(results.len(), 1);
        assert_eq!(results[0].memory.id, strong.id);
    }

    #[test]
    fn lexical_only_candidate_gets_cosine_from_stored_embedding() {
        // Arrives only via BM25; its stored embedding matches the query
        // exactly, so cosine = 1.0 clears the 0.59 gate.
        let lexical_hit = memory("lexical only", vec![0.6, 0.8]);
        let store = StubStore {
            memories: vec![lexical_hit.clone()],
        };
        let retriever = Retriever::default();

        let lexical = vec![(lexical_hit.id, 3.0)];
        let results = store_rank(&retriever, &store, &request(vec![0.6, 0.8]), &[], &lexical);

        assert_eq!(results.len(), 1);
    }

    #[test]
    fn blend_only_reorders_the_primary_shortlist() {
        // Legacy recall blended graph/recency over at most limit*3 candidates
        // ranked by similarity; a wider pool must not let a fresh but weakly
        // similar memory displace strong matches, so candidates outside the
        // top limit*3 by primary are excluded before blending.
        let old = |content: &str, sim: f32| {
            let mut m = memory(content, vec![1.0, 0.0]);
            m.created_at = Utc::now() - chrono::Duration::days(200);
            m.last_accessed = m.created_at;
            (m, sim)
        };
        let (a, a_sim) = old("strong a", 0.95);
        let (b, b_sim) = old("strong b", 0.94);
        let (c, c_sim) = old("strong c", 0.93);
        let fresh = memory("fresh diluter", vec![1.0, 0.0]);
        let store = StubStore {
            memories: vec![a.clone(), b.clone(), c.clone(), fresh.clone()],
        };
        let retriever = Retriever::default();

        let dense = vec![
            (a.id, a_sim),
            (b.id, b_sim),
            (c.id, c_sim),
            (fresh.id, 0.60),
        ];
        let mut req = request(vec![1.0, 0.0]);
        req.limit = 1;
        let results = retriever
            .rank(&store, &req, &Candidates::new(dense, Vec::new()), None)
            .unwrap();

        assert_eq!(results[0].memory.id, a.id);
    }

    #[test]
    fn source_filter_still_applies() {
        let mut filtered = memory("wrong source", vec![1.0, 0.0]);
        filtered.source = "other".to_string();
        let kept = memory("right source", vec![1.0, 0.0]);
        let store = StubStore {
            memories: vec![filtered.clone(), kept.clone()],
        };
        let retriever = Retriever::default();

        let mut req = request(vec![1.0, 0.0]);
        req.filters.source = Some("test".to_string());
        let dense = vec![(filtered.id, 0.9), (kept.id, 0.9)];
        let results = store_rank(&retriever, &store, &req, &dense, &[]);

        assert_eq!(results.len(), 1);
        assert_eq!(results[0].memory.id, kept.id);
    }

    #[test]
    fn archived_and_superseded_candidates_are_dropped_by_rank() {
        // The outbox drains every few seconds, so a candidate list can name a
        // row the store has since retired or superseded.
        let live = memory("live", vec![1.0, 0.0]);
        let mut archived = memory("archived", vec![1.0, 0.0]);
        archived.tier = crate::schema::Tier::Archived;
        let mut superseded = memory("superseded", vec![1.0, 0.0]);
        superseded.superseded_by = Some(live.id);
        let store = StubStore {
            memories: vec![live.clone(), archived.clone(), superseded.clone()],
        };
        let retriever = Retriever::default();

        let dense = vec![(archived.id, 0.99), (superseded.id, 0.98), (live.id, 0.9)];
        let results = store_rank(&retriever, &store, &request(vec![1.0, 0.0]), &dense, &[]);

        let ids: Vec<Uuid> = results.iter().map(|r| r.memory.id).collect();
        assert_eq!(ids, vec![live.id]);
    }

    #[test]
    fn an_exhausted_scope_keeps_a_similarity_floor() {
        // A cosine of 0.3 is noise in any scope; one just over the floor is
        // a real but weak match.
        let w = blend::EXHAUSTED_MIN_SIMILARITY + 0.005;
        let weak = memory("weak match", vec![w, (1.0f32 - w * w).sqrt()]);
        let noise = memory("noise", vec![0.3, (1.0f32 - 0.09).sqrt()]);
        let store = StubStore {
            memories: vec![weak.clone(), noise.clone()],
        };
        let retriever = Retriever::default();
        let pool = Candidates {
            dense: vec![(weak.id, w), (noise.id, 0.3)],
            lexical: Vec::new(),
            scope_exhausted: true,
        };

        let results = retriever
            .rank(&store, &request(vec![1.0, 0.0]), &pool, None)
            .unwrap();

        let ids: Vec<Uuid> = results.iter().map(|r| r.memory.id).collect();
        assert_eq!(ids, vec![weak.id]);
    }

    #[test]
    fn an_exhausted_scope_gates_on_cosine_even_when_reranked() {
        struct LowScorer;
        impl RerankScorer for LowScorer {
            fn rerank(&self, _: &str, docs: &[&str]) -> Result<Vec<f32>> {
                Ok(docs.iter().map(|_| 0.02).collect())
            }
        }
        let w = blend::EXHAUSTED_MIN_SIMILARITY + 0.005;
        let weak = memory("weak match", vec![w, (1.0f32 - w * w).sqrt()]);
        let noise = memory("noise", vec![0.3, (1.0f32 - 0.09).sqrt()]);
        let store = StubStore {
            memories: vec![weak.clone(), noise.clone()],
        };
        let retriever = Retriever::default();
        let pool = Candidates {
            dense: vec![(weak.id, w), (noise.id, 0.3)],
            lexical: Vec::new(),
            scope_exhausted: true,
        };

        let results = retriever
            .rank(&store, &request(vec![1.0, 0.0]), &pool, Some(&LowScorer))
            .unwrap();

        let ids: Vec<Uuid> = results.iter().map(|r| r.memory.id).collect();
        assert_eq!(ids, vec![weak.id]);
    }

    fn store_rank(
        retriever: &Retriever,
        store: &StubStore,
        request: &QueryRequest,
        dense: &[(Uuid, f32)],
        lexical: &[(Uuid, f32)],
    ) -> Vec<QueryResult> {
        retriever
            .rank(
                store,
                request,
                &Candidates::new(dense.to_vec(), lexical.to_vec()),
                None,
            )
            .unwrap()
    }
}