second-brain-core 0.11.0

Core library for second-brain: SQLite storage with vector and lexical indexes, BGE embeddings, and hybrid retrieval
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
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
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,
    /// For a memory one of whose chunks hit the query: (chunk ord, chunk
    /// cosine) of its best chunk. Rerank scores the window around that ord.
    pub best_chunk: BestChunks,
}

/// Memory id to (chunk ord, chunk cosine) of its best-matching chunk.
pub type BestChunks = HashMap<Uuid, (usize, f32)>;

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

/// Folds chunk hits into the dense list: a memory scores the better of its
/// own vector and its best chunk, and the list is re-sorted and cut to `k`.
/// Without chunk hits the list comes back untouched, so a store with no
/// chunks ranks exactly as before chunks existed.
fn merge_chunk_hits(
    dense: Vec<(Uuid, f32)>,
    chunk_hits: Vec<(Uuid, f32, usize)>,
    k: usize,
) -> (Vec<(Uuid, f32)>, BestChunks) {
    if chunk_hits.is_empty() {
        return (dense, HashMap::new());
    }
    let best_chunk: BestChunks = chunk_hits
        .iter()
        .map(|(id, similarity, ord)| (*id, (*ord, *similarity)))
        .collect();
    let mut merged = dense;
    let listed: std::collections::HashSet<Uuid> = merged.iter().map(|(id, _)| *id).collect();
    for (id, similarity) in merged.iter_mut() {
        if let Some((_, chunk)) = best_chunk.get(id) {
            *similarity = similarity.max(*chunk);
        }
    }
    merged.extend(
        chunk_hits
            .iter()
            .filter(|(id, _, _)| !listed.contains(id))
            .map(|(id, similarity, _)| (*id, *similarity)),
    );
    merged.sort_by(|a, b| b.1.partial_cmp(&a.1).unwrap_or(std::cmp::Ordering::Equal));
    merged.truncate(k);
    (merged, best_chunk)
}

/// `chunk_search` keeps one hit per memory, so it is asked for this many
/// times `dense_k` chunk hits to leave room for memories with several.
const CHUNK_K_FACTOR: usize = 3;

#[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,
    /// How many of each candidate list's top entries always enter the fused
    /// list, whatever RRF makes of them. 0 is plain RRF.
    pub fusion_floor: usize,
    /// Use sentence chunks: as dense candidates (a memory scores its best
    /// chunk when that beats its own vector), as the cosine primary, and as a
    /// rerank window scored beside the whole memory. False ranks exactly as
    /// before chunks existed.
    pub chunk_rerank: bool,
    /// Also rerank the whole memory beside its chunk window and keep the
    /// better score. False scores a chunked memory on its window alone, which
    /// keeps the rerank call the size it was before chunks.
    pub rerank_whole_chunked: bool,
    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,
            fusion_floor: 0,
            chunk_rerank: true,
            rerank_whole_chunked: true,
            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_k = self.tunables.dense_k;
        let dense = indexes.vector_search(store, &request.embedding, dense_k)?;
        let chunk_hits = if self.tunables.chunk_rerank {
            indexes.chunk_search(store, &request.embedding, dense_k * CHUNK_K_FACTOR)?
        } else {
            Vec::new()
        };
        let (dense, best_chunk) = merge_chunk_hits(dense, chunk_hits, dense_k);
        let lexical = indexes.bm25_search(&request.text, self.tunables.lexical_k)?;
        Ok(Candidates {
            best_chunk,
            ..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();

        // Exhaustion is judged on memories before chunk hits merge in: it
        // says the scope held fewer memories than dense_k, which chunks of
        // those same memories cannot change.
        let exhausted = dense.len() < self.tunables.dense_k;
        let chunk_hits = if self.tunables.chunk_rerank {
            store.filtered_chunk_search(
                &request.embedding,
                source,
                memory_type,
                project_path,
                self.tunables.dense_k,
            )?
        } else {
            Vec::new()
        };
        let (dense, best_chunk) = merge_chunk_hits(dense, chunk_hits, self.tunables.dense_k);

        // 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 exhausted {
            return Ok(Candidates {
                dense,
                lexical: Vec::new(),
                scope_exhausted: true,
                best_chunk,
            });
        }

        // 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 {
            best_chunk,
            ..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_with_floor(
            &[&dense_ids, &lexical_ids],
            rrf::RRF_K,
            self.tunables.fuse_top,
            self.tunables.fusion_floor,
        );
        let best_chunk = |id: &Uuid| {
            self.tunables
                .chunk_rerank
                .then(|| pool.best_chunk.get(id).copied())
                .flatten()
        };
        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| {
                    let whole = dense_sim
                        .get(&m.id)
                        .copied()
                        .unwrap_or_else(|| cosine(&request.embedding, &m.embedding));
                    best_chunk(&m.id).map_or(whole, |(_, chunk)| whole.max(chunk))
                })
                .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) => {
                // Windows follow the whole memories in the same call; each
                // candidate's primary is the better of its two scores.
                let mut windows: Vec<(usize, String)> = Vec::new();
                for (i, m) in candidates.iter().enumerate() {
                    if let Some((ord, _)) = best_chunk(&m.id)
                        && let Some(window) = store.chunk_window(m.id, ord)?
                    {
                        windows.push((i, window));
                    }
                }
                let whole_too = self.tunables.rerank_whole_chunked;
                let mut firsts: Vec<&str> = candidates.iter().map(|m| m.content.as_str()).collect();
                if !whole_too {
                    for (i, w) in &windows {
                        firsts[*i] = w.as_str();
                    }
                }
                let docs: Vec<&str> = firsts
                    .into_iter()
                    .chain(
                        windows
                            .iter()
                            .filter(|_| whole_too)
                            .map(|(_, w)| w.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(mut scores) => {
                        let window_scores = scores.split_off(candidates.len());
                        for ((i, _), score) in windows.iter().zip(window_scores) {
                            scores[*i] = scores[*i].max(score);
                        }
                        (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!()
        }
        /// The stub keeps a memory's chunk window in its `context`.
        fn chunk_window(&self, memory_id: Uuid, _: usize) -> Result<Option<String>> {
            Ok(self
                .memories
                .iter()
                .find(|m| m.id == memory_id)
                .and_then(|m| m.context.clone()))
        }
    }

    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,
            best_chunk: HashMap::new(),
        };

        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,
            best_chunk: HashMap::new(),
        };

        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()
    }

    /// Scores 0.8 for any document naming the planted fact and 0.1 for the
    /// rest, and records every call's documents.
    struct FactScorer {
        calls: std::sync::Mutex<Vec<Vec<String>>>,
    }

    impl FactScorer {
        fn new() -> Self {
            Self {
                calls: std::sync::Mutex::new(Vec::new()),
            }
        }
    }

    impl RerankScorer for FactScorer {
        fn rerank(&self, _: &str, docs: &[&str]) -> Result<Vec<f32>> {
            self.calls
                .lock()
                .unwrap()
                .push(docs.iter().map(|d| d.to_string()).collect());
            Ok(docs
                .iter()
                .map(|d| if d.contains("fact") { 0.8 } else { 0.1 })
                .collect())
        }
    }

    fn chunked_pool(dense: Vec<(Uuid, f32)>, best_chunk: &[(Uuid, usize, f32)]) -> Candidates {
        let mut pool = Candidates::new(dense, Vec::new());
        pool.best_chunk = best_chunk
            .iter()
            .map(|(id, ord, sim)| (*id, (*ord, *sim)))
            .collect();
        pool
    }

    #[test]
    fn the_rerank_primary_is_the_better_of_the_whole_memory_and_its_chunk_window() {
        let mut buried = memory("a long paragraph about many things", vec![1.0, 0.0]);
        buried.context = Some("the window holding the fact".to_string());
        let mut whole = memory("the fact stated outright", vec![1.0, 0.0]);
        whole.context = Some("a window about nothing".to_string());
        let plain = memory("nothing relevant here", vec![1.0, 0.0]);
        let store = StubStore {
            memories: vec![buried.clone(), whole.clone(), plain.clone()],
        };
        let pool = chunked_pool(
            vec![(buried.id, 0.7), (whole.id, 0.7), (plain.id, 0.7)],
            &[(buried.id, 2, 0.7), (whole.id, 0, 0.6)],
        );
        let scorer = FactScorer::new();

        let results = Retriever::default()
            .rank(&store, &request(vec![1.0, 0.0]), &pool, Some(&scorer))
            .unwrap();

        let mut ids: Vec<Uuid> = results.iter().map(|r| r.memory.id).collect();
        ids.sort();
        let mut expected = vec![buried.id, whole.id];
        expected.sort();
        assert_eq!(ids, expected, "plain reranks at 0.1, under the gate");
        let calls = scorer.calls.lock().unwrap();
        assert_eq!(calls.len(), 1, "whole memories and windows share one call");
        assert_eq!(
            calls[0],
            vec![
                "a long paragraph about many things",
                "the fact stated outright",
                "nothing relevant here",
                "the window holding the fact",
                "a window about nothing",
            ]
        );
    }

    #[test]
    fn without_whole_reranking_a_chunked_memory_is_scored_on_its_window_alone() {
        let mut buried = memory("a long paragraph about many things", vec![1.0, 0.0]);
        buried.context = Some("the window holding the fact".to_string());
        let plain = memory("the fact stated outright", vec![1.0, 0.0]);
        let store = StubStore {
            memories: vec![buried.clone(), plain.clone()],
        };
        let pool = chunked_pool(
            vec![(buried.id, 0.7), (plain.id, 0.7)],
            &[(buried.id, 2, 0.7)],
        );
        let scorer = FactScorer::new();
        let retriever = Retriever {
            tunables: RetrievalTunables {
                rerank_whole_chunked: false,
                ..RetrievalTunables::default()
            },
        };

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

        assert_eq!(results.len(), 2);
        assert_eq!(
            scorer.calls.lock().unwrap()[0],
            vec!["the window holding the fact", "the fact stated outright"]
        );
    }

    #[test]
    fn with_chunk_rerank_off_windows_are_neither_scored_nor_counted() {
        let mut buried = memory("a long paragraph about many things", vec![1.0, 0.0]);
        buried.context = Some("the window holding the fact".to_string());
        let store = StubStore {
            memories: vec![buried.clone()],
        };
        let pool = chunked_pool(vec![(buried.id, 0.7)], &[(buried.id, 2, 0.7)]);
        let scorer = FactScorer::new();
        let retriever = Retriever {
            tunables: RetrievalTunables {
                chunk_rerank: false,
                ..RetrievalTunables::default()
            },
        };

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

        assert!(results.is_empty());
        assert_eq!(
            scorer.calls.lock().unwrap()[0],
            vec!["a long paragraph about many things"]
        );
    }

    #[test]
    fn the_cosine_primary_takes_the_best_chunk_when_it_beats_the_memory() {
        let buried = memory("far as a whole", vec![0.0, 1.0]);
        let store = StubStore {
            memories: vec![buried.clone()],
        };
        let mut pool = chunked_pool(Vec::new(), &[(buried.id, 1, 0.9)]);
        pool.lexical = vec![(buried.id, 3.0)];

        let results = Retriever::default()
            .rank(&store, &request(vec![1.0, 0.0]), &pool, None)
            .unwrap();
        assert_eq!(results.len(), 1, "cosine 0 as a whole, 0.9 by its chunk");

        let mut exhausted = pool.clone();
        exhausted.scope_exhausted = true;
        let results = Retriever::default()
            .rank(&store, &request(vec![1.0, 0.0]), &exhausted, None)
            .unwrap();
        assert_eq!(results.len(), 1, "the exhausted floor also sees the chunk");
    }
}