vicinity 0.11.1

Approximate nearest-neighbor search
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
//! Graph-based ANN for sparse vectors using maximum inner product search.
//!
//! Designed for sparse vectors such as SPLADE embeddings, BM25 term vectors,
//! and bag-of-words representations. Vectors are stored in sparse format
//! (sorted `(index, value)` pairs) and graph search is optimized for sparsity
//! using inner-product-based similarity.
//!
//! Distance is defined as the negated inner product: lower = more similar. This
//! lets standard min-distance graph search maximize inner product.
//!
//! # Feature Flag
//!
//! ```toml
//! vicinity = { version = "0.10.5", features = ["sparse_mips"] }
//! ```
//!
//! # Quick Start
//!
//! ```ignore
//! use vicinity::sparse_mips::{SparseMipsIndex, SparseMipsParams, SparseVector};
//!
//! let params = SparseMipsParams::default();
//! let mut index = SparseMipsIndex::new(params);
//!
//! for (id, vec) in data {
//!     index.add(id, vec)?;
//! }
//! index.build()?;
//!
//! let results = index.search(&query, 10)?;
//! ```
//!
//! # Construction
//!
//! 1. Find entry point: vector with highest L2 norm (likely most "central" in IP space)
//! 2. Build initial kNN graph (brute-force for n <= 1000, NN-descent for larger)
//! 3. RNG pruning pass with alpha relaxation
//! 4. Connectivity enforcement: DFS from entry, connect unreachable nodes
//!
//! # References
//!
//! - Malkov, Yashunin (2020). "Efficient and robust approximate nearest neighbor
//!   search using Hierarchical Navigable Small World graphs." TPAMI 42(4).
//! - Jayaram Subramanya et al. (2019). "DiskANN: Fast Accurate Billion-point
//!   Nearest Neighbor Search on a Single Node." NeurIPS.

use crate::distance::FloatOrd;
use crate::RetrieveError;
use serde::{Deserialize, Serialize};
use smallvec::SmallVec;
use std::collections::{BinaryHeap, HashSet};
use std::path::Path;

const SPARSE_MIPS_FORMAT_VERSION: u32 = 1;
const SPARSE_MIPS_NEIGHBORS_MAGIC: &[u8; 8] = b"SPMIPSG1";

// ── Public types ───────────────────────────────────────────────────────────────

/// A sparse vector as sorted `(dimension_index, value)` pairs.
///
/// The `indices` array must be sorted in ascending order and have the same
/// length as `values`. Duplicate indices are not allowed.
#[derive(Clone, Debug, Default, Deserialize, Serialize)]
pub struct SparseVector {
    /// Dimension indices, sorted ascending.
    pub indices: Vec<u32>,
    /// Corresponding values.
    pub values: Vec<f32>,
}

impl SparseVector {
    /// Create a new sparse vector from unsorted (index, value) pairs.
    ///
    /// Sorts by index. Pairs with duplicate indices are summed, matching
    /// bag-of-words and term-frequency emitters that may produce repeated
    /// dimensions before compaction.
    pub fn from_pairs(mut pairs: Vec<(u32, f32)>) -> Self {
        pairs.sort_unstable_by_key(|&(i, _)| i);

        let mut indices = Vec::with_capacity(pairs.len());
        let mut values = Vec::with_capacity(pairs.len());
        for (idx, value) in pairs {
            if let Some((&last_idx, last_value)) = indices.last().zip(values.last_mut()) {
                if last_idx == idx {
                    *last_value += value;
                    continue;
                }
            }

            indices.push(idx);
            values.push(value);
        }

        Self { indices, values }
    }

    /// L2 norm of the sparse vector.
    #[inline]
    pub fn norm(&self) -> f32 {
        self.values.iter().map(|v| v * v).sum::<f32>().sqrt()
    }

    /// Number of nonzero entries.
    #[inline]
    pub fn nnz(&self) -> usize {
        self.indices.len()
    }
}

/// Construction and search parameters.
#[derive(Clone, Debug, Deserialize, Serialize)]
pub struct SparseMipsParams {
    /// Maximum out-degree per node. Default: 32.
    pub max_degree: usize,
    /// Construction beam width. Default: 200.
    pub ef_construction: usize,
    /// Search beam width. Default: 100.
    pub ef_search: usize,
    /// RNG pruning relaxation factor (>= 1.0). Default: 1.2.
    ///
    /// A larger value is more permissive, allowing more neighbors to survive
    /// pruning and generally improving recall at the cost of higher degree.
    pub alpha: f32,
}

impl Default for SparseMipsParams {
    fn default() -> Self {
        Self {
            max_degree: 32,
            ef_construction: 200,
            ef_search: 100,
            alpha: 1.2,
        }
    }
}

/// Sparse MIPS graph index.
pub struct SparseMipsIndex {
    params: SparseMipsParams,
    built: bool,

    vectors: Vec<SparseVector>,
    num_vectors: usize,
    doc_ids: Vec<u32>,

    neighbors: Vec<SmallVec<[u32; 16]>>,
    entry_point: u32,
}

#[derive(Deserialize, Serialize)]
struct SparseMipsSnapshot {
    version: u32,
    num_vectors: usize,
    total_nnz: usize,
    params: SparseMipsParams,
    entry_point: u32,
}

impl SparseMipsIndex {
    /// Create a new index. No dimension parameter is required because
    /// sparse vectors are dimension-agnostic.
    pub fn new(params: SparseMipsParams) -> Self {
        Self {
            params,
            built: false,
            vectors: Vec::new(),
            num_vectors: 0,
            doc_ids: Vec::new(),
            neighbors: Vec::new(),
            entry_point: 0,
        }
    }

    /// Add a sparse vector.
    ///
    /// Returns an error if the index has already been built.
    pub fn add(&mut self, doc_id: u32, vector: SparseVector) -> Result<(), RetrieveError> {
        if self.built {
            return Err(RetrieveError::InvalidParameter(
                "cannot add after build".into(),
            ));
        }
        self.vectors.push(vector);
        self.doc_ids.push(doc_id);
        self.num_vectors += 1;
        Ok(())
    }

    /// Build the index.
    ///
    /// Must be called before `search`. After building, no more vectors can be added.
    pub fn build(&mut self) -> Result<(), RetrieveError> {
        if self.built {
            return Ok(());
        }
        if self.num_vectors == 0 {
            return Err(RetrieveError::EmptyIndex);
        }

        let n = self.num_vectors;

        // Step 1: Entry point -- vector with highest L2 norm.
        self.entry_point = self.find_entry_point();

        // Step 2: Initial kNN graph.
        if n <= 1000 {
            self.build_knn_bruteforce();
        } else {
            self.build_knn_nndescent();
        }

        // Step 3: RNG pruning refinement pass.
        for i in 0..n {
            let candidates = self.beam_search_internal(i, self.params.ef_construction);
            let selected = self.rng_prune(i, &candidates);

            let old = std::mem::replace(
                &mut self.neighbors[i],
                selected.iter().map(|&(id, _)| id).collect(),
            );
            drop(old);

            // Bidirectional edge insertion with capacity-aware pruning.
            let max_deg = self.params.max_degree;
            for &(nb_id, _) in &selected {
                let nid = nb_id as usize;
                if !self.neighbors[nid].contains(&(i as u32)) {
                    if self.neighbors[nid].len() < max_deg {
                        self.neighbors[nid].push(i as u32);
                    } else {
                        // Re-prune the reverse neighbor list to keep degree bounded.
                        let rev_cands: Vec<(u32, f32)> = self.neighbors[nid]
                            .iter()
                            .chain(std::iter::once(&(i as u32)))
                            .map(|&cid| {
                                (
                                    cid,
                                    sparse_distance(
                                        &self.vectors[nid],
                                        &self.vectors[cid as usize],
                                    ),
                                )
                            })
                            .collect();
                        let pruned = self.rng_prune(nid, &rev_cands);
                        self.neighbors[nid] = pruned.iter().map(|&(id, _)| id).collect();
                    }
                }
            }
        }

        // Step 4: Connectivity enforcement.
        self.ensure_connectivity();

        self.built = true;
        Ok(())
    }

    /// Save a built SparseMIPS index to a directory.
    ///
    /// Sparse vectors are stored as CSR-style offsets, indices, and values.
    /// Loading restores the built graph directly.
    pub fn save_to_dir(&self, output_dir: impl AsRef<Path>) -> Result<(), RetrieveError> {
        if !self.built {
            return Err(RetrieveError::InvalidParameter(
                "cannot save unbuilt SparseMIPS index".into(),
            ));
        }
        let output_dir = output_dir.as_ref();
        std::fs::create_dir_all(output_dir)?;

        let mut offsets = Vec::with_capacity(self.num_vectors + 1);
        let mut indices = Vec::new();
        let mut values = Vec::new();
        offsets.push(0u64);
        for vector in &self.vectors {
            if vector.indices.len() != vector.values.len() {
                return Err(RetrieveError::FormatError(
                    "SparseMIPS vector has mismatched indices and values".into(),
                ));
            }
            indices.extend_from_slice(&vector.indices);
            values.extend_from_slice(&vector.values);
            offsets.push(indices.len() as u64);
        }

        let snapshot = SparseMipsSnapshot {
            version: SPARSE_MIPS_FORMAT_VERSION,
            num_vectors: self.num_vectors,
            total_nnz: indices.len(),
            params: self.params.clone(),
            entry_point: self.entry_point,
        };
        crate::graph_snapshot::write_json_atomic(&output_dir.join("manifest.json"), &snapshot)?;
        crate::graph_snapshot::write_u32_atomic(&output_dir.join("doc_ids.bin"), &self.doc_ids)?;
        crate::graph_snapshot::write_neighbors_atomic(
            &output_dir.join("neighbors.bin"),
            SPARSE_MIPS_NEIGHBORS_MAGIC,
            &self.neighbors,
        )?;
        crate::graph_snapshot::write_u64_atomic(&output_dir.join("offsets.bin"), &offsets)?;
        crate::graph_snapshot::write_u32_atomic(&output_dir.join("indices.bin"), &indices)?;
        crate::graph_snapshot::write_f32_atomic(&output_dir.join("values.bin"), &values)?;
        Ok(())
    }

    /// Load a SparseMIPS index saved by [`Self::save_to_dir`].
    pub fn load_from_dir(input_dir: impl AsRef<Path>) -> Result<Self, RetrieveError> {
        let input_dir = input_dir.as_ref();
        let snapshot: SparseMipsSnapshot =
            crate::graph_snapshot::read_json(&input_dir.join("manifest.json"))?;
        if snapshot.version != SPARSE_MIPS_FORMAT_VERSION {
            return Err(RetrieveError::FormatError(format!(
                "unsupported SparseMIPS format version {}",
                snapshot.version
            )));
        }
        if snapshot.num_vectors == 0 {
            return Err(RetrieveError::FormatError(
                "SparseMIPS manifest has zero vectors".into(),
            ));
        }
        let doc_ids = crate::graph_snapshot::read_u32_exact(
            &input_dir.join("doc_ids.bin"),
            snapshot.num_vectors,
        )?;
        let neighbors = crate::graph_snapshot::read_neighbors(
            &input_dir.join("neighbors.bin"),
            SPARSE_MIPS_NEIGHBORS_MAGIC,
            snapshot.num_vectors,
        )?;
        let offsets = crate::graph_snapshot::read_u64_exact(
            &input_dir.join("offsets.bin"),
            snapshot.num_vectors + 1,
        )?;
        let indices = crate::graph_snapshot::read_u32_exact(
            &input_dir.join("indices.bin"),
            snapshot.total_nnz,
        )?;
        let values = crate::graph_snapshot::read_f32_exact(
            &input_dir.join("values.bin"),
            snapshot.total_nnz,
        )?;
        if snapshot.entry_point as usize >= snapshot.num_vectors {
            return Err(RetrieveError::FormatError(format!(
                "SparseMIPS entry point {} exceeds vector count {}",
                snapshot.entry_point, snapshot.num_vectors
            )));
        }
        if offsets.first().copied() != Some(0)
            || offsets.last().copied() != Some(snapshot.total_nnz as u64)
        {
            return Err(RetrieveError::FormatError(
                "SparseMIPS offsets do not match manifest nnz".into(),
            ));
        }

        let mut vectors = Vec::with_capacity(snapshot.num_vectors);
        for pair in offsets.windows(2) {
            let start = pair[0] as usize;
            let end = pair[1] as usize;
            if start > end || end > indices.len() {
                return Err(RetrieveError::FormatError(
                    "SparseMIPS offsets are not monotonic".into(),
                ));
            }
            let vector_indices = indices[start..end].to_vec();
            if !vector_indices.windows(2).all(|w| w[0] < w[1]) {
                return Err(RetrieveError::FormatError(
                    "SparseMIPS vector indices must be strictly increasing".into(),
                ));
            }
            vectors.push(SparseVector {
                indices: vector_indices,
                values: values[start..end].to_vec(),
            });
        }

        Ok(Self {
            params: snapshot.params,
            built: true,
            vectors,
            num_vectors: snapshot.num_vectors,
            doc_ids,
            neighbors,
            entry_point: snapshot.entry_point,
        })
    }

    /// Search for the `k` nearest neighbors by inner product.
    ///
    /// Returns `(doc_id, distance)` pairs sorted ascending by distance
    /// (i.e., descending by inner product).
    pub fn search(&self, query: &SparseVector, k: usize) -> Result<Vec<(u32, f32)>, RetrieveError> {
        if !self.built {
            return Err(RetrieveError::InvalidParameter(
                "index must be built before search".into(),
            ));
        }
        if self.num_vectors == 0 {
            return Err(RetrieveError::EmptyIndex);
        }

        let ef = self.params.ef_search.max(k);
        let results = self.beam_search_query(query, ef);

        Ok(results
            .into_iter()
            .take(k)
            .map(|(id, dist)| (self.doc_ids[id as usize], dist))
            .collect())
    }

    /// Number of indexed vectors.
    pub fn len(&self) -> usize {
        self.num_vectors
    }

    /// Whether the index is empty.
    pub fn is_empty(&self) -> bool {
        self.num_vectors == 0
    }

    // ── Internal ───────────────────────────────────────────────────────────────

    /// Entry point: the vector with the highest L2 norm.
    fn find_entry_point(&self) -> u32 {
        let mut best = 0u32;
        let mut best_norm = self.vectors[0].norm();
        for i in 1..self.num_vectors {
            let n = self.vectors[i].norm();
            if n > best_norm {
                best_norm = n;
                best = i as u32;
            }
        }
        best
    }

    /// Brute-force initial kNN graph (used when n <= 1000).
    fn build_knn_bruteforce(&mut self) {
        let n = self.num_vectors;
        let k = (self.params.max_degree / 2).max(1).min(n - 1);
        self.neighbors = vec![SmallVec::new(); n];

        for i in 0..n {
            let mut dists: Vec<(u32, f32)> = (0..n)
                .filter(|&j| j != i)
                .map(|j| {
                    (
                        j as u32,
                        sparse_distance(&self.vectors[i], &self.vectors[j]),
                    )
                })
                .collect();
            dists.sort_unstable_by(|a, b| a.1.total_cmp(&b.1));
            dists.truncate(k);
            self.neighbors[i] = dists.iter().map(|&(id, _)| id).collect();
        }
    }

    /// NN-descent-style kNN graph construction for larger datasets.
    fn build_knn_nndescent(&mut self) {
        let (n, k) = (self.num_vectors, (self.params.max_degree / 2).max(1));
        let vecs = &self.vectors;
        self.neighbors = crate::graph_utils::build_knn_graph_nndescent(n, k, |i, j| {
            sparse_distance(&vecs[i], &vecs[j])
        });
    }

    /// RNG (Relative Neighborhood Graph) pruning with alpha relaxation.
    ///
    /// Keeps candidate `c` unless an already-selected neighbor `s` satisfies:
    /// `dist(query, s) <= alpha * dist(query, c)` AND `dist(s, c) <= alpha * dist(query, c)`.
    ///
    /// This is equivalent to Vamana's robust pruning rule.
    fn rng_prune(&self, query_idx: usize, candidates: &[(u32, f32)]) -> Vec<(u32, f32)> {
        let mut sorted: Vec<(u32, f32)> = candidates.to_vec();
        sorted.sort_unstable_by(|a, b| a.1.total_cmp(&b.1));
        sorted.dedup_by_key(|c| c.0);
        // Remove self-loops.
        sorted.retain(|&(id, _)| id as usize != query_idx);

        let max_deg = self.params.max_degree;
        let alpha = self.params.alpha;
        let mut selected: Vec<(u32, f32)> = Vec::with_capacity(max_deg);

        for &(cand_id, cand_dist) in &sorted {
            if selected.len() >= max_deg {
                break;
            }

            let mut keep = true;
            for &(sel_id, _sel_dist) in &selected {
                // Robust pruning: drop cand if selected neighbor s is already
                // close enough to cand that s would serve as a proxy.
                // Condition: alpha * dist(s, cand) <= dist(query, cand)
                let sc_dist = sparse_distance(
                    &self.vectors[sel_id as usize],
                    &self.vectors[cand_id as usize],
                );
                if alpha * sc_dist <= cand_dist {
                    keep = false;
                    break;
                }
            }

            if keep {
                selected.push((cand_id, cand_dist));
            }
        }

        selected
    }

    /// Beam search from the entry point to find candidates near node `query_idx`.
    /// Used during build; treats `vectors[query_idx]` as the query.
    fn beam_search_internal(&self, query_idx: usize, ef: usize) -> Vec<(u32, f32)> {
        self.beam_search_query(&self.vectors[query_idx].clone(), ef)
    }

    /// Beam search from the entry point toward `query`.
    fn beam_search_query(&self, query: &SparseVector, ef: usize) -> Vec<(u32, f32)> {
        let n = self.num_vectors;
        if n == 0 {
            return Vec::new();
        }

        let mut visited: HashSet<u32> = HashSet::new();
        // Min-heap by distance.
        let mut frontier: BinaryHeap<std::cmp::Reverse<(FloatOrd, u32)>> = BinaryHeap::new();
        let mut candidates: Vec<(u32, f32)> = Vec::new();

        let entry = self.entry_point;
        let entry_dist = sparse_distance(query, &self.vectors[entry as usize]);
        visited.insert(entry);
        frontier.push(std::cmp::Reverse((FloatOrd(entry_dist), entry)));
        candidates.push((entry, entry_dist));

        while let Some(std::cmp::Reverse((FloatOrd(current_dist), current_id))) = frontier.pop() {
            // Early termination: if the frontier's best is worse than the ef-th
            // result by a margin, further expansion cannot improve the top-ef.
            if candidates.len() >= ef {
                candidates.sort_unstable_by(|a, b| a.1.total_cmp(&b.1));
                if current_dist > candidates[ef - 1].1 * 1.5 {
                    break;
                }
            }

            for &neighbor in &self.neighbors[current_id as usize] {
                if visited.insert(neighbor) {
                    let dist = sparse_distance(query, &self.vectors[neighbor as usize]);
                    candidates.push((neighbor, dist));
                    frontier.push(std::cmp::Reverse((FloatOrd(dist), neighbor)));
                }
            }

            // Cap visited set to prevent runaway expansion.
            if visited.len() > ef * 10 {
                break;
            }
        }

        candidates.sort_unstable_by(|a, b| a.1.total_cmp(&b.1));
        candidates.dedup_by_key(|c| c.0);
        candidates
    }

    fn ensure_connectivity(&mut self) {
        let vecs = &self.vectors;
        crate::graph_utils::ensure_connectivity(&mut self.neighbors, self.entry_point, |i, j| {
            sparse_distance(&vecs[i], &vecs[j])
        });
    }
}

// ── Distance ──────────────────────────────────────────────────────────────────

/// Sparse inner product distance: `-dot_product(a, b)`.
///
/// Lower values indicate higher similarity (more positive inner product).
/// Uses a merge-join on sorted index arrays: O(|a| + |b|).
pub fn sparse_distance(a: &SparseVector, b: &SparseVector) -> f32 {
    let mut dot = 0.0f32;
    let mut ai = 0usize;
    let mut bi = 0usize;
    let a_idx = &a.indices;
    let b_idx = &b.indices;
    let a_val = &a.values;
    let b_val = &b.values;

    while ai < a_idx.len() && bi < b_idx.len() {
        match a_idx[ai].cmp(&b_idx[bi]) {
            std::cmp::Ordering::Equal => {
                dot += a_val[ai] * b_val[bi];
                ai += 1;
                bi += 1;
            }
            std::cmp::Ordering::Less => {
                ai += 1;
            }
            std::cmp::Ordering::Greater => {
                bi += 1;
            }
        }
    }

    -dot
}

// ── FloatOrd ──────────────────────────────────────────────────────────────────

// ── Tests ─────────────────────────────────────────────────────────────────────

#[cfg(test)]
#[allow(clippy::unwrap_used)]
mod tests {
    use super::*;

    /// Generate `n` random sparse vectors with `nnz` nonzero entries each,
    /// drawn from dimensions `0..max_dim` with values in `(0, 1)`.
    fn make_sparse(n: usize, nnz: usize, max_dim: u32, seed: u64) -> Vec<SparseVector> {
        let mut rng = seed;
        let lcg = |state: &mut u64| -> u64 {
            *state = state
                .wrapping_mul(6364136223846793005)
                .wrapping_add(1442695040888963407);
            *state
        };

        (0..n)
            .map(|_| {
                // Pick `nnz` distinct random indices.
                let mut indices: Vec<u32> = Vec::with_capacity(nnz);
                let mut attempts = 0usize;
                while indices.len() < nnz && attempts < nnz * 16 {
                    attempts += 1;
                    let idx = (lcg(&mut rng) >> 33) as u32 % max_dim;
                    if !indices.contains(&idx) {
                        indices.push(idx);
                    }
                }
                indices.sort_unstable();

                let values: Vec<f32> = indices
                    .iter()
                    .map(|_| {
                        let r = lcg(&mut rng);
                        (r >> 33) as f32 / (1u64 << 31) as f32
                    })
                    .collect();

                SparseVector { indices, values }
            })
            .collect()
    }

    #[test]
    fn build_and_search() {
        let n = 50;
        let vecs = make_sparse(n, 10, 100, 42);

        let mut index = SparseMipsIndex::new(SparseMipsParams {
            max_degree: 16,
            ef_construction: 64,
            ef_search: 32,
            alpha: 1.2,
        });

        for (i, v) in vecs.iter().enumerate() {
            index.add(i as u32, v.clone()).unwrap();
        }
        index.build().unwrap();

        assert_eq!(index.len(), n);

        let results = index.search(&vecs[0], 5).unwrap();
        assert!(!results.is_empty());
        assert!(results.len() <= 5);
        // The query vector itself should be in the results.
        assert!(results.iter().any(|&(id, _)| id == 0));
    }

    #[test]
    fn self_search_recall() {
        let n = 50;
        let vecs = make_sparse(n, 15, 200, 7);

        let mut index = SparseMipsIndex::new(SparseMipsParams {
            max_degree: 16,
            ef_construction: 100,
            ef_search: 50,
            alpha: 1.2,
        });

        for (i, v) in vecs.iter().enumerate() {
            index.add(i as u32, v.clone()).unwrap();
        }
        index.build().unwrap();

        let mut hits = 0usize;
        for (i, v) in vecs.iter().enumerate() {
            let results = index.search(v, 1).unwrap();
            if results.first().map(|&(id, _)| id) == Some(i as u32) {
                hits += 1;
            }
        }
        let recall = hits as f64 / n as f64;
        assert!(
            recall > 0.5,
            "self-search recall too low: {recall:.2} ({hits}/{n})"
        );
    }

    #[test]
    fn save_load_roundtrip_preserves_search() {
        let n = 50;
        let vecs = make_sparse(n, 15, 200, 7);
        let mut index = SparseMipsIndex::new(SparseMipsParams {
            max_degree: 16,
            ef_construction: 100,
            ef_search: 50,
            alpha: 1.2,
        });

        for (i, v) in vecs.iter().enumerate() {
            index.add(50_000 + i as u32, v.clone()).unwrap();
        }
        index.build().unwrap();
        let before = index.search(&vecs[0], 10).unwrap();

        let dir = tempfile::tempdir().unwrap();
        index.save_to_dir(dir.path()).unwrap();
        let loaded = SparseMipsIndex::load_from_dir(dir.path()).unwrap();

        assert_eq!(loaded.search(&vecs[0], 10).unwrap(), before);
        assert_eq!(loaded.len(), index.len());
        assert_eq!(loaded.entry_point, index.entry_point);
        for (left, right) in loaded.vectors.iter().zip(index.vectors.iter()) {
            assert_eq!(left.indices, right.indices);
            assert_eq!(left.values, right.values);
        }
    }

    #[test]
    fn empty_sparse_vectors() {
        // Vectors with no nonzero entries should not crash; all inner products are 0.
        let mut index = SparseMipsIndex::new(SparseMipsParams::default());
        for i in 0..5u32 {
            index
                .add(
                    i,
                    SparseVector {
                        indices: vec![],
                        values: vec![],
                    },
                )
                .unwrap();
        }
        index.build().unwrap();

        let query = SparseVector {
            indices: vec![],
            values: vec![],
        };
        let results = index.search(&query, 3).unwrap();
        assert!(!results.is_empty());
    }

    #[test]
    fn disjoint_vectors() {
        // Two groups with non-overlapping dimensions: inner product between groups = 0.
        let mut index = SparseMipsIndex::new(SparseMipsParams {
            max_degree: 8,
            ef_construction: 32,
            ef_search: 16,
            alpha: 1.2,
        });

        // Group A: dimensions 0..10
        for i in 0..5u32 {
            let sv = SparseVector {
                indices: (0u32..10).collect(),
                values: vec![1.0; 10],
            };
            index.add(i, sv).unwrap();
        }
        // Group B: dimensions 100..110
        for i in 5..10u32 {
            let sv = SparseVector {
                indices: (100u32..110).collect(),
                values: vec![1.0; 10],
            };
            index.add(i, sv).unwrap();
        }
        index.build().unwrap();

        // Query from group A should preferentially return group A ids.
        let query_a = SparseVector {
            indices: (0u32..10).collect(),
            values: vec![1.0; 10],
        };
        let results = index.search(&query_a, 3).unwrap();
        assert!(!results.is_empty());
        // All returned ids should be in group A (0..5), since inter-group IP = 0
        // and intra-group IP = 10 (distance = -10).
        let all_group_a = results.iter().all(|&(id, _)| id < 5);
        assert!(all_group_a, "expected group A results, got: {results:?}");
    }

    #[test]
    fn empty_index_errors() {
        let mut index = SparseMipsIndex::new(SparseMipsParams::default());
        assert!(index.build().is_err());
        assert!(index.search(&SparseVector::default(), 1).is_err());
    }

    #[test]
    fn add_after_build_errors() {
        let mut index = SparseMipsIndex::new(SparseMipsParams::default());
        index
            .add(
                0,
                SparseVector {
                    indices: vec![0],
                    values: vec![1.0],
                },
            )
            .unwrap();
        index.build().unwrap();
        let err = index.add(1, SparseVector::default());
        assert!(err.is_err());
    }

    #[test]
    fn sparse_distance_correctness() {
        let a = SparseVector {
            indices: vec![0, 2, 4],
            values: vec![1.0, 2.0, 3.0],
        };
        let b = SparseVector {
            indices: vec![1, 2, 3],
            values: vec![5.0, 6.0, 7.0],
        };
        // Only dimension 2 overlaps: 2.0 * 6.0 = 12.0; distance = -12.0
        let d = sparse_distance(&a, &b);
        assert!((d - (-12.0f32)).abs() < 1e-5, "expected -12.0, got {d}");

        // Disjoint vectors: dot = 0, distance = 0
        let c = SparseVector {
            indices: vec![10, 11],
            values: vec![3.0, 4.0],
        };
        let d2 = sparse_distance(&a, &c);
        assert!((d2).abs() < 1e-5, "expected 0.0, got {d2}");
    }

    #[test]
    fn from_pairs_sorts_and_deduplicates() {
        let sv = SparseVector::from_pairs(vec![(3, 1.0), (1, 2.0), (3, 5.0), (0, 0.5)]);
        assert_eq!(sv.indices, vec![0, 1, 3]);
        assert_eq!(sv.values, vec![0.5, 2.0, 6.0]);
    }
}